babylon.engine.js 92 KB

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