babylon.engine.ts 145 KB

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