babylon.engine.ts 140 KB

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