babylon.engine.ts 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  1. module BABYLON {
  2. export class _DepthCullingState {
  3. private _isDepthTestDirty = false;
  4. private _isDepthMaskDirty = false;
  5. private _isDepthFuncDirty = false;
  6. private _isCullFaceDirty = false;
  7. private _isCullDirty = false;
  8. private _isZOffsetDirty = false;
  9. private _depthTest: boolean;
  10. private _depthMask: boolean;
  11. private _depthFunc: number;
  12. private _cull: boolean;
  13. private _cullFace: number;
  14. private _zOffset: number;
  15. public get isDirty(): boolean {
  16. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  17. }
  18. public get zOffset(): number {
  19. return this._zOffset;
  20. }
  21. public set zOffset(value: number) {
  22. if (this._zOffset === value) {
  23. return;
  24. }
  25. this._zOffset = value;
  26. this._isZOffsetDirty = true;
  27. }
  28. public get cullFace(): number {
  29. return this._cullFace;
  30. }
  31. public set cullFace(value: number) {
  32. if (this._cullFace === value) {
  33. return;
  34. }
  35. this._cullFace = value;
  36. this._isCullFaceDirty = true;
  37. }
  38. public get cull() {
  39. return this._cull;
  40. }
  41. public set cull(value: boolean) {
  42. if (this._cull === value) {
  43. return;
  44. }
  45. this._cull = value;
  46. this._isCullDirty = true;
  47. }
  48. public get depthFunc(): number {
  49. return this._depthFunc;
  50. }
  51. public set depthFunc(value: number) {
  52. if (this._depthFunc === value) {
  53. return;
  54. }
  55. this._depthFunc = value;
  56. this._isDepthFuncDirty = true;
  57. }
  58. public get depthMask(): boolean {
  59. return this._depthMask;
  60. }
  61. public set depthMask(value: boolean) {
  62. if (this._depthMask === value) {
  63. return;
  64. }
  65. this._depthMask = value;
  66. this._isDepthMaskDirty = true;
  67. }
  68. public get depthTest(): boolean {
  69. return this._depthTest;
  70. }
  71. public set depthTest(value: boolean) {
  72. if (this._depthTest === value) {
  73. return;
  74. }
  75. this._depthTest = value;
  76. this._isDepthTestDirty = true;
  77. }
  78. public reset() {
  79. this._depthMask = true;
  80. this._depthTest = true;
  81. this._depthFunc = null;
  82. this._cull = null;
  83. this._cullFace = null;
  84. this._zOffset = 0;
  85. this._isDepthTestDirty = true;
  86. this._isDepthMaskDirty = true;
  87. this._isDepthFuncDirty = false;
  88. this._isCullFaceDirty = false;
  89. this._isCullDirty = false;
  90. this._isZOffsetDirty = false;
  91. }
  92. public apply(gl: WebGLRenderingContext) {
  93. if (!this.isDirty) {
  94. return;
  95. }
  96. // Cull
  97. if (this._isCullDirty) {
  98. if (this.cull) {
  99. gl.enable(gl.CULL_FACE);
  100. } else {
  101. gl.disable(gl.CULL_FACE);
  102. }
  103. this._isCullDirty = false;
  104. }
  105. // Cull face
  106. if (this._isCullFaceDirty) {
  107. gl.cullFace(this.cullFace);
  108. this._isCullFaceDirty = false;
  109. }
  110. // Depth mask
  111. if (this._isDepthMaskDirty) {
  112. gl.depthMask(this.depthMask);
  113. this._isDepthMaskDirty = false;
  114. }
  115. // Depth test
  116. if (this._isDepthTestDirty) {
  117. if (this.depthTest) {
  118. gl.enable(gl.DEPTH_TEST);
  119. } else {
  120. gl.disable(gl.DEPTH_TEST);
  121. }
  122. this._isDepthTestDirty = false;
  123. }
  124. // Depth func
  125. if (this._isDepthFuncDirty) {
  126. gl.depthFunc(this.depthFunc);
  127. this._isDepthFuncDirty = false;
  128. }
  129. // zOffset
  130. if (this._isZOffsetDirty) {
  131. if (this.zOffset) {
  132. gl.enable(gl.POLYGON_OFFSET_FILL);
  133. gl.polygonOffset(this.zOffset, 0);
  134. } else {
  135. gl.disable(gl.POLYGON_OFFSET_FILL);
  136. }
  137. this._isZOffsetDirty = false;
  138. }
  139. }
  140. }
  141. export class _AlphaState {
  142. private _isAlphaBlendDirty = false;
  143. private _isBlendFunctionParametersDirty = false;
  144. private _alphaBlend = false;
  145. private _blendFunctionParameters = new Array<number>(4);
  146. public get isDirty(): boolean {
  147. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  148. }
  149. public get alphaBlend(): boolean {
  150. return this._alphaBlend;
  151. }
  152. public set alphaBlend(value: boolean) {
  153. if (this._alphaBlend === value) {
  154. return;
  155. }
  156. this._alphaBlend = value;
  157. this._isAlphaBlendDirty = true;
  158. }
  159. public setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void {
  160. if (
  161. this._blendFunctionParameters[0] === value0 &&
  162. this._blendFunctionParameters[1] === value1 &&
  163. this._blendFunctionParameters[2] === value2 &&
  164. this._blendFunctionParameters[3] === value3
  165. ) {
  166. return;
  167. }
  168. this._blendFunctionParameters[0] = value0;
  169. this._blendFunctionParameters[1] = value1;
  170. this._blendFunctionParameters[2] = value2;
  171. this._blendFunctionParameters[3] = value3;
  172. this._isBlendFunctionParametersDirty = true;
  173. }
  174. public reset() {
  175. this._alphaBlend = false;
  176. this._blendFunctionParameters[0] = null;
  177. this._blendFunctionParameters[1] = null;
  178. this._blendFunctionParameters[2] = null;
  179. this._blendFunctionParameters[3] = null;
  180. this._isAlphaBlendDirty = true;
  181. this._isBlendFunctionParametersDirty = false;
  182. }
  183. public apply(gl: WebGLRenderingContext) {
  184. if (!this.isDirty) {
  185. return;
  186. }
  187. // Alpha blend
  188. if (this._isAlphaBlendDirty) {
  189. if (this._alphaBlend) {
  190. gl.enable(gl.BLEND);
  191. } else {
  192. gl.disable(gl.BLEND);
  193. }
  194. this._isAlphaBlendDirty = false;
  195. }
  196. // Alpha function
  197. if (this._isBlendFunctionParametersDirty) {
  198. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  199. this._isBlendFunctionParametersDirty = false;
  200. }
  201. }
  202. }
  203. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  204. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  205. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  206. gl.compileShader(shader);
  207. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  208. throw new Error(gl.getShaderInfoLog(shader));
  209. }
  210. return shader;
  211. };
  212. var getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  213. var textureType = gl.UNSIGNED_BYTE;
  214. if (type === Engine.TEXTURETYPE_FLOAT)
  215. textureType = gl.FLOAT;
  216. return textureType;
  217. };
  218. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  219. var magFilter = gl.NEAREST;
  220. var minFilter = gl.NEAREST;
  221. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  222. magFilter = gl.LINEAR;
  223. if (generateMipMaps) {
  224. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  225. } else {
  226. minFilter = gl.LINEAR;
  227. }
  228. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  229. magFilter = gl.LINEAR;
  230. if (generateMipMaps) {
  231. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  232. } else {
  233. minFilter = gl.LINEAR;
  234. }
  235. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  236. magFilter = gl.NEAREST;
  237. if (generateMipMaps) {
  238. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  239. } else {
  240. minFilter = gl.NEAREST;
  241. }
  242. }
  243. return {
  244. min: minFilter,
  245. mag: magFilter
  246. }
  247. }
  248. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  249. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  250. var engine = scene.getEngine();
  251. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  252. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  253. gl.bindTexture(gl.TEXTURE_2D, texture);
  254. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  255. texture._baseWidth = width;
  256. texture._baseHeight = height;
  257. texture._width = potWidth;
  258. texture._height = potHeight;
  259. texture.isReady = true;
  260. processFunction(potWidth, potHeight);
  261. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  264. if (!noMipmap && !isCompressed) {
  265. gl.generateMipmap(gl.TEXTURE_2D);
  266. }
  267. gl.bindTexture(gl.TEXTURE_2D, null);
  268. engine._activeTexturesCache = [];
  269. scene._removePendingData(texture);
  270. };
  271. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  272. onfinish: (images: HTMLImageElement[]) => void) => {
  273. var onload = () => {
  274. loadedImages[index] = img;
  275. loadedImages._internalCount++;
  276. scene._removePendingData(img);
  277. if (loadedImages._internalCount === 6) {
  278. onfinish(loadedImages);
  279. }
  280. };
  281. var onerror = () => {
  282. scene._removePendingData(img);
  283. };
  284. var img = Tools.LoadImage(url, onload, onerror, scene.database);
  285. scene._addPendingData(img);
  286. }
  287. var cascadeLoad = (rootUrl: string, scene,
  288. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  289. var loadedImages: any = [];
  290. loadedImages._internalCount = 0;
  291. for (var index = 0; index < 6; index++) {
  292. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  293. }
  294. };
  295. export class EngineCapabilities {
  296. public maxTexturesImageUnits: number;
  297. public maxTextureSize: number;
  298. public maxCubemapTextureSize: number;
  299. public maxRenderTextureSize: number;
  300. public standardDerivatives: boolean;
  301. public s3tc;
  302. public textureFloat: boolean;
  303. public textureAnisotropicFilterExtension;
  304. public maxAnisotropy: number;
  305. public instancedArrays;
  306. public uintIndices: boolean;
  307. public highPrecisionShaderSupported: boolean;
  308. }
  309. /**
  310. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  311. */
  312. export class Engine {
  313. // Const statics
  314. private static _ALPHA_DISABLE = 0;
  315. private static _ALPHA_ADD = 1;
  316. private static _ALPHA_COMBINE = 2;
  317. private static _DELAYLOADSTATE_NONE = 0;
  318. private static _DELAYLOADSTATE_LOADED = 1;
  319. private static _DELAYLOADSTATE_LOADING = 2;
  320. private static _DELAYLOADSTATE_NOTLOADED = 4;
  321. private static _TEXTUREFORMAT_ALPHA = 0;
  322. private static _TEXTUREFORMAT_LUMINANCE = 1;
  323. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  324. private static _TEXTUREFORMAT_RGB = 4;
  325. private static _TEXTUREFORMAT_RGBA = 4;
  326. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  327. private static _TEXTURETYPE_FLOAT = 1;
  328. public static get ALPHA_DISABLE(): number {
  329. return Engine._ALPHA_DISABLE;
  330. }
  331. public static get ALPHA_ADD(): number {
  332. return Engine._ALPHA_ADD;
  333. }
  334. public static get ALPHA_COMBINE(): number {
  335. return Engine._ALPHA_COMBINE;
  336. }
  337. public static get DELAYLOADSTATE_NONE(): number {
  338. return Engine._DELAYLOADSTATE_NONE;
  339. }
  340. public static get DELAYLOADSTATE_LOADED(): number {
  341. return Engine._DELAYLOADSTATE_LOADED;
  342. }
  343. public static get DELAYLOADSTATE_LOADING(): number {
  344. return Engine._DELAYLOADSTATE_LOADING;
  345. }
  346. public static get DELAYLOADSTATE_NOTLOADED(): number {
  347. return Engine._DELAYLOADSTATE_NOTLOADED;
  348. }
  349. public static get TEXTUREFORMAT_ALPHA(): number {
  350. return Engine._TEXTUREFORMAT_ALPHA;
  351. }
  352. public static get TEXTUREFORMAT_LUMINANCE(): number {
  353. return Engine._TEXTUREFORMAT_LUMINANCE;
  354. }
  355. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  356. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  357. }
  358. public static get TEXTUREFORMAT_RGB(): number {
  359. return Engine._TEXTUREFORMAT_RGB;
  360. }
  361. public static get TEXTUREFORMAT_RGBA(): number {
  362. return Engine._TEXTUREFORMAT_RGBA;
  363. }
  364. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  365. return Engine._TEXTURETYPE_UNSIGNED_INT;
  366. }
  367. public static get TEXTURETYPE_FLOAT(): number {
  368. return Engine._TEXTURETYPE_FLOAT;
  369. }
  370. public static get Version(): string {
  371. return "2.1.0";
  372. }
  373. // Updatable statics so stick with vars here
  374. public static Epsilon = 0.001;
  375. public static CollisionsEpsilon = 0.001;
  376. public static CodeRepository = "Babylon/";
  377. public static ShadersRepository = "Babylon/Shaders/";
  378. // Public members
  379. public isFullscreen = false;
  380. public isPointerLock = false;
  381. public cullBackFaces = true;
  382. public renderEvenInBackground = true;
  383. public scenes = new Array<Scene>();
  384. // Private Members
  385. public _gl: WebGLRenderingContext;
  386. private _renderingCanvas: HTMLCanvasElement;
  387. private _windowIsBackground = false;
  388. public static audioEngine: AudioEngine;
  389. private _onBlur: () => void;
  390. private _onFocus: () => void;
  391. private _onFullscreenChange: () => void;
  392. private _onPointerLockChange: () => void;
  393. private _hardwareScalingLevel: number;
  394. private _caps: EngineCapabilities;
  395. private _pointerLockRequested: boolean;
  396. private _alphaTest: boolean;
  397. private _resizeLoadingUI: () => void;
  398. private _loadingDiv: HTMLDivElement;
  399. private _loadingTextDiv: HTMLDivElement;
  400. private _loadingDivBackgroundColor = "black";
  401. private _drawCalls = 0;
  402. private _glVersion: string;
  403. private _glRenderer: string;
  404. private _glVendor: string;
  405. private _videoTextureSupported: boolean;
  406. private _renderingQueueLaunched = false;
  407. private _activeRenderLoops = [];
  408. // FPS
  409. private fpsRange = 60;
  410. private previousFramesDuration = [];
  411. private fps = 60;
  412. private deltaTime = 0;
  413. // States
  414. private _depthCullingState = new _DepthCullingState();
  415. private _alphaState = new _AlphaState();
  416. private _alphaMode = Engine.ALPHA_DISABLE;
  417. // Cache
  418. private _loadedTexturesCache = new Array<WebGLTexture>();
  419. public _activeTexturesCache = new Array<BaseTexture>();
  420. private _currentEffect: Effect;
  421. private _compiledEffects = {};
  422. private _vertexAttribArrays: boolean[];
  423. private _cachedViewport: Viewport;
  424. private _cachedVertexBuffers: any;
  425. private _cachedIndexBuffer: WebGLBuffer;
  426. private _cachedEffectForVertexBuffers: Effect;
  427. private _currentRenderTarget: WebGLTexture;
  428. private _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. // 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. for (var index = 0; index < this.scenes.length; index++) {
  736. var scene = this.scenes[index];
  737. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  738. var cam = scene.cameras[camIndex];
  739. cam._currentRenderId = 0;
  740. }
  741. }
  742. }
  743. public bindFramebuffer(texture: WebGLTexture): void {
  744. this._currentRenderTarget = texture;
  745. var gl = this._gl;
  746. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  747. this._gl.viewport(0, 0, texture._width, texture._height);
  748. this.wipeCaches();
  749. }
  750. public unBindFramebuffer(texture: WebGLTexture): void {
  751. this._currentRenderTarget = null;
  752. if (texture.generateMipMaps) {
  753. var gl = this._gl;
  754. gl.bindTexture(gl.TEXTURE_2D, texture);
  755. gl.generateMipmap(gl.TEXTURE_2D);
  756. gl.bindTexture(gl.TEXTURE_2D, null);
  757. }
  758. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  759. }
  760. public flushFramebuffer(): void {
  761. this._gl.flush();
  762. }
  763. public restoreDefaultFramebuffer(): void {
  764. this._currentRenderTarget = null;
  765. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  766. this.setViewport(this._cachedViewport);
  767. this.wipeCaches();
  768. }
  769. // VBOs
  770. private _resetVertexBufferBinding(): void {
  771. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  772. this._cachedVertexBuffers = null;
  773. }
  774. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  775. var vbo = this._gl.createBuffer();
  776. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  777. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  778. this._resetVertexBufferBinding();
  779. vbo.references = 1;
  780. return vbo;
  781. }
  782. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  783. var vbo = this._gl.createBuffer();
  784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  785. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  786. this._resetVertexBufferBinding();
  787. vbo.references = 1;
  788. return vbo;
  789. }
  790. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  792. if (offset === undefined) {
  793. offset = 0;
  794. }
  795. if (vertices instanceof Float32Array) {
  796. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  797. } else {
  798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  799. }
  800. this._resetVertexBufferBinding();
  801. }
  802. private _resetIndexBufferBinding(): void {
  803. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  804. this._cachedIndexBuffer = null;
  805. }
  806. public createIndexBuffer(indices: number[]): WebGLBuffer {
  807. var vbo = this._gl.createBuffer();
  808. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  809. // Check for 32 bits indices
  810. var arrayBuffer;
  811. var need32Bits = false;
  812. if (this._caps.uintIndices) {
  813. for (var index = 0; index < indices.length; index++) {
  814. if (indices[index] > 65535) {
  815. need32Bits = true;
  816. break;
  817. }
  818. }
  819. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  820. } else {
  821. arrayBuffer = new Uint16Array(indices);
  822. }
  823. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  824. this._resetIndexBufferBinding();
  825. vbo.references = 1;
  826. vbo.is32Bits = need32Bits;
  827. return vbo;
  828. }
  829. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  830. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  831. this._cachedVertexBuffers = vertexBuffer;
  832. this._cachedEffectForVertexBuffers = effect;
  833. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  834. var offset = 0;
  835. for (var index = 0; index < vertexDeclaration.length; index++) {
  836. var order = effect.getAttributeLocation(index);
  837. if (order >= 0) {
  838. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  839. }
  840. offset += vertexDeclaration[index] * 4;
  841. }
  842. }
  843. if (this._cachedIndexBuffer !== indexBuffer) {
  844. this._cachedIndexBuffer = indexBuffer;
  845. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  846. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  847. }
  848. }
  849. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  850. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  851. this._cachedVertexBuffers = vertexBuffers;
  852. this._cachedEffectForVertexBuffers = effect;
  853. var attributes = effect.getAttributesNames();
  854. for (var index = 0; index < attributes.length; index++) {
  855. var order = effect.getAttributeLocation(index);
  856. if (order >= 0) {
  857. var vertexBuffer = vertexBuffers[attributes[index]];
  858. if (!vertexBuffer) {
  859. continue;
  860. }
  861. var stride = vertexBuffer.getStrideSize();
  862. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  863. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  864. }
  865. }
  866. }
  867. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  868. this._cachedIndexBuffer = indexBuffer;
  869. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  870. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  871. }
  872. }
  873. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  874. buffer.references--;
  875. if (buffer.references === 0) {
  876. this._gl.deleteBuffer(buffer);
  877. return true;
  878. }
  879. return false;
  880. }
  881. public createInstancesBuffer(capacity: number): WebGLBuffer {
  882. var buffer = this._gl.createBuffer();
  883. buffer.capacity = capacity;
  884. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  885. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  886. return buffer;
  887. }
  888. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  889. this._gl.deleteBuffer(buffer);
  890. }
  891. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  894. for (var index = 0; index < 4; index++) {
  895. var offsetLocation = offsetLocations[index];
  896. this._gl.enableVertexAttribArray(offsetLocation);
  897. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  898. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  899. }
  900. }
  901. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  903. for (var index = 0; index < 4; index++) {
  904. var offsetLocation = offsetLocations[index];
  905. this._gl.disableVertexAttribArray(offsetLocation);
  906. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  907. }
  908. }
  909. public applyStates() {
  910. this._depthCullingState.apply(this._gl);
  911. this._alphaState.apply(this._gl);
  912. }
  913. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  914. // Apply states
  915. this.applyStates();
  916. this._drawCalls++;
  917. // Render
  918. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  919. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  920. if (instancesCount) {
  921. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  922. return;
  923. }
  924. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  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, forceExponantOfTwo = true): WebGLTexture {
  1326. var texture = this._gl.createTexture();
  1327. texture._baseWidth = width;
  1328. texture._baseHeight = height;
  1329. if (forceExponantOfTwo) {
  1330. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1331. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1332. }
  1333. this._activeTexturesCache = [];
  1334. texture._width = width;
  1335. texture._height = height;
  1336. texture.isReady = false;
  1337. texture.generateMipMaps = generateMipMaps;
  1338. texture.references = 1;
  1339. texture.samplingMode = samplingMode;
  1340. this.updateTextureSamplingMode(samplingMode, texture);
  1341. this._loadedTexturesCache.push(texture);
  1342. return texture;
  1343. }
  1344. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1345. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1346. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1347. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1348. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1349. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1350. }
  1351. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1352. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1353. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1354. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1355. if (texture.generateMipMaps) {
  1356. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1357. }
  1358. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1359. this._activeTexturesCache = [];
  1360. texture.isReady = true;
  1361. }
  1362. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1363. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1364. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1365. // Testing video texture support
  1366. if (this._videoTextureSupported === undefined) {
  1367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1368. if (this._gl.getError() !== 0) {
  1369. this._videoTextureSupported = false;
  1370. } else {
  1371. this._videoTextureSupported = true;
  1372. }
  1373. }
  1374. // Copy video through the current working canvas if video texture is not supported
  1375. if (!this._videoTextureSupported) {
  1376. if (!texture._workingCanvas) {
  1377. texture._workingCanvas = document.createElement("canvas");
  1378. texture._workingContext = texture._workingCanvas.getContext("2d");
  1379. texture._workingCanvas.width = texture._width;
  1380. texture._workingCanvas.height = texture._height;
  1381. }
  1382. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1383. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1384. } else {
  1385. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1386. }
  1387. if (texture.generateMipMaps) {
  1388. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1389. }
  1390. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1391. this._activeTexturesCache = [];
  1392. texture.isReady = true;
  1393. }
  1394. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1395. // old version had a "generateMipMaps" arg instead of options.
  1396. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1397. // in the same way, generateDepthBuffer is defaulted to true
  1398. var generateMipMaps = false;
  1399. var generateDepthBuffer = true;
  1400. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1401. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1402. if (options !== undefined) {
  1403. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1404. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1405. type = options.type === undefined ? type : options.type;
  1406. if (options.samplingMode !== undefined) {
  1407. samplingMode = options.samplingMode;
  1408. }
  1409. if (type === Engine.TEXTURETYPE_FLOAT) {
  1410. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1411. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1412. }
  1413. }
  1414. var gl = this._gl;
  1415. var texture = gl.createTexture();
  1416. gl.bindTexture(gl.TEXTURE_2D, texture);
  1417. var width = size.width || size;
  1418. var height = size.height || size;
  1419. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1420. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1421. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1422. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1423. }
  1424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1428. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1429. var depthBuffer: WebGLRenderbuffer;
  1430. // Create the depth buffer
  1431. if (generateDepthBuffer) {
  1432. depthBuffer = gl.createRenderbuffer();
  1433. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1434. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1435. }
  1436. // Create the framebuffer
  1437. var framebuffer = gl.createFramebuffer();
  1438. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1439. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1440. if (generateDepthBuffer) {
  1441. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1442. }
  1443. if (generateMipMaps) {
  1444. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1445. }
  1446. // Unbind
  1447. gl.bindTexture(gl.TEXTURE_2D, null);
  1448. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1449. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1450. texture._framebuffer = framebuffer;
  1451. if (generateDepthBuffer) {
  1452. texture._depthBuffer = depthBuffer;
  1453. }
  1454. texture._width = width;
  1455. texture._height = height;
  1456. texture.isReady = true;
  1457. texture.generateMipMaps = generateMipMaps;
  1458. texture.references = 1;
  1459. texture.samplingMode = samplingMode;
  1460. this._activeTexturesCache = [];
  1461. this._loadedTexturesCache.push(texture);
  1462. return texture;
  1463. }
  1464. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1465. var gl = this._gl;
  1466. var texture = gl.createTexture();
  1467. texture.isCube = true;
  1468. texture.url = rootUrl;
  1469. texture.references = 1;
  1470. this._loadedTexturesCache.push(texture);
  1471. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1472. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1473. if (isDDS) {
  1474. Tools.LoadFile(rootUrl, data => {
  1475. var info = Internals.DDSTools.GetDDSInfo(data);
  1476. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1477. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1478. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1479. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1480. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1481. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1482. }
  1483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1487. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1488. this._activeTexturesCache = [];
  1489. texture._width = info.width;
  1490. texture._height = info.height;
  1491. texture.isReady = true;
  1492. }, null, null, true);
  1493. } else {
  1494. cascadeLoad(rootUrl, scene, imgs => {
  1495. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1496. var height = width;
  1497. this._prepareWorkingCanvas();
  1498. this._workingCanvas.width = width;
  1499. this._workingCanvas.height = height;
  1500. var faces = [
  1501. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1502. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1503. ];
  1504. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1505. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1506. for (var index = 0; index < faces.length; index++) {
  1507. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1508. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1509. }
  1510. if (!noMipmap) {
  1511. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1512. }
  1513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1517. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1518. this._activeTexturesCache = [];
  1519. texture._width = width;
  1520. texture._height = height;
  1521. texture.isReady = true;
  1522. }, extensions);
  1523. }
  1524. return texture;
  1525. }
  1526. public _releaseTexture(texture: WebGLTexture): void {
  1527. var gl = this._gl;
  1528. if (texture._framebuffer) {
  1529. gl.deleteFramebuffer(texture._framebuffer);
  1530. }
  1531. if (texture._depthBuffer) {
  1532. gl.deleteRenderbuffer(texture._depthBuffer);
  1533. }
  1534. gl.deleteTexture(texture);
  1535. // Unbind channels
  1536. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1537. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1538. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1539. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1540. this._activeTexturesCache[channel] = null;
  1541. }
  1542. var index = this._loadedTexturesCache.indexOf(texture);
  1543. if (index !== -1) {
  1544. this._loadedTexturesCache.splice(index, 1);
  1545. }
  1546. }
  1547. public bindSamplers(effect: Effect): void {
  1548. this._gl.useProgram(effect.getProgram());
  1549. var samplers = effect.getSamplers();
  1550. for (var index = 0; index < samplers.length; index++) {
  1551. var uniform = effect.getUniform(samplers[index]);
  1552. this._gl.uniform1i(uniform, index);
  1553. }
  1554. this._currentEffect = null;
  1555. }
  1556. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1557. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1558. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1559. this._activeTexturesCache[channel] = null;
  1560. }
  1561. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1562. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1563. }
  1564. public setTexture(channel: number, texture: BaseTexture): void {
  1565. if (channel < 0) {
  1566. return;
  1567. }
  1568. // Not ready?
  1569. if (!texture || !texture.isReady()) {
  1570. if (this._activeTexturesCache[channel] != null) {
  1571. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1572. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1573. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1574. this._activeTexturesCache[channel] = null;
  1575. }
  1576. return;
  1577. }
  1578. // Video
  1579. if (texture instanceof VideoTexture) {
  1580. if ((<VideoTexture>texture).update()) {
  1581. this._activeTexturesCache[channel] = null;
  1582. }
  1583. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1584. texture.delayLoad();
  1585. return;
  1586. }
  1587. if (this._activeTexturesCache[channel] === texture) {
  1588. return;
  1589. }
  1590. this._activeTexturesCache[channel] = texture;
  1591. var internalTexture = texture.getInternalTexture();
  1592. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1593. if (internalTexture.isCube) {
  1594. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1595. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1596. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1597. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1598. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1599. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1600. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1601. }
  1602. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1603. } else {
  1604. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1605. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1606. internalTexture._cachedWrapU = texture.wrapU;
  1607. switch (texture.wrapU) {
  1608. case Texture.WRAP_ADDRESSMODE:
  1609. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1610. break;
  1611. case Texture.CLAMP_ADDRESSMODE:
  1612. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1613. break;
  1614. case Texture.MIRROR_ADDRESSMODE:
  1615. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1616. break;
  1617. }
  1618. }
  1619. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1620. internalTexture._cachedWrapV = texture.wrapV;
  1621. switch (texture.wrapV) {
  1622. case Texture.WRAP_ADDRESSMODE:
  1623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1624. break;
  1625. case Texture.CLAMP_ADDRESSMODE:
  1626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1627. break;
  1628. case Texture.MIRROR_ADDRESSMODE:
  1629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1630. break;
  1631. }
  1632. }
  1633. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1634. }
  1635. }
  1636. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1637. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1638. var value = texture.anisotropicFilteringLevel;
  1639. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1640. value = 1;
  1641. }
  1642. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1643. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1644. texture._cachedAnisotropicFilteringLevel = value;
  1645. }
  1646. }
  1647. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1648. var data = new Uint8Array(height * width * 4);
  1649. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1650. return data;
  1651. }
  1652. // Dispose
  1653. public dispose(): void {
  1654. this.hideLoadingUI();
  1655. this.stopRenderLoop();
  1656. // Release scenes
  1657. while (this.scenes.length) {
  1658. this.scenes[0].dispose();
  1659. }
  1660. // Release audio engine
  1661. Engine.audioEngine.dispose();
  1662. // Release effects
  1663. for (var name in this._compiledEffects) {
  1664. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1665. }
  1666. // Unbind
  1667. for (var i in this._vertexAttribArrays) {
  1668. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1669. continue;
  1670. }
  1671. this._gl.disableVertexAttribArray(i);
  1672. }
  1673. this._gl = null;
  1674. // Events
  1675. window.removeEventListener("blur", this._onBlur);
  1676. window.removeEventListener("focus", this._onFocus);
  1677. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1678. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1679. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1680. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1681. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1682. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1683. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1684. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1685. }
  1686. // Loading screen
  1687. public displayLoadingUI(): void {
  1688. this._loadingDiv = document.createElement("div");
  1689. this._loadingDiv.style.opacity = "0";
  1690. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1691. // Loading text
  1692. this._loadingTextDiv = document.createElement("div");
  1693. this._loadingTextDiv.style.position = "absolute";
  1694. this._loadingTextDiv.style.left = "0";
  1695. this._loadingTextDiv.style.top = "50%";
  1696. this._loadingTextDiv.style.marginTop = "80px";
  1697. this._loadingTextDiv.style.width = "100%";
  1698. this._loadingTextDiv.style.height = "20px";
  1699. this._loadingTextDiv.style.fontFamily = "Arial";
  1700. this._loadingTextDiv.style.fontSize = "14px";
  1701. this._loadingTextDiv.style.color = "white";
  1702. this._loadingTextDiv.style.textAlign = "center";
  1703. this._loadingTextDiv.innerHTML = "Loading";
  1704. this._loadingDiv.appendChild(this._loadingTextDiv);
  1705. // Loading img
  1706. var imgBack = new Image();
  1707. 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==";
  1708. imgBack.style.position = "absolute";
  1709. imgBack.style.left = "50%";
  1710. imgBack.style.top = "50%";
  1711. imgBack.style.marginLeft = "-50px";
  1712. imgBack.style.marginTop = "-50px";
  1713. imgBack.style.transition = "transform 1.0s ease";
  1714. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1715. var deg = 360;
  1716. var onTransitionEnd = () => {
  1717. deg += 360;
  1718. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1719. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1720. }
  1721. imgBack.addEventListener("transitionend", onTransitionEnd);
  1722. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1723. this._loadingDiv.appendChild(imgBack);
  1724. // front image
  1725. var imgFront = new Image();
  1726. 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=";
  1727. imgFront.style.position = "absolute";
  1728. imgFront.style.left = "50%";
  1729. imgFront.style.top = "50%";
  1730. imgFront.style.marginLeft = "-50px";
  1731. imgFront.style.marginTop = "-50px";
  1732. this._loadingDiv.appendChild(imgFront);
  1733. // Resize
  1734. this._resizeLoadingUI = () => {
  1735. var canvasRect = this.getRenderingCanvasClientRect();
  1736. this._loadingDiv.style.position = "absolute";
  1737. this._loadingDiv.style.left = canvasRect.left + "px";
  1738. this._loadingDiv.style.top = canvasRect.top + "px";
  1739. this._loadingDiv.style.width = canvasRect.width + "px";
  1740. this._loadingDiv.style.height = canvasRect.height + "px";
  1741. }
  1742. this._resizeLoadingUI();
  1743. window.addEventListener("resize", this._resizeLoadingUI);
  1744. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1745. document.body.appendChild(this._loadingDiv);
  1746. setTimeout(() => {
  1747. this._loadingDiv.style.opacity = "1";
  1748. imgBack.style.transform = "rotateZ(360deg)";
  1749. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1750. }, 0);
  1751. }
  1752. public set loadingUIText(text: string) {
  1753. if (!this._loadingDiv) {
  1754. return;
  1755. }
  1756. this._loadingTextDiv.innerHTML = text;
  1757. }
  1758. public get loadingUIBackgroundColor(): string {
  1759. return this._loadingDivBackgroundColor;
  1760. }
  1761. public set loadingUIBackgroundColor(color: string) {
  1762. this._loadingDivBackgroundColor = color;
  1763. if (!this._loadingDiv) {
  1764. return;
  1765. }
  1766. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1767. }
  1768. public hideLoadingUI(): void {
  1769. if (!this._loadingDiv) {
  1770. return;
  1771. }
  1772. var onTransitionEnd = () => {
  1773. if (!this._loadingDiv) {
  1774. return;
  1775. }
  1776. document.body.removeChild(this._loadingDiv);
  1777. window.removeEventListener("resize", this._resizeLoadingUI);
  1778. this._loadingDiv = null;
  1779. }
  1780. this._loadingDiv.style.opacity = "0";
  1781. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1782. }
  1783. // FPS
  1784. public getFps(): number {
  1785. return this.fps;
  1786. }
  1787. public getDeltaTime(): number {
  1788. return this.deltaTime;
  1789. }
  1790. private _measureFps(): void {
  1791. this.previousFramesDuration.push(Tools.Now);
  1792. var length = this.previousFramesDuration.length;
  1793. if (length >= 2) {
  1794. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1795. }
  1796. if (length >= this.fpsRange) {
  1797. if (length > this.fpsRange) {
  1798. this.previousFramesDuration.splice(0, 1);
  1799. length = this.previousFramesDuration.length;
  1800. }
  1801. var sum = 0;
  1802. for (var id = 0; id < length - 1; id++) {
  1803. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1804. }
  1805. this.fps = 1000.0 / (sum / (length - 1));
  1806. }
  1807. }
  1808. // Statics
  1809. public static isSupported(): boolean {
  1810. try {
  1811. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1812. if (navigator.isCocoonJS) {
  1813. return true;
  1814. }
  1815. var tempcanvas = document.createElement("canvas");
  1816. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1817. return gl != null && !!window.WebGLRenderingContext;
  1818. } catch (e) {
  1819. return false;
  1820. }
  1821. }
  1822. }
  1823. }