babylon.engine.ts 103 KB

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