babylon.engine.js 81 KB

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