babylon.engine.js 90 KB

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