babylon.engine.js 101 KB

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