babylon.engine.ts 78 KB

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