babylon.engine.ts 150 KB

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