babylon.engine.ts 89 KB

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