babylon.engine.ts 140 KB

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