babylon.engine.ts 224 KB

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