babylon.engine.ts 91 KB

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