babylon.engine.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var _DepthCullingState = (function () {
  4. function _DepthCullingState() {
  5. this._isDepthTestDirty = false;
  6. this._isDepthMaskDirty = false;
  7. this._isDepthFuncDirty = false;
  8. this._isCullFaceDirty = false;
  9. this._isCullDirty = false;
  10. this._isZOffsetDirty = false;
  11. }
  12. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  13. get: function () {
  14. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  15. },
  16. enumerable: true,
  17. configurable: true
  18. });
  19. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  20. get: function () {
  21. return this._zOffset;
  22. },
  23. set: function (value) {
  24. if (this._zOffset === value) {
  25. return;
  26. }
  27. this._zOffset = value;
  28. this._isZOffsetDirty = true;
  29. },
  30. enumerable: true,
  31. configurable: true
  32. });
  33. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  34. get: function () {
  35. return this._cullFace;
  36. },
  37. set: function (value) {
  38. if (this._cullFace === value) {
  39. return;
  40. }
  41. this._cullFace = value;
  42. this._isCullFaceDirty = true;
  43. },
  44. enumerable: true,
  45. configurable: true
  46. });
  47. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  48. get: function () {
  49. return this._cull;
  50. },
  51. set: function (value) {
  52. if (this._cull === value) {
  53. return;
  54. }
  55. this._cull = value;
  56. this._isCullDirty = true;
  57. },
  58. enumerable: true,
  59. configurable: true
  60. });
  61. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  62. get: function () {
  63. return this._depthFunc;
  64. },
  65. set: function (value) {
  66. if (this._depthFunc === value) {
  67. return;
  68. }
  69. this._depthFunc = value;
  70. this._isDepthFuncDirty = true;
  71. },
  72. enumerable: true,
  73. configurable: true
  74. });
  75. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  76. get: function () {
  77. return this._depthMask;
  78. },
  79. set: function (value) {
  80. if (this._depthMask === value) {
  81. return;
  82. }
  83. this._depthMask = value;
  84. this._isDepthMaskDirty = true;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  90. get: function () {
  91. return this._depthTest;
  92. },
  93. set: function (value) {
  94. if (this._depthTest === value) {
  95. return;
  96. }
  97. this._depthTest = value;
  98. this._isDepthTestDirty = true;
  99. },
  100. enumerable: true,
  101. configurable: true
  102. });
  103. _DepthCullingState.prototype.reset = function () {
  104. this._depthMask = true;
  105. this._depthTest = true;
  106. this._depthFunc = null;
  107. this._cull = null;
  108. this._cullFace = null;
  109. this._zOffset = 0;
  110. this._isDepthTestDirty = true;
  111. this._isDepthMaskDirty = true;
  112. this._isDepthFuncDirty = false;
  113. this._isCullFaceDirty = false;
  114. this._isCullDirty = false;
  115. this._isZOffsetDirty = false;
  116. };
  117. _DepthCullingState.prototype.apply = function (gl) {
  118. if (!this.isDirty) {
  119. return;
  120. }
  121. // Cull
  122. if (this._isCullDirty) {
  123. if (this.cull) {
  124. gl.enable(gl.CULL_FACE);
  125. }
  126. else {
  127. gl.disable(gl.CULL_FACE);
  128. }
  129. this._isCullDirty = false;
  130. }
  131. // Cull face
  132. if (this._isCullFaceDirty) {
  133. gl.cullFace(this.cullFace);
  134. this._isCullFaceDirty = false;
  135. }
  136. // Depth mask
  137. if (this._isDepthMaskDirty) {
  138. gl.depthMask(this.depthMask);
  139. this._isDepthMaskDirty = false;
  140. }
  141. // Depth test
  142. if (this._isDepthTestDirty) {
  143. if (this.depthTest) {
  144. gl.enable(gl.DEPTH_TEST);
  145. }
  146. else {
  147. gl.disable(gl.DEPTH_TEST);
  148. }
  149. this._isDepthTestDirty = false;
  150. }
  151. // Depth func
  152. if (this._isDepthFuncDirty) {
  153. gl.depthFunc(this.depthFunc);
  154. this._isDepthFuncDirty = false;
  155. }
  156. // zOffset
  157. if (this._isZOffsetDirty) {
  158. if (this.zOffset) {
  159. gl.enable(gl.POLYGON_OFFSET_FILL);
  160. gl.polygonOffset(this.zOffset, 0);
  161. }
  162. else {
  163. gl.disable(gl.POLYGON_OFFSET_FILL);
  164. }
  165. this._isZOffsetDirty = false;
  166. }
  167. };
  168. return _DepthCullingState;
  169. })();
  170. BABYLON._DepthCullingState = _DepthCullingState;
  171. var _AlphaState = (function () {
  172. function _AlphaState() {
  173. this._isAlphaBlendDirty = false;
  174. this._isBlendFunctionParametersDirty = false;
  175. this._alphaBlend = false;
  176. this._blendFunctionParameters = new Array(4);
  177. }
  178. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  179. get: function () {
  180. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  181. },
  182. enumerable: true,
  183. configurable: true
  184. });
  185. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  186. get: function () {
  187. return this._alphaBlend;
  188. },
  189. set: function (value) {
  190. if (this._alphaBlend === value) {
  191. return;
  192. }
  193. this._alphaBlend = value;
  194. this._isAlphaBlendDirty = true;
  195. },
  196. enumerable: true,
  197. configurable: true
  198. });
  199. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  200. if (this._blendFunctionParameters[0] === value0 &&
  201. this._blendFunctionParameters[1] === value1 &&
  202. this._blendFunctionParameters[2] === value2 &&
  203. this._blendFunctionParameters[3] === value3) {
  204. return;
  205. }
  206. this._blendFunctionParameters[0] = value0;
  207. this._blendFunctionParameters[1] = value1;
  208. this._blendFunctionParameters[2] = value2;
  209. this._blendFunctionParameters[3] = value3;
  210. this._isBlendFunctionParametersDirty = true;
  211. };
  212. _AlphaState.prototype.reset = function () {
  213. this._alphaBlend = false;
  214. this._blendFunctionParameters[0] = null;
  215. this._blendFunctionParameters[1] = null;
  216. this._blendFunctionParameters[2] = null;
  217. this._blendFunctionParameters[3] = null;
  218. this._isAlphaBlendDirty = true;
  219. this._isBlendFunctionParametersDirty = false;
  220. };
  221. _AlphaState.prototype.apply = function (gl) {
  222. if (!this.isDirty) {
  223. return;
  224. }
  225. // Alpha blend
  226. if (this._isAlphaBlendDirty) {
  227. if (this._alphaBlend) {
  228. gl.enable(gl.BLEND);
  229. }
  230. else {
  231. gl.disable(gl.BLEND);
  232. }
  233. this._isAlphaBlendDirty = false;
  234. }
  235. // Alpha function
  236. if (this._isBlendFunctionParametersDirty) {
  237. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  238. this._isBlendFunctionParametersDirty = false;
  239. }
  240. };
  241. return _AlphaState;
  242. })();
  243. BABYLON._AlphaState = _AlphaState;
  244. var compileShader = function (gl, source, type, defines) {
  245. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  246. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  247. gl.compileShader(shader);
  248. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  249. throw new Error(gl.getShaderInfoLog(shader));
  250. }
  251. return shader;
  252. };
  253. var getWebGLTextureType = function (gl, type) {
  254. var textureType = gl.UNSIGNED_BYTE;
  255. if (type === Engine.TEXTURETYPE_FLOAT)
  256. textureType = gl.FLOAT;
  257. return textureType;
  258. };
  259. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  260. var magFilter = gl.NEAREST;
  261. var minFilter = gl.NEAREST;
  262. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  263. magFilter = gl.LINEAR;
  264. if (generateMipMaps) {
  265. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  266. }
  267. else {
  268. minFilter = gl.LINEAR;
  269. }
  270. }
  271. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  272. magFilter = gl.LINEAR;
  273. if (generateMipMaps) {
  274. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  275. }
  276. else {
  277. minFilter = gl.LINEAR;
  278. }
  279. }
  280. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  281. magFilter = gl.NEAREST;
  282. if (generateMipMaps) {
  283. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  284. }
  285. else {
  286. minFilter = gl.NEAREST;
  287. }
  288. }
  289. return {
  290. min: minFilter,
  291. mag: magFilter
  292. };
  293. };
  294. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  296. var engine = scene.getEngine();
  297. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  298. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  299. gl.bindTexture(gl.TEXTURE_2D, texture);
  300. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  301. texture._baseWidth = width;
  302. texture._baseHeight = height;
  303. texture._width = potWidth;
  304. texture._height = potHeight;
  305. texture.isReady = true;
  306. processFunction(potWidth, potHeight);
  307. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  310. if (!noMipmap && !isCompressed) {
  311. gl.generateMipmap(gl.TEXTURE_2D);
  312. }
  313. gl.bindTexture(gl.TEXTURE_2D, null);
  314. engine.resetTextureCache();
  315. scene._removePendingData(texture);
  316. };
  317. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  318. var onload = function () {
  319. loadedImages[index] = img;
  320. loadedImages._internalCount++;
  321. scene._removePendingData(img);
  322. if (loadedImages._internalCount === 6) {
  323. onfinish(loadedImages);
  324. }
  325. };
  326. var onerror = function () {
  327. scene._removePendingData(img);
  328. };
  329. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  330. scene._addPendingData(img);
  331. };
  332. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  333. var loadedImages = [];
  334. loadedImages._internalCount = 0;
  335. for (var index = 0; index < 6; index++) {
  336. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  337. }
  338. };
  339. var EngineCapabilities = (function () {
  340. function EngineCapabilities() {
  341. }
  342. return EngineCapabilities;
  343. })();
  344. BABYLON.EngineCapabilities = EngineCapabilities;
  345. /**
  346. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  347. */
  348. var Engine = (function () {
  349. /**
  350. * @constructor
  351. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  352. * @param {boolean} [antialias] - enable antialias
  353. * @param options - further options to be sent to the getContext function
  354. */
  355. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  356. var _this = this;
  357. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  358. // Public members
  359. this.isFullscreen = false;
  360. this.isPointerLock = false;
  361. this.cullBackFaces = true;
  362. this.renderEvenInBackground = true;
  363. // To enable/disable IDB support and avoid XHR on .manifest
  364. this.enableOfflineSupport = true;
  365. this.scenes = new Array();
  366. this._windowIsBackground = false;
  367. this._drawCalls = 0;
  368. this._renderingQueueLaunched = false;
  369. this._activeRenderLoops = [];
  370. // FPS
  371. this.fpsRange = 60;
  372. this.previousFramesDuration = [];
  373. this.fps = 60;
  374. this.deltaTime = 0;
  375. // States
  376. this._depthCullingState = new _DepthCullingState();
  377. this._alphaState = new _AlphaState();
  378. this._alphaMode = Engine.ALPHA_DISABLE;
  379. // Cache
  380. this._loadedTexturesCache = new Array();
  381. this._maxTextureChannels = 16;
  382. this._activeTexturesCache = new Array(this._maxTextureChannels);
  383. this._compiledEffects = {};
  384. this._uintIndicesCurrentlySet = false;
  385. this._renderingCanvas = canvas;
  386. options = options || {};
  387. options.antialias = antialias;
  388. if (options.preserveDrawingBuffer === undefined) {
  389. options.preserveDrawingBuffer = false;
  390. }
  391. // GL
  392. try {
  393. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  394. }
  395. catch (e) {
  396. throw new Error("WebGL not supported");
  397. }
  398. if (!this._gl) {
  399. throw new Error("WebGL not supported");
  400. }
  401. this._onBlur = function () {
  402. _this._windowIsBackground = true;
  403. };
  404. this._onFocus = function () {
  405. _this._windowIsBackground = false;
  406. };
  407. window.addEventListener("blur", this._onBlur);
  408. window.addEventListener("focus", this._onFocus);
  409. // Viewport
  410. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  411. this.resize();
  412. // Caps
  413. this._caps = new EngineCapabilities();
  414. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  415. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  416. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  417. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  418. // Infos
  419. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  420. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  421. if (rendererInfo != null) {
  422. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  423. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  424. }
  425. if (!this._glVendor) {
  426. this._glVendor = "Unknown vendor";
  427. }
  428. if (!this._glRenderer) {
  429. this._glRenderer = "Unknown renderer";
  430. }
  431. // Extensions
  432. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  433. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  434. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  435. 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');
  436. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  437. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  438. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  439. this._caps.highPrecisionShaderSupported = true;
  440. if (this._gl.getShaderPrecisionFormat) {
  441. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  442. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  443. }
  444. // Depth buffer
  445. this.setDepthBuffer(true);
  446. this.setDepthFunctionToLessOrEqual();
  447. this.setDepthWrite(true);
  448. // Fullscreen
  449. this._onFullscreenChange = function () {
  450. if (document.fullscreen !== undefined) {
  451. _this.isFullscreen = document.fullscreen;
  452. }
  453. else if (document.mozFullScreen !== undefined) {
  454. _this.isFullscreen = document.mozFullScreen;
  455. }
  456. else if (document.webkitIsFullScreen !== undefined) {
  457. _this.isFullscreen = document.webkitIsFullScreen;
  458. }
  459. else if (document.msIsFullScreen !== undefined) {
  460. _this.isFullscreen = document.msIsFullScreen;
  461. }
  462. // Pointer lock
  463. if (_this.isFullscreen && _this._pointerLockRequested) {
  464. canvas.requestPointerLock = canvas.requestPointerLock ||
  465. canvas.msRequestPointerLock ||
  466. canvas.mozRequestPointerLock ||
  467. canvas.webkitRequestPointerLock;
  468. if (canvas.requestPointerLock) {
  469. canvas.requestPointerLock();
  470. }
  471. }
  472. };
  473. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  474. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  475. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  476. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  477. // Pointer lock
  478. this._onPointerLockChange = function () {
  479. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  480. document.webkitPointerLockElement === canvas ||
  481. document.msPointerLockElement === canvas ||
  482. document.pointerLockElement === canvas);
  483. };
  484. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  485. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  486. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  487. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  488. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  489. Engine.audioEngine = new BABYLON.AudioEngine();
  490. }
  491. //default loading screen
  492. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  493. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  494. }
  495. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  496. get: function () {
  497. return Engine._ALPHA_DISABLE;
  498. },
  499. enumerable: true,
  500. configurable: true
  501. });
  502. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  503. get: function () {
  504. return Engine._ALPHA_ONEONE;
  505. },
  506. enumerable: true,
  507. configurable: true
  508. });
  509. Object.defineProperty(Engine, "ALPHA_ADD", {
  510. get: function () {
  511. return Engine._ALPHA_ADD;
  512. },
  513. enumerable: true,
  514. configurable: true
  515. });
  516. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  517. get: function () {
  518. return Engine._ALPHA_COMBINE;
  519. },
  520. enumerable: true,
  521. configurable: true
  522. });
  523. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  524. get: function () {
  525. return Engine._ALPHA_SUBTRACT;
  526. },
  527. enumerable: true,
  528. configurable: true
  529. });
  530. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  531. get: function () {
  532. return Engine._ALPHA_MULTIPLY;
  533. },
  534. enumerable: true,
  535. configurable: true
  536. });
  537. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  538. get: function () {
  539. return Engine._ALPHA_MAXIMIZED;
  540. },
  541. enumerable: true,
  542. configurable: true
  543. });
  544. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  545. get: function () {
  546. return Engine._DELAYLOADSTATE_NONE;
  547. },
  548. enumerable: true,
  549. configurable: true
  550. });
  551. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  552. get: function () {
  553. return Engine._DELAYLOADSTATE_LOADED;
  554. },
  555. enumerable: true,
  556. configurable: true
  557. });
  558. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  559. get: function () {
  560. return Engine._DELAYLOADSTATE_LOADING;
  561. },
  562. enumerable: true,
  563. configurable: true
  564. });
  565. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  566. get: function () {
  567. return Engine._DELAYLOADSTATE_NOTLOADED;
  568. },
  569. enumerable: true,
  570. configurable: true
  571. });
  572. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  573. get: function () {
  574. return Engine._TEXTUREFORMAT_ALPHA;
  575. },
  576. enumerable: true,
  577. configurable: true
  578. });
  579. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  580. get: function () {
  581. return Engine._TEXTUREFORMAT_LUMINANCE;
  582. },
  583. enumerable: true,
  584. configurable: true
  585. });
  586. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  587. get: function () {
  588. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  589. },
  590. enumerable: true,
  591. configurable: true
  592. });
  593. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  594. get: function () {
  595. return Engine._TEXTUREFORMAT_RGB;
  596. },
  597. enumerable: true,
  598. configurable: true
  599. });
  600. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  601. get: function () {
  602. return Engine._TEXTUREFORMAT_RGBA;
  603. },
  604. enumerable: true,
  605. configurable: true
  606. });
  607. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  608. get: function () {
  609. return Engine._TEXTURETYPE_UNSIGNED_INT;
  610. },
  611. enumerable: true,
  612. configurable: true
  613. });
  614. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  615. get: function () {
  616. return Engine._TEXTURETYPE_FLOAT;
  617. },
  618. enumerable: true,
  619. configurable: true
  620. });
  621. Object.defineProperty(Engine, "Version", {
  622. get: function () {
  623. return "2.3.0-alpha";
  624. },
  625. enumerable: true,
  626. configurable: true
  627. });
  628. Engine.prototype._prepareWorkingCanvas = function () {
  629. if (this._workingCanvas) {
  630. return;
  631. }
  632. this._workingCanvas = document.createElement("canvas");
  633. this._workingContext = this._workingCanvas.getContext("2d");
  634. };
  635. Engine.prototype.resetTextureCache = function () {
  636. for (var index = 0; index < this._maxTextureChannels; index++) {
  637. this._activeTexturesCache[index] = null;
  638. }
  639. };
  640. Engine.prototype.getGlInfo = function () {
  641. return {
  642. vendor: this._glVendor,
  643. renderer: this._glRenderer,
  644. version: this._glVersion
  645. };
  646. };
  647. Engine.prototype.getAspectRatio = function (camera) {
  648. var viewport = camera.viewport;
  649. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  650. };
  651. Engine.prototype.getRenderWidth = function () {
  652. if (this._currentRenderTarget) {
  653. return this._currentRenderTarget._width;
  654. }
  655. return this._renderingCanvas.width;
  656. };
  657. Engine.prototype.getRenderHeight = function () {
  658. if (this._currentRenderTarget) {
  659. return this._currentRenderTarget._height;
  660. }
  661. return this._renderingCanvas.height;
  662. };
  663. Engine.prototype.getRenderingCanvas = function () {
  664. return this._renderingCanvas;
  665. };
  666. Engine.prototype.getRenderingCanvasClientRect = function () {
  667. return this._renderingCanvas.getBoundingClientRect();
  668. };
  669. Engine.prototype.setHardwareScalingLevel = function (level) {
  670. this._hardwareScalingLevel = level;
  671. this.resize();
  672. };
  673. Engine.prototype.getHardwareScalingLevel = function () {
  674. return this._hardwareScalingLevel;
  675. };
  676. Engine.prototype.getLoadedTexturesCache = function () {
  677. return this._loadedTexturesCache;
  678. };
  679. Engine.prototype.getCaps = function () {
  680. return this._caps;
  681. };
  682. Object.defineProperty(Engine.prototype, "drawCalls", {
  683. get: function () {
  684. return this._drawCalls;
  685. },
  686. enumerable: true,
  687. configurable: true
  688. });
  689. // Methods
  690. Engine.prototype.resetDrawCalls = function () {
  691. this._drawCalls = 0;
  692. };
  693. Engine.prototype.setDepthFunctionToGreater = function () {
  694. this._depthCullingState.depthFunc = this._gl.GREATER;
  695. };
  696. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  697. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  698. };
  699. Engine.prototype.setDepthFunctionToLess = function () {
  700. this._depthCullingState.depthFunc = this._gl.LESS;
  701. };
  702. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  703. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  704. };
  705. /**
  706. * stop executing a render loop function and remove it from the execution array
  707. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  708. */
  709. Engine.prototype.stopRenderLoop = function (renderFunction) {
  710. if (!renderFunction) {
  711. this._activeRenderLoops = [];
  712. return;
  713. }
  714. var index = this._activeRenderLoops.indexOf(renderFunction);
  715. if (index >= 0) {
  716. this._activeRenderLoops.splice(index, 1);
  717. }
  718. };
  719. Engine.prototype._renderLoop = function () {
  720. var shouldRender = true;
  721. if (!this.renderEvenInBackground && this._windowIsBackground) {
  722. shouldRender = false;
  723. }
  724. if (shouldRender) {
  725. // Start new frame
  726. this.beginFrame();
  727. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  728. var renderFunction = this._activeRenderLoops[index];
  729. renderFunction();
  730. }
  731. // Present
  732. this.endFrame();
  733. }
  734. if (this._activeRenderLoops.length > 0) {
  735. // Register new frame
  736. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  737. }
  738. else {
  739. this._renderingQueueLaunched = false;
  740. }
  741. };
  742. /**
  743. * Register and execute a render loop. The engine can have more than one render function.
  744. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  745. * @example
  746. * engine.runRenderLoop(function () {
  747. * scene.render()
  748. * })
  749. */
  750. Engine.prototype.runRenderLoop = function (renderFunction) {
  751. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  752. return;
  753. }
  754. this._activeRenderLoops.push(renderFunction);
  755. if (!this._renderingQueueLaunched) {
  756. this._renderingQueueLaunched = true;
  757. this._bindedRenderFunction = this._renderLoop.bind(this);
  758. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  759. }
  760. };
  761. /**
  762. * Toggle full screen mode.
  763. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  764. */
  765. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  766. if (this.isFullscreen) {
  767. BABYLON.Tools.ExitFullscreen();
  768. }
  769. else {
  770. this._pointerLockRequested = requestPointerLock;
  771. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  772. }
  773. };
  774. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  775. this.applyStates();
  776. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  777. if (this._depthCullingState.depthMask) {
  778. this._gl.clearDepth(1.0);
  779. }
  780. var mode = 0;
  781. if (backBuffer)
  782. mode |= this._gl.COLOR_BUFFER_BIT;
  783. if (depthStencil && this._depthCullingState.depthMask)
  784. mode |= this._gl.DEPTH_BUFFER_BIT;
  785. this._gl.clear(mode);
  786. };
  787. /**
  788. * Set the WebGL's viewport
  789. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  790. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  791. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  792. */
  793. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  794. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  795. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  796. var x = viewport.x || 0;
  797. var y = viewport.y || 0;
  798. this._cachedViewport = viewport;
  799. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  800. };
  801. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  802. this._cachedViewport = null;
  803. this._gl.viewport(x, y, width, height);
  804. };
  805. Engine.prototype.beginFrame = function () {
  806. this._measureFps();
  807. };
  808. Engine.prototype.endFrame = function () {
  809. //this.flushFramebuffer();
  810. };
  811. /**
  812. * resize the view according to the canvas' size.
  813. * @example
  814. * window.addEventListener("resize", function () {
  815. * engine.resize();
  816. * });
  817. */
  818. Engine.prototype.resize = function () {
  819. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  820. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  821. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  822. for (var index = 0; index < this.scenes.length; index++) {
  823. var scene = this.scenes[index];
  824. if (scene.debugLayer.isVisible()) {
  825. scene.debugLayer._syncPositions();
  826. }
  827. }
  828. };
  829. /**
  830. * force a specific size of the canvas
  831. * @param {number} width - the new canvas' width
  832. * @param {number} height - the new canvas' height
  833. */
  834. Engine.prototype.setSize = function (width, height) {
  835. this._renderingCanvas.width = width;
  836. this._renderingCanvas.height = height;
  837. for (var index = 0; index < this.scenes.length; index++) {
  838. var scene = this.scenes[index];
  839. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  840. var cam = scene.cameras[camIndex];
  841. cam._currentRenderId = 0;
  842. }
  843. }
  844. };
  845. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  846. this._currentRenderTarget = texture;
  847. var gl = this._gl;
  848. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  849. if (texture.isCube) {
  850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  851. }
  852. else {
  853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  854. }
  855. this._gl.viewport(0, 0, texture._width, texture._height);
  856. this.wipeCaches();
  857. };
  858. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  859. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  860. this._currentRenderTarget = null;
  861. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  862. var gl = this._gl;
  863. gl.bindTexture(gl.TEXTURE_2D, texture);
  864. gl.generateMipmap(gl.TEXTURE_2D);
  865. gl.bindTexture(gl.TEXTURE_2D, null);
  866. }
  867. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  868. };
  869. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  870. if (texture.generateMipMaps) {
  871. var gl = this._gl;
  872. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  873. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  874. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  875. }
  876. };
  877. Engine.prototype.flushFramebuffer = function () {
  878. this._gl.flush();
  879. };
  880. Engine.prototype.restoreDefaultFramebuffer = function () {
  881. this._currentRenderTarget = null;
  882. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  883. this.setViewport(this._cachedViewport);
  884. this.wipeCaches();
  885. };
  886. // VBOs
  887. Engine.prototype._resetVertexBufferBinding = function () {
  888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  889. this._cachedVertexBuffers = null;
  890. };
  891. Engine.prototype.createVertexBuffer = function (vertices) {
  892. var vbo = this._gl.createBuffer();
  893. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  894. if (vertices instanceof Float32Array) {
  895. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  896. }
  897. else {
  898. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  899. }
  900. this._resetVertexBufferBinding();
  901. vbo.references = 1;
  902. return vbo;
  903. };
  904. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  905. var vbo = this._gl.createBuffer();
  906. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  907. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  908. this._resetVertexBufferBinding();
  909. vbo.references = 1;
  910. return vbo;
  911. };
  912. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  914. if (offset === undefined) {
  915. offset = 0;
  916. }
  917. if (vertices instanceof Float32Array) {
  918. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  919. }
  920. else {
  921. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  922. }
  923. this._resetVertexBufferBinding();
  924. };
  925. Engine.prototype._resetIndexBufferBinding = function () {
  926. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  927. this._cachedIndexBuffer = null;
  928. };
  929. Engine.prototype.createIndexBuffer = function (indices) {
  930. var vbo = this._gl.createBuffer();
  931. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  932. // Check for 32 bits indices
  933. var arrayBuffer;
  934. var need32Bits = false;
  935. if (this._caps.uintIndices) {
  936. for (var index = 0; index < indices.length; index++) {
  937. if (indices[index] > 65535) {
  938. need32Bits = true;
  939. break;
  940. }
  941. }
  942. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  943. }
  944. else {
  945. arrayBuffer = new Uint16Array(indices);
  946. }
  947. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  948. this._resetIndexBufferBinding();
  949. vbo.references = 1;
  950. vbo.is32Bits = need32Bits;
  951. return vbo;
  952. };
  953. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  954. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  955. this._cachedVertexBuffers = vertexBuffer;
  956. this._cachedEffectForVertexBuffers = effect;
  957. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  958. var offset = 0;
  959. for (var index = 0; index < vertexDeclaration.length; index++) {
  960. var order = effect.getAttributeLocation(index);
  961. if (order >= 0) {
  962. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  963. }
  964. offset += vertexDeclaration[index] * 4;
  965. }
  966. }
  967. if (this._cachedIndexBuffer !== indexBuffer) {
  968. this._cachedIndexBuffer = indexBuffer;
  969. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  970. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  971. }
  972. };
  973. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  974. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  975. this._cachedVertexBuffers = vertexBuffers;
  976. this._cachedEffectForVertexBuffers = effect;
  977. var attributes = effect.getAttributesNames();
  978. for (var index = 0; index < attributes.length; index++) {
  979. var order = effect.getAttributeLocation(index);
  980. if (order >= 0) {
  981. var vertexBuffer = vertexBuffers[attributes[index]];
  982. if (!vertexBuffer) {
  983. continue;
  984. }
  985. var stride = vertexBuffer.getStrideSize();
  986. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  987. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  988. }
  989. }
  990. }
  991. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  992. this._cachedIndexBuffer = indexBuffer;
  993. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  994. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  995. }
  996. };
  997. Engine.prototype._releaseBuffer = function (buffer) {
  998. buffer.references--;
  999. if (buffer.references === 0) {
  1000. this._gl.deleteBuffer(buffer);
  1001. return true;
  1002. }
  1003. return false;
  1004. };
  1005. Engine.prototype.createInstancesBuffer = function (capacity) {
  1006. var buffer = this._gl.createBuffer();
  1007. buffer.capacity = capacity;
  1008. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  1009. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1010. return buffer;
  1011. };
  1012. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  1013. this._gl.deleteBuffer(buffer);
  1014. };
  1015. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  1016. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  1017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1018. for (var index = 0; index < 4; index++) {
  1019. var offsetLocation = offsetLocations[index];
  1020. this._gl.enableVertexAttribArray(offsetLocation);
  1021. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1022. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  1023. }
  1024. };
  1025. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  1026. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  1027. for (var index = 0; index < 4; index++) {
  1028. var offsetLocation = offsetLocations[index];
  1029. this._gl.disableVertexAttribArray(offsetLocation);
  1030. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  1031. }
  1032. };
  1033. Engine.prototype.applyStates = function () {
  1034. this._depthCullingState.apply(this._gl);
  1035. this._alphaState.apply(this._gl);
  1036. };
  1037. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  1038. // Apply states
  1039. this.applyStates();
  1040. this._drawCalls++;
  1041. // Render
  1042. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1043. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1044. if (instancesCount) {
  1045. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1046. return;
  1047. }
  1048. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1049. };
  1050. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  1051. // Apply states
  1052. this.applyStates();
  1053. this._drawCalls++;
  1054. if (instancesCount) {
  1055. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1056. return;
  1057. }
  1058. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1059. };
  1060. // Shaders
  1061. Engine.prototype._releaseEffect = function (effect) {
  1062. if (this._compiledEffects[effect._key]) {
  1063. delete this._compiledEffects[effect._key];
  1064. if (effect.getProgram()) {
  1065. this._gl.deleteProgram(effect.getProgram());
  1066. }
  1067. }
  1068. };
  1069. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  1070. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1071. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1072. var name = vertex + "+" + fragment + "@" + defines;
  1073. if (this._compiledEffects[name]) {
  1074. return this._compiledEffects[name];
  1075. }
  1076. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  1077. effect._key = name;
  1078. this._compiledEffects[name] = effect;
  1079. return effect;
  1080. };
  1081. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  1082. if (uniformsNames === void 0) { uniformsNames = []; }
  1083. if (samplers === void 0) { samplers = []; }
  1084. if (defines === void 0) { defines = ""; }
  1085. return this.createEffect({
  1086. vertex: "particles",
  1087. fragmentElement: fragmentName
  1088. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1089. };
  1090. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  1091. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  1092. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  1093. var shaderProgram = this._gl.createProgram();
  1094. this._gl.attachShader(shaderProgram, vertexShader);
  1095. this._gl.attachShader(shaderProgram, fragmentShader);
  1096. this._gl.linkProgram(shaderProgram);
  1097. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  1098. if (!linked) {
  1099. var error = this._gl.getProgramInfoLog(shaderProgram);
  1100. if (error) {
  1101. throw new Error(error);
  1102. }
  1103. }
  1104. this._gl.deleteShader(vertexShader);
  1105. this._gl.deleteShader(fragmentShader);
  1106. return shaderProgram;
  1107. };
  1108. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  1109. var results = [];
  1110. for (var index = 0; index < uniformsNames.length; index++) {
  1111. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1112. }
  1113. return results;
  1114. };
  1115. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  1116. var results = [];
  1117. for (var index = 0; index < attributesNames.length; index++) {
  1118. try {
  1119. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1120. }
  1121. catch (e) {
  1122. results.push(-1);
  1123. }
  1124. }
  1125. return results;
  1126. };
  1127. Engine.prototype.enableEffect = function (effect) {
  1128. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  1129. if (effect && effect.onBind) {
  1130. effect.onBind(effect);
  1131. }
  1132. return;
  1133. }
  1134. this._vertexAttribArrays = this._vertexAttribArrays || [];
  1135. // Use program
  1136. this._gl.useProgram(effect.getProgram());
  1137. for (var i in this._vertexAttribArrays) {
  1138. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1139. continue;
  1140. }
  1141. this._vertexAttribArrays[i] = false;
  1142. this._gl.disableVertexAttribArray(i);
  1143. }
  1144. var attributesCount = effect.getAttributesCount();
  1145. for (var index = 0; index < attributesCount; index++) {
  1146. // Attributes
  1147. var order = effect.getAttributeLocation(index);
  1148. if (order >= 0) {
  1149. this._vertexAttribArrays[order] = true;
  1150. this._gl.enableVertexAttribArray(order);
  1151. }
  1152. }
  1153. this._currentEffect = effect;
  1154. if (effect.onBind) {
  1155. effect.onBind(effect);
  1156. }
  1157. };
  1158. Engine.prototype.setArray = function (uniform, array) {
  1159. if (!uniform)
  1160. return;
  1161. this._gl.uniform1fv(uniform, array);
  1162. };
  1163. Engine.prototype.setArray2 = function (uniform, array) {
  1164. if (!uniform || array.length % 2 !== 0)
  1165. return;
  1166. this._gl.uniform2fv(uniform, array);
  1167. };
  1168. Engine.prototype.setArray3 = function (uniform, array) {
  1169. if (!uniform || array.length % 3 !== 0)
  1170. return;
  1171. this._gl.uniform3fv(uniform, array);
  1172. };
  1173. Engine.prototype.setArray4 = function (uniform, array) {
  1174. if (!uniform || array.length % 4 !== 0)
  1175. return;
  1176. this._gl.uniform4fv(uniform, array);
  1177. };
  1178. Engine.prototype.setMatrices = function (uniform, matrices) {
  1179. if (!uniform)
  1180. return;
  1181. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1182. };
  1183. Engine.prototype.setMatrix = function (uniform, matrix) {
  1184. if (!uniform)
  1185. return;
  1186. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1187. };
  1188. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  1189. if (!uniform)
  1190. return;
  1191. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1192. };
  1193. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  1194. if (!uniform)
  1195. return;
  1196. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1197. };
  1198. Engine.prototype.setFloat = function (uniform, value) {
  1199. if (!uniform)
  1200. return;
  1201. this._gl.uniform1f(uniform, value);
  1202. };
  1203. Engine.prototype.setFloat2 = function (uniform, x, y) {
  1204. if (!uniform)
  1205. return;
  1206. this._gl.uniform2f(uniform, x, y);
  1207. };
  1208. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  1209. if (!uniform)
  1210. return;
  1211. this._gl.uniform3f(uniform, x, y, z);
  1212. };
  1213. Engine.prototype.setBool = function (uniform, bool) {
  1214. if (!uniform)
  1215. return;
  1216. this._gl.uniform1i(uniform, bool);
  1217. };
  1218. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  1219. if (!uniform)
  1220. return;
  1221. this._gl.uniform4f(uniform, x, y, z, w);
  1222. };
  1223. Engine.prototype.setColor3 = function (uniform, color3) {
  1224. if (!uniform)
  1225. return;
  1226. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1227. };
  1228. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  1229. if (!uniform)
  1230. return;
  1231. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1232. };
  1233. // States
  1234. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  1235. if (zOffset === void 0) { zOffset = 0; }
  1236. if (reverseSide === void 0) { reverseSide = false; }
  1237. // Culling
  1238. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1239. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1240. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1241. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1242. if (culling) {
  1243. this._depthCullingState.cullFace = cullFace;
  1244. this._depthCullingState.cull = true;
  1245. }
  1246. else {
  1247. this._depthCullingState.cull = false;
  1248. }
  1249. }
  1250. // Z offset
  1251. this._depthCullingState.zOffset = zOffset;
  1252. };
  1253. Engine.prototype.setDepthBuffer = function (enable) {
  1254. this._depthCullingState.depthTest = enable;
  1255. };
  1256. Engine.prototype.getDepthWrite = function () {
  1257. return this._depthCullingState.depthMask;
  1258. };
  1259. Engine.prototype.setDepthWrite = function (enable) {
  1260. this._depthCullingState.depthMask = enable;
  1261. };
  1262. Engine.prototype.setColorWrite = function (enable) {
  1263. this._gl.colorMask(enable, enable, enable, enable);
  1264. };
  1265. Engine.prototype.setAlphaMode = function (mode) {
  1266. if (this._alphaMode === mode) {
  1267. return;
  1268. }
  1269. switch (mode) {
  1270. case Engine.ALPHA_DISABLE:
  1271. this.setDepthWrite(true);
  1272. this._alphaState.alphaBlend = false;
  1273. break;
  1274. case Engine.ALPHA_COMBINE:
  1275. this.setDepthWrite(false);
  1276. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1277. this._alphaState.alphaBlend = true;
  1278. break;
  1279. case Engine.ALPHA_ONEONE:
  1280. this.setDepthWrite(false);
  1281. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1282. this._alphaState.alphaBlend = true;
  1283. break;
  1284. case Engine.ALPHA_ADD:
  1285. this.setDepthWrite(false);
  1286. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1287. this._alphaState.alphaBlend = true;
  1288. break;
  1289. case Engine.ALPHA_SUBTRACT:
  1290. this.setDepthWrite(false);
  1291. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1292. this._alphaState.alphaBlend = true;
  1293. break;
  1294. case Engine.ALPHA_MULTIPLY:
  1295. this.setDepthWrite(false);
  1296. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1297. this._alphaState.alphaBlend = true;
  1298. break;
  1299. case Engine.ALPHA_MAXIMIZED:
  1300. this.setDepthWrite(false);
  1301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1302. this._alphaState.alphaBlend = true;
  1303. break;
  1304. }
  1305. this._alphaMode = mode;
  1306. };
  1307. Engine.prototype.getAlphaMode = function () {
  1308. return this._alphaMode;
  1309. };
  1310. Engine.prototype.setAlphaTesting = function (enable) {
  1311. this._alphaTest = enable;
  1312. };
  1313. Engine.prototype.getAlphaTesting = function () {
  1314. return this._alphaTest;
  1315. };
  1316. // Textures
  1317. Engine.prototype.wipeCaches = function () {
  1318. this.resetTextureCache();
  1319. this._currentEffect = null;
  1320. this._depthCullingState.reset();
  1321. this._alphaState.reset();
  1322. this._cachedVertexBuffers = null;
  1323. this._cachedIndexBuffer = null;
  1324. this._cachedEffectForVertexBuffers = null;
  1325. };
  1326. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  1327. var gl = this._gl;
  1328. gl.bindTexture(gl.TEXTURE_2D, texture);
  1329. var magFilter = gl.NEAREST;
  1330. var minFilter = gl.NEAREST;
  1331. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  1332. magFilter = gl.LINEAR;
  1333. minFilter = gl.LINEAR;
  1334. }
  1335. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  1336. magFilter = gl.LINEAR;
  1337. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1338. }
  1339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1341. gl.bindTexture(gl.TEXTURE_2D, null);
  1342. texture.samplingMode = samplingMode;
  1343. };
  1344. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  1345. var _this = this;
  1346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1347. if (onLoad === void 0) { onLoad = null; }
  1348. if (onError === void 0) { onError = null; }
  1349. if (buffer === void 0) { buffer = null; }
  1350. var texture = this._gl.createTexture();
  1351. var extension;
  1352. var fromData = false;
  1353. if (url.substr(0, 5) === "data:") {
  1354. fromData = true;
  1355. }
  1356. if (!fromData)
  1357. extension = url.substr(url.length - 4, 4).toLowerCase();
  1358. else {
  1359. var oldUrl = url;
  1360. fromData = oldUrl.split(':');
  1361. url = oldUrl;
  1362. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1363. }
  1364. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1365. var isTGA = (extension === ".tga");
  1366. scene._addPendingData(texture);
  1367. texture.url = url;
  1368. texture.noMipmap = noMipmap;
  1369. texture.references = 1;
  1370. texture.samplingMode = samplingMode;
  1371. this._loadedTexturesCache.push(texture);
  1372. var onerror = function () {
  1373. scene._removePendingData(texture);
  1374. if (onError) {
  1375. onError();
  1376. }
  1377. };
  1378. var callback;
  1379. if (isTGA) {
  1380. callback = function (arrayBuffer) {
  1381. var data = new Uint8Array(arrayBuffer);
  1382. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1383. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  1384. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  1385. if (onLoad) {
  1386. onLoad();
  1387. }
  1388. }, samplingMode);
  1389. };
  1390. if (!(fromData instanceof Array))
  1391. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  1392. callback(arrayBuffer);
  1393. }, onerror, scene.database, true);
  1394. else
  1395. callback(buffer);
  1396. }
  1397. else if (isDDS) {
  1398. callback = function (data) {
  1399. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1400. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1401. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  1402. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  1403. if (onLoad) {
  1404. onLoad();
  1405. }
  1406. }, samplingMode);
  1407. };
  1408. if (!(fromData instanceof Array))
  1409. BABYLON.Tools.LoadFile(url, function (data) {
  1410. callback(data);
  1411. }, onerror, scene.database, true);
  1412. else
  1413. callback(buffer);
  1414. }
  1415. else {
  1416. var onload = function (img) {
  1417. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  1418. var isPot = (img.width === potWidth && img.height === potHeight);
  1419. if (!isPot) {
  1420. _this._prepareWorkingCanvas();
  1421. _this._workingCanvas.width = potWidth;
  1422. _this._workingCanvas.height = potHeight;
  1423. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1424. _this._workingContext.imageSmoothingEnabled = false;
  1425. _this._workingContext.mozImageSmoothingEnabled = false;
  1426. _this._workingContext.oImageSmoothingEnabled = false;
  1427. _this._workingContext.webkitImageSmoothingEnabled = false;
  1428. _this._workingContext.msImageSmoothingEnabled = false;
  1429. }
  1430. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1431. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1432. _this._workingContext.imageSmoothingEnabled = true;
  1433. _this._workingContext.mozImageSmoothingEnabled = true;
  1434. _this._workingContext.oImageSmoothingEnabled = true;
  1435. _this._workingContext.webkitImageSmoothingEnabled = true;
  1436. _this._workingContext.msImageSmoothingEnabled = true;
  1437. }
  1438. }
  1439. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  1440. if (onLoad) {
  1441. onLoad();
  1442. }
  1443. }, samplingMode);
  1444. };
  1445. if (!(fromData instanceof Array))
  1446. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1447. else
  1448. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1449. }
  1450. return texture;
  1451. };
  1452. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  1453. if (compression === void 0) { compression = null; }
  1454. var internalFormat = this._gl.RGBA;
  1455. switch (format) {
  1456. case Engine.TEXTUREFORMAT_ALPHA:
  1457. internalFormat = this._gl.ALPHA;
  1458. break;
  1459. case Engine.TEXTUREFORMAT_LUMINANCE:
  1460. internalFormat = this._gl.LUMINANCE;
  1461. break;
  1462. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1463. internalFormat = this._gl.LUMINANCE_ALPHA;
  1464. break;
  1465. case Engine.TEXTUREFORMAT_RGB:
  1466. internalFormat = this._gl.RGB;
  1467. break;
  1468. case Engine.TEXTUREFORMAT_RGBA:
  1469. internalFormat = this._gl.RGBA;
  1470. break;
  1471. }
  1472. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1473. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1474. if (compression) {
  1475. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1476. }
  1477. else {
  1478. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1479. }
  1480. if (texture.generateMipMaps) {
  1481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1482. }
  1483. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1484. this.resetTextureCache();
  1485. texture.isReady = true;
  1486. };
  1487. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  1488. if (compression === void 0) { compression = null; }
  1489. var texture = this._gl.createTexture();
  1490. texture._baseWidth = width;
  1491. texture._baseHeight = height;
  1492. texture._width = width;
  1493. texture._height = height;
  1494. texture.references = 1;
  1495. this.updateRawTexture(texture, data, format, invertY, compression);
  1496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1497. // Filters
  1498. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1499. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1500. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1501. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1502. texture.samplingMode = samplingMode;
  1503. this._loadedTexturesCache.push(texture);
  1504. return texture;
  1505. };
  1506. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  1507. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  1508. var texture = this._gl.createTexture();
  1509. texture._baseWidth = width;
  1510. texture._baseHeight = height;
  1511. if (forceExponantOfTwo) {
  1512. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1513. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1514. }
  1515. this.resetTextureCache();
  1516. texture._width = width;
  1517. texture._height = height;
  1518. texture.isReady = false;
  1519. texture.generateMipMaps = generateMipMaps;
  1520. texture.references = 1;
  1521. texture.samplingMode = samplingMode;
  1522. this.updateTextureSamplingMode(samplingMode, texture);
  1523. this._loadedTexturesCache.push(texture);
  1524. return texture;
  1525. };
  1526. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  1527. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1528. if (texture.isCube) {
  1529. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  1530. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1531. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1532. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1533. }
  1534. else {
  1535. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1536. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1537. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1538. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1539. }
  1540. };
  1541. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  1542. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1543. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1544. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1545. if (texture.generateMipMaps) {
  1546. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1547. }
  1548. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1549. this.resetTextureCache();
  1550. texture.isReady = true;
  1551. };
  1552. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  1553. if (texture._isDisabled) {
  1554. return;
  1555. }
  1556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1557. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1558. try {
  1559. // Testing video texture support
  1560. if (this._videoTextureSupported === undefined) {
  1561. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1562. if (this._gl.getError() !== 0) {
  1563. this._videoTextureSupported = false;
  1564. }
  1565. else {
  1566. this._videoTextureSupported = true;
  1567. }
  1568. }
  1569. // Copy video through the current working canvas if video texture is not supported
  1570. if (!this._videoTextureSupported) {
  1571. if (!texture._workingCanvas) {
  1572. texture._workingCanvas = document.createElement("canvas");
  1573. texture._workingContext = texture._workingCanvas.getContext("2d");
  1574. texture._workingCanvas.width = texture._width;
  1575. texture._workingCanvas.height = texture._height;
  1576. }
  1577. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1579. }
  1580. else {
  1581. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1582. }
  1583. if (texture.generateMipMaps) {
  1584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1585. }
  1586. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1587. this.resetTextureCache();
  1588. texture.isReady = true;
  1589. }
  1590. catch (ex) {
  1591. // Something unexpected
  1592. // Let's disable the texture
  1593. texture._isDisabled = true;
  1594. }
  1595. };
  1596. Engine.prototype.createRenderTargetTexture = function (size, options) {
  1597. // old version had a "generateMipMaps" arg instead of options.
  1598. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1599. // in the same way, generateDepthBuffer is defaulted to true
  1600. var generateMipMaps = false;
  1601. var generateDepthBuffer = true;
  1602. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1603. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1604. if (options !== undefined) {
  1605. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1606. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1607. type = options.type === undefined ? type : options.type;
  1608. if (options.samplingMode !== undefined) {
  1609. samplingMode = options.samplingMode;
  1610. }
  1611. if (type === Engine.TEXTURETYPE_FLOAT) {
  1612. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1613. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1614. }
  1615. }
  1616. var gl = this._gl;
  1617. var texture = gl.createTexture();
  1618. gl.bindTexture(gl.TEXTURE_2D, texture);
  1619. var width = size.width || size;
  1620. var height = size.height || size;
  1621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1622. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1623. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1624. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1625. }
  1626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1630. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1631. var depthBuffer;
  1632. // Create the depth buffer
  1633. if (generateDepthBuffer) {
  1634. depthBuffer = gl.createRenderbuffer();
  1635. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1636. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1637. }
  1638. // Create the framebuffer
  1639. var framebuffer = gl.createFramebuffer();
  1640. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1641. if (generateDepthBuffer) {
  1642. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1643. }
  1644. if (generateMipMaps) {
  1645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1646. }
  1647. // Unbind
  1648. gl.bindTexture(gl.TEXTURE_2D, null);
  1649. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1650. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1651. texture._framebuffer = framebuffer;
  1652. if (generateDepthBuffer) {
  1653. texture._depthBuffer = depthBuffer;
  1654. }
  1655. texture._width = width;
  1656. texture._height = height;
  1657. texture.isReady = true;
  1658. texture.generateMipMaps = generateMipMaps;
  1659. texture.references = 1;
  1660. texture.samplingMode = samplingMode;
  1661. this.resetTextureCache();
  1662. this._loadedTexturesCache.push(texture);
  1663. return texture;
  1664. };
  1665. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  1666. var gl = this._gl;
  1667. var texture = gl.createTexture();
  1668. var generateMipMaps = true;
  1669. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1670. if (options !== undefined) {
  1671. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1672. if (options.samplingMode !== undefined) {
  1673. samplingMode = options.samplingMode;
  1674. }
  1675. }
  1676. texture.isCube = true;
  1677. texture.references = 1;
  1678. texture.generateMipMaps = generateMipMaps;
  1679. texture.references = 1;
  1680. texture.samplingMode = samplingMode;
  1681. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1682. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1683. for (var face = 0; face < 6; face++) {
  1684. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1685. }
  1686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1690. // Create the depth buffer
  1691. var depthBuffer = gl.createRenderbuffer();
  1692. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1693. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1694. // Create the framebuffer
  1695. var framebuffer = gl.createFramebuffer();
  1696. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1697. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1698. // Unbind
  1699. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1700. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1701. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1702. texture._framebuffer = framebuffer;
  1703. texture._depthBuffer = depthBuffer;
  1704. this.resetTextureCache();
  1705. texture._width = size;
  1706. texture._height = size;
  1707. texture.isReady = true;
  1708. return texture;
  1709. };
  1710. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  1711. var _this = this;
  1712. var gl = this._gl;
  1713. var texture = gl.createTexture();
  1714. texture.isCube = true;
  1715. texture.url = rootUrl;
  1716. texture.references = 1;
  1717. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1718. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1719. if (isDDS) {
  1720. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  1721. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1722. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1723. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1724. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1725. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  1726. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1727. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1728. }
  1729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1733. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1734. _this.resetTextureCache();
  1735. texture._width = info.width;
  1736. texture._height = info.height;
  1737. texture.isReady = true;
  1738. }, null, null, true);
  1739. }
  1740. else {
  1741. cascadeLoad(rootUrl, scene, function (imgs) {
  1742. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  1743. var height = width;
  1744. _this._prepareWorkingCanvas();
  1745. _this._workingCanvas.width = width;
  1746. _this._workingCanvas.height = height;
  1747. var faces = [
  1748. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1749. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1750. ];
  1751. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1752. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1753. for (var index = 0; index < faces.length; index++) {
  1754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1755. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  1756. }
  1757. if (!noMipmap) {
  1758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1759. }
  1760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1764. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1765. _this.resetTextureCache();
  1766. texture._width = width;
  1767. texture._height = height;
  1768. texture.isReady = true;
  1769. }, extensions);
  1770. }
  1771. return texture;
  1772. };
  1773. Engine.prototype._releaseTexture = function (texture) {
  1774. var gl = this._gl;
  1775. if (texture._framebuffer) {
  1776. gl.deleteFramebuffer(texture._framebuffer);
  1777. }
  1778. if (texture._depthBuffer) {
  1779. gl.deleteRenderbuffer(texture._depthBuffer);
  1780. }
  1781. gl.deleteTexture(texture);
  1782. // Unbind channels
  1783. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1784. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1785. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1786. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1787. this._activeTexturesCache[channel] = null;
  1788. }
  1789. var index = this._loadedTexturesCache.indexOf(texture);
  1790. if (index !== -1) {
  1791. this._loadedTexturesCache.splice(index, 1);
  1792. }
  1793. };
  1794. Engine.prototype.bindSamplers = function (effect) {
  1795. this._gl.useProgram(effect.getProgram());
  1796. var samplers = effect.getSamplers();
  1797. for (var index = 0; index < samplers.length; index++) {
  1798. var uniform = effect.getUniform(samplers[index]);
  1799. this._gl.uniform1i(uniform, index);
  1800. }
  1801. this._currentEffect = null;
  1802. };
  1803. Engine.prototype._bindTexture = function (channel, texture) {
  1804. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1805. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1806. this._activeTexturesCache[channel] = null;
  1807. };
  1808. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  1809. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1810. };
  1811. Engine.prototype.setTexture = function (channel, texture) {
  1812. if (channel < 0) {
  1813. return;
  1814. }
  1815. // Not ready?
  1816. if (!texture || !texture.isReady()) {
  1817. if (this._activeTexturesCache[channel] != null) {
  1818. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1819. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1820. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1821. this._activeTexturesCache[channel] = null;
  1822. }
  1823. return;
  1824. }
  1825. // Video
  1826. if (texture instanceof BABYLON.VideoTexture) {
  1827. if (texture.update()) {
  1828. this._activeTexturesCache[channel] = null;
  1829. }
  1830. }
  1831. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  1832. texture.delayLoad();
  1833. return;
  1834. }
  1835. if (this._activeTexturesCache[channel] === texture) {
  1836. return;
  1837. }
  1838. this._activeTexturesCache[channel] = texture;
  1839. var internalTexture = texture.getInternalTexture();
  1840. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1841. if (internalTexture.isCube) {
  1842. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1843. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1844. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1845. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1846. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1847. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1848. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1849. }
  1850. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1851. }
  1852. else {
  1853. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1854. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1855. internalTexture._cachedWrapU = texture.wrapU;
  1856. switch (texture.wrapU) {
  1857. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1859. break;
  1860. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1862. break;
  1863. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1865. break;
  1866. }
  1867. }
  1868. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1869. internalTexture._cachedWrapV = texture.wrapV;
  1870. switch (texture.wrapV) {
  1871. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1873. break;
  1874. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1876. break;
  1877. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1878. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1879. break;
  1880. }
  1881. }
  1882. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1883. }
  1884. };
  1885. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  1886. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1887. var value = texture.anisotropicFilteringLevel;
  1888. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1889. value = 1;
  1890. }
  1891. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1892. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1893. texture._cachedAnisotropicFilteringLevel = value;
  1894. }
  1895. };
  1896. Engine.prototype.readPixels = function (x, y, width, height) {
  1897. var data = new Uint8Array(height * width * 4);
  1898. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1899. return data;
  1900. };
  1901. Engine.prototype.releaseInternalTexture = function (texture) {
  1902. if (!texture) {
  1903. return;
  1904. }
  1905. texture.references--;
  1906. // Final reference ?
  1907. if (texture.references === 0) {
  1908. var texturesCache = this.getLoadedTexturesCache();
  1909. var index = texturesCache.indexOf(texture);
  1910. if (index > -1) {
  1911. texturesCache.splice(index, 1);
  1912. }
  1913. this._releaseTexture(texture);
  1914. }
  1915. };
  1916. // Dispose
  1917. Engine.prototype.dispose = function () {
  1918. this.hideLoadingUI();
  1919. this.stopRenderLoop();
  1920. // Release scenes
  1921. while (this.scenes.length) {
  1922. this.scenes[0].dispose();
  1923. }
  1924. // Release audio engine
  1925. Engine.audioEngine.dispose();
  1926. // Release effects
  1927. for (var name in this._compiledEffects) {
  1928. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1929. }
  1930. // Unbind
  1931. for (var i in this._vertexAttribArrays) {
  1932. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1933. continue;
  1934. }
  1935. this._gl.disableVertexAttribArray(i);
  1936. }
  1937. this._gl = null;
  1938. // Events
  1939. window.removeEventListener("blur", this._onBlur);
  1940. window.removeEventListener("focus", this._onFocus);
  1941. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1942. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1943. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1944. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1945. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1946. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1947. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1948. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1949. };
  1950. // Loading screen
  1951. Engine.prototype.displayLoadingUI = function () {
  1952. this._loadingScreen.displayLoadingUI();
  1953. };
  1954. Engine.prototype.hideLoadingUI = function () {
  1955. this._loadingScreen.hideLoadingUI();
  1956. };
  1957. Object.defineProperty(Engine.prototype, "loadingScreen", {
  1958. get: function () {
  1959. return this._loadingScreen;
  1960. },
  1961. set: function (loadingScreen) {
  1962. this._loadingScreen = loadingScreen;
  1963. },
  1964. enumerable: true,
  1965. configurable: true
  1966. });
  1967. Object.defineProperty(Engine.prototype, "loadingUIText", {
  1968. set: function (text) {
  1969. this._loadingScreen.loadingUIText = text;
  1970. },
  1971. enumerable: true,
  1972. configurable: true
  1973. });
  1974. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  1975. set: function (color) {
  1976. this._loadingScreen.loadingUIBackgroundColor = color;
  1977. },
  1978. enumerable: true,
  1979. configurable: true
  1980. });
  1981. // FPS
  1982. Engine.prototype.getFps = function () {
  1983. return this.fps;
  1984. };
  1985. Engine.prototype.getDeltaTime = function () {
  1986. return this.deltaTime;
  1987. };
  1988. Engine.prototype._measureFps = function () {
  1989. this.previousFramesDuration.push(BABYLON.Tools.Now);
  1990. var length = this.previousFramesDuration.length;
  1991. if (length >= 2) {
  1992. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1993. }
  1994. if (length >= this.fpsRange) {
  1995. if (length > this.fpsRange) {
  1996. this.previousFramesDuration.splice(0, 1);
  1997. length = this.previousFramesDuration.length;
  1998. }
  1999. var sum = 0;
  2000. for (var id = 0; id < length - 1; id++) {
  2001. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2002. }
  2003. this.fps = 1000.0 / (sum / (length - 1));
  2004. }
  2005. };
  2006. // Statics
  2007. Engine.isSupported = function () {
  2008. try {
  2009. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2010. if (navigator.isCocoonJS) {
  2011. return true;
  2012. }
  2013. var tempcanvas = document.createElement("canvas");
  2014. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2015. return gl != null && !!window.WebGLRenderingContext;
  2016. }
  2017. catch (e) {
  2018. return false;
  2019. }
  2020. };
  2021. // Const statics
  2022. Engine._ALPHA_DISABLE = 0;
  2023. Engine._ALPHA_ADD = 1;
  2024. Engine._ALPHA_COMBINE = 2;
  2025. Engine._ALPHA_SUBTRACT = 3;
  2026. Engine._ALPHA_MULTIPLY = 4;
  2027. Engine._ALPHA_MAXIMIZED = 5;
  2028. Engine._ALPHA_ONEONE = 6;
  2029. Engine._DELAYLOADSTATE_NONE = 0;
  2030. Engine._DELAYLOADSTATE_LOADED = 1;
  2031. Engine._DELAYLOADSTATE_LOADING = 2;
  2032. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  2033. Engine._TEXTUREFORMAT_ALPHA = 0;
  2034. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  2035. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  2036. Engine._TEXTUREFORMAT_RGB = 4;
  2037. Engine._TEXTUREFORMAT_RGBA = 5;
  2038. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  2039. Engine._TEXTURETYPE_FLOAT = 1;
  2040. // Updatable statics so stick with vars here
  2041. Engine.Epsilon = 0.001;
  2042. Engine.CollisionsEpsilon = 0.001;
  2043. Engine.CodeRepository = "src/";
  2044. Engine.ShadersRepository = "src/Shaders/";
  2045. return Engine;
  2046. })();
  2047. BABYLON.Engine = Engine;
  2048. })(BABYLON || (BABYLON = {}));