babylon.engine.ts 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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 === true) {
  85. gl.enable(gl.CULL_FACE);
  86. } else if (this.cull === false) {
  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 === true) {
  104. gl.enable(gl.DEPTH_TEST);
  105. } else if (this.depthTest === false) {
  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 === true) {
  166. gl.enable(gl.BLEND);
  167. } else if (this._alphaBlend === false) {
  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 getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  189. var magFilter = gl.NEAREST;
  190. var minFilter = gl.NEAREST;
  191. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  192. magFilter = gl.LINEAR;
  193. if (generateMipMaps) {
  194. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  195. } else {
  196. minFilter = gl.LINEAR;
  197. }
  198. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  199. magFilter = gl.LINEAR;
  200. if (generateMipMaps) {
  201. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  202. } else {
  203. minFilter = gl.LINEAR;
  204. }
  205. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  206. magFilter = gl.NEAREST;
  207. if (generateMipMaps) {
  208. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  209. } else {
  210. minFilter = gl.NEAREST;
  211. }
  212. }
  213. return {
  214. min: minFilter,
  215. mag: magFilter
  216. }
  217. }
  218. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  219. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  220. var engine = scene.getEngine();
  221. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  222. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  223. gl.bindTexture(gl.TEXTURE_2D, texture);
  224. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  225. processFunction(potWidth, potHeight);
  226. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  229. if (!noMipmap && !isCompressed) {
  230. gl.generateMipmap(gl.TEXTURE_2D);
  231. }
  232. gl.bindTexture(gl.TEXTURE_2D, null);
  233. engine._activeTexturesCache = [];
  234. texture._baseWidth = width;
  235. texture._baseHeight = height;
  236. texture._width = potWidth;
  237. texture._height = potHeight;
  238. texture.isReady = true;
  239. scene._removePendingData(texture);
  240. };
  241. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  242. onfinish: (images: HTMLImageElement[]) => void) => {
  243. var img: HTMLImageElement;
  244. var onload = () => {
  245. loadedImages[index] = img;
  246. loadedImages._internalCount++;
  247. scene._removePendingData(img);
  248. if (loadedImages._internalCount == 6) {
  249. onfinish(loadedImages);
  250. }
  251. };
  252. var onerror = () => {
  253. scene._removePendingData(img);
  254. };
  255. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  256. scene._addPendingData(img);
  257. }
  258. var cascadeLoad = (rootUrl: string, scene,
  259. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  260. var loadedImages:any = [];
  261. loadedImages._internalCount = 0;
  262. for (var index = 0; index < 6; index++) {
  263. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  264. }
  265. };
  266. export class EngineCapabilities {
  267. public maxTexturesImageUnits: number;
  268. public maxTextureSize: number;
  269. public maxCubemapTextureSize: number;
  270. public maxRenderTextureSize: number;
  271. public standardDerivatives: boolean;
  272. public s3tc;
  273. public textureFloat: boolean;
  274. public textureAnisotropicFilterExtension;
  275. public maxAnisotropy: number;
  276. public instancedArrays;
  277. }
  278. export class Engine {
  279. // Const statics
  280. private static _ALPHA_DISABLE = 0;
  281. private static _ALPHA_ADD = 1;
  282. private static _ALPHA_COMBINE = 2;
  283. private static _DELAYLOADSTATE_NONE = 0;
  284. private static _DELAYLOADSTATE_LOADED = 1;
  285. private static _DELAYLOADSTATE_LOADING = 2;
  286. private static _DELAYLOADSTATE_NOTLOADED = 4;
  287. public static get ALPHA_DISABLE(): number {
  288. return Engine._ALPHA_DISABLE;
  289. }
  290. public static get ALPHA_ADD(): number {
  291. return Engine._ALPHA_ADD;
  292. }
  293. public static get ALPHA_COMBINE(): number {
  294. return Engine._ALPHA_COMBINE;
  295. }
  296. public static get DELAYLOADSTATE_NONE(): number {
  297. return Engine._DELAYLOADSTATE_NONE;
  298. }
  299. public static get DELAYLOADSTATE_LOADED(): number {
  300. return Engine._DELAYLOADSTATE_LOADED;
  301. }
  302. public static get DELAYLOADSTATE_LOADING(): number {
  303. return Engine._DELAYLOADSTATE_LOADING;
  304. }
  305. public static get DELAYLOADSTATE_NOTLOADED(): number {
  306. return Engine._DELAYLOADSTATE_NOTLOADED;
  307. }
  308. public static get Version(): string {
  309. return "2.0.0";
  310. }
  311. // Updatable statics so stick with vars here
  312. public static Epsilon = 0.001;
  313. public static CollisionsEpsilon = 0.001;
  314. public static ShadersRepository = "Babylon/Shaders/";
  315. // Public members
  316. public isFullscreen = false;
  317. public isPointerLock = false;
  318. public forceWireframe = false;
  319. public cullBackFaces = true;
  320. public renderEvenInBackground = true;
  321. public scenes = new Array<Scene>();
  322. // Private Members
  323. private _gl: WebGLRenderingContext;
  324. private _renderingCanvas: HTMLCanvasElement;
  325. private _windowIsBackground = false;
  326. private _onBlur: () => void;
  327. private _onFocus: () => void;
  328. private _onFullscreenChange: () => void;
  329. private _onPointerLockChange: () => void;
  330. private _hardwareScalingLevel: number;
  331. private _caps: EngineCapabilities;
  332. private _pointerLockRequested: boolean;
  333. private _alphaTest: boolean;
  334. private _runningLoop = false;
  335. private _renderFunction: () => void;
  336. private _resizeLoadingUI: () => void;
  337. private _loadingDiv: HTMLDivElement;
  338. private _loadingTextDiv: HTMLDivElement;
  339. private _loadingDivBackgroundColor = "black";
  340. // States
  341. private _depthCullingState = new _DepthCullingState();
  342. private _alphaState = new _AlphaState();
  343. // Cache
  344. private _loadedTexturesCache = new Array<WebGLTexture>();
  345. public _activeTexturesCache = new Array<BaseTexture>();
  346. private _currentEffect: Effect;
  347. private _compiledEffects = {};
  348. private _vertexAttribArrays: boolean[];
  349. private _cachedViewport: Viewport;
  350. private _cachedVertexBuffers: any;
  351. private _cachedIndexBuffer: WebGLBuffer;
  352. private _cachedEffectForVertexBuffers: Effect;
  353. private _currentRenderTarget: WebGLTexture;
  354. private _canvasClientRect: ClientRect;
  355. private _workingCanvas: HTMLCanvasElement;
  356. private _workingContext: CanvasRenderingContext2D;
  357. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  358. this._renderingCanvas = canvas;
  359. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  360. options = options || {};
  361. options.antialias = antialias;
  362. // GL
  363. try {
  364. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  365. } catch (e) {
  366. throw new Error("WebGL not supported");
  367. }
  368. if (!this._gl) {
  369. throw new Error("WebGL not supported");
  370. }
  371. this._onBlur = () => {
  372. this._windowIsBackground = true;
  373. };
  374. this._onFocus = () => {
  375. this._windowIsBackground = false;
  376. };
  377. window.addEventListener("blur", this._onBlur);
  378. window.addEventListener("focus", this._onFocus);
  379. // Textures
  380. this._workingCanvas = document.createElement("canvas");
  381. this._workingContext = this._workingCanvas.getContext("2d");
  382. // Viewport
  383. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  384. this.resize();
  385. // Caps
  386. this._caps = new EngineCapabilities();
  387. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  388. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  389. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  390. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  391. // Extensions
  392. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  393. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  394. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  395. 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');
  396. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  397. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  398. // Depth buffer
  399. this.setDepthBuffer(true);
  400. this.setDepthFunctionToLessOrEqual();
  401. this.setDepthWrite(true);
  402. // Fullscreen
  403. this._onFullscreenChange = () => {
  404. if (document.fullscreen !== undefined) {
  405. this.isFullscreen = document.fullscreen;
  406. } else if (document.mozFullScreen !== undefined) {
  407. this.isFullscreen = document.mozFullScreen;
  408. } else if (document.webkitIsFullScreen !== undefined) {
  409. this.isFullscreen = document.webkitIsFullScreen;
  410. } else if (document.msIsFullScreen !== undefined) {
  411. this.isFullscreen = document.msIsFullScreen;
  412. }
  413. // Pointer lock
  414. if (this.isFullscreen && this._pointerLockRequested) {
  415. canvas.requestPointerLock = canvas.requestPointerLock ||
  416. canvas.msRequestPointerLock ||
  417. canvas.mozRequestPointerLock ||
  418. canvas.webkitRequestPointerLock;
  419. if (canvas.requestPointerLock) {
  420. canvas.requestPointerLock();
  421. }
  422. }
  423. };
  424. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  425. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  426. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  427. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  428. // Pointer lock
  429. this._onPointerLockChange = () => {
  430. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  431. document.webkitPointerLockElement === canvas ||
  432. document.msPointerLockElement === canvas ||
  433. document.pointerLockElement === canvas
  434. );
  435. };
  436. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  437. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  438. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  439. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  440. }
  441. public getAspectRatio(camera: Camera): number {
  442. var viewport = camera.viewport;
  443. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  444. }
  445. public getRenderWidth(): number {
  446. if (this._currentRenderTarget) {
  447. return this._currentRenderTarget._width;
  448. }
  449. return this._renderingCanvas.width;
  450. }
  451. public getRenderHeight(): number {
  452. if (this._currentRenderTarget) {
  453. return this._currentRenderTarget._height;
  454. }
  455. return this._renderingCanvas.height;
  456. }
  457. public getRenderingCanvas(): HTMLCanvasElement {
  458. return this._renderingCanvas;
  459. }
  460. public getRenderingCanvasClientRect(): ClientRect {
  461. return this._renderingCanvas.getBoundingClientRect();
  462. }
  463. public setHardwareScalingLevel(level: number): void {
  464. this._hardwareScalingLevel = level;
  465. this.resize();
  466. }
  467. public getHardwareScalingLevel(): number {
  468. return this._hardwareScalingLevel;
  469. }
  470. public getLoadedTexturesCache(): WebGLTexture[] {
  471. return this._loadedTexturesCache;
  472. }
  473. public getCaps(): EngineCapabilities {
  474. return this._caps;
  475. }
  476. // Methods
  477. public setDepthFunctionToGreater(): void {
  478. this._depthCullingState.depthFunc = this._gl.GREATER;
  479. }
  480. public setDepthFunctionToGreaterOrEqual(): void {
  481. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  482. }
  483. public setDepthFunctionToLess(): void {
  484. this._depthCullingState.depthFunc = this._gl.LESS;
  485. }
  486. public setDepthFunctionToLessOrEqual(): void {
  487. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  488. }
  489. public stopRenderLoop(): void {
  490. this._renderFunction = null;
  491. this._runningLoop = false;
  492. }
  493. public _renderLoop(): void {
  494. var shouldRender = true;
  495. if (!this.renderEvenInBackground && this._windowIsBackground) {
  496. shouldRender = false;
  497. }
  498. if (shouldRender) {
  499. // Start new frame
  500. this.beginFrame();
  501. if (this._renderFunction) {
  502. this._renderFunction();
  503. }
  504. // Present
  505. this.endFrame();
  506. }
  507. if (this._runningLoop) {
  508. // Register new frame
  509. BABYLON.Tools.QueueNewFrame(() => {
  510. this._renderLoop();
  511. });
  512. }
  513. }
  514. public runRenderLoop(renderFunction: () => void): void {
  515. this._runningLoop = true;
  516. this._renderFunction = renderFunction;
  517. BABYLON.Tools.QueueNewFrame(() => {
  518. this._renderLoop();
  519. });
  520. }
  521. public switchFullscreen(requestPointerLock: boolean): void {
  522. if (this.isFullscreen) {
  523. BABYLON.Tools.ExitFullscreen();
  524. } else {
  525. this._pointerLockRequested = requestPointerLock;
  526. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  527. }
  528. }
  529. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  530. this.applyStates();
  531. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  532. if (this._depthCullingState.depthMask) {
  533. this._gl.clearDepth(1.0);
  534. }
  535. var mode = 0;
  536. if (backBuffer)
  537. mode |= this._gl.COLOR_BUFFER_BIT;
  538. if (depthStencil && this._depthCullingState.depthMask)
  539. mode |= this._gl.DEPTH_BUFFER_BIT;
  540. this._gl.clear(mode);
  541. }
  542. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  543. var width = requiredWidth || this._renderingCanvas.width;
  544. var height = requiredHeight || this._renderingCanvas.height;
  545. var x = viewport.x || 0;
  546. var y = viewport.y || 0;
  547. this._cachedViewport = viewport;
  548. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  549. }
  550. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  551. this._cachedViewport = null;
  552. this._gl.viewport(x, y, width, height);
  553. }
  554. public beginFrame(): void {
  555. BABYLON.Tools._MeasureFps();
  556. }
  557. public endFrame(): void {
  558. this.flushFramebuffer();
  559. }
  560. public resize(): void {
  561. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  562. }
  563. public setSize(width: number, height: number): void {
  564. this._renderingCanvas.width = width;
  565. this._renderingCanvas.height = height;
  566. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  567. }
  568. public bindFramebuffer(texture: WebGLTexture): void {
  569. this._currentRenderTarget = texture;
  570. var gl = this._gl;
  571. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  572. this._gl.viewport(0, 0, texture._width, texture._height);
  573. this.wipeCaches();
  574. }
  575. public unBindFramebuffer(texture: WebGLTexture): void {
  576. this._currentRenderTarget = null;
  577. if (texture.generateMipMaps) {
  578. var gl = this._gl;
  579. gl.bindTexture(gl.TEXTURE_2D, texture);
  580. gl.generateMipmap(gl.TEXTURE_2D);
  581. gl.bindTexture(gl.TEXTURE_2D, null);
  582. }
  583. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  584. }
  585. public flushFramebuffer(): void {
  586. this._gl.flush();
  587. }
  588. public restoreDefaultFramebuffer(): void {
  589. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  590. this.setViewport(this._cachedViewport);
  591. this.wipeCaches();
  592. }
  593. // VBOs
  594. private _resetVertexBufferBinding(): void {
  595. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  596. this._cachedVertexBuffers = null;
  597. }
  598. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  599. var vbo = this._gl.createBuffer();
  600. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  601. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  602. this._resetVertexBufferBinding();
  603. vbo.references = 1;
  604. return vbo;
  605. }
  606. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  607. var vbo = this._gl.createBuffer();
  608. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  609. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  610. this._resetVertexBufferBinding();
  611. vbo.references = 1;
  612. return vbo;
  613. }
  614. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
  615. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  616. //if (length && length != vertices.length) {
  617. // this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  618. //} else {
  619. if (vertices instanceof Float32Array) {
  620. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  621. } else {
  622. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  623. }
  624. // }
  625. this._resetVertexBufferBinding();
  626. }
  627. private _resetIndexBufferBinding(): void {
  628. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  629. this._cachedIndexBuffer = null;
  630. }
  631. public createIndexBuffer(indices: number[]): WebGLBuffer {
  632. var vbo = this._gl.createBuffer();
  633. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  634. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  635. this._resetIndexBufferBinding();
  636. vbo.references = 1;
  637. return vbo;
  638. }
  639. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  640. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  641. this._cachedVertexBuffers = vertexBuffer;
  642. this._cachedEffectForVertexBuffers = effect;
  643. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  644. var offset = 0;
  645. for (var index = 0; index < vertexDeclaration.length; index++) {
  646. var order = effect.getAttributeLocation(index);
  647. if (order >= 0) {
  648. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  649. }
  650. offset += vertexDeclaration[index] * 4;
  651. }
  652. }
  653. if (this._cachedIndexBuffer !== indexBuffer) {
  654. this._cachedIndexBuffer = indexBuffer;
  655. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  656. }
  657. }
  658. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  659. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  660. this._cachedVertexBuffers = vertexBuffers;
  661. this._cachedEffectForVertexBuffers = effect;
  662. var attributes = effect.getAttributesNames();
  663. for (var index = 0; index < attributes.length; index++) {
  664. var order = effect.getAttributeLocation(index);
  665. if (order >= 0) {
  666. var vertexBuffer = vertexBuffers[attributes[index]];
  667. if (!vertexBuffer) {
  668. continue;
  669. }
  670. var stride = vertexBuffer.getStrideSize();
  671. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  672. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  673. }
  674. }
  675. }
  676. if (indexBuffer!= null && this._cachedIndexBuffer !== indexBuffer) {
  677. this._cachedIndexBuffer = indexBuffer;
  678. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  679. }
  680. }
  681. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  682. buffer.references--;
  683. if (buffer.references === 0) {
  684. this._gl.deleteBuffer(buffer);
  685. return true;
  686. }
  687. return false;
  688. }
  689. public createInstancesBuffer(capacity: number): WebGLBuffer {
  690. var buffer = this._gl.createBuffer();
  691. buffer.capacity = capacity;
  692. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  693. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  694. return buffer;
  695. }
  696. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  697. this._gl.deleteBuffer(buffer);
  698. }
  699. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  700. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  702. for (var index = 0; index < 4; index++) {
  703. var offsetLocation = offsetLocations[index];
  704. this._gl.enableVertexAttribArray(offsetLocation);
  705. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  706. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  707. }
  708. }
  709. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  710. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  711. for (var index = 0; index < 4; index++) {
  712. var offsetLocation = offsetLocations[index];
  713. this._gl.disableVertexAttribArray(offsetLocation);
  714. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  715. }
  716. }
  717. public applyStates() {
  718. this._depthCullingState.apply(this._gl);
  719. this._alphaState.apply(this._gl);
  720. }
  721. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  722. // Apply states
  723. this.applyStates();
  724. // Render
  725. if (instancesCount) {
  726. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  727. return;
  728. }
  729. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  730. }
  731. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  732. // Apply states
  733. this.applyStates();
  734. if (instancesCount) {
  735. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  736. return;
  737. }
  738. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  739. }
  740. // Shaders
  741. public _releaseEffect(effect: Effect): void {
  742. if (this._compiledEffects[effect._key]) {
  743. delete this._compiledEffects[effect._key];
  744. if (effect.getProgram()) {
  745. this._gl.deleteProgram(effect.getProgram());
  746. }
  747. }
  748. }
  749. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  750. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  751. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  752. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  753. var name = vertex + "+" + fragment + "@" + defines;
  754. if (this._compiledEffects[name]) {
  755. return this._compiledEffects[name];
  756. }
  757. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  758. effect._key = name;
  759. this._compiledEffects[name] = effect;
  760. return effect;
  761. }
  762. public createEffectForParticles(fragmentName: string, uniformsNames: string[]= [], samplers: string[]= [], defines = "", fallbacks?: EffectFallbacks,
  763. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  764. return this.createEffect(
  765. {
  766. vertex: "particles",
  767. fragmentElement: fragmentName
  768. },
  769. ["position", "color", "options"],
  770. ["view", "projection"].concat(uniformsNames),
  771. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  772. }
  773. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  774. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  775. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  776. var shaderProgram = this._gl.createProgram();
  777. this._gl.attachShader(shaderProgram, vertexShader);
  778. this._gl.attachShader(shaderProgram, fragmentShader);
  779. this._gl.linkProgram(shaderProgram);
  780. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  781. if (!linked) {
  782. var error = this._gl.getProgramInfoLog(shaderProgram);
  783. if (error) {
  784. throw new Error(error);
  785. }
  786. }
  787. this._gl.deleteShader(vertexShader);
  788. this._gl.deleteShader(fragmentShader);
  789. return shaderProgram;
  790. }
  791. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  792. var results = [];
  793. for (var index = 0; index < uniformsNames.length; index++) {
  794. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  795. }
  796. return results;
  797. }
  798. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  799. var results = [];
  800. for (var index = 0; index < attributesNames.length; index++) {
  801. try {
  802. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  803. } catch (e) {
  804. results.push(-1);
  805. }
  806. }
  807. return results;
  808. }
  809. public enableEffect(effect: Effect): void {
  810. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  811. if (effect && effect.onBind) {
  812. effect.onBind(effect);
  813. }
  814. return;
  815. }
  816. this._vertexAttribArrays = this._vertexAttribArrays || [];
  817. // Use program
  818. this._gl.useProgram(effect.getProgram());
  819. for (var i in this._vertexAttribArrays) {
  820. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  821. continue;
  822. }
  823. this._vertexAttribArrays[i] = false;
  824. this._gl.disableVertexAttribArray(i);
  825. }
  826. var attributesCount = effect.getAttributesCount();
  827. for (var index = 0; index < attributesCount; index++) {
  828. // Attributes
  829. var order = effect.getAttributeLocation(index);
  830. if (order >= 0) {
  831. this._vertexAttribArrays[order] = true;
  832. this._gl.enableVertexAttribArray(order);
  833. }
  834. }
  835. this._currentEffect = effect;
  836. if (effect.onBind) {
  837. effect.onBind(effect);
  838. }
  839. }
  840. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  841. if (!uniform)
  842. return;
  843. this._gl.uniform1fv(uniform, array);
  844. }
  845. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  846. if (!uniform)
  847. return;
  848. this._gl.uniformMatrix4fv(uniform, false, matrices);
  849. }
  850. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  851. if (!uniform)
  852. return;
  853. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  854. }
  855. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  856. if (!uniform)
  857. return;
  858. this._gl.uniform1f(uniform, value);
  859. }
  860. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  861. if (!uniform)
  862. return;
  863. this._gl.uniform2f(uniform, x, y);
  864. }
  865. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  866. if (!uniform)
  867. return;
  868. this._gl.uniform3f(uniform, x, y, z);
  869. }
  870. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  871. if (!uniform)
  872. return;
  873. this._gl.uniform1i(uniform, bool);
  874. }
  875. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  876. if (!uniform)
  877. return;
  878. this._gl.uniform4f(uniform, x, y, z, w);
  879. }
  880. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  881. if (!uniform)
  882. return;
  883. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  884. }
  885. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  886. if (!uniform)
  887. return;
  888. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  889. }
  890. // States
  891. public setState(culling: boolean, force?: boolean): void {
  892. // Culling
  893. if (this._depthCullingState.cull !== culling || force) {
  894. if (culling) {
  895. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  896. this._depthCullingState.cull = true;
  897. } else {
  898. this._depthCullingState.cull = false;
  899. }
  900. }
  901. }
  902. public setDepthBuffer(enable: boolean): void {
  903. this._depthCullingState.depthTest = enable;
  904. }
  905. public getDepthWrite(): boolean {
  906. return this._depthCullingState.depthMask;
  907. }
  908. public setDepthWrite(enable: boolean): void {
  909. this._depthCullingState.depthMask = enable;
  910. }
  911. public setColorWrite(enable: boolean): void {
  912. this._gl.colorMask(enable, enable, enable, enable);
  913. }
  914. public setAlphaMode(mode: number): void {
  915. switch (mode) {
  916. case BABYLON.Engine.ALPHA_DISABLE:
  917. this.setDepthWrite(true);
  918. this._alphaState.alphaBlend = false;
  919. break;
  920. case BABYLON.Engine.ALPHA_COMBINE:
  921. this.setDepthWrite(false);
  922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  923. this._alphaState.alphaBlend = true;
  924. break;
  925. case BABYLON.Engine.ALPHA_ADD:
  926. this.setDepthWrite(false);
  927. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  928. this._alphaState.alphaBlend = true;
  929. break;
  930. }
  931. }
  932. public setAlphaTesting(enable: boolean): void {
  933. this._alphaTest = enable;
  934. }
  935. public getAlphaTesting(): boolean {
  936. return this._alphaTest;
  937. }
  938. // Textures
  939. public wipeCaches(): void {
  940. this._activeTexturesCache = [];
  941. this._currentEffect = null;
  942. this._depthCullingState.reset();
  943. this._alphaState.reset();
  944. this._cachedVertexBuffers = null;
  945. this._cachedIndexBuffer = null;
  946. this._cachedEffectForVertexBuffers = null;
  947. }
  948. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  949. var gl = this._gl;
  950. gl.bindTexture(gl.TEXTURE_2D, texture);
  951. var magFilter = gl.NEAREST;
  952. var minFilter = gl.NEAREST;
  953. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  954. magFilter = gl.LINEAR;
  955. minFilter = gl.LINEAR;
  956. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  957. magFilter = gl.LINEAR;
  958. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  959. }
  960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  962. gl.bindTexture(gl.TEXTURE_2D, null);
  963. }
  964. 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 {
  965. var texture = this._gl.createTexture();
  966. var extension: string;
  967. var fromData: any = false;
  968. if (url.substr(0, 5) === "data:") {
  969. fromData = true;
  970. }
  971. if (!fromData)
  972. extension = url.substr(url.length - 4, 4).toLowerCase();
  973. else {
  974. var oldUrl = url;
  975. fromData = oldUrl.split(':');
  976. url = oldUrl;
  977. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  978. }
  979. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  980. var isTGA = (extension === ".tga");
  981. scene._addPendingData(texture);
  982. texture.url = url;
  983. texture.noMipmap = noMipmap;
  984. texture.references = 1;
  985. this._loadedTexturesCache.push(texture);
  986. var onerror = () => {
  987. scene._removePendingData(texture);
  988. if (onError) {
  989. onError();
  990. }
  991. };
  992. if (isTGA) {
  993. var callback = (arrayBuffer) => {
  994. var data = new Uint8Array(arrayBuffer);
  995. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  996. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  997. Internals.TGATools.UploadContent(this._gl, data);
  998. if (onLoad) {
  999. onLoad();
  1000. }
  1001. }, samplingMode);
  1002. };
  1003. if (!(fromData instanceof Array))
  1004. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  1005. callback(arrayBuffer);
  1006. }, onerror, scene.database, true);
  1007. else
  1008. callback(buffer);
  1009. } else if (isDDS) {
  1010. callback = (data) => {
  1011. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1012. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  1013. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1014. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1015. if (onLoad) {
  1016. onLoad();
  1017. }
  1018. }, samplingMode);
  1019. };
  1020. if (!(fromData instanceof Array))
  1021. BABYLON.Tools.LoadFile(url, data => {
  1022. callback(data);
  1023. }, onerror, scene.database, true);
  1024. else
  1025. callback(buffer);
  1026. } else {
  1027. var onload = (img) => {
  1028. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1029. var isPot = (img.width == potWidth && img.height == potHeight);
  1030. if (!isPot) {
  1031. this._workingCanvas.width = potWidth;
  1032. this._workingCanvas.height = potHeight;
  1033. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1034. }
  1035. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1036. if (onLoad) {
  1037. onLoad();
  1038. }
  1039. }, samplingMode);
  1040. };
  1041. if (!(fromData instanceof Array))
  1042. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1043. else
  1044. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1045. }
  1046. return texture;
  1047. }
  1048. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1049. var texture = this._gl.createTexture();
  1050. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1051. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1052. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1053. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1054. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1055. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1056. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1057. this._activeTexturesCache = [];
  1058. texture._baseWidth = width;
  1059. texture._baseHeight = height;
  1060. texture._width = width;
  1061. texture._height = height;
  1062. texture.isReady = false;
  1063. texture.generateMipMaps = generateMipMaps;
  1064. texture.references = 1;
  1065. this._loadedTexturesCache.push(texture);
  1066. return texture;
  1067. }
  1068. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1069. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1070. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1071. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1072. if (texture.generateMipMaps) {
  1073. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1074. }
  1075. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1076. this._activeTexturesCache = [];
  1077. texture.isReady = true;
  1078. }
  1079. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1080. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1081. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1082. // Scale the video if it is a NPOT using the current working canvas
  1083. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1084. if (!texture._workingCanvas) {
  1085. texture._workingCanvas = document.createElement("canvas");
  1086. texture._workingContext = texture._workingCanvas.getContext("2d");
  1087. texture._workingCanvas.width = texture._width;
  1088. texture._workingCanvas.height = texture._height;
  1089. }
  1090. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1091. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1092. } else {
  1093. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1094. }
  1095. if (texture.generateMipMaps) {
  1096. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1097. }
  1098. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1099. this._activeTexturesCache = [];
  1100. texture.isReady = true;
  1101. }
  1102. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1103. // old version had a "generateMipMaps" arg instead of options.
  1104. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1105. // in the same way, generateDepthBuffer is defaulted to true
  1106. var generateMipMaps = false;
  1107. var generateDepthBuffer = true;
  1108. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1109. if (options !== undefined) {
  1110. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1111. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1112. if (options.samplingMode !== undefined) {
  1113. samplingMode = options.samplingMode;
  1114. }
  1115. }
  1116. var gl = this._gl;
  1117. var texture = gl.createTexture();
  1118. gl.bindTexture(gl.TEXTURE_2D, texture);
  1119. var width = size.width || size;
  1120. var height = size.height || size;
  1121. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1126. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1127. var depthBuffer: WebGLRenderbuffer;
  1128. // Create the depth buffer
  1129. if (generateDepthBuffer) {
  1130. depthBuffer = gl.createRenderbuffer();
  1131. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1132. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1133. }
  1134. // Create the framebuffer
  1135. var framebuffer = gl.createFramebuffer();
  1136. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1137. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1138. if (generateDepthBuffer) {
  1139. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1140. }
  1141. // Unbind
  1142. gl.bindTexture(gl.TEXTURE_2D, null);
  1143. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1144. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1145. texture._framebuffer = framebuffer;
  1146. if (generateDepthBuffer) {
  1147. texture._depthBuffer = depthBuffer;
  1148. }
  1149. texture._width = width;
  1150. texture._height = height;
  1151. texture.isReady = true;
  1152. texture.generateMipMaps = generateMipMaps;
  1153. texture.references = 1;
  1154. this._activeTexturesCache = [];
  1155. this._loadedTexturesCache.push(texture);
  1156. return texture;
  1157. }
  1158. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1159. var gl = this._gl;
  1160. var texture = gl.createTexture();
  1161. texture.isCube = true;
  1162. texture.url = rootUrl;
  1163. texture.references = 1;
  1164. this._loadedTexturesCache.push(texture);
  1165. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1166. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1167. if (isDDS) {
  1168. BABYLON.Tools.LoadFile(rootUrl, data => {
  1169. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1170. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1171. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1173. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1174. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  1175. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1176. }
  1177. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1178. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1179. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1180. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1181. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1182. this._activeTexturesCache = [];
  1183. texture._width = info.width;
  1184. texture._height = info.height;
  1185. texture.isReady = true;
  1186. }, null, null, true);
  1187. } else {
  1188. cascadeLoad(rootUrl, scene, imgs => {
  1189. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1190. var height = width;
  1191. this._workingCanvas.width = width;
  1192. this._workingCanvas.height = height;
  1193. var faces = [
  1194. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1195. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1196. ];
  1197. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1198. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1199. for (var index = 0; index < faces.length; index++) {
  1200. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1201. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1202. }
  1203. if (!noMipmap) {
  1204. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1205. }
  1206. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1207. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1210. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1211. this._activeTexturesCache = [];
  1212. texture._width = width;
  1213. texture._height = height;
  1214. texture.isReady = true;
  1215. }, extensions);
  1216. }
  1217. return texture;
  1218. }
  1219. public _releaseTexture(texture: WebGLTexture): void {
  1220. var gl = this._gl;
  1221. if (texture._framebuffer) {
  1222. gl.deleteFramebuffer(texture._framebuffer);
  1223. }
  1224. if (texture._depthBuffer) {
  1225. gl.deleteRenderbuffer(texture._depthBuffer);
  1226. }
  1227. gl.deleteTexture(texture);
  1228. // Unbind channels
  1229. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1230. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1231. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1232. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1233. this._activeTexturesCache[channel] = null;
  1234. }
  1235. var index = this._loadedTexturesCache.indexOf(texture);
  1236. if (index !== -1) {
  1237. this._loadedTexturesCache.splice(index, 1);
  1238. }
  1239. }
  1240. public bindSamplers(effect: Effect): void {
  1241. this._gl.useProgram(effect.getProgram());
  1242. var samplers = effect.getSamplers();
  1243. for (var index = 0; index < samplers.length; index++) {
  1244. var uniform = effect.getUniform(samplers[index]);
  1245. this._gl.uniform1i(uniform, index);
  1246. }
  1247. this._currentEffect = null;
  1248. }
  1249. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1250. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1251. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1252. this._activeTexturesCache[channel] = null;
  1253. }
  1254. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1255. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1256. }
  1257. public setTexture(channel: number, texture: BaseTexture): void {
  1258. if (channel < 0) {
  1259. return;
  1260. }
  1261. // Not ready?
  1262. if (!texture || !texture.isReady()) {
  1263. if (this._activeTexturesCache[channel] != null) {
  1264. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1265. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1266. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1267. this._activeTexturesCache[channel] = null;
  1268. }
  1269. return;
  1270. }
  1271. // Video
  1272. if (texture instanceof BABYLON.VideoTexture) {
  1273. if ((<VideoTexture>texture).update()) {
  1274. this._activeTexturesCache[channel] = null;
  1275. }
  1276. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1277. texture.delayLoad();
  1278. return;
  1279. }
  1280. if (this._activeTexturesCache[channel] == texture) {
  1281. return;
  1282. }
  1283. this._activeTexturesCache[channel] = texture;
  1284. var internalTexture = texture.getInternalTexture();
  1285. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1286. if (internalTexture.isCube) {
  1287. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1288. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1289. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1290. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1291. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1292. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1293. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1294. }
  1295. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1296. } else {
  1297. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1298. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1299. internalTexture._cachedWrapU = texture.wrapU;
  1300. switch (texture.wrapU) {
  1301. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1303. break;
  1304. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1306. break;
  1307. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1309. break;
  1310. }
  1311. }
  1312. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1313. internalTexture._cachedWrapV = texture.wrapV;
  1314. switch (texture.wrapV) {
  1315. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1316. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1317. break;
  1318. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1320. break;
  1321. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1322. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1323. break;
  1324. }
  1325. }
  1326. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1327. }
  1328. }
  1329. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1330. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1331. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1332. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1333. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1334. }
  1335. }
  1336. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1337. var data = new Uint8Array(height * width * 4);
  1338. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1339. return data;
  1340. }
  1341. // Dispose
  1342. public dispose(): void {
  1343. this.hideLoadingUI();
  1344. this.stopRenderLoop();
  1345. // Release scenes
  1346. while (this.scenes.length) {
  1347. this.scenes[0].dispose();
  1348. }
  1349. // Release effects
  1350. for (var name in this._compiledEffects) {
  1351. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1352. }
  1353. // Unbind
  1354. for (var i in this._vertexAttribArrays) {
  1355. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1356. continue;
  1357. }
  1358. this._gl.disableVertexAttribArray(i);
  1359. }
  1360. // Events
  1361. window.removeEventListener("blur", this._onBlur);
  1362. window.removeEventListener("focus", this._onFocus);
  1363. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1364. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1365. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1366. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1367. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1368. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1369. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1370. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1371. }
  1372. // Loading screen
  1373. public displayLoadingUI(): void {
  1374. this._loadingDiv = document.createElement("div");
  1375. this._loadingDiv.style.opacity = "0";
  1376. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1377. // Loading text
  1378. this._loadingTextDiv = document.createElement("div");
  1379. this._loadingTextDiv.style.position = "absolute";
  1380. this._loadingTextDiv.style.left = "0";
  1381. this._loadingTextDiv.style.top = "50%";
  1382. this._loadingTextDiv.style.marginTop = "80px";
  1383. this._loadingTextDiv.style.width = "100%";
  1384. this._loadingTextDiv.style.height = "20px";
  1385. this._loadingTextDiv.style.fontFamily = "Arial";
  1386. this._loadingTextDiv.style.fontSize = "14px";
  1387. this._loadingTextDiv.style.color = "white";
  1388. this._loadingTextDiv.style.textAlign = "center";
  1389. this._loadingTextDiv.innerHTML = "Loading";
  1390. this._loadingDiv.appendChild(this._loadingTextDiv);
  1391. // Loading img
  1392. var imgBack = new Image();
  1393. 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==";
  1394. imgBack.style.position = "absolute";
  1395. imgBack.style.left = "50%";
  1396. imgBack.style.top = "50%";
  1397. imgBack.style.marginLeft = "-50px";
  1398. imgBack.style.marginTop = "-50px";
  1399. imgBack.style.transition = "transform 1.0s ease";
  1400. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1401. var deg = 360;
  1402. var onTransitionEnd = () => {
  1403. deg += 360;
  1404. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1405. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1406. }
  1407. imgBack.addEventListener("transitionend", onTransitionEnd);
  1408. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1409. this._loadingDiv.appendChild(imgBack);
  1410. // front image
  1411. var imgFront = new Image();
  1412. 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=";
  1413. imgFront.style.position = "absolute";
  1414. imgFront.style.left = "50%";
  1415. imgFront.style.top = "50%";
  1416. imgFront.style.marginLeft = "-50px";
  1417. imgFront.style.marginTop = "-50px";
  1418. this._loadingDiv.appendChild(imgFront);
  1419. // Resize
  1420. this._resizeLoadingUI = () => {
  1421. var canvasRect = this.getRenderingCanvasClientRect();
  1422. this._loadingDiv.style.position = "absolute";
  1423. this._loadingDiv.style.left = canvasRect.left + "px";
  1424. this._loadingDiv.style.top = canvasRect.top + "px";
  1425. this._loadingDiv.style.width = canvasRect.width + "px";
  1426. this._loadingDiv.style.height = canvasRect.height + "px";
  1427. }
  1428. this._resizeLoadingUI();
  1429. window.addEventListener("resize", this._resizeLoadingUI);
  1430. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1431. document.body.appendChild(this._loadingDiv);
  1432. setTimeout(() => {
  1433. this._loadingDiv.style.opacity = "1";
  1434. imgBack.style.transform = "rotateZ(360deg)";
  1435. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1436. }, 0);
  1437. }
  1438. public set loadingUIText(text: string) {
  1439. if (!this._loadingDiv) {
  1440. return;
  1441. }
  1442. this._loadingTextDiv.innerHTML = text;
  1443. }
  1444. public get loadingUIBackgroundColor(): string {
  1445. return this._loadingDivBackgroundColor;
  1446. }
  1447. public set loadingUIBackgroundColor(color: string) {
  1448. this._loadingDivBackgroundColor = color;
  1449. if (!this._loadingDiv) {
  1450. return;
  1451. }
  1452. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1453. }
  1454. public hideLoadingUI(): void {
  1455. if (!this._loadingDiv) {
  1456. return;
  1457. }
  1458. var onTransitionEnd = () => {
  1459. if (!this._loadingDiv) {
  1460. return;
  1461. }
  1462. document.body.removeChild(this._loadingDiv);
  1463. window.removeEventListener("resize", this._resizeLoadingUI);
  1464. this._loadingDiv = null;
  1465. }
  1466. this._loadingDiv.style.opacity = "0";
  1467. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1468. }
  1469. // Statics
  1470. public static isSupported(): boolean {
  1471. try {
  1472. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1473. if (navigator.isCocoonJS) {
  1474. return true;
  1475. }
  1476. var tempcanvas = document.createElement("canvas");
  1477. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1478. return gl != null && !!window.WebGLRenderingContext;
  1479. } catch (e) {
  1480. return false;
  1481. }
  1482. }
  1483. }
  1484. }