babylon.engine.ts 129 KB

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