babylon.engine.js 122 KB

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