babylon.engine.ts 128 KB

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