babylon.engine.ts 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310
  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.2.0-alpha";
  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 _uintIndicesCurrentlySet = false;
  429. private _workingCanvas: HTMLCanvasElement;
  430. private _workingContext: CanvasRenderingContext2D;
  431. /**
  432. * @constructor
  433. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  434. * @param {boolean} [antialias] - enable antialias
  435. * @param options - further options to be sent to the getContext function
  436. */
  437. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  438. this._renderingCanvas = canvas;
  439. options = options || {};
  440. options.antialias = antialias;
  441. if (options.preserveDrawingBuffer === undefined) {
  442. options.preserveDrawingBuffer = false;
  443. }
  444. // GL
  445. try {
  446. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  447. } catch (e) {
  448. throw new Error("WebGL not supported");
  449. }
  450. if (!this._gl) {
  451. throw new Error("WebGL not supported");
  452. }
  453. this._onBlur = () => {
  454. this._windowIsBackground = true;
  455. };
  456. this._onFocus = () => {
  457. this._windowIsBackground = false;
  458. };
  459. window.addEventListener("blur", this._onBlur);
  460. window.addEventListener("focus", this._onFocus);
  461. // Viewport
  462. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  463. this.resize();
  464. // Caps
  465. this._caps = new EngineCapabilities();
  466. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  467. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  468. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  469. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  470. // Infos
  471. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  472. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  473. if (rendererInfo != null) {
  474. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  475. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  476. }
  477. if (!this._glVendor) {
  478. this._glVendor = "Unknown vendor";
  479. }
  480. if (!this._glRenderer) {
  481. this._glRenderer = "Unknown renderer";
  482. }
  483. // Extensions
  484. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  485. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  486. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  487. 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');
  488. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  489. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  490. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  491. this._caps.highPrecisionShaderSupported = true;
  492. if (this._gl.getShaderPrecisionFormat) {
  493. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  494. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  495. }
  496. // Depth buffer
  497. this.setDepthBuffer(true);
  498. this.setDepthFunctionToLessOrEqual();
  499. this.setDepthWrite(true);
  500. // Fullscreen
  501. this._onFullscreenChange = () => {
  502. if (document.fullscreen !== undefined) {
  503. this.isFullscreen = document.fullscreen;
  504. } else if (document.mozFullScreen !== undefined) {
  505. this.isFullscreen = document.mozFullScreen;
  506. } else if (document.webkitIsFullScreen !== undefined) {
  507. this.isFullscreen = document.webkitIsFullScreen;
  508. } else if (document.msIsFullScreen !== undefined) {
  509. this.isFullscreen = document.msIsFullScreen;
  510. }
  511. // Pointer lock
  512. if (this.isFullscreen && this._pointerLockRequested) {
  513. canvas.requestPointerLock = canvas.requestPointerLock ||
  514. canvas.msRequestPointerLock ||
  515. canvas.mozRequestPointerLock ||
  516. canvas.webkitRequestPointerLock;
  517. if (canvas.requestPointerLock) {
  518. canvas.requestPointerLock();
  519. }
  520. }
  521. };
  522. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  523. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  524. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  525. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  526. // Pointer lock
  527. this._onPointerLockChange = () => {
  528. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  529. document.webkitPointerLockElement === canvas ||
  530. document.msPointerLockElement === canvas ||
  531. document.pointerLockElement === canvas
  532. );
  533. };
  534. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  535. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  536. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  537. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  538. if (!Engine.audioEngine) {
  539. Engine.audioEngine = new AudioEngine();
  540. }
  541. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  542. }
  543. private _prepareWorkingCanvas(): void {
  544. if (this._workingCanvas) {
  545. return;
  546. }
  547. this._workingCanvas = document.createElement("canvas");
  548. this._workingContext = this._workingCanvas.getContext("2d");
  549. }
  550. public getGlInfo() {
  551. return {
  552. vendor: this._glVendor,
  553. renderer: this._glRenderer,
  554. version: this._glVersion
  555. }
  556. }
  557. public getAspectRatio(camera: Camera): number {
  558. var viewport = camera.viewport;
  559. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  560. }
  561. public getRenderWidth(): number {
  562. if (this._currentRenderTarget) {
  563. return this._currentRenderTarget._width;
  564. }
  565. return this._renderingCanvas.width;
  566. }
  567. public getRenderHeight(): number {
  568. if (this._currentRenderTarget) {
  569. return this._currentRenderTarget._height;
  570. }
  571. return this._renderingCanvas.height;
  572. }
  573. public getRenderingCanvas(): HTMLCanvasElement {
  574. return this._renderingCanvas;
  575. }
  576. public getRenderingCanvasClientRect(): ClientRect {
  577. return this._renderingCanvas.getBoundingClientRect();
  578. }
  579. public setHardwareScalingLevel(level: number): void {
  580. this._hardwareScalingLevel = level;
  581. this.resize();
  582. }
  583. public getHardwareScalingLevel(): number {
  584. return this._hardwareScalingLevel;
  585. }
  586. public getLoadedTexturesCache(): WebGLTexture[] {
  587. return this._loadedTexturesCache;
  588. }
  589. public getCaps(): EngineCapabilities {
  590. return this._caps;
  591. }
  592. public get drawCalls(): number {
  593. return this._drawCalls;
  594. }
  595. // Methods
  596. public resetDrawCalls(): void {
  597. this._drawCalls = 0;
  598. }
  599. public setDepthFunctionToGreater(): void {
  600. this._depthCullingState.depthFunc = this._gl.GREATER;
  601. }
  602. public setDepthFunctionToGreaterOrEqual(): void {
  603. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  604. }
  605. public setDepthFunctionToLess(): void {
  606. this._depthCullingState.depthFunc = this._gl.LESS;
  607. }
  608. public setDepthFunctionToLessOrEqual(): void {
  609. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  610. }
  611. /**
  612. * stop executing a render loop function and remove it from the execution array
  613. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  614. */
  615. public stopRenderLoop(renderFunction?: () => void): void {
  616. if (!renderFunction) {
  617. this._activeRenderLoops = [];
  618. return;
  619. }
  620. var index = this._activeRenderLoops.indexOf(renderFunction);
  621. if (index >= 0) {
  622. this._activeRenderLoops.splice(index, 1);
  623. }
  624. }
  625. public _renderLoop(): void {
  626. var shouldRender = true;
  627. if (!this.renderEvenInBackground && this._windowIsBackground) {
  628. shouldRender = false;
  629. }
  630. if (shouldRender) {
  631. // Start new frame
  632. this.beginFrame();
  633. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  634. var renderFunction = this._activeRenderLoops[index];
  635. renderFunction();
  636. }
  637. // Present
  638. this.endFrame();
  639. }
  640. if (this._activeRenderLoops.length > 0) {
  641. // Register new frame
  642. Tools.QueueNewFrame(() => {
  643. this._renderLoop();
  644. });
  645. } else {
  646. this._renderingQueueLaunched = false;
  647. }
  648. }
  649. /**
  650. * Register and execute a render loop. The engine can have more than one render function.
  651. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  652. * @example
  653. * engine.runRenderLoop(function () {
  654. * scene.render()
  655. * })
  656. */
  657. public runRenderLoop(renderFunction: () => void): void {
  658. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  659. return;
  660. }
  661. this._activeRenderLoops.push(renderFunction);
  662. if (!this._renderingQueueLaunched) {
  663. this._renderingQueueLaunched = true;
  664. Tools.QueueNewFrame(() => {
  665. this._renderLoop();
  666. });
  667. }
  668. }
  669. /**
  670. * Toggle full screen mode.
  671. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  672. */
  673. public switchFullscreen(requestPointerLock: boolean): void {
  674. if (this.isFullscreen) {
  675. Tools.ExitFullscreen();
  676. } else {
  677. this._pointerLockRequested = requestPointerLock;
  678. Tools.RequestFullscreen(this._renderingCanvas);
  679. }
  680. }
  681. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  682. this.applyStates();
  683. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  684. if (this._depthCullingState.depthMask) {
  685. this._gl.clearDepth(1.0);
  686. }
  687. var mode = 0;
  688. if (backBuffer)
  689. mode |= this._gl.COLOR_BUFFER_BIT;
  690. if (depthStencil && this._depthCullingState.depthMask)
  691. mode |= this._gl.DEPTH_BUFFER_BIT;
  692. this._gl.clear(mode);
  693. }
  694. /**
  695. * Set the WebGL's viewport
  696. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  697. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  698. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  699. */
  700. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  701. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  702. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  703. var x = viewport.x || 0;
  704. var y = viewport.y || 0;
  705. this._cachedViewport = viewport;
  706. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  707. }
  708. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  709. this._cachedViewport = null;
  710. this._gl.viewport(x, y, width, height);
  711. }
  712. public beginFrame(): void {
  713. this._measureFps();
  714. }
  715. public endFrame(): void {
  716. //this.flushFramebuffer();
  717. }
  718. /**
  719. * resize the view according to the canvas' size.
  720. * @example
  721. * window.addEventListener("resize", function () {
  722. * engine.resize();
  723. * });
  724. */
  725. public resize(): void {
  726. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  727. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  728. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  729. }
  730. /**
  731. * force a specific size of the canvas
  732. * @param {number} width - the new canvas' width
  733. * @param {number} height - the new canvas' height
  734. */
  735. public setSize(width: number, height: number): void {
  736. this._renderingCanvas.width = width;
  737. this._renderingCanvas.height = height;
  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. if (texture._isDisabled) {
  1367. return;
  1368. }
  1369. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1370. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1371. try
  1372. {
  1373. // Testing video texture support
  1374. if (this._videoTextureSupported === undefined) {
  1375. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1376. if (this._gl.getError() !== 0) {
  1377. this._videoTextureSupported = false;
  1378. } else {
  1379. this._videoTextureSupported = true;
  1380. }
  1381. }
  1382. // Copy video through the current working canvas if video texture is not supported
  1383. if (!this._videoTextureSupported) {
  1384. if (!texture._workingCanvas) {
  1385. texture._workingCanvas = document.createElement("canvas");
  1386. texture._workingContext = texture._workingCanvas.getContext("2d");
  1387. texture._workingCanvas.width = texture._width;
  1388. texture._workingCanvas.height = texture._height;
  1389. }
  1390. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1392. } else {
  1393. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1394. }
  1395. if (texture.generateMipMaps) {
  1396. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1397. }
  1398. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1399. this._activeTexturesCache = [];
  1400. texture.isReady = true;
  1401. } catch (ex) {
  1402. // Something unexpected
  1403. // Let's disable the texture
  1404. texture._isDisabled = true;
  1405. }
  1406. }
  1407. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1408. // old version had a "generateMipMaps" arg instead of options.
  1409. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1410. // in the same way, generateDepthBuffer is defaulted to true
  1411. var generateMipMaps = false;
  1412. var generateDepthBuffer = true;
  1413. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1414. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1415. if (options !== undefined) {
  1416. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1417. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1418. type = options.type === undefined ? type : options.type;
  1419. if (options.samplingMode !== undefined) {
  1420. samplingMode = options.samplingMode;
  1421. }
  1422. if (type === Engine.TEXTURETYPE_FLOAT) {
  1423. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1424. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1425. }
  1426. }
  1427. var gl = this._gl;
  1428. var texture = gl.createTexture();
  1429. gl.bindTexture(gl.TEXTURE_2D, texture);
  1430. var width = size.width || size;
  1431. var height = size.height || size;
  1432. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1433. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1434. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1435. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1436. }
  1437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1441. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1442. var depthBuffer: WebGLRenderbuffer;
  1443. // Create the depth buffer
  1444. if (generateDepthBuffer) {
  1445. depthBuffer = gl.createRenderbuffer();
  1446. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1447. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1448. }
  1449. // Create the framebuffer
  1450. var framebuffer = gl.createFramebuffer();
  1451. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1452. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1453. if (generateDepthBuffer) {
  1454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1455. }
  1456. if (generateMipMaps) {
  1457. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1458. }
  1459. // Unbind
  1460. gl.bindTexture(gl.TEXTURE_2D, null);
  1461. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1462. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1463. texture._framebuffer = framebuffer;
  1464. if (generateDepthBuffer) {
  1465. texture._depthBuffer = depthBuffer;
  1466. }
  1467. texture._width = width;
  1468. texture._height = height;
  1469. texture.isReady = true;
  1470. texture.generateMipMaps = generateMipMaps;
  1471. texture.references = 1;
  1472. texture.samplingMode = samplingMode;
  1473. this._activeTexturesCache = [];
  1474. this._loadedTexturesCache.push(texture);
  1475. return texture;
  1476. }
  1477. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1478. var gl = this._gl;
  1479. var texture = gl.createTexture();
  1480. texture.isCube = true;
  1481. texture.url = rootUrl;
  1482. texture.references = 1;
  1483. this._loadedTexturesCache.push(texture);
  1484. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1485. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1486. if (isDDS) {
  1487. Tools.LoadFile(rootUrl, data => {
  1488. var info = Internals.DDSTools.GetDDSInfo(data);
  1489. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1490. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1491. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1492. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1493. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1494. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1495. }
  1496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1500. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1501. this._activeTexturesCache = [];
  1502. texture._width = info.width;
  1503. texture._height = info.height;
  1504. texture.isReady = true;
  1505. }, null, null, true);
  1506. } else {
  1507. cascadeLoad(rootUrl, scene, imgs => {
  1508. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1509. var height = width;
  1510. this._prepareWorkingCanvas();
  1511. this._workingCanvas.width = width;
  1512. this._workingCanvas.height = height;
  1513. var faces = [
  1514. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1515. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1516. ];
  1517. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1518. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1519. for (var index = 0; index < faces.length; index++) {
  1520. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1521. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1522. }
  1523. if (!noMipmap) {
  1524. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1525. }
  1526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1530. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1531. this._activeTexturesCache = [];
  1532. texture._width = width;
  1533. texture._height = height;
  1534. texture.isReady = true;
  1535. }, extensions);
  1536. }
  1537. return texture;
  1538. }
  1539. public _releaseTexture(texture: WebGLTexture): void {
  1540. var gl = this._gl;
  1541. if (texture._framebuffer) {
  1542. gl.deleteFramebuffer(texture._framebuffer);
  1543. }
  1544. if (texture._depthBuffer) {
  1545. gl.deleteRenderbuffer(texture._depthBuffer);
  1546. }
  1547. gl.deleteTexture(texture);
  1548. // Unbind channels
  1549. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1550. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1551. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1552. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1553. this._activeTexturesCache[channel] = null;
  1554. }
  1555. var index = this._loadedTexturesCache.indexOf(texture);
  1556. if (index !== -1) {
  1557. this._loadedTexturesCache.splice(index, 1);
  1558. }
  1559. }
  1560. public bindSamplers(effect: Effect): void {
  1561. this._gl.useProgram(effect.getProgram());
  1562. var samplers = effect.getSamplers();
  1563. for (var index = 0; index < samplers.length; index++) {
  1564. var uniform = effect.getUniform(samplers[index]);
  1565. this._gl.uniform1i(uniform, index);
  1566. }
  1567. this._currentEffect = null;
  1568. }
  1569. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1570. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1571. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1572. this._activeTexturesCache[channel] = null;
  1573. }
  1574. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1575. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1576. }
  1577. public setTexture(channel: number, texture: BaseTexture): void {
  1578. if (channel < 0) {
  1579. return;
  1580. }
  1581. // Not ready?
  1582. if (!texture || !texture.isReady()) {
  1583. if (this._activeTexturesCache[channel] != null) {
  1584. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1585. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1586. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1587. this._activeTexturesCache[channel] = null;
  1588. }
  1589. return;
  1590. }
  1591. // Video
  1592. if (texture instanceof VideoTexture) {
  1593. if ((<VideoTexture>texture).update()) {
  1594. this._activeTexturesCache[channel] = null;
  1595. }
  1596. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1597. texture.delayLoad();
  1598. return;
  1599. }
  1600. if (this._activeTexturesCache[channel] === texture) {
  1601. return;
  1602. }
  1603. this._activeTexturesCache[channel] = texture;
  1604. var internalTexture = texture.getInternalTexture();
  1605. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1606. if (internalTexture.isCube) {
  1607. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1608. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1609. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1610. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1611. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1613. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1614. }
  1615. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1616. } else {
  1617. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1618. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1619. internalTexture._cachedWrapU = texture.wrapU;
  1620. switch (texture.wrapU) {
  1621. case Texture.WRAP_ADDRESSMODE:
  1622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1623. break;
  1624. case Texture.CLAMP_ADDRESSMODE:
  1625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1626. break;
  1627. case Texture.MIRROR_ADDRESSMODE:
  1628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1629. break;
  1630. }
  1631. }
  1632. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1633. internalTexture._cachedWrapV = texture.wrapV;
  1634. switch (texture.wrapV) {
  1635. case Texture.WRAP_ADDRESSMODE:
  1636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1637. break;
  1638. case Texture.CLAMP_ADDRESSMODE:
  1639. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1640. break;
  1641. case Texture.MIRROR_ADDRESSMODE:
  1642. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1643. break;
  1644. }
  1645. }
  1646. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1647. }
  1648. }
  1649. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1650. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1651. var value = texture.anisotropicFilteringLevel;
  1652. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1653. value = 1;
  1654. }
  1655. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1656. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1657. texture._cachedAnisotropicFilteringLevel = value;
  1658. }
  1659. }
  1660. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1661. var data = new Uint8Array(height * width * 4);
  1662. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1663. return data;
  1664. }
  1665. // Dispose
  1666. public dispose(): void {
  1667. this.hideLoadingUI();
  1668. this.stopRenderLoop();
  1669. // Release scenes
  1670. while (this.scenes.length) {
  1671. this.scenes[0].dispose();
  1672. }
  1673. // Release audio engine
  1674. Engine.audioEngine.dispose();
  1675. // Release effects
  1676. for (var name in this._compiledEffects) {
  1677. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1678. }
  1679. // Unbind
  1680. for (var i in this._vertexAttribArrays) {
  1681. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1682. continue;
  1683. }
  1684. this._gl.disableVertexAttribArray(i);
  1685. }
  1686. this._gl = null;
  1687. // Events
  1688. window.removeEventListener("blur", this._onBlur);
  1689. window.removeEventListener("focus", this._onFocus);
  1690. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1691. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1692. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1693. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1694. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1695. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1696. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1697. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1698. }
  1699. // Loading screen
  1700. public displayLoadingUI(): void {
  1701. this._loadingDiv = document.createElement("div");
  1702. this._loadingDiv.style.opacity = "0";
  1703. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1704. // Loading text
  1705. this._loadingTextDiv = document.createElement("div");
  1706. this._loadingTextDiv.style.position = "absolute";
  1707. this._loadingTextDiv.style.left = "0";
  1708. this._loadingTextDiv.style.top = "50%";
  1709. this._loadingTextDiv.style.marginTop = "80px";
  1710. this._loadingTextDiv.style.width = "100%";
  1711. this._loadingTextDiv.style.height = "20px";
  1712. this._loadingTextDiv.style.fontFamily = "Arial";
  1713. this._loadingTextDiv.style.fontSize = "14px";
  1714. this._loadingTextDiv.style.color = "white";
  1715. this._loadingTextDiv.style.textAlign = "center";
  1716. this._loadingTextDiv.innerHTML = "Loading";
  1717. this._loadingDiv.appendChild(this._loadingTextDiv);
  1718. // Loading img
  1719. var imgBack = new Image();
  1720. 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==";
  1721. imgBack.style.position = "absolute";
  1722. imgBack.style.left = "50%";
  1723. imgBack.style.top = "50%";
  1724. imgBack.style.marginLeft = "-50px";
  1725. imgBack.style.marginTop = "-50px";
  1726. imgBack.style.transition = "transform 1.0s ease";
  1727. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1728. var deg = 360;
  1729. var onTransitionEnd = () => {
  1730. deg += 360;
  1731. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1732. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1733. }
  1734. imgBack.addEventListener("transitionend", onTransitionEnd);
  1735. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1736. this._loadingDiv.appendChild(imgBack);
  1737. // front image
  1738. var imgFront = new Image();
  1739. 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=";
  1740. imgFront.style.position = "absolute";
  1741. imgFront.style.left = "50%";
  1742. imgFront.style.top = "50%";
  1743. imgFront.style.marginLeft = "-50px";
  1744. imgFront.style.marginTop = "-50px";
  1745. this._loadingDiv.appendChild(imgFront);
  1746. // Resize
  1747. this._resizeLoadingUI = () => {
  1748. var canvasRect = this.getRenderingCanvasClientRect();
  1749. this._loadingDiv.style.position = "absolute";
  1750. this._loadingDiv.style.left = canvasRect.left + "px";
  1751. this._loadingDiv.style.top = canvasRect.top + "px";
  1752. this._loadingDiv.style.width = canvasRect.width + "px";
  1753. this._loadingDiv.style.height = canvasRect.height + "px";
  1754. }
  1755. this._resizeLoadingUI();
  1756. window.addEventListener("resize", this._resizeLoadingUI);
  1757. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1758. document.body.appendChild(this._loadingDiv);
  1759. setTimeout(() => {
  1760. this._loadingDiv.style.opacity = "1";
  1761. imgBack.style.transform = "rotateZ(360deg)";
  1762. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1763. }, 0);
  1764. }
  1765. public set loadingUIText(text: string) {
  1766. if (!this._loadingDiv) {
  1767. return;
  1768. }
  1769. this._loadingTextDiv.innerHTML = text;
  1770. }
  1771. public get loadingUIBackgroundColor(): string {
  1772. return this._loadingDivBackgroundColor;
  1773. }
  1774. public set loadingUIBackgroundColor(color: string) {
  1775. this._loadingDivBackgroundColor = color;
  1776. if (!this._loadingDiv) {
  1777. return;
  1778. }
  1779. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1780. }
  1781. public hideLoadingUI(): void {
  1782. if (!this._loadingDiv) {
  1783. return;
  1784. }
  1785. var onTransitionEnd = () => {
  1786. if (!this._loadingDiv) {
  1787. return;
  1788. }
  1789. document.body.removeChild(this._loadingDiv);
  1790. window.removeEventListener("resize", this._resizeLoadingUI);
  1791. this._loadingDiv = null;
  1792. }
  1793. this._loadingDiv.style.opacity = "0";
  1794. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1795. }
  1796. // FPS
  1797. public getFps(): number {
  1798. return this.fps;
  1799. }
  1800. public getDeltaTime(): number {
  1801. return this.deltaTime;
  1802. }
  1803. private _measureFps(): void {
  1804. this.previousFramesDuration.push(Tools.Now);
  1805. var length = this.previousFramesDuration.length;
  1806. if (length >= 2) {
  1807. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1808. }
  1809. if (length >= this.fpsRange) {
  1810. if (length > this.fpsRange) {
  1811. this.previousFramesDuration.splice(0, 1);
  1812. length = this.previousFramesDuration.length;
  1813. }
  1814. var sum = 0;
  1815. for (var id = 0; id < length - 1; id++) {
  1816. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1817. }
  1818. this.fps = 1000.0 / (sum / (length - 1));
  1819. }
  1820. }
  1821. // Statics
  1822. public static isSupported(): boolean {
  1823. try {
  1824. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1825. if (navigator.isCocoonJS) {
  1826. return true;
  1827. }
  1828. var tempcanvas = document.createElement("canvas");
  1829. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1830. return gl != null && !!window.WebGLRenderingContext;
  1831. } catch (e) {
  1832. return false;
  1833. }
  1834. }
  1835. }
  1836. }