babylon.engine.ts 85 KB

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