babylon.engine.ts 194 KB

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