babylon.engine.js 98 KB

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