babylon.engine.ts 178 KB

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