babylon.engine.js 99 KB

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