babylon.engine.ts 130 KB

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