babylon.engine.ts 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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) {
  85. gl.enable(gl.CULL_FACE);
  86. } else {
  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) {
  104. gl.enable(gl.DEPTH_TEST);
  105. } else {
  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) {
  166. gl.enable(gl.BLEND);
  167. } else {
  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 getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  189. var textureType = gl.UNSIGNED_BYTE;
  190. if (type === Engine.TEXTURETYPE_FLOAT)
  191. textureType = gl.FLOAT;
  192. return textureType;
  193. };
  194. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  195. var magFilter = gl.NEAREST;
  196. var minFilter = gl.NEAREST;
  197. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  198. magFilter = gl.LINEAR;
  199. if (generateMipMaps) {
  200. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  201. } else {
  202. minFilter = gl.LINEAR;
  203. }
  204. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  205. magFilter = gl.LINEAR;
  206. if (generateMipMaps) {
  207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  208. } else {
  209. minFilter = gl.LINEAR;
  210. }
  211. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  212. magFilter = gl.NEAREST;
  213. if (generateMipMaps) {
  214. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  215. } else {
  216. minFilter = gl.NEAREST;
  217. }
  218. }
  219. return {
  220. min: minFilter,
  221. mag: magFilter
  222. }
  223. }
  224. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  225. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  226. var engine = scene.getEngine();
  227. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  228. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  229. gl.bindTexture(gl.TEXTURE_2D, texture);
  230. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  231. processFunction(potWidth, potHeight);
  232. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  235. if (!noMipmap && !isCompressed) {
  236. gl.generateMipmap(gl.TEXTURE_2D);
  237. }
  238. gl.bindTexture(gl.TEXTURE_2D, null);
  239. engine._activeTexturesCache = [];
  240. texture._baseWidth = width;
  241. texture._baseHeight = height;
  242. texture._width = potWidth;
  243. texture._height = potHeight;
  244. texture.isReady = true;
  245. texture.samplingMode = samplingMode;
  246. scene._removePendingData(texture);
  247. };
  248. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  249. onfinish: (images: HTMLImageElement[]) => void) => {
  250. var onload = () => {
  251. loadedImages[index] = img;
  252. loadedImages._internalCount++;
  253. scene._removePendingData(img);
  254. if (loadedImages._internalCount === 6) {
  255. onfinish(loadedImages);
  256. }
  257. };
  258. var onerror = () => {
  259. scene._removePendingData(img);
  260. };
  261. var img = Tools.LoadImage(url, onload, onerror, scene.database);
  262. scene._addPendingData(img);
  263. }
  264. var cascadeLoad = (rootUrl: string, scene,
  265. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  266. var loadedImages: any = [];
  267. loadedImages._internalCount = 0;
  268. for (var index = 0; index < 6; index++) {
  269. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  270. }
  271. };
  272. export class EngineCapabilities {
  273. public maxTexturesImageUnits: number;
  274. public maxTextureSize: number;
  275. public maxCubemapTextureSize: number;
  276. public maxRenderTextureSize: number;
  277. public standardDerivatives: boolean;
  278. public s3tc;
  279. public textureFloat: boolean;
  280. public textureAnisotropicFilterExtension;
  281. public maxAnisotropy: number;
  282. public instancedArrays;
  283. public uintIndices: boolean;
  284. }
  285. /**
  286. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  287. */
  288. export class Engine {
  289. // Const statics
  290. private static _ALPHA_DISABLE = 0;
  291. private static _ALPHA_ADD = 1;
  292. private static _ALPHA_COMBINE = 2;
  293. private static _DELAYLOADSTATE_NONE = 0;
  294. private static _DELAYLOADSTATE_LOADED = 1;
  295. private static _DELAYLOADSTATE_LOADING = 2;
  296. private static _DELAYLOADSTATE_NOTLOADED = 4;
  297. private static _TEXTUREFORMAT_ALPHA = 0;
  298. private static _TEXTUREFORMAT_LUMINANCE = 1;
  299. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  300. private static _TEXTUREFORMAT_RGB = 4;
  301. private static _TEXTUREFORMAT_RGBA = 4;
  302. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  303. private static _TEXTURETYPE_FLOAT = 1;
  304. public static get ALPHA_DISABLE(): number {
  305. return Engine._ALPHA_DISABLE;
  306. }
  307. public static get ALPHA_ADD(): number {
  308. return Engine._ALPHA_ADD;
  309. }
  310. public static get ALPHA_COMBINE(): number {
  311. return Engine._ALPHA_COMBINE;
  312. }
  313. public static get DELAYLOADSTATE_NONE(): number {
  314. return Engine._DELAYLOADSTATE_NONE;
  315. }
  316. public static get DELAYLOADSTATE_LOADED(): number {
  317. return Engine._DELAYLOADSTATE_LOADED;
  318. }
  319. public static get DELAYLOADSTATE_LOADING(): number {
  320. return Engine._DELAYLOADSTATE_LOADING;
  321. }
  322. public static get DELAYLOADSTATE_NOTLOADED(): number {
  323. return Engine._DELAYLOADSTATE_NOTLOADED;
  324. }
  325. public static get TEXTUREFORMAT_ALPHA(): number {
  326. return Engine._TEXTUREFORMAT_ALPHA;
  327. }
  328. public static get TEXTUREFORMAT_LUMINANCE(): number {
  329. return Engine._TEXTUREFORMAT_LUMINANCE;
  330. }
  331. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  332. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  333. }
  334. public static get TEXTUREFORMAT_RGB(): number {
  335. return Engine._TEXTUREFORMAT_RGB;
  336. }
  337. public static get TEXTUREFORMAT_RGBA(): number {
  338. return Engine._TEXTUREFORMAT_RGBA;
  339. }
  340. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  341. return Engine._TEXTURETYPE_UNSIGNED_INT;
  342. }
  343. public static get TEXTURETYPE_FLOAT(): number {
  344. return Engine._TEXTURETYPE_FLOAT;
  345. }
  346. public static get Version(): string {
  347. return "2.0.0";
  348. }
  349. // Updatable statics so stick with vars here
  350. public static Epsilon = 0.001;
  351. public static CollisionsEpsilon = 0.001;
  352. public static ShadersRepository = "Babylon/Shaders/";
  353. // Public members
  354. public isFullscreen = false;
  355. public isPointerLock = false;
  356. public cullBackFaces = true;
  357. public renderEvenInBackground = true;
  358. public scenes = new Array<Scene>();
  359. // Private Members
  360. public _gl: WebGLRenderingContext;
  361. private _renderingCanvas: HTMLCanvasElement;
  362. private _windowIsBackground = false;
  363. private _audioEngine: AudioEngine;
  364. private _onBlur: () => void;
  365. private _onFocus: () => void;
  366. private _onFullscreenChange: () => void;
  367. private _onPointerLockChange: () => void;
  368. private _hardwareScalingLevel: number;
  369. private _caps: EngineCapabilities;
  370. private _pointerLockRequested: boolean;
  371. private _alphaTest: boolean;
  372. private _resizeLoadingUI: () => void;
  373. private _loadingDiv: HTMLDivElement;
  374. private _loadingTextDiv: HTMLDivElement;
  375. private _loadingDivBackgroundColor = "black";
  376. private _drawCalls = 0;
  377. private _glVersion: string;
  378. private _glRenderer: string;
  379. private _glVendor: string;
  380. private _renderingQueueLaunched = false;
  381. private _activeRenderLoops = [];
  382. // FPS
  383. private fpsRange = 60;
  384. private previousFramesDuration = [];
  385. private fps = 60;
  386. private deltaTime = 0;
  387. // States
  388. private _depthCullingState = new _DepthCullingState();
  389. private _alphaState = new _AlphaState();
  390. private _alphaMode = Engine.ALPHA_DISABLE;
  391. // Cache
  392. private _loadedTexturesCache = new Array<WebGLTexture>();
  393. public _activeTexturesCache = new Array<BaseTexture>();
  394. private _currentEffect: Effect;
  395. private _compiledEffects = {};
  396. private _vertexAttribArrays: boolean[];
  397. private _cachedViewport: Viewport;
  398. private _cachedVertexBuffers: any;
  399. private _cachedIndexBuffer: WebGLBuffer;
  400. private _cachedEffectForVertexBuffers: Effect;
  401. private _currentRenderTarget: WebGLTexture;
  402. private _canvasClientRect: ClientRect;
  403. private _uintIndicesCurrentlySet = false;
  404. private _workingCanvas: HTMLCanvasElement;
  405. private _workingContext: CanvasRenderingContext2D;
  406. /**
  407. * @constructor
  408. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  409. * @param {boolean} [antialias] - enable antialias
  410. * @param options - further options to be sent to the getContext function
  411. */
  412. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  413. this._renderingCanvas = canvas;
  414. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  415. options = options || {};
  416. options.antialias = antialias;
  417. // GL
  418. try {
  419. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  420. } catch (e) {
  421. throw new Error("WebGL not supported");
  422. }
  423. if (!this._gl) {
  424. throw new Error("WebGL not supported");
  425. }
  426. this._onBlur = () => {
  427. this._windowIsBackground = true;
  428. };
  429. this._onFocus = () => {
  430. this._windowIsBackground = false;
  431. };
  432. window.addEventListener("blur", this._onBlur);
  433. window.addEventListener("focus", this._onFocus);
  434. // Textures
  435. this._workingCanvas = document.createElement("canvas");
  436. this._workingContext = this._workingCanvas.getContext("2d");
  437. // Viewport
  438. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  439. this.resize();
  440. // Caps
  441. this._caps = new EngineCapabilities();
  442. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  443. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  444. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  445. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  446. // Infos
  447. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  448. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  449. if (rendererInfo != null) {
  450. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  451. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  452. }
  453. if (!this._glVendor) {
  454. this._glVendor = "Unknown vendor";
  455. }
  456. if (!this._glRenderer) {
  457. this._glRenderer = "Unknown renderer";
  458. }
  459. // Extensions
  460. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  461. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  462. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  463. 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');
  464. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  465. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  466. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  467. // Depth buffer
  468. this.setDepthBuffer(true);
  469. this.setDepthFunctionToLessOrEqual();
  470. this.setDepthWrite(true);
  471. // Fullscreen
  472. this._onFullscreenChange = () => {
  473. if (document.fullscreen !== undefined) {
  474. this.isFullscreen = document.fullscreen;
  475. } else if (document.mozFullScreen !== undefined) {
  476. this.isFullscreen = document.mozFullScreen;
  477. } else if (document.webkitIsFullScreen !== undefined) {
  478. this.isFullscreen = document.webkitIsFullScreen;
  479. } else if (document.msIsFullScreen !== undefined) {
  480. this.isFullscreen = document.msIsFullScreen;
  481. }
  482. // Pointer lock
  483. if (this.isFullscreen && this._pointerLockRequested) {
  484. canvas.requestPointerLock = canvas.requestPointerLock ||
  485. canvas.msRequestPointerLock ||
  486. canvas.mozRequestPointerLock ||
  487. canvas.webkitRequestPointerLock;
  488. if (canvas.requestPointerLock) {
  489. canvas.requestPointerLock();
  490. }
  491. }
  492. };
  493. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  494. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  495. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  496. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  497. // Pointer lock
  498. this._onPointerLockChange = () => {
  499. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  500. document.webkitPointerLockElement === canvas ||
  501. document.msPointerLockElement === canvas ||
  502. document.pointerLockElement === canvas
  503. );
  504. };
  505. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  506. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  507. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  508. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  509. this._audioEngine = new AudioEngine();
  510. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  511. }
  512. public getGlInfo() {
  513. return {
  514. vendor: this._glVendor,
  515. renderer: this._glRenderer,
  516. version: this._glVersion
  517. }
  518. }
  519. public getAudioEngine(): AudioEngine {
  520. return this._audioEngine;
  521. }
  522. public getAspectRatio(camera: Camera): number {
  523. var viewport = camera.viewport;
  524. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  525. }
  526. public getRenderWidth(): number {
  527. if (this._currentRenderTarget) {
  528. return this._currentRenderTarget._width;
  529. }
  530. return this._renderingCanvas.width;
  531. }
  532. public getRenderHeight(): number {
  533. if (this._currentRenderTarget) {
  534. return this._currentRenderTarget._height;
  535. }
  536. return this._renderingCanvas.height;
  537. }
  538. public getRenderingCanvas(): HTMLCanvasElement {
  539. return this._renderingCanvas;
  540. }
  541. public getRenderingCanvasClientRect(): ClientRect {
  542. return this._renderingCanvas.getBoundingClientRect();
  543. }
  544. public setHardwareScalingLevel(level: number): void {
  545. this._hardwareScalingLevel = level;
  546. this.resize();
  547. }
  548. public getHardwareScalingLevel(): number {
  549. return this._hardwareScalingLevel;
  550. }
  551. public getLoadedTexturesCache(): WebGLTexture[] {
  552. return this._loadedTexturesCache;
  553. }
  554. public getCaps(): EngineCapabilities {
  555. return this._caps;
  556. }
  557. public get drawCalls(): number {
  558. return this._drawCalls;
  559. }
  560. // Methods
  561. public resetDrawCalls(): void {
  562. this._drawCalls = 0;
  563. }
  564. public setDepthFunctionToGreater(): void {
  565. this._depthCullingState.depthFunc = this._gl.GREATER;
  566. }
  567. public setDepthFunctionToGreaterOrEqual(): void {
  568. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  569. }
  570. public setDepthFunctionToLess(): void {
  571. this._depthCullingState.depthFunc = this._gl.LESS;
  572. }
  573. public setDepthFunctionToLessOrEqual(): void {
  574. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  575. }
  576. /**
  577. * stop executing a render loop function and remove it from the execution array
  578. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  579. */
  580. public stopRenderLoop(renderFunction?: () => void): void {
  581. if (!renderFunction) {
  582. this._activeRenderLoops = [];
  583. return;
  584. }
  585. var index = this._activeRenderLoops.indexOf(renderFunction);
  586. if (index >= 0) {
  587. this._activeRenderLoops.splice(index, 1);
  588. }
  589. }
  590. public _renderLoop(): void {
  591. var shouldRender = true;
  592. if (!this.renderEvenInBackground && this._windowIsBackground) {
  593. shouldRender = false;
  594. }
  595. if (shouldRender) {
  596. // Start new frame
  597. this.beginFrame();
  598. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  599. var renderFunction = this._activeRenderLoops[index];
  600. renderFunction();
  601. }
  602. // Present
  603. this.endFrame();
  604. }
  605. if (this._activeRenderLoops.length > 0) {
  606. // Register new frame
  607. Tools.QueueNewFrame(() => {
  608. this._renderLoop();
  609. });
  610. } else {
  611. this._renderingQueueLaunched = false;
  612. }
  613. }
  614. /**
  615. * Register and execute a render loop. The engine can have more than one render function.
  616. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  617. * @example
  618. * engine.runRenderLoop(function () {
  619. * scene.render()
  620. * })
  621. */
  622. public runRenderLoop(renderFunction: () => void): void {
  623. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  624. return;
  625. }
  626. this._activeRenderLoops.push(renderFunction);
  627. if (!this._renderingQueueLaunched) {
  628. this._renderingQueueLaunched = true;
  629. Tools.QueueNewFrame(() => {
  630. this._renderLoop();
  631. });
  632. }
  633. }
  634. /**
  635. * Toggle full screen mode.
  636. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  637. */
  638. public switchFullscreen(requestPointerLock: boolean): void {
  639. if (this.isFullscreen) {
  640. Tools.ExitFullscreen();
  641. } else {
  642. this._pointerLockRequested = requestPointerLock;
  643. Tools.RequestFullscreen(this._renderingCanvas);
  644. }
  645. }
  646. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  647. this.applyStates();
  648. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  649. if (this._depthCullingState.depthMask) {
  650. this._gl.clearDepth(1.0);
  651. }
  652. var mode = 0;
  653. if (backBuffer)
  654. mode |= this._gl.COLOR_BUFFER_BIT;
  655. if (depthStencil && this._depthCullingState.depthMask)
  656. mode |= this._gl.DEPTH_BUFFER_BIT;
  657. this._gl.clear(mode);
  658. }
  659. /**
  660. * Set the WebGL's viewport
  661. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  662. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  663. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  664. */
  665. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  666. var width = requiredWidth || this._renderingCanvas.width;
  667. var height = requiredHeight || this._renderingCanvas.height;
  668. var x = viewport.x || 0;
  669. var y = viewport.y || 0;
  670. this._cachedViewport = viewport;
  671. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  672. }
  673. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  674. this._cachedViewport = null;
  675. this._gl.viewport(x, y, width, height);
  676. }
  677. public beginFrame(): void {
  678. this._measureFps();
  679. }
  680. public endFrame(): void {
  681. this.flushFramebuffer();
  682. }
  683. /**
  684. * resize the view according to the canvas' size.
  685. * @example
  686. * window.addEventListener("resize", function () {
  687. * engine.resize();
  688. * });
  689. */
  690. public resize(): void {
  691. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  692. }
  693. /**
  694. * force a specific size of the canvas
  695. * @param {number} width - the new canvas' width
  696. * @param {number} height - the new canvas' height
  697. */
  698. public setSize(width: number, height: number): void {
  699. this._renderingCanvas.width = width;
  700. this._renderingCanvas.height = height;
  701. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  702. }
  703. public bindFramebuffer(texture: WebGLTexture): void {
  704. this._currentRenderTarget = texture;
  705. var gl = this._gl;
  706. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  707. this._gl.viewport(0, 0, texture._width, texture._height);
  708. this.wipeCaches();
  709. }
  710. public unBindFramebuffer(texture: WebGLTexture): void {
  711. this._currentRenderTarget = null;
  712. if (texture.generateMipMaps) {
  713. var gl = this._gl;
  714. gl.bindTexture(gl.TEXTURE_2D, texture);
  715. gl.generateMipmap(gl.TEXTURE_2D);
  716. gl.bindTexture(gl.TEXTURE_2D, null);
  717. }
  718. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  719. }
  720. public flushFramebuffer(): void {
  721. // this._gl.flush();
  722. }
  723. public restoreDefaultFramebuffer(): void {
  724. this._currentRenderTarget = null;
  725. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  726. this.setViewport(this._cachedViewport);
  727. this.wipeCaches();
  728. }
  729. // VBOs
  730. private _resetVertexBufferBinding(): void {
  731. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  732. this._cachedVertexBuffers = null;
  733. }
  734. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  735. var vbo = this._gl.createBuffer();
  736. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  737. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  738. this._resetVertexBufferBinding();
  739. vbo.references = 1;
  740. return vbo;
  741. }
  742. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  743. var vbo = this._gl.createBuffer();
  744. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  745. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  746. this._resetVertexBufferBinding();
  747. vbo.references = 1;
  748. return vbo;
  749. }
  750. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  751. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  752. if (offset === undefined) {
  753. offset = 0;
  754. }
  755. if (vertices instanceof Float32Array) {
  756. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  757. } else {
  758. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  759. }
  760. this._resetVertexBufferBinding();
  761. }
  762. private _resetIndexBufferBinding(): void {
  763. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  764. this._cachedIndexBuffer = null;
  765. }
  766. public createIndexBuffer(indices: number[]): WebGLBuffer {
  767. var vbo = this._gl.createBuffer();
  768. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  769. // Check for 32 bits indices
  770. var arrayBuffer;
  771. var need32Bits = false;
  772. if (this._caps.uintIndices) {
  773. for (var index = 0; index < indices.length; index++) {
  774. if (indices[index] > 65535) {
  775. need32Bits = true;
  776. break;
  777. }
  778. }
  779. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  780. } else {
  781. arrayBuffer = new Uint16Array(indices);
  782. }
  783. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  784. this._resetIndexBufferBinding();
  785. vbo.references = 1;
  786. vbo.is32Bits = need32Bits;
  787. return vbo;
  788. }
  789. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  790. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  791. this._cachedVertexBuffers = vertexBuffer;
  792. this._cachedEffectForVertexBuffers = effect;
  793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  794. var offset = 0;
  795. for (var index = 0; index < vertexDeclaration.length; index++) {
  796. var order = effect.getAttributeLocation(index);
  797. if (order >= 0) {
  798. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  799. }
  800. offset += vertexDeclaration[index] * 4;
  801. }
  802. }
  803. if (this._cachedIndexBuffer !== indexBuffer) {
  804. this._cachedIndexBuffer = indexBuffer;
  805. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  806. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  807. }
  808. }
  809. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  810. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  811. this._cachedVertexBuffers = vertexBuffers;
  812. this._cachedEffectForVertexBuffers = effect;
  813. var attributes = effect.getAttributesNames();
  814. for (var index = 0; index < attributes.length; index++) {
  815. var order = effect.getAttributeLocation(index);
  816. if (order >= 0) {
  817. var vertexBuffer = vertexBuffers[attributes[index]];
  818. if (!vertexBuffer) {
  819. continue;
  820. }
  821. var stride = vertexBuffer.getStrideSize();
  822. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  823. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  824. }
  825. }
  826. }
  827. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  828. this._cachedIndexBuffer = indexBuffer;
  829. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  830. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  831. }
  832. }
  833. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  834. buffer.references--;
  835. if (buffer.references === 0) {
  836. this._gl.deleteBuffer(buffer);
  837. return true;
  838. }
  839. return false;
  840. }
  841. public createInstancesBuffer(capacity: number): WebGLBuffer {
  842. var buffer = this._gl.createBuffer();
  843. buffer.capacity = capacity;
  844. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  845. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  846. return buffer;
  847. }
  848. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  849. this._gl.deleteBuffer(buffer);
  850. }
  851. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  852. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  853. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  854. for (var index = 0; index < 4; index++) {
  855. var offsetLocation = offsetLocations[index];
  856. this._gl.enableVertexAttribArray(offsetLocation);
  857. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  858. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  859. }
  860. }
  861. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  862. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  863. for (var index = 0; index < 4; index++) {
  864. var offsetLocation = offsetLocations[index];
  865. this._gl.disableVertexAttribArray(offsetLocation);
  866. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  867. }
  868. }
  869. public applyStates() {
  870. this._depthCullingState.apply(this._gl);
  871. this._alphaState.apply(this._gl);
  872. }
  873. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  874. // Apply states
  875. this.applyStates();
  876. this._drawCalls++;
  877. // Render
  878. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  879. if (instancesCount) {
  880. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  881. return;
  882. }
  883. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  884. }
  885. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  886. // Apply states
  887. this.applyStates();
  888. this._drawCalls++;
  889. if (instancesCount) {
  890. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  891. return;
  892. }
  893. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  894. }
  895. // Shaders
  896. public _releaseEffect(effect: Effect): void {
  897. if (this._compiledEffects[effect._key]) {
  898. delete this._compiledEffects[effect._key];
  899. if (effect.getProgram()) {
  900. this._gl.deleteProgram(effect.getProgram());
  901. }
  902. }
  903. }
  904. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  905. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  906. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  907. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  908. var name = vertex + "+" + fragment + "@" + defines;
  909. if (this._compiledEffects[name]) {
  910. return this._compiledEffects[name];
  911. }
  912. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  913. effect._key = name;
  914. this._compiledEffects[name] = effect;
  915. return effect;
  916. }
  917. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  918. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  919. return this.createEffect(
  920. {
  921. vertex: "particles",
  922. fragmentElement: fragmentName
  923. },
  924. ["position", "color", "options"],
  925. ["view", "projection"].concat(uniformsNames),
  926. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  927. }
  928. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  929. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  930. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  931. var shaderProgram = this._gl.createProgram();
  932. this._gl.attachShader(shaderProgram, vertexShader);
  933. this._gl.attachShader(shaderProgram, fragmentShader);
  934. this._gl.linkProgram(shaderProgram);
  935. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  936. if (!linked) {
  937. var error = this._gl.getProgramInfoLog(shaderProgram);
  938. if (error) {
  939. throw new Error(error);
  940. }
  941. }
  942. this._gl.deleteShader(vertexShader);
  943. this._gl.deleteShader(fragmentShader);
  944. return shaderProgram;
  945. }
  946. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  947. var results = [];
  948. for (var index = 0; index < uniformsNames.length; index++) {
  949. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  950. }
  951. return results;
  952. }
  953. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  954. var results = [];
  955. for (var index = 0; index < attributesNames.length; index++) {
  956. try {
  957. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  958. } catch (e) {
  959. results.push(-1);
  960. }
  961. }
  962. return results;
  963. }
  964. public enableEffect(effect: Effect): void {
  965. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  966. if (effect && effect.onBind) {
  967. effect.onBind(effect);
  968. }
  969. return;
  970. }
  971. this._vertexAttribArrays = this._vertexAttribArrays || [];
  972. // Use program
  973. this._gl.useProgram(effect.getProgram());
  974. for (var i in this._vertexAttribArrays) {
  975. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  976. continue;
  977. }
  978. this._vertexAttribArrays[i] = false;
  979. this._gl.disableVertexAttribArray(i);
  980. }
  981. var attributesCount = effect.getAttributesCount();
  982. for (var index = 0; index < attributesCount; index++) {
  983. // Attributes
  984. var order = effect.getAttributeLocation(index);
  985. if (order >= 0) {
  986. this._vertexAttribArrays[order] = true;
  987. this._gl.enableVertexAttribArray(order);
  988. }
  989. }
  990. this._currentEffect = effect;
  991. if (effect.onBind) {
  992. effect.onBind(effect);
  993. }
  994. }
  995. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  996. if (!uniform)
  997. return;
  998. this._gl.uniform1fv(uniform, array);
  999. }
  1000. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1001. if (!uniform)
  1002. return;
  1003. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1004. }
  1005. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1006. if (!uniform)
  1007. return;
  1008. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1009. }
  1010. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1011. if (!uniform)
  1012. return;
  1013. this._gl.uniform1f(uniform, value);
  1014. }
  1015. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1016. if (!uniform)
  1017. return;
  1018. this._gl.uniform2f(uniform, x, y);
  1019. }
  1020. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1021. if (!uniform)
  1022. return;
  1023. this._gl.uniform3f(uniform, x, y, z);
  1024. }
  1025. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1026. if (!uniform)
  1027. return;
  1028. this._gl.uniform1i(uniform, bool);
  1029. }
  1030. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1031. if (!uniform)
  1032. return;
  1033. this._gl.uniform4f(uniform, x, y, z, w);
  1034. }
  1035. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1036. if (!uniform)
  1037. return;
  1038. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1039. }
  1040. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1041. if (!uniform)
  1042. return;
  1043. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1044. }
  1045. // States
  1046. public setState(culling: boolean, force?: boolean): void {
  1047. // Culling
  1048. if (this._depthCullingState.cull !== culling || force) {
  1049. if (culling) {
  1050. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1051. this._depthCullingState.cull = true;
  1052. } else {
  1053. this._depthCullingState.cull = false;
  1054. }
  1055. }
  1056. }
  1057. public setDepthBuffer(enable: boolean): void {
  1058. this._depthCullingState.depthTest = enable;
  1059. }
  1060. public getDepthWrite(): boolean {
  1061. return this._depthCullingState.depthMask;
  1062. }
  1063. public setDepthWrite(enable: boolean): void {
  1064. this._depthCullingState.depthMask = enable;
  1065. }
  1066. public setColorWrite(enable: boolean): void {
  1067. this._gl.colorMask(enable, enable, enable, enable);
  1068. }
  1069. public setAlphaMode(mode: number): void {
  1070. switch (mode) {
  1071. case Engine.ALPHA_DISABLE:
  1072. this.setDepthWrite(true);
  1073. this._alphaState.alphaBlend = false;
  1074. break;
  1075. case Engine.ALPHA_COMBINE:
  1076. this.setDepthWrite(false);
  1077. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1078. this._alphaState.alphaBlend = true;
  1079. break;
  1080. case Engine.ALPHA_ADD:
  1081. this.setDepthWrite(false);
  1082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1083. this._alphaState.alphaBlend = true;
  1084. break;
  1085. }
  1086. this._alphaMode = mode;
  1087. }
  1088. public getAlphaMode(): number {
  1089. return this._alphaMode;
  1090. }
  1091. public setAlphaTesting(enable: boolean): void {
  1092. this._alphaTest = enable;
  1093. }
  1094. public getAlphaTesting(): boolean {
  1095. return this._alphaTest;
  1096. }
  1097. // Textures
  1098. public wipeCaches(): void {
  1099. this._activeTexturesCache = [];
  1100. this._currentEffect = null;
  1101. this._depthCullingState.reset();
  1102. this._alphaState.reset();
  1103. this._cachedVertexBuffers = null;
  1104. this._cachedIndexBuffer = null;
  1105. this._cachedEffectForVertexBuffers = null;
  1106. }
  1107. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1108. var gl = this._gl;
  1109. gl.bindTexture(gl.TEXTURE_2D, texture);
  1110. var magFilter = gl.NEAREST;
  1111. var minFilter = gl.NEAREST;
  1112. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1113. magFilter = gl.LINEAR;
  1114. minFilter = gl.LINEAR;
  1115. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1116. magFilter = gl.LINEAR;
  1117. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1118. }
  1119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1121. gl.bindTexture(gl.TEXTURE_2D, null);
  1122. texture.samplingMode = samplingMode;
  1123. }
  1124. 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 {
  1125. var texture = this._gl.createTexture();
  1126. var extension: string;
  1127. var fromData: any = false;
  1128. if (url.substr(0, 5) === "data:") {
  1129. fromData = true;
  1130. }
  1131. if (!fromData)
  1132. extension = url.substr(url.length - 4, 4).toLowerCase();
  1133. else {
  1134. var oldUrl = url;
  1135. fromData = oldUrl.split(':');
  1136. url = oldUrl;
  1137. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1138. }
  1139. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1140. var isTGA = (extension === ".tga");
  1141. scene._addPendingData(texture);
  1142. texture.url = url;
  1143. texture.noMipmap = noMipmap;
  1144. texture.references = 1;
  1145. this._loadedTexturesCache.push(texture);
  1146. var onerror = () => {
  1147. scene._removePendingData(texture);
  1148. if (onError) {
  1149. onError();
  1150. }
  1151. };
  1152. if (isTGA) {
  1153. var callback = (arrayBuffer) => {
  1154. var data = new Uint8Array(arrayBuffer);
  1155. var header = Internals.TGATools.GetTGAHeader(data);
  1156. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false,() => {
  1157. Internals.TGATools.UploadContent(this._gl, data);
  1158. if (onLoad) {
  1159. onLoad();
  1160. }
  1161. }, samplingMode);
  1162. };
  1163. if (!(fromData instanceof Array))
  1164. Tools.LoadFile(url, arrayBuffer => {
  1165. callback(arrayBuffer);
  1166. }, onerror, scene.database, true);
  1167. else
  1168. callback(buffer);
  1169. } else if (isDDS) {
  1170. callback = (data) => {
  1171. var info = Internals.DDSTools.GetDDSInfo(data);
  1172. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1173. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC,() => {
  1174. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1175. if (onLoad) {
  1176. onLoad();
  1177. }
  1178. }, samplingMode);
  1179. };
  1180. if (!(fromData instanceof Array))
  1181. Tools.LoadFile(url, data => {
  1182. callback(data);
  1183. }, onerror, scene.database, true);
  1184. else
  1185. callback(buffer);
  1186. } else {
  1187. var onload = (img) => {
  1188. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false,(potWidth, potHeight) => {
  1189. var isPot = (img.width === potWidth && img.height === potHeight);
  1190. if (!isPot) {
  1191. this._workingCanvas.width = potWidth;
  1192. this._workingCanvas.height = potHeight;
  1193. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1194. this._workingContext.imageSmoothingEnabled = false;
  1195. this._workingContext.mozImageSmoothingEnabled = false;
  1196. this._workingContext.oImageSmoothingEnabled = false;
  1197. this._workingContext.webkitImageSmoothingEnabled = false;
  1198. this._workingContext.msImageSmoothingEnabled = false;
  1199. }
  1200. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1201. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1202. this._workingContext.imageSmoothingEnabled = true;
  1203. this._workingContext.mozImageSmoothingEnabled = true;
  1204. this._workingContext.oImageSmoothingEnabled = true;
  1205. this._workingContext.webkitImageSmoothingEnabled = true;
  1206. this._workingContext.msImageSmoothingEnabled = true;
  1207. }
  1208. }
  1209. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1210. if (onLoad) {
  1211. onLoad();
  1212. }
  1213. }, samplingMode);
  1214. };
  1215. if (!(fromData instanceof Array))
  1216. Tools.LoadImage(url, onload, onerror, scene.database);
  1217. else
  1218. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1219. }
  1220. return texture;
  1221. }
  1222. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number): WebGLTexture {
  1223. var texture = this._gl.createTexture();
  1224. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1225. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1226. // Format
  1227. var internalFormat = this._gl.RGBA;
  1228. switch (format) {
  1229. case Engine.TEXTUREFORMAT_ALPHA:
  1230. internalFormat = this._gl.ALPHA;
  1231. break;
  1232. case Engine.TEXTUREFORMAT_LUMINANCE:
  1233. internalFormat = this._gl.LUMINANCE;
  1234. break;
  1235. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1236. internalFormat = this._gl.LUMINANCE_ALPHA;
  1237. break;
  1238. case Engine.TEXTUREFORMAT_RGB:
  1239. internalFormat = this._gl.RGB;
  1240. break;
  1241. case Engine.TEXTUREFORMAT_RGBA:
  1242. internalFormat = this._gl.RGBA;
  1243. break;
  1244. }
  1245. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1246. if (generateMipMaps) {
  1247. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1248. }
  1249. // Filters
  1250. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1251. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1252. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1253. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1254. this._activeTexturesCache = [];
  1255. texture._baseWidth = width;
  1256. texture._baseHeight = height;
  1257. texture._width = width;
  1258. texture._height = height;
  1259. texture.isReady = true;
  1260. texture.references = 1;
  1261. texture.samplingMode = samplingMode;
  1262. this._loadedTexturesCache.push(texture);
  1263. return texture;
  1264. }
  1265. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1266. var texture = this._gl.createTexture();
  1267. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1268. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1269. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1270. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1273. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1274. this._activeTexturesCache = [];
  1275. texture._baseWidth = width;
  1276. texture._baseHeight = height;
  1277. texture._width = width;
  1278. texture._height = height;
  1279. texture.isReady = false;
  1280. texture.generateMipMaps = generateMipMaps;
  1281. texture.references = 1;
  1282. texture.samplingMode = samplingMode;
  1283. this._loadedTexturesCache.push(texture);
  1284. return texture;
  1285. }
  1286. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1287. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1288. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1289. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1290. if (texture.generateMipMaps) {
  1291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1292. }
  1293. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1294. this._activeTexturesCache = [];
  1295. texture.isReady = true;
  1296. }
  1297. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1298. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1299. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1300. // Scale the video if it is a NPOT using the current working canvas
  1301. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1302. if (!texture._workingCanvas) {
  1303. texture._workingCanvas = document.createElement("canvas");
  1304. texture._workingContext = texture._workingCanvas.getContext("2d");
  1305. texture._workingCanvas.width = texture._width;
  1306. texture._workingCanvas.height = texture._height;
  1307. }
  1308. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1310. } else {
  1311. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1312. }
  1313. if (texture.generateMipMaps) {
  1314. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1315. }
  1316. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1317. this._activeTexturesCache = [];
  1318. texture.isReady = true;
  1319. }
  1320. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1321. // old version had a "generateMipMaps" arg instead of options.
  1322. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1323. // in the same way, generateDepthBuffer is defaulted to true
  1324. var generateMipMaps = false;
  1325. var generateDepthBuffer = true;
  1326. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1327. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1328. if (options !== undefined) {
  1329. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1330. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1331. type = options.type === undefined ? type : options.type;
  1332. if (options.samplingMode !== undefined) {
  1333. samplingMode = options.samplingMode;
  1334. }
  1335. if (type === Engine.TEXTURETYPE_FLOAT) {
  1336. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1337. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1338. }
  1339. }
  1340. var gl = this._gl;
  1341. var texture = gl.createTexture();
  1342. gl.bindTexture(gl.TEXTURE_2D, texture);
  1343. var width = size.width || size;
  1344. var height = size.height || size;
  1345. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1346. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1347. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1348. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1349. }
  1350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1354. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1355. var depthBuffer: WebGLRenderbuffer;
  1356. // Create the depth buffer
  1357. if (generateDepthBuffer) {
  1358. depthBuffer = gl.createRenderbuffer();
  1359. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1360. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1361. }
  1362. // Create the framebuffer
  1363. var framebuffer = gl.createFramebuffer();
  1364. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1365. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1366. if (generateDepthBuffer) {
  1367. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1368. }
  1369. // Unbind
  1370. gl.bindTexture(gl.TEXTURE_2D, null);
  1371. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1372. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1373. texture._framebuffer = framebuffer;
  1374. if (generateDepthBuffer) {
  1375. texture._depthBuffer = depthBuffer;
  1376. }
  1377. texture._width = width;
  1378. texture._height = height;
  1379. texture.isReady = true;
  1380. texture.generateMipMaps = generateMipMaps;
  1381. texture.references = 1;
  1382. texture.samplingMode = samplingMode;
  1383. this._activeTexturesCache = [];
  1384. this._loadedTexturesCache.push(texture);
  1385. return texture;
  1386. }
  1387. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1388. var gl = this._gl;
  1389. var texture = gl.createTexture();
  1390. texture.isCube = true;
  1391. texture.url = rootUrl;
  1392. texture.references = 1;
  1393. this._loadedTexturesCache.push(texture);
  1394. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1395. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1396. if (isDDS) {
  1397. Tools.LoadFile(rootUrl, data => {
  1398. var info = Internals.DDSTools.GetDDSInfo(data);
  1399. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1400. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1401. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1402. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1403. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1404. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1405. }
  1406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1409. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1410. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1411. this._activeTexturesCache = [];
  1412. texture._width = info.width;
  1413. texture._height = info.height;
  1414. texture.isReady = true;
  1415. }, null, null, true);
  1416. } else {
  1417. cascadeLoad(rootUrl, scene, imgs => {
  1418. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1419. var height = width;
  1420. this._workingCanvas.width = width;
  1421. this._workingCanvas.height = height;
  1422. var faces = [
  1423. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1424. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1425. ];
  1426. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1428. for (var index = 0; index < faces.length; index++) {
  1429. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1430. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1431. }
  1432. if (!noMipmap) {
  1433. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1434. }
  1435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1439. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1440. this._activeTexturesCache = [];
  1441. texture._width = width;
  1442. texture._height = height;
  1443. texture.isReady = true;
  1444. }, extensions);
  1445. }
  1446. return texture;
  1447. }
  1448. public _releaseTexture(texture: WebGLTexture): void {
  1449. var gl = this._gl;
  1450. if (texture._framebuffer) {
  1451. gl.deleteFramebuffer(texture._framebuffer);
  1452. }
  1453. if (texture._depthBuffer) {
  1454. gl.deleteRenderbuffer(texture._depthBuffer);
  1455. }
  1456. gl.deleteTexture(texture);
  1457. // Unbind channels
  1458. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1459. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1460. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1461. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1462. this._activeTexturesCache[channel] = null;
  1463. }
  1464. var index = this._loadedTexturesCache.indexOf(texture);
  1465. if (index !== -1) {
  1466. this._loadedTexturesCache.splice(index, 1);
  1467. }
  1468. }
  1469. public bindSamplers(effect: Effect): void {
  1470. this._gl.useProgram(effect.getProgram());
  1471. var samplers = effect.getSamplers();
  1472. for (var index = 0; index < samplers.length; index++) {
  1473. var uniform = effect.getUniform(samplers[index]);
  1474. this._gl.uniform1i(uniform, index);
  1475. }
  1476. this._currentEffect = null;
  1477. }
  1478. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1479. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1480. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1481. this._activeTexturesCache[channel] = null;
  1482. }
  1483. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1484. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1485. }
  1486. public setTexture(channel: number, texture: BaseTexture): void {
  1487. if (channel < 0) {
  1488. return;
  1489. }
  1490. // Not ready?
  1491. if (!texture || !texture.isReady()) {
  1492. if (this._activeTexturesCache[channel] != null) {
  1493. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1494. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1495. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1496. this._activeTexturesCache[channel] = null;
  1497. }
  1498. return;
  1499. }
  1500. // Video
  1501. if (texture instanceof VideoTexture) {
  1502. if ((<VideoTexture>texture).update()) {
  1503. this._activeTexturesCache[channel] = null;
  1504. }
  1505. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1506. texture.delayLoad();
  1507. return;
  1508. }
  1509. if (this._activeTexturesCache[channel] === texture) {
  1510. return;
  1511. }
  1512. this._activeTexturesCache[channel] = texture;
  1513. var internalTexture = texture.getInternalTexture();
  1514. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1515. if (internalTexture.isCube) {
  1516. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1517. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1518. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1519. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1520. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1521. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1522. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1523. }
  1524. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1525. } else {
  1526. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1527. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1528. internalTexture._cachedWrapU = texture.wrapU;
  1529. switch (texture.wrapU) {
  1530. case Texture.WRAP_ADDRESSMODE:
  1531. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1532. break;
  1533. case Texture.CLAMP_ADDRESSMODE:
  1534. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1535. break;
  1536. case Texture.MIRROR_ADDRESSMODE:
  1537. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1538. break;
  1539. }
  1540. }
  1541. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1542. internalTexture._cachedWrapV = texture.wrapV;
  1543. switch (texture.wrapV) {
  1544. case Texture.WRAP_ADDRESSMODE:
  1545. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1546. break;
  1547. case Texture.CLAMP_ADDRESSMODE:
  1548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1549. break;
  1550. case Texture.MIRROR_ADDRESSMODE:
  1551. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1552. break;
  1553. }
  1554. }
  1555. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1556. }
  1557. }
  1558. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1559. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1560. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1561. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1562. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1563. }
  1564. }
  1565. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1566. var data = new Uint8Array(height * width * 4);
  1567. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1568. return data;
  1569. }
  1570. // Dispose
  1571. public dispose(): void {
  1572. this.hideLoadingUI();
  1573. this.stopRenderLoop();
  1574. // Release scenes
  1575. while (this.scenes.length) {
  1576. this.scenes[0].dispose();
  1577. }
  1578. // Release effects
  1579. for (var name in this._compiledEffects) {
  1580. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1581. }
  1582. // Unbind
  1583. for (var i in this._vertexAttribArrays) {
  1584. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1585. continue;
  1586. }
  1587. this._gl.disableVertexAttribArray(i);
  1588. }
  1589. // Events
  1590. window.removeEventListener("blur", this._onBlur);
  1591. window.removeEventListener("focus", this._onFocus);
  1592. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1593. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1594. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1595. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1596. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1597. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1598. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1599. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1600. }
  1601. // Loading screen
  1602. public displayLoadingUI(): void {
  1603. this._loadingDiv = document.createElement("div");
  1604. this._loadingDiv.style.opacity = "0";
  1605. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1606. // Loading text
  1607. this._loadingTextDiv = document.createElement("div");
  1608. this._loadingTextDiv.style.position = "absolute";
  1609. this._loadingTextDiv.style.left = "0";
  1610. this._loadingTextDiv.style.top = "50%";
  1611. this._loadingTextDiv.style.marginTop = "80px";
  1612. this._loadingTextDiv.style.width = "100%";
  1613. this._loadingTextDiv.style.height = "20px";
  1614. this._loadingTextDiv.style.fontFamily = "Arial";
  1615. this._loadingTextDiv.style.fontSize = "14px";
  1616. this._loadingTextDiv.style.color = "white";
  1617. this._loadingTextDiv.style.textAlign = "center";
  1618. this._loadingTextDiv.innerHTML = "Loading";
  1619. this._loadingDiv.appendChild(this._loadingTextDiv);
  1620. // Loading img
  1621. var imgBack = new Image();
  1622. 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==";
  1623. imgBack.style.position = "absolute";
  1624. imgBack.style.left = "50%";
  1625. imgBack.style.top = "50%";
  1626. imgBack.style.marginLeft = "-50px";
  1627. imgBack.style.marginTop = "-50px";
  1628. imgBack.style.transition = "transform 1.0s ease";
  1629. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1630. var deg = 360;
  1631. var onTransitionEnd = () => {
  1632. deg += 360;
  1633. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1634. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1635. }
  1636. imgBack.addEventListener("transitionend", onTransitionEnd);
  1637. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1638. this._loadingDiv.appendChild(imgBack);
  1639. // front image
  1640. var imgFront = new Image();
  1641. 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=";
  1642. imgFront.style.position = "absolute";
  1643. imgFront.style.left = "50%";
  1644. imgFront.style.top = "50%";
  1645. imgFront.style.marginLeft = "-50px";
  1646. imgFront.style.marginTop = "-50px";
  1647. this._loadingDiv.appendChild(imgFront);
  1648. // Resize
  1649. this._resizeLoadingUI = () => {
  1650. var canvasRect = this.getRenderingCanvasClientRect();
  1651. this._loadingDiv.style.position = "absolute";
  1652. this._loadingDiv.style.left = canvasRect.left + "px";
  1653. this._loadingDiv.style.top = canvasRect.top + "px";
  1654. this._loadingDiv.style.width = canvasRect.width + "px";
  1655. this._loadingDiv.style.height = canvasRect.height + "px";
  1656. }
  1657. this._resizeLoadingUI();
  1658. window.addEventListener("resize", this._resizeLoadingUI);
  1659. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1660. document.body.appendChild(this._loadingDiv);
  1661. setTimeout(() => {
  1662. this._loadingDiv.style.opacity = "1";
  1663. imgBack.style.transform = "rotateZ(360deg)";
  1664. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1665. }, 0);
  1666. }
  1667. public set loadingUIText(text: string) {
  1668. if (!this._loadingDiv) {
  1669. return;
  1670. }
  1671. this._loadingTextDiv.innerHTML = text;
  1672. }
  1673. public get loadingUIBackgroundColor(): string {
  1674. return this._loadingDivBackgroundColor;
  1675. }
  1676. public set loadingUIBackgroundColor(color: string) {
  1677. this._loadingDivBackgroundColor = color;
  1678. if (!this._loadingDiv) {
  1679. return;
  1680. }
  1681. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1682. }
  1683. public hideLoadingUI(): void {
  1684. if (!this._loadingDiv) {
  1685. return;
  1686. }
  1687. var onTransitionEnd = () => {
  1688. if (!this._loadingDiv) {
  1689. return;
  1690. }
  1691. document.body.removeChild(this._loadingDiv);
  1692. window.removeEventListener("resize", this._resizeLoadingUI);
  1693. this._loadingDiv = null;
  1694. }
  1695. this._loadingDiv.style.opacity = "0";
  1696. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1697. }
  1698. // FPS
  1699. public getFps(): number {
  1700. return this.fps;
  1701. }
  1702. public getDeltaTime(): number {
  1703. return this.deltaTime;
  1704. }
  1705. private _measureFps(): void {
  1706. this.previousFramesDuration.push(Tools.Now);
  1707. var length = this.previousFramesDuration.length;
  1708. if (length >= 2) {
  1709. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1710. }
  1711. if (length >= this.fpsRange) {
  1712. if (length > this.fpsRange) {
  1713. this.previousFramesDuration.splice(0, 1);
  1714. length = this.previousFramesDuration.length;
  1715. }
  1716. var sum = 0;
  1717. for (var id = 0; id < length - 1; id++) {
  1718. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1719. }
  1720. this.fps = 1000.0 / (sum / (length - 1));
  1721. }
  1722. }
  1723. // Statics
  1724. public static isSupported(): boolean {
  1725. try {
  1726. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1727. if (navigator.isCocoonJS) {
  1728. return true;
  1729. }
  1730. var tempcanvas = document.createElement("canvas");
  1731. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1732. return gl != null && !!window.WebGLRenderingContext;
  1733. } catch (e) {
  1734. return false;
  1735. }
  1736. }
  1737. }
  1738. }