babylon.engine.js 95 KB

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