babylon.engine.ts 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141
  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 _depthTest: boolean;
  9. private _depthMask: boolean;
  10. private _depthFunc: number;
  11. private _cull: boolean;
  12. private _cullFace: number;
  13. public get isDirty(): boolean {
  14. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  15. }
  16. public get cullFace(): number {
  17. return this._cullFace;
  18. }
  19. public set cullFace(value: number) {
  20. if (this._cullFace === value) {
  21. return;
  22. }
  23. this._cullFace = value;
  24. this._isCullFaceDirty = true;
  25. }
  26. public get cull() {
  27. return this._cull;
  28. }
  29. public set cull(value: boolean) {
  30. if (this._cull === value) {
  31. return;
  32. }
  33. this._cull = value;
  34. this._isCullDirty = true;
  35. }
  36. public get depthFunc(): number {
  37. return this._depthFunc;
  38. }
  39. public set depthFunc(value: number) {
  40. if (this._depthFunc === value) {
  41. return;
  42. }
  43. this._depthFunc = value;
  44. this._isDepthFuncDirty = true;
  45. }
  46. public get depthMask(): boolean {
  47. return this._depthMask;
  48. }
  49. public set depthMask(value: boolean) {
  50. if (this._depthMask === value) {
  51. return;
  52. }
  53. this._depthMask = value;
  54. this._isDepthMaskDirty = true;
  55. }
  56. public get depthTest(): boolean {
  57. return this._depthTest;
  58. }
  59. public set depthTest(value: boolean) {
  60. if (this._depthTest === value) {
  61. return;
  62. }
  63. this._depthTest = value;
  64. this._isDepthTestDirty = true;
  65. }
  66. public reset() {
  67. this._depthMask = true;
  68. this._depthTest = true;
  69. this._depthFunc = null;
  70. this._cull = null;
  71. this._cullFace = null;
  72. this._isDepthTestDirty = true;
  73. this._isDepthMaskDirty = true;
  74. this._isDepthFuncDirty = false;
  75. this._isCullFaceDirty = false;
  76. this._isCullDirty = false;
  77. }
  78. public apply(gl: WebGLRenderingContext) {
  79. if (!this.isDirty) {
  80. return;
  81. }
  82. // Cull
  83. if (this._isCullDirty) {
  84. if (this.cull) {
  85. gl.enable(gl.CULL_FACE);
  86. } else {
  87. gl.disable(gl.CULL_FACE);
  88. }
  89. this._isCullDirty = false;
  90. }
  91. // Cull face
  92. if (this._isCullFaceDirty) {
  93. gl.cullFace(this.cullFace);
  94. this._isCullFaceDirty = false;
  95. }
  96. // Depth mask
  97. if (this._isDepthMaskDirty) {
  98. gl.depthMask(this.depthMask);
  99. this._isDepthMaskDirty = false;
  100. }
  101. // Depth test
  102. if (this._isDepthTestDirty) {
  103. if (this.depthTest) {
  104. gl.enable(gl.DEPTH_TEST);
  105. } else {
  106. gl.disable(gl.DEPTH_TEST);
  107. }
  108. this._isDepthTestDirty = false;
  109. }
  110. // Depth func
  111. if (this._isDepthFuncDirty) {
  112. gl.depthFunc(this.depthFunc);
  113. this._isDepthFuncDirty = false;
  114. }
  115. }
  116. }
  117. export class _AlphaState {
  118. private _isAlphaBlendDirty = false;
  119. private _isBlendFunctionParametersDirty = false;
  120. private _alphaBlend = false;
  121. private _blendFunctionParameters = new Array<number>(4);
  122. public get isDirty(): boolean {
  123. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  124. }
  125. public get alphaBlend(): boolean {
  126. return this._alphaBlend;
  127. }
  128. public set alphaBlend(value: boolean) {
  129. if (this._alphaBlend === value) {
  130. return;
  131. }
  132. this._alphaBlend = value;
  133. this._isAlphaBlendDirty = true;
  134. }
  135. public setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void {
  136. if (
  137. this._blendFunctionParameters[0] === value0 &&
  138. this._blendFunctionParameters[1] === value1 &&
  139. this._blendFunctionParameters[2] === value2 &&
  140. this._blendFunctionParameters[3] === value3
  141. ) {
  142. return;
  143. }
  144. this._blendFunctionParameters[0] = value0;
  145. this._blendFunctionParameters[1] = value1;
  146. this._blendFunctionParameters[2] = value2;
  147. this._blendFunctionParameters[3] = value3;
  148. this._isBlendFunctionParametersDirty = true;
  149. }
  150. public reset() {
  151. this._alphaBlend = false;
  152. this._blendFunctionParameters[0] = null;
  153. this._blendFunctionParameters[1] = null;
  154. this._blendFunctionParameters[2] = null;
  155. this._blendFunctionParameters[3] = null;
  156. this._isAlphaBlendDirty = true;
  157. this._isBlendFunctionParametersDirty = false;
  158. }
  159. public apply(gl: WebGLRenderingContext) {
  160. if (!this.isDirty) {
  161. return;
  162. }
  163. // Alpha blend
  164. if (this._isAlphaBlendDirty) {
  165. if (this._alphaBlend) {
  166. gl.enable(gl.BLEND);
  167. } else {
  168. gl.disable(gl.BLEND);
  169. }
  170. this._isAlphaBlendDirty = false;
  171. }
  172. // Alpha function
  173. if (this._isBlendFunctionParametersDirty) {
  174. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  175. this._isBlendFunctionParametersDirty = false;
  176. }
  177. }
  178. }
  179. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  180. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  181. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  182. gl.compileShader(shader);
  183. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  184. throw new Error(gl.getShaderInfoLog(shader));
  185. }
  186. return shader;
  187. };
  188. var getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  189. var textureType = gl.UNSIGNED_BYTE;
  190. if (type === Engine.TEXTURETYPE_FLOAT)
  191. textureType = gl.FLOAT;
  192. return textureType;
  193. };
  194. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  195. var magFilter = gl.NEAREST;
  196. var minFilter = gl.NEAREST;
  197. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  198. magFilter = gl.LINEAR;
  199. if (generateMipMaps) {
  200. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  201. } else {
  202. minFilter = gl.LINEAR;
  203. }
  204. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  205. magFilter = gl.LINEAR;
  206. if (generateMipMaps) {
  207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  208. } else {
  209. minFilter = gl.LINEAR;
  210. }
  211. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  212. magFilter = gl.NEAREST;
  213. if (generateMipMaps) {
  214. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  215. } else {
  216. minFilter = gl.NEAREST;
  217. }
  218. }
  219. return {
  220. min: minFilter,
  221. mag: magFilter
  222. }
  223. }
  224. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  225. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  226. var engine = scene.getEngine();
  227. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  228. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  229. gl.bindTexture(gl.TEXTURE_2D, texture);
  230. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  231. processFunction(potWidth, potHeight);
  232. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  235. if (!noMipmap && !isCompressed) {
  236. gl.generateMipmap(gl.TEXTURE_2D);
  237. }
  238. gl.bindTexture(gl.TEXTURE_2D, null);
  239. engine._activeTexturesCache = [];
  240. texture._baseWidth = width;
  241. texture._baseHeight = height;
  242. texture._width = potWidth;
  243. texture._height = potHeight;
  244. texture.isReady = true;
  245. texture.samplingMode = samplingMode;
  246. scene._removePendingData(texture);
  247. };
  248. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  249. onfinish: (images: HTMLImageElement[]) => void) => {
  250. var onload = () => {
  251. loadedImages[index] = img;
  252. loadedImages._internalCount++;
  253. scene._removePendingData(img);
  254. if (loadedImages._internalCount === 6) {
  255. onfinish(loadedImages);
  256. }
  257. };
  258. var onerror = () => {
  259. scene._removePendingData(img);
  260. };
  261. var img = Tools.LoadImage(url, onload, onerror, scene.database);
  262. scene._addPendingData(img);
  263. }
  264. var cascadeLoad = (rootUrl: string, scene,
  265. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  266. var loadedImages: any = [];
  267. loadedImages._internalCount = 0;
  268. for (var index = 0; index < 6; index++) {
  269. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  270. }
  271. };
  272. export class EngineCapabilities {
  273. public maxTexturesImageUnits: number;
  274. public maxTextureSize: number;
  275. public maxCubemapTextureSize: number;
  276. public maxRenderTextureSize: number;
  277. public standardDerivatives: boolean;
  278. public s3tc;
  279. public textureFloat: boolean;
  280. public textureAnisotropicFilterExtension;
  281. public maxAnisotropy: number;
  282. public instancedArrays;
  283. public uintIndices: boolean;
  284. }
  285. export class Engine {
  286. // Const statics
  287. private static _ALPHA_DISABLE = 0;
  288. private static _ALPHA_ADD = 1;
  289. private static _ALPHA_COMBINE = 2;
  290. private static _DELAYLOADSTATE_NONE = 0;
  291. private static _DELAYLOADSTATE_LOADED = 1;
  292. private static _DELAYLOADSTATE_LOADING = 2;
  293. private static _DELAYLOADSTATE_NOTLOADED = 4;
  294. private static _TEXTUREFORMAT_ALPHA = 0;
  295. private static _TEXTUREFORMAT_LUMINANCE = 1;
  296. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  297. private static _TEXTUREFORMAT_RGB = 4;
  298. private static _TEXTUREFORMAT_RGBA = 4;
  299. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  300. private static _TEXTURETYPE_FLOAT = 1;
  301. public static get ALPHA_DISABLE(): number {
  302. return Engine._ALPHA_DISABLE;
  303. }
  304. public static get ALPHA_ADD(): number {
  305. return Engine._ALPHA_ADD;
  306. }
  307. public static get ALPHA_COMBINE(): number {
  308. return Engine._ALPHA_COMBINE;
  309. }
  310. public static get DELAYLOADSTATE_NONE(): number {
  311. return Engine._DELAYLOADSTATE_NONE;
  312. }
  313. public static get DELAYLOADSTATE_LOADED(): number {
  314. return Engine._DELAYLOADSTATE_LOADED;
  315. }
  316. public static get DELAYLOADSTATE_LOADING(): number {
  317. return Engine._DELAYLOADSTATE_LOADING;
  318. }
  319. public static get DELAYLOADSTATE_NOTLOADED(): number {
  320. return Engine._DELAYLOADSTATE_NOTLOADED;
  321. }
  322. public static get TEXTUREFORMAT_ALPHA(): number {
  323. return Engine._TEXTUREFORMAT_ALPHA;
  324. }
  325. public static get TEXTUREFORMAT_LUMINANCE(): number {
  326. return Engine._TEXTUREFORMAT_LUMINANCE;
  327. }
  328. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  329. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  330. }
  331. public static get TEXTUREFORMAT_RGB(): number {
  332. return Engine._TEXTUREFORMAT_RGB;
  333. }
  334. public static get TEXTUREFORMAT_RGBA(): number {
  335. return Engine._TEXTUREFORMAT_RGBA;
  336. }
  337. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  338. return Engine._TEXTURETYPE_UNSIGNED_INT;
  339. }
  340. public static get TEXTURETYPE_FLOAT(): number {
  341. return Engine._TEXTURETYPE_FLOAT;
  342. }
  343. public static get Version(): string {
  344. return "2.0.0";
  345. }
  346. // Updatable statics so stick with vars here
  347. public static Epsilon = 0.001;
  348. public static CollisionsEpsilon = 0.001;
  349. public static ShadersRepository = "Babylon/Shaders/";
  350. // Public members
  351. public isFullscreen = false;
  352. public isPointerLock = false;
  353. public cullBackFaces = true;
  354. public renderEvenInBackground = true;
  355. public scenes = new Array<Scene>();
  356. // Private Members
  357. public _gl: WebGLRenderingContext;
  358. private _renderingCanvas: HTMLCanvasElement;
  359. private _windowIsBackground = false;
  360. private _audioEngine: AudioEngine;
  361. private _onBlur: () => void;
  362. private _onFocus: () => void;
  363. private _onFullscreenChange: () => void;
  364. private _onPointerLockChange: () => void;
  365. private _hardwareScalingLevel: number;
  366. private _caps: EngineCapabilities;
  367. private _pointerLockRequested: boolean;
  368. private _alphaTest: boolean;
  369. private _resizeLoadingUI: () => void;
  370. private _loadingDiv: HTMLDivElement;
  371. private _loadingTextDiv: HTMLDivElement;
  372. private _loadingDivBackgroundColor = "black";
  373. private _drawCalls = 0;
  374. private _glVersion: string;
  375. private _glRenderer: string;
  376. private _glVendor: string;
  377. private _renderingQueueLaunched = false;
  378. private _activeRenderLoops = [];
  379. // FPS
  380. private fpsRange = 60;
  381. private previousFramesDuration = [];
  382. private fps = 60;
  383. private deltaTime = 0;
  384. // States
  385. private _depthCullingState = new _DepthCullingState();
  386. private _alphaState = new _AlphaState();
  387. private _alphaMode = Engine.ALPHA_DISABLE;
  388. // Cache
  389. private _loadedTexturesCache = new Array<WebGLTexture>();
  390. public _activeTexturesCache = new Array<BaseTexture>();
  391. private _currentEffect: Effect;
  392. private _compiledEffects = {};
  393. private _vertexAttribArrays: boolean[];
  394. private _cachedViewport: Viewport;
  395. private _cachedVertexBuffers: any;
  396. private _cachedIndexBuffer: WebGLBuffer;
  397. private _cachedEffectForVertexBuffers: Effect;
  398. private _currentRenderTarget: WebGLTexture;
  399. private _canvasClientRect: ClientRect;
  400. private _uintIndicesCurrentlySet = false;
  401. private _workingCanvas: HTMLCanvasElement;
  402. private _workingContext: CanvasRenderingContext2D;
  403. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  404. this._renderingCanvas = canvas;
  405. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  406. options = options || {};
  407. options.antialias = antialias;
  408. // GL
  409. try {
  410. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  411. } catch (e) {
  412. throw new Error("WebGL not supported");
  413. }
  414. if (!this._gl) {
  415. throw new Error("WebGL not supported");
  416. }
  417. this._onBlur = () => {
  418. this._windowIsBackground = true;
  419. };
  420. this._onFocus = () => {
  421. this._windowIsBackground = false;
  422. };
  423. window.addEventListener("blur", this._onBlur);
  424. window.addEventListener("focus", this._onFocus);
  425. // Textures
  426. this._workingCanvas = document.createElement("canvas");
  427. this._workingContext = this._workingCanvas.getContext("2d");
  428. // Viewport
  429. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  430. this.resize();
  431. // Caps
  432. this._caps = new EngineCapabilities();
  433. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  434. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  435. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  436. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  437. // Infos
  438. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  439. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  440. if (rendererInfo != null) {
  441. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  442. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  443. }
  444. if (!this._glVendor) {
  445. this._glVendor = "Unknown vendor";
  446. }
  447. if (!this._glRenderer) {
  448. this._glRenderer = "Unknown renderer";
  449. }
  450. // Extensions
  451. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  452. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  453. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  454. 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');
  455. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  456. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  457. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  458. // Depth buffer
  459. this.setDepthBuffer(true);
  460. this.setDepthFunctionToLessOrEqual();
  461. this.setDepthWrite(true);
  462. // Fullscreen
  463. this._onFullscreenChange = () => {
  464. if (document.fullscreen !== undefined) {
  465. this.isFullscreen = document.fullscreen;
  466. } else if (document.mozFullScreen !== undefined) {
  467. this.isFullscreen = document.mozFullScreen;
  468. } else if (document.webkitIsFullScreen !== undefined) {
  469. this.isFullscreen = document.webkitIsFullScreen;
  470. } else if (document.msIsFullScreen !== undefined) {
  471. this.isFullscreen = document.msIsFullScreen;
  472. }
  473. // Pointer lock
  474. if (this.isFullscreen && this._pointerLockRequested) {
  475. canvas.requestPointerLock = canvas.requestPointerLock ||
  476. canvas.msRequestPointerLock ||
  477. canvas.mozRequestPointerLock ||
  478. canvas.webkitRequestPointerLock;
  479. if (canvas.requestPointerLock) {
  480. canvas.requestPointerLock();
  481. }
  482. }
  483. };
  484. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  485. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  486. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  487. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  488. // Pointer lock
  489. this._onPointerLockChange = () => {
  490. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  491. document.webkitPointerLockElement === canvas ||
  492. document.msPointerLockElement === canvas ||
  493. document.pointerLockElement === canvas
  494. );
  495. };
  496. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  497. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  498. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  499. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  500. this._audioEngine = new AudioEngine();
  501. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  502. }
  503. public getGlInfo() {
  504. return {
  505. vendor: this._glVendor,
  506. renderer: this._glRenderer,
  507. version: this._glVersion
  508. }
  509. }
  510. public getAudioEngine(): AudioEngine {
  511. return this._audioEngine;
  512. }
  513. public getAspectRatio(camera: Camera): number {
  514. var viewport = camera.viewport;
  515. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  516. }
  517. public getRenderWidth(): number {
  518. if (this._currentRenderTarget) {
  519. return this._currentRenderTarget._width;
  520. }
  521. return this._renderingCanvas.width;
  522. }
  523. public getRenderHeight(): number {
  524. if (this._currentRenderTarget) {
  525. return this._currentRenderTarget._height;
  526. }
  527. return this._renderingCanvas.height;
  528. }
  529. public getRenderingCanvas(): HTMLCanvasElement {
  530. return this._renderingCanvas;
  531. }
  532. public getRenderingCanvasClientRect(): ClientRect {
  533. return this._renderingCanvas.getBoundingClientRect();
  534. }
  535. public setHardwareScalingLevel(level: number): void {
  536. this._hardwareScalingLevel = level;
  537. this.resize();
  538. }
  539. public getHardwareScalingLevel(): number {
  540. return this._hardwareScalingLevel;
  541. }
  542. public getLoadedTexturesCache(): WebGLTexture[] {
  543. return this._loadedTexturesCache;
  544. }
  545. public getCaps(): EngineCapabilities {
  546. return this._caps;
  547. }
  548. public get drawCalls(): number {
  549. return this._drawCalls;
  550. }
  551. // Methods
  552. public resetDrawCalls(): void {
  553. this._drawCalls = 0;
  554. }
  555. public setDepthFunctionToGreater(): void {
  556. this._depthCullingState.depthFunc = this._gl.GREATER;
  557. }
  558. public setDepthFunctionToGreaterOrEqual(): void {
  559. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  560. }
  561. public setDepthFunctionToLess(): void {
  562. this._depthCullingState.depthFunc = this._gl.LESS;
  563. }
  564. public setDepthFunctionToLessOrEqual(): void {
  565. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  566. }
  567. public stopRenderLoop(renderFunction?: () => void): void {
  568. if (!renderFunction) {
  569. this._activeRenderLoops = [];
  570. return;
  571. }
  572. var index = this._activeRenderLoops.indexOf(renderFunction);
  573. if (index >= 0) {
  574. this._activeRenderLoops.splice(index, 1);
  575. }
  576. }
  577. public _renderLoop(): void {
  578. var shouldRender = true;
  579. if (!this.renderEvenInBackground && this._windowIsBackground) {
  580. shouldRender = false;
  581. }
  582. if (shouldRender) {
  583. // Start new frame
  584. this.beginFrame();
  585. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  586. var renderFunction = this._activeRenderLoops[index];
  587. renderFunction();
  588. }
  589. // Present
  590. this.endFrame();
  591. }
  592. if (this._activeRenderLoops.length > 0) {
  593. // Register new frame
  594. Tools.QueueNewFrame(() => {
  595. this._renderLoop();
  596. });
  597. } else {
  598. this._renderingQueueLaunched = false;
  599. }
  600. }
  601. public runRenderLoop(renderFunction: () => void): void {
  602. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  603. return;
  604. }
  605. this._activeRenderLoops.push(renderFunction);
  606. if (!this._renderingQueueLaunched) {
  607. this._renderingQueueLaunched = true;
  608. Tools.QueueNewFrame(() => {
  609. this._renderLoop();
  610. });
  611. }
  612. }
  613. public switchFullscreen(requestPointerLock: boolean): void {
  614. if (this.isFullscreen) {
  615. Tools.ExitFullscreen();
  616. } else {
  617. this._pointerLockRequested = requestPointerLock;
  618. Tools.RequestFullscreen(this._renderingCanvas);
  619. }
  620. }
  621. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  622. this.applyStates();
  623. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  624. if (this._depthCullingState.depthMask) {
  625. this._gl.clearDepth(1.0);
  626. }
  627. var mode = 0;
  628. if (backBuffer)
  629. mode |= this._gl.COLOR_BUFFER_BIT;
  630. if (depthStencil && this._depthCullingState.depthMask)
  631. mode |= this._gl.DEPTH_BUFFER_BIT;
  632. this._gl.clear(mode);
  633. }
  634. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  635. var width = requiredWidth || this._renderingCanvas.width;
  636. var height = requiredHeight || this._renderingCanvas.height;
  637. var x = viewport.x || 0;
  638. var y = viewport.y || 0;
  639. this._cachedViewport = viewport;
  640. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  641. }
  642. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  643. this._cachedViewport = null;
  644. this._gl.viewport(x, y, width, height);
  645. }
  646. public beginFrame(): void {
  647. this._measureFps();
  648. }
  649. public endFrame(): void {
  650. this.flushFramebuffer();
  651. }
  652. public resize(): void {
  653. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  654. }
  655. public setSize(width: number, height: number): void {
  656. this._renderingCanvas.width = width;
  657. this._renderingCanvas.height = height;
  658. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  659. }
  660. public bindFramebuffer(texture: WebGLTexture): void {
  661. this._currentRenderTarget = texture;
  662. var gl = this._gl;
  663. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  664. this._gl.viewport(0, 0, texture._width, texture._height);
  665. this.wipeCaches();
  666. }
  667. public unBindFramebuffer(texture: WebGLTexture): void {
  668. this._currentRenderTarget = null;
  669. if (texture.generateMipMaps) {
  670. var gl = this._gl;
  671. gl.bindTexture(gl.TEXTURE_2D, texture);
  672. gl.generateMipmap(gl.TEXTURE_2D);
  673. gl.bindTexture(gl.TEXTURE_2D, null);
  674. }
  675. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  676. }
  677. public flushFramebuffer(): void {
  678. // this._gl.flush();
  679. }
  680. public restoreDefaultFramebuffer(): void {
  681. this._currentRenderTarget = null;
  682. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  683. this.setViewport(this._cachedViewport);
  684. this.wipeCaches();
  685. }
  686. // VBOs
  687. private _resetVertexBufferBinding(): void {
  688. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  689. this._cachedVertexBuffers = null;
  690. }
  691. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  692. var vbo = this._gl.createBuffer();
  693. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  694. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  695. this._resetVertexBufferBinding();
  696. vbo.references = 1;
  697. return vbo;
  698. }
  699. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  700. var vbo = this._gl.createBuffer();
  701. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  702. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  703. this._resetVertexBufferBinding();
  704. vbo.references = 1;
  705. return vbo;
  706. }
  707. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  708. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  709. if (offset === undefined) {
  710. offset = 0;
  711. }
  712. if (vertices instanceof Float32Array) {
  713. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  714. } else {
  715. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  716. }
  717. this._resetVertexBufferBinding();
  718. }
  719. private _resetIndexBufferBinding(): void {
  720. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  721. this._cachedIndexBuffer = null;
  722. }
  723. public createIndexBuffer(indices: number[]): WebGLBuffer {
  724. var vbo = this._gl.createBuffer();
  725. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  726. // Check for 32 bits indices
  727. var arrayBuffer;
  728. var need32Bits = false;
  729. if (this._caps.uintIndices) {
  730. for (var index = 0; index < indices.length; index++) {
  731. if (indices[index] > 65535) {
  732. need32Bits = true;
  733. break;
  734. }
  735. }
  736. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  737. } else {
  738. arrayBuffer = new Uint16Array(indices);
  739. }
  740. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  741. this._resetIndexBufferBinding();
  742. vbo.references = 1;
  743. vbo.is32Bits = need32Bits;
  744. return vbo;
  745. }
  746. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  747. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  748. this._cachedVertexBuffers = vertexBuffer;
  749. this._cachedEffectForVertexBuffers = effect;
  750. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  751. var offset = 0;
  752. for (var index = 0; index < vertexDeclaration.length; index++) {
  753. var order = effect.getAttributeLocation(index);
  754. if (order >= 0) {
  755. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  756. }
  757. offset += vertexDeclaration[index] * 4;
  758. }
  759. }
  760. if (this._cachedIndexBuffer !== indexBuffer) {
  761. this._cachedIndexBuffer = indexBuffer;
  762. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  763. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  764. }
  765. }
  766. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  767. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  768. this._cachedVertexBuffers = vertexBuffers;
  769. this._cachedEffectForVertexBuffers = effect;
  770. var attributes = effect.getAttributesNames();
  771. for (var index = 0; index < attributes.length; index++) {
  772. var order = effect.getAttributeLocation(index);
  773. if (order >= 0) {
  774. var vertexBuffer = vertexBuffers[attributes[index]];
  775. if (!vertexBuffer) {
  776. continue;
  777. }
  778. var stride = vertexBuffer.getStrideSize();
  779. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  780. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  781. }
  782. }
  783. }
  784. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  785. this._cachedIndexBuffer = indexBuffer;
  786. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  787. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  788. }
  789. }
  790. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  791. buffer.references--;
  792. if (buffer.references === 0) {
  793. this._gl.deleteBuffer(buffer);
  794. return true;
  795. }
  796. return false;
  797. }
  798. public createInstancesBuffer(capacity: number): WebGLBuffer {
  799. var buffer = this._gl.createBuffer();
  800. buffer.capacity = capacity;
  801. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  802. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  803. return buffer;
  804. }
  805. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  806. this._gl.deleteBuffer(buffer);
  807. }
  808. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  809. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  811. for (var index = 0; index < 4; index++) {
  812. var offsetLocation = offsetLocations[index];
  813. this._gl.enableVertexAttribArray(offsetLocation);
  814. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  815. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  816. }
  817. }
  818. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  819. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  820. for (var index = 0; index < 4; index++) {
  821. var offsetLocation = offsetLocations[index];
  822. this._gl.disableVertexAttribArray(offsetLocation);
  823. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  824. }
  825. }
  826. public applyStates() {
  827. this._depthCullingState.apply(this._gl);
  828. this._alphaState.apply(this._gl);
  829. }
  830. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  831. // Apply states
  832. this.applyStates();
  833. this._drawCalls++;
  834. // Render
  835. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  836. if (instancesCount) {
  837. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  838. return;
  839. }
  840. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  841. }
  842. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  843. // Apply states
  844. this.applyStates();
  845. this._drawCalls++;
  846. if (instancesCount) {
  847. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  848. return;
  849. }
  850. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  851. }
  852. // Shaders
  853. public _releaseEffect(effect: Effect): void {
  854. if (this._compiledEffects[effect._key]) {
  855. delete this._compiledEffects[effect._key];
  856. if (effect.getProgram()) {
  857. this._gl.deleteProgram(effect.getProgram());
  858. }
  859. }
  860. }
  861. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  862. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  863. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  864. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  865. var name = vertex + "+" + fragment + "@" + defines;
  866. if (this._compiledEffects[name]) {
  867. return this._compiledEffects[name];
  868. }
  869. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  870. effect._key = name;
  871. this._compiledEffects[name] = effect;
  872. return effect;
  873. }
  874. public createEffectForParticles(fragmentName: string, uniformsNames: string[]= [], samplers: string[]= [], defines = "", fallbacks?: EffectFallbacks,
  875. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  876. return this.createEffect(
  877. {
  878. vertex: "particles",
  879. fragmentElement: fragmentName
  880. },
  881. ["position", "color", "options"],
  882. ["view", "projection"].concat(uniformsNames),
  883. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  884. }
  885. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  886. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  887. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  888. var shaderProgram = this._gl.createProgram();
  889. this._gl.attachShader(shaderProgram, vertexShader);
  890. this._gl.attachShader(shaderProgram, fragmentShader);
  891. this._gl.linkProgram(shaderProgram);
  892. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  893. if (!linked) {
  894. var error = this._gl.getProgramInfoLog(shaderProgram);
  895. if (error) {
  896. throw new Error(error);
  897. }
  898. }
  899. this._gl.deleteShader(vertexShader);
  900. this._gl.deleteShader(fragmentShader);
  901. return shaderProgram;
  902. }
  903. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  904. var results = [];
  905. for (var index = 0; index < uniformsNames.length; index++) {
  906. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  907. }
  908. return results;
  909. }
  910. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  911. var results = [];
  912. for (var index = 0; index < attributesNames.length; index++) {
  913. try {
  914. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  915. } catch (e) {
  916. results.push(-1);
  917. }
  918. }
  919. return results;
  920. }
  921. public enableEffect(effect: Effect): void {
  922. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  923. if (effect && effect.onBind) {
  924. effect.onBind(effect);
  925. }
  926. return;
  927. }
  928. this._vertexAttribArrays = this._vertexAttribArrays || [];
  929. // Use program
  930. this._gl.useProgram(effect.getProgram());
  931. for (var i in this._vertexAttribArrays) {
  932. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  933. continue;
  934. }
  935. this._vertexAttribArrays[i] = false;
  936. this._gl.disableVertexAttribArray(i);
  937. }
  938. var attributesCount = effect.getAttributesCount();
  939. for (var index = 0; index < attributesCount; index++) {
  940. // Attributes
  941. var order = effect.getAttributeLocation(index);
  942. if (order >= 0) {
  943. this._vertexAttribArrays[order] = true;
  944. this._gl.enableVertexAttribArray(order);
  945. }
  946. }
  947. this._currentEffect = effect;
  948. if (effect.onBind) {
  949. effect.onBind(effect);
  950. }
  951. }
  952. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  953. if (!uniform)
  954. return;
  955. this._gl.uniform1fv(uniform, array);
  956. }
  957. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  958. if (!uniform)
  959. return;
  960. this._gl.uniformMatrix4fv(uniform, false, matrices);
  961. }
  962. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  963. if (!uniform)
  964. return;
  965. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  966. }
  967. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  968. if (!uniform)
  969. return;
  970. this._gl.uniform1f(uniform, value);
  971. }
  972. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  973. if (!uniform)
  974. return;
  975. this._gl.uniform2f(uniform, x, y);
  976. }
  977. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  978. if (!uniform)
  979. return;
  980. this._gl.uniform3f(uniform, x, y, z);
  981. }
  982. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  983. if (!uniform)
  984. return;
  985. this._gl.uniform1i(uniform, bool);
  986. }
  987. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  988. if (!uniform)
  989. return;
  990. this._gl.uniform4f(uniform, x, y, z, w);
  991. }
  992. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  993. if (!uniform)
  994. return;
  995. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  996. }
  997. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  998. if (!uniform)
  999. return;
  1000. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1001. }
  1002. // States
  1003. public setState(culling: boolean, force?: boolean): void {
  1004. // Culling
  1005. if (this._depthCullingState.cull !== culling || force) {
  1006. if (culling) {
  1007. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1008. this._depthCullingState.cull = true;
  1009. } else {
  1010. this._depthCullingState.cull = false;
  1011. }
  1012. }
  1013. }
  1014. public setDepthBuffer(enable: boolean): void {
  1015. this._depthCullingState.depthTest = enable;
  1016. }
  1017. public getDepthWrite(): boolean {
  1018. return this._depthCullingState.depthMask;
  1019. }
  1020. public setDepthWrite(enable: boolean): void {
  1021. this._depthCullingState.depthMask = enable;
  1022. }
  1023. public setColorWrite(enable: boolean): void {
  1024. this._gl.colorMask(enable, enable, enable, enable);
  1025. }
  1026. public setAlphaMode(mode: number): void {
  1027. switch (mode) {
  1028. case Engine.ALPHA_DISABLE:
  1029. this.setDepthWrite(true);
  1030. this._alphaState.alphaBlend = false;
  1031. break;
  1032. case Engine.ALPHA_COMBINE:
  1033. this.setDepthWrite(false);
  1034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1035. this._alphaState.alphaBlend = true;
  1036. break;
  1037. case Engine.ALPHA_ADD:
  1038. this.setDepthWrite(false);
  1039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1040. this._alphaState.alphaBlend = true;
  1041. break;
  1042. }
  1043. this._alphaMode = mode;
  1044. }
  1045. public getAlphaMode(): number {
  1046. return this._alphaMode;
  1047. }
  1048. public setAlphaTesting(enable: boolean): void {
  1049. this._alphaTest = enable;
  1050. }
  1051. public getAlphaTesting(): boolean {
  1052. return this._alphaTest;
  1053. }
  1054. // Textures
  1055. public wipeCaches(): void {
  1056. this._activeTexturesCache = [];
  1057. this._currentEffect = null;
  1058. this._depthCullingState.reset();
  1059. this._alphaState.reset();
  1060. this._cachedVertexBuffers = null;
  1061. this._cachedIndexBuffer = null;
  1062. this._cachedEffectForVertexBuffers = null;
  1063. }
  1064. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1065. var gl = this._gl;
  1066. gl.bindTexture(gl.TEXTURE_2D, texture);
  1067. var magFilter = gl.NEAREST;
  1068. var minFilter = gl.NEAREST;
  1069. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1070. magFilter = gl.LINEAR;
  1071. minFilter = gl.LINEAR;
  1072. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1073. magFilter = gl.LINEAR;
  1074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1075. }
  1076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1078. gl.bindTexture(gl.TEXTURE_2D, null);
  1079. texture.samplingMode = samplingMode;
  1080. }
  1081. 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 {
  1082. var texture = this._gl.createTexture();
  1083. var extension: string;
  1084. var fromData: any = false;
  1085. if (url.substr(0, 5) === "data:") {
  1086. fromData = true;
  1087. }
  1088. if (!fromData)
  1089. extension = url.substr(url.length - 4, 4).toLowerCase();
  1090. else {
  1091. var oldUrl = url;
  1092. fromData = oldUrl.split(':');
  1093. url = oldUrl;
  1094. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1095. }
  1096. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1097. var isTGA = (extension === ".tga");
  1098. scene._addPendingData(texture);
  1099. texture.url = url;
  1100. texture.noMipmap = noMipmap;
  1101. texture.references = 1;
  1102. this._loadedTexturesCache.push(texture);
  1103. var onerror = () => {
  1104. scene._removePendingData(texture);
  1105. if (onError) {
  1106. onError();
  1107. }
  1108. };
  1109. if (isTGA) {
  1110. var callback = (arrayBuffer) => {
  1111. var data = new Uint8Array(arrayBuffer);
  1112. var header = Internals.TGATools.GetTGAHeader(data);
  1113. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1114. Internals.TGATools.UploadContent(this._gl, data);
  1115. if (onLoad) {
  1116. onLoad();
  1117. }
  1118. }, samplingMode);
  1119. };
  1120. if (!(fromData instanceof Array))
  1121. Tools.LoadFile(url, arrayBuffer => {
  1122. callback(arrayBuffer);
  1123. }, onerror, scene.database, true);
  1124. else
  1125. callback(buffer);
  1126. } else if (isDDS) {
  1127. callback = (data) => {
  1128. var info = Internals.DDSTools.GetDDSInfo(data);
  1129. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1130. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1131. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1132. if (onLoad) {
  1133. onLoad();
  1134. }
  1135. }, samplingMode);
  1136. };
  1137. if (!(fromData instanceof Array))
  1138. Tools.LoadFile(url, data => {
  1139. callback(data);
  1140. }, onerror, scene.database, true);
  1141. else
  1142. callback(buffer);
  1143. } else {
  1144. var onload = (img) => {
  1145. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1146. var isPot = (img.width === potWidth && img.height === potHeight);
  1147. if (!isPot) {
  1148. this._workingCanvas.width = potWidth;
  1149. this._workingCanvas.height = potHeight;
  1150. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1151. this._workingContext.imageSmoothingEnabled = false;
  1152. this._workingContext.mozImageSmoothingEnabled = false;
  1153. this._workingContext.oImageSmoothingEnabled = false;
  1154. this._workingContext.webkitImageSmoothingEnabled = false;
  1155. this._workingContext.msImageSmoothingEnabled = false;
  1156. }
  1157. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1158. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1159. this._workingContext.imageSmoothingEnabled = true;
  1160. this._workingContext.mozImageSmoothingEnabled = true;
  1161. this._workingContext.oImageSmoothingEnabled = true;
  1162. this._workingContext.webkitImageSmoothingEnabled = true;
  1163. this._workingContext.msImageSmoothingEnabled = true;
  1164. }
  1165. }
  1166. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1167. if (onLoad) {
  1168. onLoad();
  1169. }
  1170. }, samplingMode);
  1171. };
  1172. if (!(fromData instanceof Array))
  1173. Tools.LoadImage(url, onload, onerror, scene.database);
  1174. else
  1175. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1176. }
  1177. return texture;
  1178. }
  1179. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number): WebGLTexture {
  1180. var texture = this._gl.createTexture();
  1181. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1182. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1183. // Format
  1184. var internalFormat = this._gl.RGBA;
  1185. switch (format) {
  1186. case Engine.TEXTUREFORMAT_ALPHA:
  1187. internalFormat = this._gl.ALPHA;
  1188. break;
  1189. case Engine.TEXTUREFORMAT_LUMINANCE:
  1190. internalFormat = this._gl.LUMINANCE;
  1191. break;
  1192. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1193. internalFormat = this._gl.LUMINANCE_ALPHA;
  1194. break;
  1195. case Engine.TEXTUREFORMAT_RGB:
  1196. internalFormat = this._gl.RGB;
  1197. break;
  1198. case Engine.TEXTUREFORMAT_RGBA:
  1199. internalFormat = this._gl.RGBA;
  1200. break;
  1201. }
  1202. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1203. if (generateMipMaps) {
  1204. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1205. }
  1206. // Filters
  1207. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1210. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1211. this._activeTexturesCache = [];
  1212. texture._baseWidth = width;
  1213. texture._baseHeight = height;
  1214. texture._width = width;
  1215. texture._height = height;
  1216. texture.isReady = true;
  1217. texture.references = 1;
  1218. texture.samplingMode = samplingMode;
  1219. this._loadedTexturesCache.push(texture);
  1220. return texture;
  1221. }
  1222. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1223. var texture = this._gl.createTexture();
  1224. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1225. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1226. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1227. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1228. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1229. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1230. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1231. this._activeTexturesCache = [];
  1232. texture._baseWidth = width;
  1233. texture._baseHeight = height;
  1234. texture._width = width;
  1235. texture._height = height;
  1236. texture.isReady = false;
  1237. texture.generateMipMaps = generateMipMaps;
  1238. texture.references = 1;
  1239. texture.samplingMode = samplingMode;
  1240. this._loadedTexturesCache.push(texture);
  1241. return texture;
  1242. }
  1243. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1244. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1245. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1246. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1247. if (texture.generateMipMaps) {
  1248. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1249. }
  1250. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1251. this._activeTexturesCache = [];
  1252. texture.isReady = true;
  1253. }
  1254. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1255. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1256. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1257. // Scale the video if it is a NPOT using the current working canvas
  1258. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1259. if (!texture._workingCanvas) {
  1260. texture._workingCanvas = document.createElement("canvas");
  1261. texture._workingContext = texture._workingCanvas.getContext("2d");
  1262. texture._workingCanvas.width = texture._width;
  1263. texture._workingCanvas.height = texture._height;
  1264. }
  1265. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1266. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1267. } else {
  1268. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1269. }
  1270. if (texture.generateMipMaps) {
  1271. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1272. }
  1273. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1274. this._activeTexturesCache = [];
  1275. texture.isReady = true;
  1276. }
  1277. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1278. // old version had a "generateMipMaps" arg instead of options.
  1279. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1280. // in the same way, generateDepthBuffer is defaulted to true
  1281. var generateMipMaps = false;
  1282. var generateDepthBuffer = true;
  1283. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1284. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1285. if (options !== undefined) {
  1286. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1287. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1288. type = options.type === undefined ? type : options.type;
  1289. if (options.samplingMode !== undefined) {
  1290. samplingMode = options.samplingMode;
  1291. }
  1292. if (type === Engine.TEXTURETYPE_FLOAT) {
  1293. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1294. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1295. }
  1296. }
  1297. var gl = this._gl;
  1298. var texture = gl.createTexture();
  1299. gl.bindTexture(gl.TEXTURE_2D, texture);
  1300. var width = size.width || size;
  1301. var height = size.height || size;
  1302. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1303. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1304. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1305. Tools.Warn("Floating point not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1306. }
  1307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1311. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1312. var depthBuffer: WebGLRenderbuffer;
  1313. // Create the depth buffer
  1314. if (generateDepthBuffer) {
  1315. depthBuffer = gl.createRenderbuffer();
  1316. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1317. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1318. }
  1319. // Create the framebuffer
  1320. var framebuffer = gl.createFramebuffer();
  1321. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1322. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1323. if (generateDepthBuffer) {
  1324. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1325. }
  1326. // Unbind
  1327. gl.bindTexture(gl.TEXTURE_2D, null);
  1328. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1329. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1330. texture._framebuffer = framebuffer;
  1331. if (generateDepthBuffer) {
  1332. texture._depthBuffer = depthBuffer;
  1333. }
  1334. texture._width = width;
  1335. texture._height = height;
  1336. texture.isReady = true;
  1337. texture.generateMipMaps = generateMipMaps;
  1338. texture.references = 1;
  1339. texture.samplingMode = samplingMode;
  1340. this._activeTexturesCache = [];
  1341. this._loadedTexturesCache.push(texture);
  1342. return texture;
  1343. }
  1344. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1345. var gl = this._gl;
  1346. var texture = gl.createTexture();
  1347. texture.isCube = true;
  1348. texture.url = rootUrl;
  1349. texture.references = 1;
  1350. this._loadedTexturesCache.push(texture);
  1351. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1352. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1353. if (isDDS) {
  1354. Tools.LoadFile(rootUrl, data => {
  1355. var info = Internals.DDSTools.GetDDSInfo(data);
  1356. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1357. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1358. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1359. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1360. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1361. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1362. }
  1363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1367. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1368. this._activeTexturesCache = [];
  1369. texture._width = info.width;
  1370. texture._height = info.height;
  1371. texture.isReady = true;
  1372. }, null, null, true);
  1373. } else {
  1374. cascadeLoad(rootUrl, scene, imgs => {
  1375. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1376. var height = width;
  1377. this._workingCanvas.width = width;
  1378. this._workingCanvas.height = height;
  1379. var faces = [
  1380. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1381. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1382. ];
  1383. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1384. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1385. for (var index = 0; index < faces.length; index++) {
  1386. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1387. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1388. }
  1389. if (!noMipmap) {
  1390. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1391. }
  1392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1396. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1397. this._activeTexturesCache = [];
  1398. texture._width = width;
  1399. texture._height = height;
  1400. texture.isReady = true;
  1401. }, extensions);
  1402. }
  1403. return texture;
  1404. }
  1405. public _releaseTexture(texture: WebGLTexture): void {
  1406. var gl = this._gl;
  1407. if (texture._framebuffer) {
  1408. gl.deleteFramebuffer(texture._framebuffer);
  1409. }
  1410. if (texture._depthBuffer) {
  1411. gl.deleteRenderbuffer(texture._depthBuffer);
  1412. }
  1413. gl.deleteTexture(texture);
  1414. // Unbind channels
  1415. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1416. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1417. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1418. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1419. this._activeTexturesCache[channel] = null;
  1420. }
  1421. var index = this._loadedTexturesCache.indexOf(texture);
  1422. if (index !== -1) {
  1423. this._loadedTexturesCache.splice(index, 1);
  1424. }
  1425. }
  1426. public bindSamplers(effect: Effect): void {
  1427. this._gl.useProgram(effect.getProgram());
  1428. var samplers = effect.getSamplers();
  1429. for (var index = 0; index < samplers.length; index++) {
  1430. var uniform = effect.getUniform(samplers[index]);
  1431. this._gl.uniform1i(uniform, index);
  1432. }
  1433. this._currentEffect = null;
  1434. }
  1435. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1436. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1437. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1438. this._activeTexturesCache[channel] = null;
  1439. }
  1440. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1441. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1442. }
  1443. public setTexture(channel: number, texture: BaseTexture): void {
  1444. if (channel < 0) {
  1445. return;
  1446. }
  1447. // Not ready?
  1448. if (!texture || !texture.isReady()) {
  1449. if (this._activeTexturesCache[channel] != null) {
  1450. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1451. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1452. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1453. this._activeTexturesCache[channel] = null;
  1454. }
  1455. return;
  1456. }
  1457. // Video
  1458. if (texture instanceof VideoTexture) {
  1459. if ((<VideoTexture>texture).update()) {
  1460. this._activeTexturesCache[channel] = null;
  1461. }
  1462. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1463. texture.delayLoad();
  1464. return;
  1465. }
  1466. if (this._activeTexturesCache[channel] === texture) {
  1467. return;
  1468. }
  1469. this._activeTexturesCache[channel] = texture;
  1470. var internalTexture = texture.getInternalTexture();
  1471. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1472. if (internalTexture.isCube) {
  1473. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1474. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1475. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1476. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1477. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1478. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1479. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1480. }
  1481. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1482. } else {
  1483. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1484. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1485. internalTexture._cachedWrapU = texture.wrapU;
  1486. switch (texture.wrapU) {
  1487. case Texture.WRAP_ADDRESSMODE:
  1488. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1489. break;
  1490. case Texture.CLAMP_ADDRESSMODE:
  1491. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1492. break;
  1493. case Texture.MIRROR_ADDRESSMODE:
  1494. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1495. break;
  1496. }
  1497. }
  1498. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1499. internalTexture._cachedWrapV = texture.wrapV;
  1500. switch (texture.wrapV) {
  1501. case Texture.WRAP_ADDRESSMODE:
  1502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1503. break;
  1504. case Texture.CLAMP_ADDRESSMODE:
  1505. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1506. break;
  1507. case Texture.MIRROR_ADDRESSMODE:
  1508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1509. break;
  1510. }
  1511. }
  1512. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1513. }
  1514. }
  1515. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1516. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1517. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1518. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1519. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1520. }
  1521. }
  1522. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1523. var data = new Uint8Array(height * width * 4);
  1524. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1525. return data;
  1526. }
  1527. // Dispose
  1528. public dispose(): void {
  1529. this.hideLoadingUI();
  1530. this.stopRenderLoop();
  1531. // Release scenes
  1532. while (this.scenes.length) {
  1533. this.scenes[0].dispose();
  1534. }
  1535. // Release effects
  1536. for (var name in this._compiledEffects) {
  1537. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1538. }
  1539. // Unbind
  1540. for (var i in this._vertexAttribArrays) {
  1541. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1542. continue;
  1543. }
  1544. this._gl.disableVertexAttribArray(i);
  1545. }
  1546. // Events
  1547. window.removeEventListener("blur", this._onBlur);
  1548. window.removeEventListener("focus", this._onFocus);
  1549. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1550. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1551. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1552. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1553. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1554. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1555. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1556. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1557. }
  1558. // Loading screen
  1559. public displayLoadingUI(): void {
  1560. this._loadingDiv = document.createElement("div");
  1561. this._loadingDiv.style.opacity = "0";
  1562. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1563. // Loading text
  1564. this._loadingTextDiv = document.createElement("div");
  1565. this._loadingTextDiv.style.position = "absolute";
  1566. this._loadingTextDiv.style.left = "0";
  1567. this._loadingTextDiv.style.top = "50%";
  1568. this._loadingTextDiv.style.marginTop = "80px";
  1569. this._loadingTextDiv.style.width = "100%";
  1570. this._loadingTextDiv.style.height = "20px";
  1571. this._loadingTextDiv.style.fontFamily = "Arial";
  1572. this._loadingTextDiv.style.fontSize = "14px";
  1573. this._loadingTextDiv.style.color = "white";
  1574. this._loadingTextDiv.style.textAlign = "center";
  1575. this._loadingTextDiv.innerHTML = "Loading";
  1576. this._loadingDiv.appendChild(this._loadingTextDiv);
  1577. // Loading img
  1578. var imgBack = new Image();
  1579. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  1580. imgBack.style.position = "absolute";
  1581. imgBack.style.left = "50%";
  1582. imgBack.style.top = "50%";
  1583. imgBack.style.marginLeft = "-50px";
  1584. imgBack.style.marginTop = "-50px";
  1585. imgBack.style.transition = "transform 1.0s ease";
  1586. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1587. var deg = 360;
  1588. var onTransitionEnd = () => {
  1589. deg += 360;
  1590. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1591. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1592. }
  1593. imgBack.addEventListener("transitionend", onTransitionEnd);
  1594. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1595. this._loadingDiv.appendChild(imgBack);
  1596. // front image
  1597. var imgFront = new Image();
  1598. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  1599. imgFront.style.position = "absolute";
  1600. imgFront.style.left = "50%";
  1601. imgFront.style.top = "50%";
  1602. imgFront.style.marginLeft = "-50px";
  1603. imgFront.style.marginTop = "-50px";
  1604. this._loadingDiv.appendChild(imgFront);
  1605. // Resize
  1606. this._resizeLoadingUI = () => {
  1607. var canvasRect = this.getRenderingCanvasClientRect();
  1608. this._loadingDiv.style.position = "absolute";
  1609. this._loadingDiv.style.left = canvasRect.left + "px";
  1610. this._loadingDiv.style.top = canvasRect.top + "px";
  1611. this._loadingDiv.style.width = canvasRect.width + "px";
  1612. this._loadingDiv.style.height = canvasRect.height + "px";
  1613. }
  1614. this._resizeLoadingUI();
  1615. window.addEventListener("resize", this._resizeLoadingUI);
  1616. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1617. document.body.appendChild(this._loadingDiv);
  1618. setTimeout(() => {
  1619. this._loadingDiv.style.opacity = "1";
  1620. imgBack.style.transform = "rotateZ(360deg)";
  1621. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1622. }, 0);
  1623. }
  1624. public set loadingUIText(text: string) {
  1625. if (!this._loadingDiv) {
  1626. return;
  1627. }
  1628. this._loadingTextDiv.innerHTML = text;
  1629. }
  1630. public get loadingUIBackgroundColor(): string {
  1631. return this._loadingDivBackgroundColor;
  1632. }
  1633. public set loadingUIBackgroundColor(color: string) {
  1634. this._loadingDivBackgroundColor = color;
  1635. if (!this._loadingDiv) {
  1636. return;
  1637. }
  1638. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1639. }
  1640. public hideLoadingUI(): void {
  1641. if (!this._loadingDiv) {
  1642. return;
  1643. }
  1644. var onTransitionEnd = () => {
  1645. if (!this._loadingDiv) {
  1646. return;
  1647. }
  1648. document.body.removeChild(this._loadingDiv);
  1649. window.removeEventListener("resize", this._resizeLoadingUI);
  1650. this._loadingDiv = null;
  1651. }
  1652. this._loadingDiv.style.opacity = "0";
  1653. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1654. }
  1655. // FPS
  1656. public getFps(): number {
  1657. return this.fps;
  1658. }
  1659. public getDeltaTime(): number {
  1660. return this.deltaTime;
  1661. }
  1662. private _measureFps(): void {
  1663. this.previousFramesDuration.push(Tools.Now);
  1664. var length = this.previousFramesDuration.length;
  1665. if (length >= 2) {
  1666. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1667. }
  1668. if (length >= this.fpsRange) {
  1669. if (length > this.fpsRange) {
  1670. this.previousFramesDuration.splice(0, 1);
  1671. length = this.previousFramesDuration.length;
  1672. }
  1673. var sum = 0;
  1674. for (var id = 0; id < length - 1; id++) {
  1675. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1676. }
  1677. this.fps = 1000.0 / (sum / (length - 1));
  1678. }
  1679. }
  1680. // Statics
  1681. public static isSupported(): boolean {
  1682. try {
  1683. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1684. if (navigator.isCocoonJS) {
  1685. return true;
  1686. }
  1687. var tempcanvas = document.createElement("canvas");
  1688. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1689. return gl != null && !!window.WebGLRenderingContext;
  1690. } catch (e) {
  1691. return false;
  1692. }
  1693. }
  1694. }
  1695. }