babylon.engine.ts 140 KB

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