babylon.engine.js 90 KB

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