babylon.engine.ts 88 KB

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