babylon.engine.ts 89 KB

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