babylon.engine.ts 117 KB

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