babylon.engine.ts 86 KB

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