babylon.engine.js 93 KB

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