babylon.engine.ts 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  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 _runningLoop = false;
  336. private _renderFunction: () => void;
  337. private _resizeLoadingUI: () => void;
  338. private _loadingDiv: HTMLDivElement;
  339. private _loadingTextDiv: HTMLDivElement;
  340. private _loadingDivBackgroundColor = "black";
  341. private _drawCalls = 0;
  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(): void {
  511. this._renderFunction = null;
  512. this._runningLoop = false;
  513. }
  514. public _renderLoop(): void {
  515. var shouldRender = true;
  516. if (!this.renderEvenInBackground && this._windowIsBackground) {
  517. shouldRender = false;
  518. }
  519. if (shouldRender) {
  520. // Start new frame
  521. this.beginFrame();
  522. if (this._renderFunction) {
  523. this._renderFunction();
  524. }
  525. // Present
  526. this.endFrame();
  527. }
  528. if (this._runningLoop) {
  529. // Register new frame
  530. BABYLON.Tools.QueueNewFrame(() => {
  531. this._renderLoop();
  532. });
  533. }
  534. }
  535. public runRenderLoop(renderFunction: () => void): void {
  536. this._runningLoop = true;
  537. this._renderFunction = renderFunction;
  538. BABYLON.Tools.QueueNewFrame(() => {
  539. this._renderLoop();
  540. });
  541. }
  542. public switchFullscreen(requestPointerLock: boolean): void {
  543. if (this.isFullscreen) {
  544. BABYLON.Tools.ExitFullscreen();
  545. } else {
  546. this._pointerLockRequested = requestPointerLock;
  547. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  548. }
  549. }
  550. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  551. this.applyStates();
  552. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  553. if (this._depthCullingState.depthMask) {
  554. this._gl.clearDepth(1.0);
  555. }
  556. var mode = 0;
  557. if (backBuffer)
  558. mode |= this._gl.COLOR_BUFFER_BIT;
  559. if (depthStencil && this._depthCullingState.depthMask)
  560. mode |= this._gl.DEPTH_BUFFER_BIT;
  561. this._gl.clear(mode);
  562. }
  563. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  564. var width = requiredWidth || this._renderingCanvas.width;
  565. var height = requiredHeight || this._renderingCanvas.height;
  566. var x = viewport.x || 0;
  567. var y = viewport.y || 0;
  568. this._cachedViewport = viewport;
  569. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  570. }
  571. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  572. this._cachedViewport = null;
  573. this._gl.viewport(x, y, width, height);
  574. }
  575. public beginFrame(): void {
  576. this._measureFps();
  577. }
  578. public endFrame(): void {
  579. this.flushFramebuffer();
  580. }
  581. public resize(): void {
  582. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  583. }
  584. public setSize(width: number, height: number): void {
  585. this._renderingCanvas.width = width;
  586. this._renderingCanvas.height = height;
  587. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  588. }
  589. public bindFramebuffer(texture: WebGLTexture): void {
  590. this._currentRenderTarget = texture;
  591. var gl = this._gl;
  592. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  593. this._gl.viewport(0, 0, texture._width, texture._height);
  594. this.wipeCaches();
  595. }
  596. public unBindFramebuffer(texture: WebGLTexture): void {
  597. this._currentRenderTarget = null;
  598. if (texture.generateMipMaps) {
  599. var gl = this._gl;
  600. gl.bindTexture(gl.TEXTURE_2D, texture);
  601. gl.generateMipmap(gl.TEXTURE_2D);
  602. gl.bindTexture(gl.TEXTURE_2D, null);
  603. }
  604. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  605. }
  606. public flushFramebuffer(): void {
  607. // this._gl.flush();
  608. }
  609. public restoreDefaultFramebuffer(): void {
  610. this._currentRenderTarget = null;
  611. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  612. this.setViewport(this._cachedViewport);
  613. this.wipeCaches();
  614. }
  615. // VBOs
  616. private _resetVertexBufferBinding(): void {
  617. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  618. this._cachedVertexBuffers = null;
  619. }
  620. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  621. var vbo = this._gl.createBuffer();
  622. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  623. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  624. this._resetVertexBufferBinding();
  625. vbo.references = 1;
  626. return vbo;
  627. }
  628. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  629. var vbo = this._gl.createBuffer();
  630. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  631. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  632. this._resetVertexBufferBinding();
  633. vbo.references = 1;
  634. return vbo;
  635. }
  636. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  637. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  638. if (offset === undefined) {
  639. offset = 0;
  640. }
  641. if (vertices instanceof Float32Array) {
  642. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  643. } else {
  644. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  645. }
  646. this._resetVertexBufferBinding();
  647. }
  648. private _resetIndexBufferBinding(): void {
  649. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  650. this._cachedIndexBuffer = null;
  651. }
  652. public createIndexBuffer(indices: number[]): WebGLBuffer {
  653. var vbo = this._gl.createBuffer();
  654. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  655. // Check for 32 bits indices
  656. var arrayBuffer;
  657. var need32Bits = false;
  658. if (this._caps.uintIndices) {
  659. for (var index = 0; index < indices.length; index++) {
  660. if (indices[index] > 65535) {
  661. need32Bits = true;
  662. break;
  663. }
  664. }
  665. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  666. } else {
  667. arrayBuffer = new Uint16Array(indices);
  668. }
  669. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  670. this._resetIndexBufferBinding();
  671. vbo.references = 1;
  672. vbo.is32Bits = need32Bits;
  673. return vbo;
  674. }
  675. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  676. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  677. this._cachedVertexBuffers = vertexBuffer;
  678. this._cachedEffectForVertexBuffers = effect;
  679. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  680. var offset = 0;
  681. for (var index = 0; index < vertexDeclaration.length; index++) {
  682. var order = effect.getAttributeLocation(index);
  683. if (order >= 0) {
  684. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  685. }
  686. offset += vertexDeclaration[index] * 4;
  687. }
  688. }
  689. if (this._cachedIndexBuffer !== indexBuffer) {
  690. this._cachedIndexBuffer = indexBuffer;
  691. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  692. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  693. }
  694. }
  695. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  696. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  697. this._cachedVertexBuffers = vertexBuffers;
  698. this._cachedEffectForVertexBuffers = effect;
  699. var attributes = effect.getAttributesNames();
  700. for (var index = 0; index < attributes.length; index++) {
  701. var order = effect.getAttributeLocation(index);
  702. if (order >= 0) {
  703. var vertexBuffer = vertexBuffers[attributes[index]];
  704. if (!vertexBuffer) {
  705. continue;
  706. }
  707. var stride = vertexBuffer.getStrideSize();
  708. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  709. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  710. }
  711. }
  712. }
  713. if (indexBuffer!= null && this._cachedIndexBuffer !== indexBuffer) {
  714. this._cachedIndexBuffer = indexBuffer;
  715. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  716. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  717. }
  718. }
  719. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  720. buffer.references--;
  721. if (buffer.references === 0) {
  722. this._gl.deleteBuffer(buffer);
  723. return true;
  724. }
  725. return false;
  726. }
  727. public createInstancesBuffer(capacity: number): WebGLBuffer {
  728. var buffer = this._gl.createBuffer();
  729. buffer.capacity = capacity;
  730. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  731. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  732. return buffer;
  733. }
  734. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  735. this._gl.deleteBuffer(buffer);
  736. }
  737. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  738. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  739. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  740. for (var index = 0; index < 4; index++) {
  741. var offsetLocation = offsetLocations[index];
  742. this._gl.enableVertexAttribArray(offsetLocation);
  743. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  744. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  745. }
  746. }
  747. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  748. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  749. for (var index = 0; index < 4; index++) {
  750. var offsetLocation = offsetLocations[index];
  751. this._gl.disableVertexAttribArray(offsetLocation);
  752. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  753. }
  754. }
  755. public applyStates() {
  756. this._depthCullingState.apply(this._gl);
  757. this._alphaState.apply(this._gl);
  758. }
  759. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  760. // Apply states
  761. this.applyStates();
  762. // Render
  763. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  764. if (instancesCount) {
  765. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  766. return;
  767. }
  768. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  769. this._drawCalls++;
  770. }
  771. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  772. // Apply states
  773. this.applyStates();
  774. if (instancesCount) {
  775. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  776. return;
  777. }
  778. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  779. this._drawCalls++;
  780. }
  781. // Shaders
  782. public _releaseEffect(effect: Effect): void {
  783. if (this._compiledEffects[effect._key]) {
  784. delete this._compiledEffects[effect._key];
  785. if (effect.getProgram()) {
  786. this._gl.deleteProgram(effect.getProgram());
  787. }
  788. }
  789. }
  790. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  791. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  792. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  793. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  794. var name = vertex + "+" + fragment + "@" + defines;
  795. if (this._compiledEffects[name]) {
  796. return this._compiledEffects[name];
  797. }
  798. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  799. effect._key = name;
  800. this._compiledEffects[name] = effect;
  801. return effect;
  802. }
  803. public createEffectForParticles(fragmentName: string, uniformsNames: string[]= [], samplers: string[]= [], defines = "", fallbacks?: EffectFallbacks,
  804. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  805. return this.createEffect(
  806. {
  807. vertex: "particles",
  808. fragmentElement: fragmentName
  809. },
  810. ["position", "color", "options"],
  811. ["view", "projection"].concat(uniformsNames),
  812. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  813. }
  814. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  815. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  816. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  817. var shaderProgram = this._gl.createProgram();
  818. this._gl.attachShader(shaderProgram, vertexShader);
  819. this._gl.attachShader(shaderProgram, fragmentShader);
  820. this._gl.linkProgram(shaderProgram);
  821. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  822. if (!linked) {
  823. var error = this._gl.getProgramInfoLog(shaderProgram);
  824. if (error) {
  825. throw new Error(error);
  826. }
  827. }
  828. this._gl.deleteShader(vertexShader);
  829. this._gl.deleteShader(fragmentShader);
  830. return shaderProgram;
  831. }
  832. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  833. var results = [];
  834. for (var index = 0; index < uniformsNames.length; index++) {
  835. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  836. }
  837. return results;
  838. }
  839. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  840. var results = [];
  841. for (var index = 0; index < attributesNames.length; index++) {
  842. try {
  843. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  844. } catch (e) {
  845. results.push(-1);
  846. }
  847. }
  848. return results;
  849. }
  850. public enableEffect(effect: Effect): void {
  851. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  852. if (effect && effect.onBind) {
  853. effect.onBind(effect);
  854. }
  855. return;
  856. }
  857. this._vertexAttribArrays = this._vertexAttribArrays || [];
  858. // Use program
  859. this._gl.useProgram(effect.getProgram());
  860. for (var i in this._vertexAttribArrays) {
  861. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  862. continue;
  863. }
  864. this._vertexAttribArrays[i] = false;
  865. this._gl.disableVertexAttribArray(i);
  866. }
  867. var attributesCount = effect.getAttributesCount();
  868. for (var index = 0; index < attributesCount; index++) {
  869. // Attributes
  870. var order = effect.getAttributeLocation(index);
  871. if (order >= 0) {
  872. this._vertexAttribArrays[order] = true;
  873. this._gl.enableVertexAttribArray(order);
  874. }
  875. }
  876. this._currentEffect = effect;
  877. if (effect.onBind) {
  878. effect.onBind(effect);
  879. }
  880. }
  881. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  882. if (!uniform)
  883. return;
  884. this._gl.uniform1fv(uniform, array);
  885. }
  886. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  887. if (!uniform)
  888. return;
  889. this._gl.uniformMatrix4fv(uniform, false, matrices);
  890. }
  891. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  892. if (!uniform)
  893. return;
  894. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  895. }
  896. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  897. if (!uniform)
  898. return;
  899. this._gl.uniform1f(uniform, value);
  900. }
  901. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  902. if (!uniform)
  903. return;
  904. this._gl.uniform2f(uniform, x, y);
  905. }
  906. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  907. if (!uniform)
  908. return;
  909. this._gl.uniform3f(uniform, x, y, z);
  910. }
  911. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  912. if (!uniform)
  913. return;
  914. this._gl.uniform1i(uniform, bool);
  915. }
  916. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  917. if (!uniform)
  918. return;
  919. this._gl.uniform4f(uniform, x, y, z, w);
  920. }
  921. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  922. if (!uniform)
  923. return;
  924. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  925. }
  926. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  927. if (!uniform)
  928. return;
  929. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  930. }
  931. // States
  932. public setState(culling: boolean, force?: boolean): void {
  933. // Culling
  934. if (this._depthCullingState.cull !== culling || force) {
  935. if (culling) {
  936. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  937. this._depthCullingState.cull = true;
  938. } else {
  939. this._depthCullingState.cull = false;
  940. }
  941. }
  942. }
  943. public setDepthBuffer(enable: boolean): void {
  944. this._depthCullingState.depthTest = enable;
  945. }
  946. public getDepthWrite(): boolean {
  947. return this._depthCullingState.depthMask;
  948. }
  949. public setDepthWrite(enable: boolean): void {
  950. this._depthCullingState.depthMask = enable;
  951. }
  952. public setColorWrite(enable: boolean): void {
  953. this._gl.colorMask(enable, enable, enable, enable);
  954. }
  955. public setAlphaMode(mode: number): void {
  956. switch (mode) {
  957. case BABYLON.Engine.ALPHA_DISABLE:
  958. this.setDepthWrite(true);
  959. this._alphaState.alphaBlend = false;
  960. break;
  961. case BABYLON.Engine.ALPHA_COMBINE:
  962. this.setDepthWrite(false);
  963. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  964. this._alphaState.alphaBlend = true;
  965. break;
  966. case BABYLON.Engine.ALPHA_ADD:
  967. this.setDepthWrite(false);
  968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  969. this._alphaState.alphaBlend = true;
  970. break;
  971. }
  972. this._alphaMode = mode;
  973. }
  974. public getAlphaMode(): number {
  975. return this._alphaMode;
  976. }
  977. public setAlphaTesting(enable: boolean): void {
  978. this._alphaTest = enable;
  979. }
  980. public getAlphaTesting(): boolean {
  981. return this._alphaTest;
  982. }
  983. // Textures
  984. public wipeCaches(): void {
  985. this._activeTexturesCache = [];
  986. this._currentEffect = null;
  987. this._depthCullingState.reset();
  988. this._alphaState.reset();
  989. this._cachedVertexBuffers = null;
  990. this._cachedIndexBuffer = null;
  991. this._cachedEffectForVertexBuffers = null;
  992. }
  993. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  994. var gl = this._gl;
  995. gl.bindTexture(gl.TEXTURE_2D, texture);
  996. var magFilter = gl.NEAREST;
  997. var minFilter = gl.NEAREST;
  998. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  999. magFilter = gl.LINEAR;
  1000. minFilter = gl.LINEAR;
  1001. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  1002. magFilter = gl.LINEAR;
  1003. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1004. }
  1005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1007. gl.bindTexture(gl.TEXTURE_2D, null);
  1008. }
  1009. 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 {
  1010. var texture = this._gl.createTexture();
  1011. var extension: string;
  1012. var fromData: any = false;
  1013. if (url.substr(0, 5) === "data:") {
  1014. fromData = true;
  1015. }
  1016. if (!fromData)
  1017. extension = url.substr(url.length - 4, 4).toLowerCase();
  1018. else {
  1019. var oldUrl = url;
  1020. fromData = oldUrl.split(':');
  1021. url = oldUrl;
  1022. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1023. }
  1024. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1025. var isTGA = (extension === ".tga");
  1026. scene._addPendingData(texture);
  1027. texture.url = url;
  1028. texture.noMipmap = noMipmap;
  1029. texture.references = 1;
  1030. this._loadedTexturesCache.push(texture);
  1031. var onerror = () => {
  1032. scene._removePendingData(texture);
  1033. if (onError) {
  1034. onError();
  1035. }
  1036. };
  1037. if (isTGA) {
  1038. var callback = (arrayBuffer) => {
  1039. var data = new Uint8Array(arrayBuffer);
  1040. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1041. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1042. Internals.TGATools.UploadContent(this._gl, data);
  1043. if (onLoad) {
  1044. onLoad();
  1045. }
  1046. }, samplingMode);
  1047. };
  1048. if (!(fromData instanceof Array))
  1049. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  1050. callback(arrayBuffer);
  1051. }, onerror, scene.database, true);
  1052. else
  1053. callback(buffer);
  1054. } else if (isDDS) {
  1055. callback = (data) => {
  1056. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1057. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  1058. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1059. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1060. if (onLoad) {
  1061. onLoad();
  1062. }
  1063. }, samplingMode);
  1064. };
  1065. if (!(fromData instanceof Array))
  1066. BABYLON.Tools.LoadFile(url, data => {
  1067. callback(data);
  1068. }, onerror, scene.database, true);
  1069. else
  1070. callback(buffer);
  1071. } else {
  1072. var onload = (img) => {
  1073. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1074. var isPot = (img.width == potWidth && img.height == potHeight);
  1075. if (!isPot) {
  1076. this._workingCanvas.width = potWidth;
  1077. this._workingCanvas.height = potHeight;
  1078. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1079. }
  1080. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1081. if (onLoad) {
  1082. onLoad();
  1083. }
  1084. }, samplingMode);
  1085. };
  1086. if (!(fromData instanceof Array))
  1087. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1088. else
  1089. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1090. }
  1091. return texture;
  1092. }
  1093. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1094. var texture = this._gl.createTexture();
  1095. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1096. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1097. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1098. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1099. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1100. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1101. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1102. this._activeTexturesCache = [];
  1103. texture._baseWidth = width;
  1104. texture._baseHeight = height;
  1105. texture._width = width;
  1106. texture._height = height;
  1107. texture.isReady = false;
  1108. texture.generateMipMaps = generateMipMaps;
  1109. texture.references = 1;
  1110. this._loadedTexturesCache.push(texture);
  1111. return texture;
  1112. }
  1113. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1114. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1115. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1116. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1117. if (texture.generateMipMaps) {
  1118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1119. }
  1120. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1121. this._activeTexturesCache = [];
  1122. texture.isReady = true;
  1123. }
  1124. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1125. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1126. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1127. // Scale the video if it is a NPOT using the current working canvas
  1128. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1129. if (!texture._workingCanvas) {
  1130. texture._workingCanvas = document.createElement("canvas");
  1131. texture._workingContext = texture._workingCanvas.getContext("2d");
  1132. texture._workingCanvas.width = texture._width;
  1133. texture._workingCanvas.height = texture._height;
  1134. }
  1135. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1136. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1137. } else {
  1138. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1139. }
  1140. if (texture.generateMipMaps) {
  1141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1142. }
  1143. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1144. this._activeTexturesCache = [];
  1145. texture.isReady = true;
  1146. }
  1147. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1148. // old version had a "generateMipMaps" arg instead of options.
  1149. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1150. // in the same way, generateDepthBuffer is defaulted to true
  1151. var generateMipMaps = false;
  1152. var generateDepthBuffer = true;
  1153. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1154. if (options !== undefined) {
  1155. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1156. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1157. if (options.samplingMode !== undefined) {
  1158. samplingMode = options.samplingMode;
  1159. }
  1160. }
  1161. var gl = this._gl;
  1162. var texture = gl.createTexture();
  1163. gl.bindTexture(gl.TEXTURE_2D, texture);
  1164. var width = size.width || size;
  1165. var height = size.height || size;
  1166. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1172. var depthBuffer: WebGLRenderbuffer;
  1173. // Create the depth buffer
  1174. if (generateDepthBuffer) {
  1175. depthBuffer = gl.createRenderbuffer();
  1176. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1177. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1178. }
  1179. // Create the framebuffer
  1180. var framebuffer = gl.createFramebuffer();
  1181. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1183. if (generateDepthBuffer) {
  1184. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1185. }
  1186. // Unbind
  1187. gl.bindTexture(gl.TEXTURE_2D, null);
  1188. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1189. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1190. texture._framebuffer = framebuffer;
  1191. if (generateDepthBuffer) {
  1192. texture._depthBuffer = depthBuffer;
  1193. }
  1194. texture._width = width;
  1195. texture._height = height;
  1196. texture.isReady = true;
  1197. texture.generateMipMaps = generateMipMaps;
  1198. texture.references = 1;
  1199. this._activeTexturesCache = [];
  1200. this._loadedTexturesCache.push(texture);
  1201. return texture;
  1202. }
  1203. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1204. var gl = this._gl;
  1205. var texture = gl.createTexture();
  1206. texture.isCube = true;
  1207. texture.url = rootUrl;
  1208. texture.references = 1;
  1209. this._loadedTexturesCache.push(texture);
  1210. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1211. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1212. if (isDDS) {
  1213. BABYLON.Tools.LoadFile(rootUrl, data => {
  1214. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1215. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1216. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1217. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1218. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1219. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  1220. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1221. }
  1222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1226. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1227. this._activeTexturesCache = [];
  1228. texture._width = info.width;
  1229. texture._height = info.height;
  1230. texture.isReady = true;
  1231. }, null, null, true);
  1232. } else {
  1233. cascadeLoad(rootUrl, scene, imgs => {
  1234. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1235. var height = width;
  1236. this._workingCanvas.width = width;
  1237. this._workingCanvas.height = height;
  1238. var faces = [
  1239. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1240. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1241. ];
  1242. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1244. for (var index = 0; index < faces.length; index++) {
  1245. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1246. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1247. }
  1248. if (!noMipmap) {
  1249. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1250. }
  1251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1252. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1255. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1256. this._activeTexturesCache = [];
  1257. texture._width = width;
  1258. texture._height = height;
  1259. texture.isReady = true;
  1260. }, extensions);
  1261. }
  1262. return texture;
  1263. }
  1264. public _releaseTexture(texture: WebGLTexture): void {
  1265. var gl = this._gl;
  1266. if (texture._framebuffer) {
  1267. gl.deleteFramebuffer(texture._framebuffer);
  1268. }
  1269. if (texture._depthBuffer) {
  1270. gl.deleteRenderbuffer(texture._depthBuffer);
  1271. }
  1272. gl.deleteTexture(texture);
  1273. // Unbind channels
  1274. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1275. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1276. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1277. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1278. this._activeTexturesCache[channel] = null;
  1279. }
  1280. var index = this._loadedTexturesCache.indexOf(texture);
  1281. if (index !== -1) {
  1282. this._loadedTexturesCache.splice(index, 1);
  1283. }
  1284. }
  1285. public bindSamplers(effect: Effect): void {
  1286. this._gl.useProgram(effect.getProgram());
  1287. var samplers = effect.getSamplers();
  1288. for (var index = 0; index < samplers.length; index++) {
  1289. var uniform = effect.getUniform(samplers[index]);
  1290. this._gl.uniform1i(uniform, index);
  1291. }
  1292. this._currentEffect = null;
  1293. }
  1294. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1295. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1296. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1297. this._activeTexturesCache[channel] = null;
  1298. }
  1299. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1300. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1301. }
  1302. public setTexture(channel: number, texture: BaseTexture): void {
  1303. if (channel < 0) {
  1304. return;
  1305. }
  1306. // Not ready?
  1307. if (!texture || !texture.isReady()) {
  1308. if (this._activeTexturesCache[channel] != null) {
  1309. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1310. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1311. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1312. this._activeTexturesCache[channel] = null;
  1313. }
  1314. return;
  1315. }
  1316. // Video
  1317. if (texture instanceof BABYLON.VideoTexture) {
  1318. if ((<VideoTexture>texture).update()) {
  1319. this._activeTexturesCache[channel] = null;
  1320. }
  1321. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1322. texture.delayLoad();
  1323. return;
  1324. }
  1325. if (this._activeTexturesCache[channel] == texture) {
  1326. return;
  1327. }
  1328. this._activeTexturesCache[channel] = texture;
  1329. var internalTexture = texture.getInternalTexture();
  1330. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1331. if (internalTexture.isCube) {
  1332. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1333. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1334. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1335. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1336. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1337. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1338. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1339. }
  1340. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1341. } else {
  1342. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1343. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1344. internalTexture._cachedWrapU = texture.wrapU;
  1345. switch (texture.wrapU) {
  1346. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1347. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1348. break;
  1349. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1350. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1351. break;
  1352. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1353. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1354. break;
  1355. }
  1356. }
  1357. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1358. internalTexture._cachedWrapV = texture.wrapV;
  1359. switch (texture.wrapV) {
  1360. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1361. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1362. break;
  1363. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1364. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, 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_T, this._gl.MIRRORED_REPEAT);
  1368. break;
  1369. }
  1370. }
  1371. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1372. }
  1373. }
  1374. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1375. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1376. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1377. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1378. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1379. }
  1380. }
  1381. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1382. var data = new Uint8Array(height * width * 4);
  1383. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1384. return data;
  1385. }
  1386. // Dispose
  1387. public dispose(): void {
  1388. this.hideLoadingUI();
  1389. this.stopRenderLoop();
  1390. // Release scenes
  1391. while (this.scenes.length) {
  1392. this.scenes[0].dispose();
  1393. }
  1394. // Release effects
  1395. for (var name in this._compiledEffects) {
  1396. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1397. }
  1398. // Unbind
  1399. for (var i in this._vertexAttribArrays) {
  1400. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1401. continue;
  1402. }
  1403. this._gl.disableVertexAttribArray(i);
  1404. }
  1405. // Events
  1406. window.removeEventListener("blur", this._onBlur);
  1407. window.removeEventListener("focus", this._onFocus);
  1408. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1409. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1410. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1411. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1412. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1413. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1414. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1415. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1416. }
  1417. // Loading screen
  1418. public displayLoadingUI(): void {
  1419. this._loadingDiv = document.createElement("div");
  1420. this._loadingDiv.style.opacity = "0";
  1421. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1422. // Loading text
  1423. this._loadingTextDiv = document.createElement("div");
  1424. this._loadingTextDiv.style.position = "absolute";
  1425. this._loadingTextDiv.style.left = "0";
  1426. this._loadingTextDiv.style.top = "50%";
  1427. this._loadingTextDiv.style.marginTop = "80px";
  1428. this._loadingTextDiv.style.width = "100%";
  1429. this._loadingTextDiv.style.height = "20px";
  1430. this._loadingTextDiv.style.fontFamily = "Arial";
  1431. this._loadingTextDiv.style.fontSize = "14px";
  1432. this._loadingTextDiv.style.color = "white";
  1433. this._loadingTextDiv.style.textAlign = "center";
  1434. this._loadingTextDiv.innerHTML = "Loading";
  1435. this._loadingDiv.appendChild(this._loadingTextDiv);
  1436. // Loading img
  1437. var imgBack = new Image();
  1438. 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==";
  1439. imgBack.style.position = "absolute";
  1440. imgBack.style.left = "50%";
  1441. imgBack.style.top = "50%";
  1442. imgBack.style.marginLeft = "-50px";
  1443. imgBack.style.marginTop = "-50px";
  1444. imgBack.style.transition = "transform 1.0s ease";
  1445. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1446. var deg = 360;
  1447. var onTransitionEnd = () => {
  1448. deg += 360;
  1449. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1450. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1451. }
  1452. imgBack.addEventListener("transitionend", onTransitionEnd);
  1453. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1454. this._loadingDiv.appendChild(imgBack);
  1455. // front image
  1456. var imgFront = new Image();
  1457. 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=";
  1458. imgFront.style.position = "absolute";
  1459. imgFront.style.left = "50%";
  1460. imgFront.style.top = "50%";
  1461. imgFront.style.marginLeft = "-50px";
  1462. imgFront.style.marginTop = "-50px";
  1463. this._loadingDiv.appendChild(imgFront);
  1464. // Resize
  1465. this._resizeLoadingUI = () => {
  1466. var canvasRect = this.getRenderingCanvasClientRect();
  1467. this._loadingDiv.style.position = "absolute";
  1468. this._loadingDiv.style.left = canvasRect.left + "px";
  1469. this._loadingDiv.style.top = canvasRect.top + "px";
  1470. this._loadingDiv.style.width = canvasRect.width + "px";
  1471. this._loadingDiv.style.height = canvasRect.height + "px";
  1472. }
  1473. this._resizeLoadingUI();
  1474. window.addEventListener("resize", this._resizeLoadingUI);
  1475. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1476. document.body.appendChild(this._loadingDiv);
  1477. setTimeout(() => {
  1478. this._loadingDiv.style.opacity = "1";
  1479. imgBack.style.transform = "rotateZ(360deg)";
  1480. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1481. }, 0);
  1482. }
  1483. public set loadingUIText(text: string) {
  1484. if (!this._loadingDiv) {
  1485. return;
  1486. }
  1487. this._loadingTextDiv.innerHTML = text;
  1488. }
  1489. public get loadingUIBackgroundColor(): string {
  1490. return this._loadingDivBackgroundColor;
  1491. }
  1492. public set loadingUIBackgroundColor(color: string) {
  1493. this._loadingDivBackgroundColor = color;
  1494. if (!this._loadingDiv) {
  1495. return;
  1496. }
  1497. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1498. }
  1499. public hideLoadingUI(): void {
  1500. if (!this._loadingDiv) {
  1501. return;
  1502. }
  1503. var onTransitionEnd = () => {
  1504. if (!this._loadingDiv) {
  1505. return;
  1506. }
  1507. document.body.removeChild(this._loadingDiv);
  1508. window.removeEventListener("resize", this._resizeLoadingUI);
  1509. this._loadingDiv = null;
  1510. }
  1511. this._loadingDiv.style.opacity = "0";
  1512. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1513. }
  1514. // FPS
  1515. public getFps(): number {
  1516. return this.fps;
  1517. }
  1518. public getDeltaTime(): number {
  1519. return this.deltaTime;
  1520. }
  1521. private _measureFps(): void {
  1522. this.previousFramesDuration.push(Tools.Now);
  1523. var length = this.previousFramesDuration.length;
  1524. if (length >= 2) {
  1525. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1526. }
  1527. if (length >= this.fpsRange) {
  1528. if (length > this.fpsRange) {
  1529. this.previousFramesDuration.splice(0, 1);
  1530. length = this.previousFramesDuration.length;
  1531. }
  1532. var sum = 0;
  1533. for (var id = 0; id < length - 1; id++) {
  1534. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1535. }
  1536. this.fps = 1000.0 / (sum / (length - 1));
  1537. }
  1538. }
  1539. // Statics
  1540. public static isSupported(): boolean {
  1541. try {
  1542. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1543. if (navigator.isCocoonJS) {
  1544. return true;
  1545. }
  1546. var tempcanvas = document.createElement("canvas");
  1547. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1548. return gl != null && !!window.WebGLRenderingContext;
  1549. } catch (e) {
  1550. return false;
  1551. }
  1552. }
  1553. }
  1554. }