babylon.engine.ts 146 KB

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