babylon.engine.ts 319 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448
  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. class BufferPointer {
  145. public active: boolean;
  146. public index: number;
  147. public size: number;
  148. public type: number;
  149. public normalized: boolean;
  150. public stride: number;
  151. public offset: number;
  152. public buffer: WebGLBuffer;
  153. }
  154. /**
  155. * Interface for attribute information associated with buffer instanciation
  156. */
  157. export class InstancingAttributeInfo {
  158. /**
  159. * Index/offset of the attribute in the vertex shader
  160. */
  161. index: number;
  162. /**
  163. * size of the attribute, 1, 2, 3 or 4
  164. */
  165. attributeSize: number;
  166. /**
  167. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  168. * default is FLOAT
  169. */
  170. attribyteType: number;
  171. /**
  172. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  173. */
  174. normalized: boolean;
  175. /**
  176. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  177. */
  178. offset: number;
  179. /**
  180. * Name of the GLSL attribute, for debugging purpose only
  181. */
  182. attributeName: string;
  183. }
  184. /**
  185. * Define options used to create a render target texture
  186. */
  187. export class RenderTargetCreationOptions {
  188. /**
  189. * Specifies is mipmaps must be generated
  190. */
  191. generateMipMaps?: boolean;
  192. /** Specifies whether or not a depth should be allocated in the texture (true by default) */
  193. generateDepthBuffer?: boolean;
  194. /** Specifies whether or not a stencil should be allocated in the texture (false by default)*/
  195. generateStencilBuffer?: boolean;
  196. /** Defines texture type (int by default) */
  197. type?: number;
  198. /** Defines sampling mode (trilinear by default) */
  199. samplingMode?: number;
  200. /** Defines format (RGBA by default) */
  201. format?: number;
  202. }
  203. /**
  204. * Define options used to create a depth texture
  205. */
  206. export class DepthTextureCreationOptions {
  207. /** Specifies whether or not a stencil should be allocated in the texture */
  208. generateStencil?: boolean;
  209. /** Specifies whether or not bilinear filtering is enable on the texture */
  210. bilinearFiltering?: boolean;
  211. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  212. comparisonFunction?: number;
  213. /** Specifies if the created texture is a cube texture */
  214. isCube?: boolean;
  215. }
  216. /**
  217. * Class used to describe the capabilities of the engine relatively to the current browser
  218. */
  219. export class EngineCapabilities {
  220. /** Maximum textures units per fragment shader */
  221. public maxTexturesImageUnits: number;
  222. /** Maximum texture units per vertex shader */
  223. public maxVertexTextureImageUnits: number;
  224. /** Maximum textures units in the entire pipeline */
  225. public maxCombinedTexturesImageUnits: number;
  226. /** Maximum texture size */
  227. public maxTextureSize: number;
  228. /** Maximum cube texture size */
  229. public maxCubemapTextureSize: number;
  230. /** Maximum render texture size */
  231. public maxRenderTextureSize: number;
  232. /** Maximum number of vertex attributes */
  233. public maxVertexAttribs: number;
  234. /** Maximum number of varyings */
  235. public maxVaryingVectors: number;
  236. /** Maximum number of uniforms per vertex shader */
  237. public maxVertexUniformVectors: number;
  238. /** Maximum number of uniforms per fragment shader */
  239. public maxFragmentUniformVectors: number;
  240. /** Defines if standard derivates (dx/dy) are supported */
  241. public standardDerivatives: boolean;
  242. /** Defines if s3tc texture compression is supported */
  243. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  244. /** Defines if pvrtc texture compression is supported */
  245. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  246. /** Defines if etc1 texture compression is supported */
  247. public etc1: any; //WEBGL_compressed_texture_etc1;
  248. /** Defines if etc2 texture compression is supported */
  249. public etc2: any; //WEBGL_compressed_texture_etc;
  250. /** Defines if astc texture compression is supported */
  251. public astc: any; //WEBGL_compressed_texture_astc;
  252. /** Defines if float textures are supported */
  253. public textureFloat: boolean;
  254. /** Defines if vertex array objects are supported */
  255. public vertexArrayObject: boolean;
  256. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  257. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  258. /** Gets the maximum level of anisotropy supported */
  259. public maxAnisotropy: number;
  260. /** Defines if instancing is supported */
  261. public instancedArrays: boolean;
  262. /** Defines if 32 bits indices are supported */
  263. public uintIndices: boolean;
  264. /** Defines if high precision shaders are supported */
  265. public highPrecisionShaderSupported: boolean;
  266. /** Defines if depth reading in the fragment shader is supported */
  267. public fragmentDepthSupported: boolean;
  268. /** Defines if float texture linear filtering is supported*/
  269. public textureFloatLinearFiltering: boolean;
  270. /** Defines if rendering to float textures is supported */
  271. public textureFloatRender: boolean;
  272. /** Defines if half float textures are supported*/
  273. public textureHalfFloat: boolean;
  274. /** Defines if half float texture linear filtering is supported*/
  275. public textureHalfFloatLinearFiltering: boolean;
  276. /** Defines if rendering to half float textures is supported */
  277. public textureHalfFloatRender: boolean;
  278. /** Defines if textureLOD shader command is supported */
  279. public textureLOD: boolean;
  280. /** Defines if draw buffers extension is supported */
  281. public drawBuffersExtension: boolean;
  282. /** Defines if depth textures are supported */
  283. public depthTextureExtension: boolean;
  284. /** Defines if float color buffer are supported */
  285. public colorBufferFloat: boolean;
  286. /** Gets disjoint timer query extension (null if not supported) */
  287. public timerQuery: EXT_disjoint_timer_query;
  288. /** Defines if timestamp can be used with timer query */
  289. public canUseTimestampForTimerQuery: boolean;
  290. }
  291. /** Interface defining initialization parameters for Engine class */
  292. export interface EngineOptions extends WebGLContextAttributes {
  293. /**
  294. * Defines if the engine should no exceed a specified device ratio
  295. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  296. */
  297. limitDeviceRatio?: number;
  298. /**
  299. * Defines if webvr should be enabled automatically
  300. * @see http://doc.babylonjs.com/how_to/webvr_camera
  301. */
  302. autoEnableWebVR?: boolean;
  303. /**
  304. * Defines if webgl2 should be turned off even if supported
  305. * @see http://doc.babylonjs.com/features/webgl2
  306. */
  307. disableWebGL2Support?: boolean;
  308. /**
  309. * Defines if webaudio should be initialized as well
  310. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  311. */
  312. audioEngine?: boolean;
  313. /**
  314. * Defines if animations should run using a deterministic lock step
  315. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  316. */
  317. deterministicLockstep?: boolean;
  318. /** Defines the maximum steps to use with deterministic lock step mode */
  319. lockstepMaxSteps?: number;
  320. /**
  321. * Defines that engine should ignore context lost events
  322. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  323. */
  324. doNotHandleContextLost?: boolean;
  325. }
  326. /**
  327. * Defines the interface used by display changed events
  328. */
  329. export interface IDisplayChangedEventArgs {
  330. /** Gets the vrDisplay object (if any) */
  331. vrDisplay: Nullable<any>;
  332. /** Gets a boolean indicating if webVR is supported */
  333. vrSupported: boolean;
  334. }
  335. /**
  336. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  337. */
  338. export class Engine {
  339. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  340. public static ExceptionList = [
  341. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  342. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  343. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  344. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  345. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  346. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  347. ];
  348. /** Gets the list of created engines */
  349. public static Instances = new Array<Engine>();
  350. /**
  351. * Gets the latest created engine
  352. */
  353. public static get LastCreatedEngine(): Nullable<Engine> {
  354. if (Engine.Instances.length === 0) {
  355. return null;
  356. }
  357. return Engine.Instances[Engine.Instances.length - 1];
  358. }
  359. /**
  360. * Gets the latest created scene
  361. */
  362. public static get LastCreatedScene(): Nullable<Scene> {
  363. var lastCreatedEngine = Engine.LastCreatedEngine;
  364. if (!lastCreatedEngine) {
  365. return null;
  366. }
  367. if (lastCreatedEngine.scenes.length === 0) {
  368. return null;
  369. }
  370. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  371. }
  372. /**
  373. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  374. * @param flag defines which part of the materials must be marked as dirty
  375. * @param predicate defines a predicate used to filter which materials should be affected
  376. */
  377. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  378. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  379. var engine = Engine.Instances[engineIndex];
  380. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  381. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  382. }
  383. }
  384. }
  385. // Const statics
  386. private static _ALPHA_DISABLE = 0;
  387. private static _ALPHA_ADD = 1;
  388. private static _ALPHA_COMBINE = 2;
  389. private static _ALPHA_SUBTRACT = 3;
  390. private static _ALPHA_MULTIPLY = 4;
  391. private static _ALPHA_MAXIMIZED = 5;
  392. private static _ALPHA_ONEONE = 6;
  393. private static _ALPHA_PREMULTIPLIED = 7;
  394. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  395. private static _ALPHA_INTERPOLATE = 9;
  396. private static _ALPHA_SCREENMODE = 10;
  397. private static _DELAYLOADSTATE_NONE = 0;
  398. private static _DELAYLOADSTATE_LOADED = 1;
  399. private static _DELAYLOADSTATE_LOADING = 2;
  400. private static _DELAYLOADSTATE_NOTLOADED = 4;
  401. private static _TEXTUREFORMAT_ALPHA = 0;
  402. private static _TEXTUREFORMAT_LUMINANCE = 1;
  403. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  404. private static _TEXTUREFORMAT_RGB = 4;
  405. private static _TEXTUREFORMAT_RGBA = 5;
  406. private static _TEXTUREFORMAT_R32F = 6;
  407. private static _TEXTUREFORMAT_RG32F = 7;
  408. private static _TEXTUREFORMAT_RGB32F = 8;
  409. private static _TEXTUREFORMAT_RGBA32F = 9;
  410. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  411. private static _TEXTURETYPE_FLOAT = 1;
  412. private static _TEXTURETYPE_HALF_FLOAT = 2;
  413. // Depht or Stencil test Constants.
  414. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  415. 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.
  416. 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.
  417. 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.
  418. 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.
  419. 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.
  420. 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.
  421. 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.
  422. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  423. public static get NEVER(): number {
  424. return Engine._NEVER;
  425. }
  426. /** 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 */
  427. public static get ALWAYS(): number {
  428. return Engine._ALWAYS;
  429. }
  430. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  431. public static get LESS(): number {
  432. return Engine._LESS;
  433. }
  434. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  435. public static get EQUAL(): number {
  436. return Engine._EQUAL;
  437. }
  438. /** 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 */
  439. public static get LEQUAL(): number {
  440. return Engine._LEQUAL;
  441. }
  442. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  443. public static get GREATER(): number {
  444. return Engine._GREATER;
  445. }
  446. /** 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 */
  447. public static get GEQUAL(): number {
  448. return Engine._GEQUAL;
  449. }
  450. /** 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 */
  451. public static get NOTEQUAL(): number {
  452. return Engine._NOTEQUAL;
  453. }
  454. // Stencil Actions Constants.
  455. private static _KEEP = 0x1E00;
  456. private static _REPLACE = 0x1E01;
  457. private static _INCR = 0x1E02;
  458. private static _DECR = 0x1E03;
  459. private static _INVERT = 0x150A;
  460. private static _INCR_WRAP = 0x8507;
  461. private static _DECR_WRAP = 0x8508;
  462. /** Passed to stencilOperation to specify that stencil value must be kept */
  463. public static get KEEP(): number {
  464. return Engine._KEEP;
  465. }
  466. /** Passed to stencilOperation to specify that stencil value must be replaced */
  467. public static get REPLACE(): number {
  468. return Engine._REPLACE;
  469. }
  470. /** Passed to stencilOperation to specify that stencil value must be incremented */
  471. public static get INCR(): number {
  472. return Engine._INCR;
  473. }
  474. /** Passed to stencilOperation to specify that stencil value must be decremented */
  475. public static get DECR(): number {
  476. return Engine._DECR;
  477. }
  478. /** Passed to stencilOperation to specify that stencil value must be inverted */
  479. public static get INVERT(): number {
  480. return Engine._INVERT;
  481. }
  482. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  483. public static get INCR_WRAP(): number {
  484. return Engine._INCR_WRAP;
  485. }
  486. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  487. public static get DECR_WRAP(): number {
  488. return Engine._DECR_WRAP;
  489. }
  490. // Alpha
  491. /** Defines that alpha blending is disabled */
  492. public static get ALPHA_DISABLE(): number {
  493. return Engine._ALPHA_DISABLE;
  494. }
  495. /** Defines that alpha blending to SRC + DEST */
  496. public static get ALPHA_ONEONE(): number {
  497. return Engine._ALPHA_ONEONE;
  498. }
  499. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  500. public static get ALPHA_ADD(): number {
  501. return Engine._ALPHA_ADD;
  502. }
  503. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  504. public static get ALPHA_COMBINE(): number {
  505. return Engine._ALPHA_COMBINE;
  506. }
  507. /** Defines that alpha blending to DEST - SRC * DEST */
  508. public static get ALPHA_SUBTRACT(): number {
  509. return Engine._ALPHA_SUBTRACT;
  510. }
  511. /** Defines that alpha blending to SRC * DEST */
  512. public static get ALPHA_MULTIPLY(): number {
  513. return Engine._ALPHA_MULTIPLY;
  514. }
  515. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  516. public static get ALPHA_MAXIMIZED(): number {
  517. return Engine._ALPHA_MAXIMIZED;
  518. }
  519. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  520. public static get ALPHA_PREMULTIPLIED(): number {
  521. return Engine._ALPHA_PREMULTIPLIED;
  522. }
  523. /**
  524. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  525. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  526. */
  527. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  528. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  529. }
  530. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  531. public static get ALPHA_INTERPOLATE(): number {
  532. return Engine._ALPHA_INTERPOLATE;
  533. }
  534. /**
  535. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  536. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  537. */
  538. public static get ALPHA_SCREENMODE(): number {
  539. return Engine._ALPHA_SCREENMODE;
  540. }
  541. // Delays
  542. /** Defines that the ressource is not delayed*/
  543. public static get DELAYLOADSTATE_NONE(): number {
  544. return Engine._DELAYLOADSTATE_NONE;
  545. }
  546. /** Defines that the ressource was successfully delay loaded */
  547. public static get DELAYLOADSTATE_LOADED(): number {
  548. return Engine._DELAYLOADSTATE_LOADED;
  549. }
  550. /** Defines that the ressource is currently delay loading */
  551. public static get DELAYLOADSTATE_LOADING(): number {
  552. return Engine._DELAYLOADSTATE_LOADING;
  553. }
  554. /** Defines that the ressource is delayed and has not started loading */
  555. public static get DELAYLOADSTATE_NOTLOADED(): number {
  556. return Engine._DELAYLOADSTATE_NOTLOADED;
  557. }
  558. /** ALPHA */
  559. public static get TEXTUREFORMAT_ALPHA(): number {
  560. return Engine._TEXTUREFORMAT_ALPHA;
  561. }
  562. /** LUMINANCE */
  563. public static get TEXTUREFORMAT_LUMINANCE(): number {
  564. return Engine._TEXTUREFORMAT_LUMINANCE;
  565. }
  566. /**
  567. * R32F
  568. */
  569. public static get TEXTUREFORMAT_R32F(): number {
  570. return Engine._TEXTUREFORMAT_R32F;
  571. }
  572. /**
  573. * RG32F
  574. */
  575. public static get TEXTUREFORMAT_RG32F(): number {
  576. return Engine._TEXTUREFORMAT_RG32F;
  577. }
  578. /**
  579. * RGB32F
  580. */
  581. public static get TEXTUREFORMAT_RGB32F(): number {
  582. return Engine._TEXTUREFORMAT_RGB32F;
  583. }
  584. /**
  585. * RGBA32F
  586. */
  587. public static get TEXTUREFORMAT_RGBA32F(): number {
  588. return Engine._TEXTUREFORMAT_RGBA32F;
  589. }
  590. /** LUMINANCE_ALPHA */
  591. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  592. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  593. }
  594. /** RGB */
  595. public static get TEXTUREFORMAT_RGB(): number {
  596. return Engine._TEXTUREFORMAT_RGB;
  597. }
  598. /** RGBA */
  599. public static get TEXTUREFORMAT_RGBA(): number {
  600. return Engine._TEXTUREFORMAT_RGBA;
  601. }
  602. /** UNSIGNED_INT */
  603. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  604. return Engine._TEXTURETYPE_UNSIGNED_INT;
  605. }
  606. /** FLOAT */
  607. public static get TEXTURETYPE_FLOAT(): number {
  608. return Engine._TEXTURETYPE_FLOAT;
  609. }
  610. /** HALF_FLOAT */
  611. public static get TEXTURETYPE_HALF_FLOAT(): number {
  612. return Engine._TEXTURETYPE_HALF_FLOAT;
  613. }
  614. // Texture rescaling mode
  615. private static _SCALEMODE_FLOOR = 1;
  616. private static _SCALEMODE_NEAREST = 2;
  617. private static _SCALEMODE_CEILING = 3;
  618. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  619. public static get SCALEMODE_FLOOR(): number {
  620. return Engine._SCALEMODE_FLOOR;
  621. }
  622. /** Defines that texture rescaling will look for the nearest power of 2 size */
  623. public static get SCALEMODE_NEAREST(): number {
  624. return Engine._SCALEMODE_NEAREST;
  625. }
  626. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  627. public static get SCALEMODE_CEILING(): number {
  628. return Engine._SCALEMODE_CEILING;
  629. }
  630. /**
  631. * Returns the current version of the framework
  632. */
  633. public static get Version(): string {
  634. return "3.2.0-beta.5";
  635. }
  636. // Updatable statics so stick with vars here
  637. /**
  638. * Gets or sets the epsilon value used by collision engine
  639. */
  640. public static CollisionsEpsilon = 0.001;
  641. /**
  642. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  643. */
  644. public static CodeRepository = "src/";
  645. /**
  646. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  647. */
  648. public static ShadersRepository = "src/Shaders/";
  649. // Public members
  650. /**
  651. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  652. */
  653. public forcePOTTextures = false;
  654. /**
  655. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  656. */
  657. public isFullscreen = false;
  658. /**
  659. * Gets a boolean indicating if the pointer is currently locked
  660. */
  661. public isPointerLock = false;
  662. /**
  663. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  664. */
  665. public cullBackFaces = true;
  666. /**
  667. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  668. */
  669. public renderEvenInBackground = true;
  670. /**
  671. * Gets or sets a boolean indicating that cache can be kept between frames
  672. */
  673. public preventCacheWipeBetweenFrames = false;
  674. /**
  675. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  676. **/
  677. public enableOfflineSupport = false;
  678. /**
  679. * Gets the list of created scenes
  680. */
  681. public scenes = new Array<Scene>();
  682. /**
  683. * Gets the list of created postprocesses
  684. */
  685. public postProcesses = new Array<PostProcess>();
  686. // Observables
  687. /**
  688. * Observable event triggered each time the rendering canvas is resized
  689. */
  690. public onResizeObservable = new Observable<Engine>();
  691. /**
  692. * Observable event triggered each time the canvas loses focus
  693. */
  694. public onCanvasBlurObservable = new Observable<Engine>();
  695. /**
  696. * Observable event triggered each time the canvas gains focus
  697. */
  698. public onCanvasFocusObservable = new Observable<Engine>();
  699. /**
  700. * Observable event triggered each time the canvas receives pointerout event
  701. */
  702. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  703. /**
  704. * Observable event triggered before each texture is initialized
  705. */
  706. public onBeforeTextureInitObservable = new Observable<Texture>();
  707. //WebVR
  708. private _vrDisplay: any = undefined;
  709. private _vrSupported: boolean = false;
  710. private _oldSize: Size;
  711. private _oldHardwareScaleFactor: number;
  712. private _vrExclusivePointerMode = false;
  713. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  714. /**
  715. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  716. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  717. */
  718. public get isInVRExclusivePointerMode(): boolean {
  719. return this._vrExclusivePointerMode;
  720. }
  721. // Uniform buffers list
  722. /**
  723. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  724. */
  725. public disableUniformBuffers = false;
  726. /** @ignore */
  727. public _uniformBuffers = new Array<UniformBuffer>();
  728. /**
  729. * Gets a boolean indicating that the engine supports uniform buffers
  730. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  731. */
  732. public get supportsUniformBuffers(): boolean {
  733. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  734. }
  735. // Observables
  736. /**
  737. * Observable raised when the engine begins a new frame
  738. */
  739. public onBeginFrameObservable = new Observable<Engine>();
  740. /**
  741. * Observable raised when the engine ends the current frame
  742. */
  743. public onEndFrameObservable = new Observable<Engine>();
  744. /**
  745. * Observable raised when the engine is about to compile a shader
  746. */
  747. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  748. /**
  749. * Observable raised when the engine has jsut compiled a shader
  750. */
  751. public onAfterShaderCompilationObservable = new Observable<Engine>();
  752. // Private Members
  753. private _gl: WebGLRenderingContext;
  754. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  755. private _windowIsBackground = false;
  756. private _webGLVersion = 1.0;
  757. /**
  758. * Gets a boolean indicating that only power of 2 textures are supported
  759. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  760. */
  761. public get needPOTTextures(): boolean {
  762. return this._webGLVersion < 2 || this.forcePOTTextures;
  763. }
  764. /** @ignore */
  765. public _badOS = false;
  766. /** @ignore */
  767. public _badDesktopOS = false;
  768. /**
  769. * Gets or sets a value indicating if we want to disable texture binding optmization.
  770. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  771. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  772. */
  773. public disableTextureBindingOptimization = false;
  774. /**
  775. * Gets the audio engine
  776. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  777. * @ignoreNaming
  778. */
  779. public static audioEngine: AudioEngine;
  780. // Focus
  781. private _onFocus: () => void;
  782. private _onBlur: () => void;
  783. private _onCanvasPointerOut: (event: PointerEvent) => void;
  784. private _onCanvasBlur: () => void;
  785. private _onCanvasFocus: () => void;
  786. private _onFullscreenChange: () => void;
  787. private _onPointerLockChange: () => void;
  788. private _onVRDisplayPointerRestricted: () => void;
  789. private _onVRDisplayPointerUnrestricted: () => void;
  790. // VRDisplay connection
  791. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  792. private _onVrDisplayDisconnect: Nullable<() => void>;
  793. private _onVrDisplayPresentChange: Nullable<() => void>;
  794. /**
  795. * Observable signaled when VR display mode changes
  796. */
  797. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  798. /**
  799. * Observable signaled when VR request present is complete
  800. */
  801. public onVRRequestPresentComplete = new Observable<boolean>();
  802. /**
  803. * Observable signaled when VR request present starts
  804. */
  805. public onVRRequestPresentStart = new Observable<Engine>();
  806. private _hardwareScalingLevel: number;
  807. /** @ignore */
  808. protected _caps: EngineCapabilities;
  809. private _pointerLockRequested: boolean;
  810. private _isStencilEnable: boolean;
  811. private _colorWrite = true;
  812. private _loadingScreen: ILoadingScreen;
  813. /** @ignore */
  814. public _drawCalls = new PerfCounter();
  815. /** @ignore */
  816. public _textureCollisions = new PerfCounter();
  817. private _glVersion: string;
  818. private _glRenderer: string;
  819. private _glVendor: string;
  820. private _videoTextureSupported: boolean;
  821. private _renderingQueueLaunched = false;
  822. private _activeRenderLoops = new Array<() => void>();
  823. // Deterministic lockstepMaxSteps
  824. private _deterministicLockstep: boolean = false;
  825. private _lockstepMaxSteps: number = 4;
  826. // Lost context
  827. /**
  828. * Observable signaled when a context lost event is raised
  829. */
  830. public onContextLostObservable = new Observable<Engine>();
  831. /**
  832. * Observable signaled when a context restored event is raised
  833. */
  834. public onContextRestoredObservable = new Observable<Engine>();
  835. private _onContextLost: (evt: Event) => void;
  836. private _onContextRestored: (evt: Event) => void;
  837. private _contextWasLost = false;
  838. private _doNotHandleContextLost = false;
  839. // FPS
  840. private _performanceMonitor = new PerformanceMonitor();
  841. private _fps = 60;
  842. private _deltaTime = 0;
  843. /**
  844. * Turn this value on if you want to pause FPS computation when in background
  845. */
  846. public disablePerformanceMonitorInBackground = false;
  847. /**
  848. * Gets the performance monitor attached to this engine
  849. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  850. */
  851. public get performanceMonitor(): PerformanceMonitor {
  852. return this._performanceMonitor;
  853. }
  854. // States
  855. /** @ignore */
  856. protected _depthCullingState = new _DepthCullingState();
  857. /** @ignore */
  858. protected _stencilState = new _StencilState();
  859. /** @ignore */
  860. protected _alphaState = new _AlphaState();
  861. /** @ignore */
  862. protected _alphaMode = Engine.ALPHA_DISABLE;
  863. // Cache
  864. private _internalTexturesCache = new Array<InternalTexture>();
  865. /** @ignore */
  866. protected _activeChannel = 0;
  867. private _currentTextureChannel = -1;
  868. /** @ignore */
  869. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  870. /** @ignore */
  871. protected _currentEffect: Nullable<Effect>;
  872. /** @ignore */
  873. protected _currentProgram: Nullable<WebGLProgram>;
  874. private _compiledEffects: { [key: string]: Effect } = {}
  875. private _vertexAttribArraysEnabled: boolean[] = [];
  876. /** @ignore */
  877. protected _cachedViewport: Nullable<Viewport>;
  878. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  879. /** @ignore */
  880. protected _cachedVertexBuffers: any;
  881. /** @ignore */
  882. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  883. /** @ignore */
  884. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  885. /** @ignore */
  886. protected _currentRenderTarget: Nullable<InternalTexture>;
  887. private _uintIndicesCurrentlySet = false;
  888. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  889. /** @ignore */
  890. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  891. private _currentBufferPointers = new Array<BufferPointer>();
  892. private _currentInstanceLocations = new Array<number>();
  893. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  894. private _textureUnits: Int32Array;
  895. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  896. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  897. private _workingCanvas: Nullable<HTMLCanvasElement>;
  898. private _workingContext: Nullable<CanvasRenderingContext2D>;
  899. private _rescalePostProcess: PassPostProcess;
  900. private _dummyFramebuffer: WebGLFramebuffer;
  901. private _externalData: StringDictionary<Object>;
  902. private _bindedRenderFunction: any;
  903. private _vaoRecordInProgress = false;
  904. private _mustWipeVertexAttributes = false;
  905. private _emptyTexture: Nullable<InternalTexture>;
  906. private _emptyCubeTexture: Nullable<InternalTexture>;
  907. private _emptyTexture3D: Nullable<InternalTexture>;
  908. private _frameHandler: number;
  909. private _nextFreeTextureSlots = new Array<number>();
  910. private _maxSimultaneousTextures = 0;
  911. private _activeRequests = new Array<IFileRequest>();
  912. // Hardware supported Compressed Textures
  913. private _texturesSupported = new Array<string>();
  914. private _textureFormatInUse: Nullable<string>;
  915. /**
  916. * Gets the list of texture formats supported
  917. */
  918. public get texturesSupported(): Array<string> {
  919. return this._texturesSupported;
  920. }
  921. /**
  922. * Gets the list of texture formats in use
  923. */
  924. public get textureFormatInUse(): Nullable<string> {
  925. return this._textureFormatInUse;
  926. }
  927. /**
  928. * Gets the current viewport
  929. */
  930. public get currentViewport(): Nullable<Viewport> {
  931. return this._cachedViewport;
  932. }
  933. /**
  934. * Gets the default empty texture
  935. */
  936. public get emptyTexture(): InternalTexture {
  937. if (!this._emptyTexture) {
  938. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  939. }
  940. return this._emptyTexture;
  941. }
  942. /**
  943. * Gets the default empty 3D texture
  944. */
  945. public get emptyTexture3D(): InternalTexture {
  946. if (!this._emptyTexture3D) {
  947. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  948. }
  949. return this._emptyTexture3D;
  950. }
  951. /**
  952. * Gets the default empty cube texture
  953. */
  954. public get emptyCubeTexture(): InternalTexture {
  955. if (!this._emptyCubeTexture) {
  956. var faceData = new Uint8Array(4);
  957. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  958. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  959. }
  960. return this._emptyCubeTexture;
  961. }
  962. /**
  963. * Creates a new engine
  964. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  965. * @param antialias defines enable antialiasing (default: false)
  966. * @param options defines further options to be sent to the getContext() function
  967. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  968. */
  969. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  970. // Register promises
  971. PromisePolyfill.Apply();
  972. let canvas: Nullable<HTMLCanvasElement> = null;
  973. Engine.Instances.push(this);
  974. if (!canvasOrContext) {
  975. return;
  976. }
  977. options = options || {};
  978. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  979. canvas = <HTMLCanvasElement>canvasOrContext;
  980. this._renderingCanvas = canvas;
  981. if (antialias != null) {
  982. options.antialias = antialias;
  983. }
  984. if (options.deterministicLockstep === undefined) {
  985. options.deterministicLockstep = false;
  986. }
  987. if (options.lockstepMaxSteps === undefined) {
  988. options.lockstepMaxSteps = 4;
  989. }
  990. if (options.preserveDrawingBuffer === undefined) {
  991. options.preserveDrawingBuffer = false;
  992. }
  993. if (options.audioEngine === undefined) {
  994. options.audioEngine = true;
  995. }
  996. if (options.stencil === undefined) {
  997. options.stencil = true;
  998. }
  999. this._deterministicLockstep = options.deterministicLockstep;
  1000. this._lockstepMaxSteps = options.lockstepMaxSteps;
  1001. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  1002. // Exceptions
  1003. if (navigator && navigator.userAgent) {
  1004. let ua = navigator.userAgent;
  1005. for (var exception of Engine.ExceptionList) {
  1006. let key = exception.key;
  1007. let targets = exception.targets;
  1008. if (ua.indexOf(key) > -1) {
  1009. if (exception.capture && exception.captureConstraint) {
  1010. let capture = exception.capture;
  1011. let constraint = exception.captureConstraint;
  1012. let regex = new RegExp(capture);
  1013. let matches = regex.exec(ua);
  1014. if (matches && matches.length > 0) {
  1015. let capturedValue = parseInt(matches[matches.length - 1]);
  1016. if (capturedValue >= constraint) {
  1017. continue;
  1018. }
  1019. }
  1020. }
  1021. for (var target of targets) {
  1022. switch (target) {
  1023. case "uniformBuffer":
  1024. this.disableUniformBuffers = true;
  1025. break;
  1026. case "textureBindingOptimization":
  1027. this.disableTextureBindingOptimization = true;
  1028. break;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. }
  1034. // GL
  1035. if (!options.disableWebGL2Support) {
  1036. try {
  1037. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  1038. if (this._gl) {
  1039. this._webGLVersion = 2.0;
  1040. }
  1041. } catch (e) {
  1042. // Do nothing
  1043. }
  1044. }
  1045. if (!this._gl) {
  1046. if (!canvas) {
  1047. throw new Error("The provided canvas is null or undefined.");
  1048. }
  1049. try {
  1050. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  1051. } catch (e) {
  1052. throw new Error("WebGL not supported");
  1053. }
  1054. }
  1055. if (!this._gl) {
  1056. throw new Error("WebGL not supported");
  1057. }
  1058. this._onCanvasFocus = () => {
  1059. this.onCanvasFocusObservable.notifyObservers(this);
  1060. }
  1061. this._onCanvasBlur = () => {
  1062. this.onCanvasBlurObservable.notifyObservers(this);
  1063. }
  1064. canvas.addEventListener("focus", this._onCanvasFocus);
  1065. canvas.addEventListener("blur", this._onCanvasBlur);
  1066. this._onBlur = () => {
  1067. if (this.disablePerformanceMonitorInBackground) {
  1068. this._performanceMonitor.disable();
  1069. }
  1070. this._windowIsBackground = true;
  1071. };
  1072. this._onFocus = () => {
  1073. if (this.disablePerformanceMonitorInBackground) {
  1074. this._performanceMonitor.enable();
  1075. }
  1076. this._windowIsBackground = false;
  1077. };
  1078. this._onCanvasPointerOut = (ev) => {
  1079. this.onCanvasPointerOutObservable.notifyObservers(ev);
  1080. };
  1081. window.addEventListener("blur", this._onBlur);
  1082. window.addEventListener("focus", this._onFocus);
  1083. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  1084. // Context lost
  1085. if (!this._doNotHandleContextLost) {
  1086. this._onContextLost = (evt: Event) => {
  1087. evt.preventDefault();
  1088. this._contextWasLost = true;
  1089. Tools.Warn("WebGL context lost.");
  1090. this.onContextLostObservable.notifyObservers(this);
  1091. };
  1092. this._onContextRestored = (evt: Event) => {
  1093. // Adding a timeout to avoid race condition at browser level
  1094. setTimeout(() => {
  1095. // Rebuild gl context
  1096. this._initGLContext();
  1097. // Rebuild effects
  1098. this._rebuildEffects();
  1099. // Rebuild textures
  1100. this._rebuildInternalTextures();
  1101. // Rebuild buffers
  1102. this._rebuildBuffers();
  1103. // Cache
  1104. this.wipeCaches(true);
  1105. Tools.Warn("WebGL context successfully restored.");
  1106. this.onContextRestoredObservable.notifyObservers(this);
  1107. this._contextWasLost = false;
  1108. }, 0);
  1109. };
  1110. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  1111. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  1112. }
  1113. } else {
  1114. this._gl = <WebGLRenderingContext>canvasOrContext;
  1115. this._renderingCanvas = this._gl.canvas
  1116. if (this._gl.renderbufferStorageMultisample) {
  1117. this._webGLVersion = 2.0;
  1118. }
  1119. options.stencil = this._gl.getContextAttributes().stencil;
  1120. }
  1121. // Viewport
  1122. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  1123. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  1124. this.resize();
  1125. this._isStencilEnable = options.stencil ? true : false;
  1126. this._initGLContext();
  1127. if (canvas) {
  1128. // Fullscreen
  1129. this._onFullscreenChange = () => {
  1130. if (document.fullscreen !== undefined) {
  1131. this.isFullscreen = document.fullscreen;
  1132. } else if (document.mozFullScreen !== undefined) {
  1133. this.isFullscreen = document.mozFullScreen;
  1134. } else if (document.webkitIsFullScreen !== undefined) {
  1135. this.isFullscreen = document.webkitIsFullScreen;
  1136. } else if (document.msIsFullScreen !== undefined) {
  1137. this.isFullscreen = document.msIsFullScreen;
  1138. }
  1139. // Pointer lock
  1140. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  1141. canvas.requestPointerLock = canvas.requestPointerLock ||
  1142. canvas.msRequestPointerLock ||
  1143. canvas.mozRequestPointerLock ||
  1144. canvas.webkitRequestPointerLock;
  1145. if (canvas.requestPointerLock) {
  1146. canvas.requestPointerLock();
  1147. }
  1148. }
  1149. };
  1150. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  1151. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  1152. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  1153. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  1154. // Pointer lock
  1155. this._onPointerLockChange = () => {
  1156. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  1157. document.webkitPointerLockElement === canvas ||
  1158. document.msPointerLockElement === canvas ||
  1159. document.pointerLockElement === canvas
  1160. );
  1161. };
  1162. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  1163. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1164. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1165. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1166. this._onVRDisplayPointerRestricted = () => {
  1167. if (canvas) {
  1168. canvas.requestPointerLock();
  1169. }
  1170. }
  1171. this._onVRDisplayPointerUnrestricted = () => {
  1172. document.exitPointerLock();
  1173. }
  1174. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1175. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1176. }
  1177. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  1178. Engine.audioEngine = new AudioEngine();
  1179. }
  1180. // Prepare buffer pointers
  1181. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1182. this._currentBufferPointers[i] = new BufferPointer();
  1183. }
  1184. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1185. // Load WebVR Devices
  1186. if (options.autoEnableWebVR) {
  1187. this.initWebVR();
  1188. }
  1189. // Detect if we are running on a faulty buggy OS.
  1190. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1191. // Detect if we are running on a faulty buggy desktop OS.
  1192. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1193. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  1194. this.enableOfflineSupport = (Database !== undefined);
  1195. }
  1196. private _rebuildInternalTextures(): void {
  1197. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1198. for (var internalTexture of currentState) {
  1199. internalTexture._rebuild();
  1200. }
  1201. }
  1202. private _rebuildEffects(): void {
  1203. for (var key in this._compiledEffects) {
  1204. let effect = <Effect>this._compiledEffects[key];
  1205. effect._prepareEffect();
  1206. }
  1207. Effect.ResetCache();
  1208. }
  1209. private _rebuildBuffers(): void {
  1210. // Index / Vertex
  1211. for (var scene of this.scenes) {
  1212. scene.resetCachedMaterial();
  1213. scene._rebuildGeometries();
  1214. scene._rebuildTextures();
  1215. }
  1216. // Uniforms
  1217. for (var uniformBuffer of this._uniformBuffers) {
  1218. uniformBuffer._rebuild();
  1219. }
  1220. }
  1221. private _initGLContext(): void {
  1222. // Caps
  1223. this._caps = new EngineCapabilities();
  1224. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1225. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1226. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1227. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1228. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1229. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1230. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1231. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1232. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1233. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1234. // Infos
  1235. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1236. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1237. if (rendererInfo != null) {
  1238. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1239. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1240. }
  1241. if (!this._glVendor) {
  1242. this._glVendor = "Unknown vendor";
  1243. }
  1244. if (!this._glRenderer) {
  1245. this._glRenderer = "Unknown renderer";
  1246. }
  1247. // Constants
  1248. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1249. if (this._gl.RGBA16F !== 0x881A) {
  1250. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1251. }
  1252. if (this._gl.RGBA32F !== 0x8814) {
  1253. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1254. }
  1255. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1256. this._gl.DEPTH24_STENCIL8 = 35056;
  1257. }
  1258. // Extensions
  1259. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1260. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1261. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1262. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1263. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1264. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1265. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1266. 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');
  1267. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1268. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1269. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1270. this._caps.highPrecisionShaderSupported = true;
  1271. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1272. if (this._caps.timerQuery) {
  1273. if (this._webGLVersion === 1) {
  1274. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1275. }
  1276. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1277. }
  1278. // Checks if some of the format renders first to allow the use of webgl inspector.
  1279. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1280. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1281. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1282. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true: false;
  1283. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true: false;
  1284. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1285. if (this._webGLVersion > 1) {
  1286. this._gl.HALF_FLOAT_OES = 0x140B;
  1287. }
  1288. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1289. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true: false;
  1290. // Draw buffers
  1291. if (this._webGLVersion > 1) {
  1292. this._caps.drawBuffersExtension = true;
  1293. } else {
  1294. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1295. if (drawBuffersExtension !== null) {
  1296. this._caps.drawBuffersExtension = true;
  1297. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1298. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1299. for (var i = 0; i < 16; i++) {
  1300. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1301. }
  1302. } else {
  1303. this._caps.drawBuffersExtension = false;
  1304. }
  1305. }
  1306. // Depth Texture
  1307. if (this._webGLVersion > 1) {
  1308. this._caps.depthTextureExtension = true;
  1309. } else {
  1310. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1311. if (depthTextureExtension != null) {
  1312. this._caps.depthTextureExtension = true;
  1313. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1314. }
  1315. }
  1316. // Vertex array object
  1317. if (this._webGLVersion > 1) {
  1318. this._caps.vertexArrayObject = true;
  1319. } else {
  1320. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1321. if (vertexArrayObjectExtension != null) {
  1322. this._caps.vertexArrayObject = true;
  1323. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1324. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1325. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1326. } else {
  1327. this._caps.vertexArrayObject = false;
  1328. }
  1329. }
  1330. // Instances count
  1331. if (this._webGLVersion > 1) {
  1332. this._caps.instancedArrays = true;
  1333. } else {
  1334. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1335. if (instanceExtension != null) {
  1336. this._caps.instancedArrays = true;
  1337. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1338. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1339. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1340. } else {
  1341. this._caps.instancedArrays = false;
  1342. }
  1343. }
  1344. // Intelligently add supported compressed formats in order to check for.
  1345. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1346. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1347. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1348. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1349. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1350. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1351. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1352. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1353. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1354. if (this._gl.getShaderPrecisionFormat) {
  1355. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1356. if (highp) {
  1357. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1358. }
  1359. }
  1360. // Depth buffer
  1361. this.setDepthBuffer(true);
  1362. this.setDepthFunctionToLessOrEqual();
  1363. this.setDepthWrite(true);
  1364. // Texture maps
  1365. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1366. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1367. this._nextFreeTextureSlots.push(slot);
  1368. }
  1369. }
  1370. /**
  1371. * Gets version of the current webGL context
  1372. */
  1373. public get webGLVersion(): number {
  1374. return this._webGLVersion;
  1375. }
  1376. /**
  1377. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1378. */
  1379. public get isStencilEnable(): boolean {
  1380. return this._isStencilEnable;
  1381. }
  1382. private _prepareWorkingCanvas(): void {
  1383. if (this._workingCanvas) {
  1384. return;
  1385. }
  1386. this._workingCanvas = document.createElement("canvas");
  1387. let context = this._workingCanvas.getContext("2d");
  1388. if (context) {
  1389. this._workingContext = context;
  1390. }
  1391. }
  1392. /**
  1393. * Reset the texture cache to empty state
  1394. */
  1395. public resetTextureCache() {
  1396. for (var key in this._boundTexturesCache) {
  1397. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1398. continue;
  1399. }
  1400. let boundTexture = this._boundTexturesCache[key];
  1401. if (boundTexture) {
  1402. this._removeDesignatedSlot(boundTexture);
  1403. }
  1404. this._boundTexturesCache[key] = null;
  1405. }
  1406. if (!this.disableTextureBindingOptimization) {
  1407. this._nextFreeTextureSlots = [];
  1408. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1409. this._nextFreeTextureSlots.push(slot);
  1410. }
  1411. }
  1412. this._currentTextureChannel = -1;
  1413. }
  1414. /**
  1415. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1416. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1417. * @returns true if engine is in deterministic lock step mode
  1418. */
  1419. public isDeterministicLockStep(): boolean {
  1420. return this._deterministicLockstep;
  1421. }
  1422. /**
  1423. * Gets the max steps when engine is running in deterministic lock step
  1424. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1425. * @returns the max steps
  1426. */
  1427. public getLockstepMaxSteps(): number {
  1428. return this._lockstepMaxSteps;
  1429. }
  1430. /**
  1431. * Gets an object containing information about the current webGL context
  1432. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1433. */
  1434. public getGlInfo() {
  1435. return {
  1436. vendor: this._glVendor,
  1437. renderer: this._glRenderer,
  1438. version: this._glVersion
  1439. }
  1440. }
  1441. /**
  1442. * Gets current aspect ratio
  1443. * @param camera defines the camera to use to get the aspect ratio
  1444. * @param useScreen defines if screen size must be used (or the current render target if any)
  1445. * @returns a number defining the aspect ratio
  1446. */
  1447. public getAspectRatio(camera: Camera, useScreen = false): number {
  1448. var viewport = camera.viewport;
  1449. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1450. }
  1451. /**
  1452. * Gets the current render width
  1453. * @param useScreen defines if screen size must be used (or the current render target if any)
  1454. * @returns a number defining the current render width
  1455. */
  1456. public getRenderWidth(useScreen = false): number {
  1457. if (!useScreen && this._currentRenderTarget) {
  1458. return this._currentRenderTarget.width;
  1459. }
  1460. return this._gl.drawingBufferWidth;
  1461. }
  1462. /**
  1463. * Gets the current render height
  1464. * @param useScreen defines if screen size must be used (or the current render target if any)
  1465. * @returns a number defining the current render height
  1466. */
  1467. public getRenderHeight(useScreen = false): number {
  1468. if (!useScreen && this._currentRenderTarget) {
  1469. return this._currentRenderTarget.height;
  1470. }
  1471. return this._gl.drawingBufferHeight;
  1472. }
  1473. /**
  1474. * Gets the HTML canvas attached with the current webGL context
  1475. * @returns a HTML canvas
  1476. */
  1477. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1478. return this._renderingCanvas;
  1479. }
  1480. /**
  1481. * Gets the client rect of the HTML canvas attached with the current webGL context
  1482. * @returns a client rectanglee
  1483. */
  1484. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1485. if (!this._renderingCanvas) {
  1486. return null;
  1487. }
  1488. return this._renderingCanvas.getBoundingClientRect();
  1489. }
  1490. /**
  1491. * Defines the hardware scaling level.
  1492. * By default the hardware scaling level is computed from the window device ratio.
  1493. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1494. * @param level defines the level to use
  1495. */
  1496. public setHardwareScalingLevel(level: number): void {
  1497. this._hardwareScalingLevel = level;
  1498. this.resize();
  1499. }
  1500. /**
  1501. * Gets the current hardware scaling level.
  1502. * By default the hardware scaling level is computed from the window device ratio.
  1503. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1504. * @returns a number indicating the current hardware scaling level
  1505. */
  1506. public getHardwareScalingLevel(): number {
  1507. return this._hardwareScalingLevel;
  1508. }
  1509. /**
  1510. * Gets the list of loaded textures
  1511. * @returns an array containing all loaded textures
  1512. */
  1513. public getLoadedTexturesCache(): InternalTexture[] {
  1514. return this._internalTexturesCache;
  1515. }
  1516. /**
  1517. * Gets the object containing all engine capabilities
  1518. * @returns the EngineCapabilities object
  1519. */
  1520. public getCaps(): EngineCapabilities {
  1521. return this._caps;
  1522. }
  1523. /** @ignore */
  1524. public get drawCalls(): number {
  1525. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1526. return 0;
  1527. }
  1528. /** @ignore */
  1529. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1530. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1531. return null;
  1532. }
  1533. /**
  1534. * Gets the current depth function
  1535. * @returns a number defining the depth function
  1536. */
  1537. public getDepthFunction(): Nullable<number> {
  1538. return this._depthCullingState.depthFunc;
  1539. }
  1540. /**
  1541. * Sets the current depth function
  1542. * @param depthFunc defines the function to use
  1543. */
  1544. public setDepthFunction(depthFunc: number) {
  1545. this._depthCullingState.depthFunc = depthFunc;
  1546. }
  1547. /**
  1548. * Sets the current depth function to GREATER
  1549. */
  1550. public setDepthFunctionToGreater(): void {
  1551. this._depthCullingState.depthFunc = this._gl.GREATER;
  1552. }
  1553. /**
  1554. * Sets the current depth function to GEQUAL
  1555. */
  1556. public setDepthFunctionToGreaterOrEqual(): void {
  1557. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1558. }
  1559. /**
  1560. * Sets the current depth function to LESS
  1561. */
  1562. public setDepthFunctionToLess(): void {
  1563. this._depthCullingState.depthFunc = this._gl.LESS;
  1564. }
  1565. /**
  1566. * Sets the current depth function to LEQUAL
  1567. */
  1568. public setDepthFunctionToLessOrEqual(): void {
  1569. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1570. }
  1571. /**
  1572. * Gets a boolean indicating if stencil buffer is enabled
  1573. * @returns the current stencil buffer state
  1574. */
  1575. public getStencilBuffer(): boolean {
  1576. return this._stencilState.stencilTest;
  1577. }
  1578. /**
  1579. * Enable or disable the stencil buffer
  1580. * @param enable defines if the stencil buffer must be enabled or disabled
  1581. */
  1582. public setStencilBuffer(enable: boolean): void {
  1583. this._stencilState.stencilTest = enable;
  1584. }
  1585. /**
  1586. * Gets the current stencil mask
  1587. * @returns a number defining the new stencil mask to use
  1588. */
  1589. public getStencilMask(): number {
  1590. return this._stencilState.stencilMask;
  1591. }
  1592. /**
  1593. * Sets the current stencil mask
  1594. * @param mask defines the new stencil mask to use
  1595. */
  1596. public setStencilMask(mask: number): void {
  1597. this._stencilState.stencilMask = mask;
  1598. }
  1599. /**
  1600. * Gets the current stencil function
  1601. * @returns a number defining the stencil function to use
  1602. */
  1603. public getStencilFunction(): number {
  1604. return this._stencilState.stencilFunc;
  1605. }
  1606. /**
  1607. * Gets the current stencil reference value
  1608. * @returns a number defining the stencil reference value to use
  1609. */
  1610. public getStencilFunctionReference(): number {
  1611. return this._stencilState.stencilFuncRef;
  1612. }
  1613. /**
  1614. * Gets the current stencil mask
  1615. * @returns a number defining the stencil mask to use
  1616. */
  1617. public getStencilFunctionMask(): number {
  1618. return this._stencilState.stencilFuncMask;
  1619. }
  1620. /**
  1621. * Sets the current stencil function
  1622. * @param stencilFunc defines the new stencil function to use
  1623. */
  1624. public setStencilFunction(stencilFunc: number) {
  1625. this._stencilState.stencilFunc = stencilFunc;
  1626. }
  1627. /**
  1628. * Sets the current stencil reference
  1629. * @param reference defines the new stencil reference to use
  1630. */
  1631. public setStencilFunctionReference(reference: number) {
  1632. this._stencilState.stencilFuncRef = reference;
  1633. }
  1634. /**
  1635. * Sets the current stencil mask
  1636. * @param mask defines the new stencil mask to use
  1637. */
  1638. public setStencilFunctionMask(mask: number) {
  1639. this._stencilState.stencilFuncMask = mask;
  1640. }
  1641. /**
  1642. * Gets the current stencil operation when stencil fails
  1643. * @returns a number defining stencil operation to use when stencil fails
  1644. */
  1645. public getStencilOperationFail(): number {
  1646. return this._stencilState.stencilOpStencilFail;
  1647. }
  1648. /**
  1649. * Gets the current stencil operation when depth fails
  1650. * @returns a number defining stencil operation to use when depth fails
  1651. */
  1652. public getStencilOperationDepthFail(): number {
  1653. return this._stencilState.stencilOpDepthFail;
  1654. }
  1655. /**
  1656. * Gets the current stencil operation when stencil passes
  1657. * @returns a number defining stencil operation to use when stencil passes
  1658. */
  1659. public getStencilOperationPass(): number {
  1660. return this._stencilState.stencilOpStencilDepthPass;
  1661. }
  1662. /**
  1663. * Sets the stencil operation to use when stencil fails
  1664. * @param operation defines the stencil operation to use when stencil fails
  1665. */
  1666. public setStencilOperationFail(operation: number): void {
  1667. this._stencilState.stencilOpStencilFail = operation;
  1668. }
  1669. /**
  1670. * Sets the stencil operation to use when depth fails
  1671. * @param operation defines the stencil operation to use when depth fails
  1672. */
  1673. public setStencilOperationDepthFail(operation: number): void {
  1674. this._stencilState.stencilOpDepthFail = operation;
  1675. }
  1676. /**
  1677. * Sets the stencil operation to use when stencil passes
  1678. * @param operation defines the stencil operation to use when stencil passes
  1679. */
  1680. public setStencilOperationPass(operation: number): void {
  1681. this._stencilState.stencilOpStencilDepthPass = operation;
  1682. }
  1683. /**
  1684. * Sets a boolean indicating if the dithering state is enabled or disabled
  1685. * @param value defines the dithering state
  1686. */
  1687. public setDitheringState(value: boolean): void {
  1688. if (value) {
  1689. this._gl.enable(this._gl.DITHER);
  1690. } else {
  1691. this._gl.disable(this._gl.DITHER);
  1692. }
  1693. }
  1694. /**
  1695. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1696. * @param value defines the rasterizer state
  1697. */
  1698. public setRasterizerState(value: boolean): void {
  1699. if (value) {
  1700. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1701. } else {
  1702. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1703. }
  1704. }
  1705. /**
  1706. * stop executing a render loop function and remove it from the execution array
  1707. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1708. */
  1709. public stopRenderLoop(renderFunction?: () => void): void {
  1710. if (!renderFunction) {
  1711. this._activeRenderLoops = [];
  1712. return;
  1713. }
  1714. var index = this._activeRenderLoops.indexOf(renderFunction);
  1715. if (index >= 0) {
  1716. this._activeRenderLoops.splice(index, 1);
  1717. }
  1718. }
  1719. /** @ignore */
  1720. public _renderLoop(): void {
  1721. if (!this._contextWasLost) {
  1722. var shouldRender = true;
  1723. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1724. shouldRender = false;
  1725. }
  1726. if (shouldRender) {
  1727. // Start new frame
  1728. this.beginFrame();
  1729. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1730. var renderFunction = this._activeRenderLoops[index];
  1731. renderFunction();
  1732. }
  1733. // Present
  1734. this.endFrame();
  1735. }
  1736. }
  1737. if (this._activeRenderLoops.length > 0) {
  1738. // Register new frame
  1739. var requester = null;
  1740. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1741. requester = this._vrDisplay;
  1742. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1743. } else {
  1744. this._renderingQueueLaunched = false;
  1745. }
  1746. }
  1747. /**
  1748. * Register and execute a render loop. The engine can have more than one render function
  1749. * @param renderFunction defines the function to continuously execute
  1750. */
  1751. public runRenderLoop(renderFunction: () => void): void {
  1752. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1753. return;
  1754. }
  1755. this._activeRenderLoops.push(renderFunction);
  1756. if (!this._renderingQueueLaunched) {
  1757. this._renderingQueueLaunched = true;
  1758. this._bindedRenderFunction = this._renderLoop.bind(this);
  1759. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1760. }
  1761. }
  1762. /**
  1763. * Toggle full screen mode
  1764. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1765. * @param options defines an option object to be sent to the requestFullscreen function
  1766. */
  1767. public switchFullscreen(requestPointerLock: boolean): void {
  1768. if (this.isFullscreen) {
  1769. Tools.ExitFullscreen();
  1770. } else {
  1771. this._pointerLockRequested = requestPointerLock;
  1772. if (this._renderingCanvas) {
  1773. Tools.RequestFullscreen(this._renderingCanvas);
  1774. }
  1775. }
  1776. }
  1777. /**
  1778. * Clear the current render buffer or the current render target (if any is set up)
  1779. * @param color defines the color to use
  1780. * @param backBuffer defines if the back buffer must be cleared
  1781. * @param depth defines if the depth buffer must be cleared
  1782. * @param stencil defines if the stencil buffer must be cleared
  1783. */
  1784. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1785. this.applyStates();
  1786. var mode = 0;
  1787. if (backBuffer && color) {
  1788. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1789. mode |= this._gl.COLOR_BUFFER_BIT;
  1790. }
  1791. if (depth) {
  1792. this._gl.clearDepth(1.0);
  1793. mode |= this._gl.DEPTH_BUFFER_BIT;
  1794. }
  1795. if (stencil) {
  1796. this._gl.clearStencil(0);
  1797. mode |= this._gl.STENCIL_BUFFER_BIT;
  1798. }
  1799. this._gl.clear(mode);
  1800. }
  1801. /**
  1802. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1803. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1804. * @param y defines the y-coordinate of the corner of the clear rectangle
  1805. * @param width defines the width of the clear rectangle
  1806. * @param height defines the height of the clear rectangle
  1807. * @param clearColor defines the clear color
  1808. */
  1809. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1810. let gl = this._gl;
  1811. // Save state
  1812. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1813. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1814. // Change state
  1815. gl.enable(gl.SCISSOR_TEST);
  1816. gl.scissor(x, y, width, height);
  1817. // Clear
  1818. this.clear(clearColor, true, true, true);
  1819. // Restore state
  1820. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1821. if (curScissor === true) {
  1822. gl.enable(gl.SCISSOR_TEST);
  1823. } else {
  1824. gl.disable(gl.SCISSOR_TEST);
  1825. }
  1826. }
  1827. /**
  1828. * Set the WebGL's viewport
  1829. * @param viewport defines the viewport element to be used
  1830. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1831. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1832. */
  1833. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1834. var width = requiredWidth || this.getRenderWidth();
  1835. var height = requiredHeight || this.getRenderHeight();
  1836. var x = viewport.x || 0;
  1837. var y = viewport.y || 0;
  1838. this._cachedViewport = viewport;
  1839. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1840. }
  1841. /**
  1842. * Directly set the WebGL Viewport
  1843. * @param x defines the x coordinate of the viewport (in screen space)
  1844. * @param y defines the y coordinate of the viewport (in screen space)
  1845. * @param width defines the width of the viewport (in screen space)
  1846. * @param height defines the height of the viewport (in screen space)
  1847. * @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
  1848. */
  1849. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1850. let currentViewport = this._cachedViewport;
  1851. this._cachedViewport = null;
  1852. this._gl.viewport(x, y, width, height);
  1853. return currentViewport;
  1854. }
  1855. /**
  1856. * Begin a new frame
  1857. */
  1858. public beginFrame(): void {
  1859. this.onBeginFrameObservable.notifyObservers(this);
  1860. this._measureFps();
  1861. }
  1862. /**
  1863. * Enf the current frame
  1864. */
  1865. public endFrame(): void {
  1866. // Force a flush in case we are using a bad OS.
  1867. if (this._badOS) {
  1868. this.flushFramebuffer();
  1869. }
  1870. // Submit frame to the vr device, if enabled
  1871. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1872. // TODO: We should only submit the frame if we read frameData successfully.
  1873. this._vrDisplay.submitFrame();
  1874. }
  1875. this.onEndFrameObservable.notifyObservers(this);
  1876. }
  1877. /**
  1878. * Resize the view according to the canvas' size
  1879. */
  1880. public resize(): void {
  1881. // We're not resizing the size of the canvas while in VR mode & presenting
  1882. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1883. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1884. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1885. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1886. }
  1887. }
  1888. /**
  1889. * Force a specific size of the canvas
  1890. * @param width defines the new canvas' width
  1891. * @param height defines the new canvas' height
  1892. */
  1893. public setSize(width: number, height: number): void {
  1894. if (!this._renderingCanvas) {
  1895. return;
  1896. }
  1897. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1898. return;
  1899. }
  1900. this._renderingCanvas.width = width;
  1901. this._renderingCanvas.height = height;
  1902. for (var index = 0; index < this.scenes.length; index++) {
  1903. var scene = this.scenes[index];
  1904. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1905. var cam = scene.cameras[camIndex];
  1906. cam._currentRenderId = 0;
  1907. }
  1908. }
  1909. if (this.onResizeObservable.hasObservers) {
  1910. this.onResizeObservable.notifyObservers(this);
  1911. }
  1912. }
  1913. // WebVR functions
  1914. /**
  1915. * Gets a boolean indicating if a webVR device was detected
  1916. * @returns true if a webVR device was detected
  1917. */
  1918. public isVRDevicePresent(): boolean {
  1919. return !!this._vrDisplay;
  1920. }
  1921. /**
  1922. * Gets the current webVR device
  1923. * @returns the current webVR device (or null)
  1924. */
  1925. public getVRDevice(): any {
  1926. return this._vrDisplay;
  1927. }
  1928. /**
  1929. * Initializes a webVR display and starts listening to display change events
  1930. * The onVRDisplayChangedObservable will be notified upon these changes
  1931. * @returns The onVRDisplayChangedObservable
  1932. */
  1933. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1934. this.initWebVRAsync();
  1935. return this.onVRDisplayChangedObservable;
  1936. }
  1937. /**
  1938. * Initializes a webVR display and starts listening to display change events
  1939. * The onVRDisplayChangedObservable will be notified upon these changes
  1940. * @returns A promise containing a VRDisplay and if vr is supported
  1941. */
  1942. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1943. var notifyObservers = () => {
  1944. var eventArgs = {
  1945. vrDisplay: this._vrDisplay,
  1946. vrSupported: this._vrSupported
  1947. };
  1948. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1949. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1950. }
  1951. if (!this._onVrDisplayConnect) {
  1952. this._onVrDisplayConnect = (event) => {
  1953. this._vrDisplay = event.display;
  1954. notifyObservers();
  1955. };
  1956. this._onVrDisplayDisconnect = () => {
  1957. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1958. this._vrDisplay = undefined;
  1959. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1960. notifyObservers();
  1961. };
  1962. this._onVrDisplayPresentChange = () => {
  1963. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1964. }
  1965. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1966. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1967. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1968. }
  1969. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1970. this._webVRInitPromise.then(notifyObservers);
  1971. return this._webVRInitPromise;
  1972. }
  1973. /**
  1974. * Call this function to switch to webVR mode
  1975. * Will do nothing if webVR is not supported or if there is no webVR device
  1976. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1977. */
  1978. public enableVR() {
  1979. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1980. var onResolved = () => {
  1981. this.onVRRequestPresentComplete.notifyObservers(true);
  1982. this._onVRFullScreenTriggered();
  1983. };
  1984. var onRejected = () => {
  1985. this.onVRRequestPresentComplete.notifyObservers(false);
  1986. };
  1987. this.onVRRequestPresentStart.notifyObservers(this);
  1988. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1989. }
  1990. }
  1991. /**
  1992. * Call this function to leave webVR mode
  1993. * Will do nothing if webVR is not supported or if there is no webVR device
  1994. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1995. */
  1996. public disableVR() {
  1997. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1998. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1999. }
  2000. }
  2001. private _onVRFullScreenTriggered = () => {
  2002. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  2003. //get the old size before we change
  2004. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  2005. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  2006. //get the width and height, change the render size
  2007. var leftEye = this._vrDisplay.getEyeParameters('left');
  2008. this.setHardwareScalingLevel(1);
  2009. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  2010. } else {
  2011. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  2012. this.setSize(this._oldSize.width, this._oldSize.height);
  2013. }
  2014. }
  2015. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  2016. return new Promise((res, rej)=>{
  2017. if (navigator.getVRDisplays) {
  2018. navigator.getVRDisplays().then((devices: Array<any>)=>{
  2019. this._vrSupported = true;
  2020. // note that devices may actually be an empty array. This is fine;
  2021. // we expect this._vrDisplay to be undefined in this case.
  2022. this._vrDisplay = devices[0];
  2023. res({
  2024. vrDisplay: this._vrDisplay,
  2025. vrSupported: this._vrSupported
  2026. });
  2027. });
  2028. } else {
  2029. this._vrDisplay = undefined;
  2030. this._vrSupported = false;
  2031. res({
  2032. vrDisplay: this._vrDisplay,
  2033. vrSupported: this._vrSupported
  2034. });
  2035. }
  2036. });
  2037. }
  2038. /**
  2039. * Binds the frame buffer to the specified texture.
  2040. * @param texture The texture to render to or null for the default canvas
  2041. * @param faceIndex The face of the texture to render to in case of cube texture
  2042. * @param requiredWidth The width of the target to render to
  2043. * @param requiredHeight The height of the target to render to
  2044. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  2045. * @param depthStencilTexture The depth stencil texture to use to render
  2046. */
  2047. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture): void {
  2048. if (this._currentRenderTarget) {
  2049. this.unBindFramebuffer(this._currentRenderTarget);
  2050. }
  2051. this._currentRenderTarget = texture;
  2052. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  2053. var gl = this._gl;
  2054. if (texture.isCube) {
  2055. if (faceIndex === undefined) {
  2056. faceIndex = 0;
  2057. }
  2058. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  2059. if (depthStencilTexture) {
  2060. if (depthStencilTexture._generateStencilBuffer) {
  2061. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  2062. }
  2063. else {
  2064. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  2065. }
  2066. }
  2067. }
  2068. if (this._cachedViewport && !forceFullscreenViewport) {
  2069. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  2070. } else {
  2071. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  2072. }
  2073. this.wipeCaches();
  2074. }
  2075. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  2076. if (this._currentFramebuffer !== framebuffer) {
  2077. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  2078. this._currentFramebuffer = framebuffer;
  2079. }
  2080. }
  2081. /**
  2082. * Unbind the current render target texture from the webGL context
  2083. * @param texture defines the render target texture to unbind
  2084. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2085. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2086. */
  2087. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2088. this._currentRenderTarget = null;
  2089. // If MSAA, we need to bitblt back to main texture
  2090. var gl = this._gl;
  2091. if (texture._MSAAFramebuffer) {
  2092. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  2093. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  2094. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2095. 0, 0, texture.width, texture.height,
  2096. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2097. }
  2098. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2099. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2100. gl.generateMipmap(gl.TEXTURE_2D);
  2101. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2102. }
  2103. if (onBeforeUnbind) {
  2104. if (texture._MSAAFramebuffer) {
  2105. // Bind the correct framebuffer
  2106. this.bindUnboundFramebuffer(texture._framebuffer);
  2107. }
  2108. onBeforeUnbind();
  2109. }
  2110. this.bindUnboundFramebuffer(null);
  2111. }
  2112. /**
  2113. * Unbind a list of render target textures from the webGL context
  2114. * This is used only when drawBuffer extension or webGL2 are active
  2115. * @param textures defines the render target textures to unbind
  2116. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2117. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2118. */
  2119. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2120. this._currentRenderTarget = null;
  2121. // If MSAA, we need to bitblt back to main texture
  2122. var gl = this._gl;
  2123. if (textures[0]._MSAAFramebuffer) {
  2124. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  2125. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  2126. var attachments = textures[0]._attachments;
  2127. if (!attachments) {
  2128. attachments = new Array(textures.length);
  2129. textures[0]._attachments = attachments;
  2130. }
  2131. for (var i = 0; i < textures.length; i++) {
  2132. var texture = textures[i];
  2133. for (var j = 0; j < attachments.length; j++) {
  2134. attachments[j] = gl.NONE;
  2135. }
  2136. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2137. gl.readBuffer(attachments[i]);
  2138. gl.drawBuffers(attachments);
  2139. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2140. 0, 0, texture.width, texture.height,
  2141. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2142. }
  2143. for (var i = 0; i < attachments.length; i++) {
  2144. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2145. }
  2146. gl.drawBuffers(attachments);
  2147. }
  2148. for (var i = 0; i < textures.length; i++) {
  2149. var texture = textures[i];
  2150. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2151. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2152. gl.generateMipmap(gl.TEXTURE_2D);
  2153. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2154. }
  2155. }
  2156. if (onBeforeUnbind) {
  2157. if (textures[0]._MSAAFramebuffer) {
  2158. // Bind the correct framebuffer
  2159. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  2160. }
  2161. onBeforeUnbind();
  2162. }
  2163. this.bindUnboundFramebuffer(null);
  2164. }
  2165. /**
  2166. * Force the mipmap generation for the given render target texture
  2167. * @param texture defines the render target texture to use
  2168. */
  2169. public generateMipMapsForCubemap(texture: InternalTexture) {
  2170. if (texture.generateMipMaps) {
  2171. var gl = this._gl;
  2172. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2173. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2174. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2175. }
  2176. }
  2177. /**
  2178. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2179. */
  2180. public flushFramebuffer(): void {
  2181. this._gl.flush();
  2182. }
  2183. /**
  2184. * Unbind the current render target and bind the default framebuffer
  2185. */
  2186. public restoreDefaultFramebuffer(): void {
  2187. if (this._currentRenderTarget) {
  2188. this.unBindFramebuffer(this._currentRenderTarget);
  2189. } else {
  2190. this.bindUnboundFramebuffer(null);
  2191. }
  2192. if (this._cachedViewport) {
  2193. this.setViewport(this._cachedViewport);
  2194. }
  2195. this.wipeCaches();
  2196. }
  2197. // UBOs
  2198. /**
  2199. * Create an uniform buffer
  2200. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2201. * @param elements defines the content of the uniform buffer
  2202. * @returns the webGL uniform buffer
  2203. */
  2204. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2205. var ubo = this._gl.createBuffer();
  2206. if (!ubo) {
  2207. throw new Error("Unable to create uniform buffer");
  2208. }
  2209. this.bindUniformBuffer(ubo);
  2210. if (elements instanceof Float32Array) {
  2211. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2212. } else {
  2213. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2214. }
  2215. this.bindUniformBuffer(null);
  2216. ubo.references = 1;
  2217. return ubo;
  2218. }
  2219. /**
  2220. * Create a dynamic uniform buffer
  2221. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2222. * @param elements defines the content of the uniform buffer
  2223. * @returns the webGL uniform buffer
  2224. */
  2225. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2226. var ubo = this._gl.createBuffer();
  2227. if (!ubo) {
  2228. throw new Error("Unable to create dynamic uniform buffer");
  2229. }
  2230. this.bindUniformBuffer(ubo);
  2231. if (elements instanceof Float32Array) {
  2232. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2233. } else {
  2234. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2235. }
  2236. this.bindUniformBuffer(null);
  2237. ubo.references = 1;
  2238. return ubo;
  2239. }
  2240. /**
  2241. * Update an existing uniform buffer
  2242. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2243. * @param uniformBuffer defines the target uniform buffer
  2244. * @param elements defines the content to update
  2245. * @param offset defines the offset in the uniform buffer where update should start
  2246. * @param count defines the size of the data to update
  2247. */
  2248. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2249. this.bindUniformBuffer(uniformBuffer);
  2250. if (offset === undefined) {
  2251. offset = 0;
  2252. }
  2253. if (count === undefined) {
  2254. if (elements instanceof Float32Array) {
  2255. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2256. } else {
  2257. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2258. }
  2259. } else {
  2260. if (elements instanceof Float32Array) {
  2261. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2262. } else {
  2263. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2264. }
  2265. }
  2266. this.bindUniformBuffer(null);
  2267. }
  2268. // VBOs
  2269. private _resetVertexBufferBinding(): void {
  2270. this.bindArrayBuffer(null);
  2271. this._cachedVertexBuffers = null;
  2272. }
  2273. /**
  2274. * Creates a vertex buffer
  2275. * @param data the data for the vertex buffer
  2276. * @returns the new WebGL static buffer
  2277. */
  2278. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2279. var vbo = this._gl.createBuffer();
  2280. if (!vbo) {
  2281. throw new Error("Unable to create vertex buffer");
  2282. }
  2283. this.bindArrayBuffer(vbo);
  2284. if (data instanceof Array) {
  2285. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2286. } else {
  2287. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2288. }
  2289. this._resetVertexBufferBinding();
  2290. vbo.references = 1;
  2291. return vbo;
  2292. }
  2293. /**
  2294. * Creates a dynamic vertex buffer
  2295. * @param data the data for the dynamic vertex buffer
  2296. * @returns the new WebGL dynamic buffer
  2297. */
  2298. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2299. var vbo = this._gl.createBuffer();
  2300. if (!vbo) {
  2301. throw new Error("Unable to create dynamic vertex buffer");
  2302. }
  2303. this.bindArrayBuffer(vbo);
  2304. if (data instanceof Array) {
  2305. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2306. } else {
  2307. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2308. }
  2309. this._resetVertexBufferBinding();
  2310. vbo.references = 1;
  2311. return vbo;
  2312. }
  2313. /**
  2314. * Update a dynamic index buffer
  2315. * @param indexBuffer defines the target index buffer
  2316. * @param indices defines the data to update
  2317. * @param offset defines the offset in the target index buffer where update should start
  2318. */
  2319. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2320. // Force cache update
  2321. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2322. this.bindIndexBuffer(indexBuffer);
  2323. var arrayBuffer;
  2324. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2325. arrayBuffer = indices;
  2326. } else {
  2327. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2328. }
  2329. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2330. this._resetIndexBufferBinding();
  2331. }
  2332. /**
  2333. * Updates a dynamic vertex buffer.
  2334. * @param vertexBuffer the vertex buffer to update
  2335. * @param data the data used to update the vertex buffer
  2336. * @param byteOffset the byte offset of the data
  2337. * @param byteLength the byte length of the data
  2338. */
  2339. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2340. this.bindArrayBuffer(vertexBuffer);
  2341. if (byteOffset === undefined) {
  2342. byteOffset = 0;
  2343. }
  2344. if (byteLength === undefined) {
  2345. if (data instanceof Array) {
  2346. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2347. } else {
  2348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2349. }
  2350. } else {
  2351. if (data instanceof Array) {
  2352. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2353. } else {
  2354. if (data instanceof ArrayBuffer) {
  2355. data = new Uint8Array(data, byteOffset, byteLength);
  2356. } else {
  2357. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2358. }
  2359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2360. }
  2361. }
  2362. this._resetVertexBufferBinding();
  2363. }
  2364. private _resetIndexBufferBinding(): void {
  2365. this.bindIndexBuffer(null);
  2366. this._cachedIndexBuffer = null;
  2367. }
  2368. /**
  2369. * Creates a new index buffer
  2370. * @param indices defines the content of the index buffer
  2371. * @param updatable defines if the index buffer must be updatable
  2372. * @returns a new webGL buffer
  2373. */
  2374. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2375. var vbo = this._gl.createBuffer();
  2376. if (!vbo) {
  2377. throw new Error("Unable to create index buffer");
  2378. }
  2379. this.bindIndexBuffer(vbo);
  2380. // Check for 32 bits indices
  2381. var arrayBuffer;
  2382. var need32Bits = false;
  2383. if (indices instanceof Uint16Array) {
  2384. arrayBuffer = indices;
  2385. } else {
  2386. //check 32 bit support
  2387. if (this._caps.uintIndices) {
  2388. if (indices instanceof Uint32Array) {
  2389. arrayBuffer = indices;
  2390. need32Bits = true;
  2391. } else {
  2392. //number[] or Int32Array, check if 32 bit is necessary
  2393. for (var index = 0; index < indices.length; index++) {
  2394. if (indices[index] > 65535) {
  2395. need32Bits = true;
  2396. break;
  2397. }
  2398. }
  2399. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2400. }
  2401. } else {
  2402. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2403. arrayBuffer = new Uint16Array(indices);
  2404. }
  2405. }
  2406. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2407. this._resetIndexBufferBinding();
  2408. vbo.references = 1;
  2409. vbo.is32Bits = need32Bits;
  2410. return vbo;
  2411. }
  2412. /**
  2413. * Bind a webGL buffer to the webGL context
  2414. * @param buffer defines the buffer to bind
  2415. */
  2416. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2417. if (!this._vaoRecordInProgress) {
  2418. this._unbindVertexArrayObject();
  2419. }
  2420. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2421. }
  2422. /**
  2423. * Bind an uniform buffer to the current webGL context
  2424. * @param buffer defines the buffer to bind
  2425. */
  2426. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2427. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2428. }
  2429. /**
  2430. * Bind a buffer to the current webGL context at a given location
  2431. * @param buffer defines the buffer to bind
  2432. * @param location defines the index where to bind the buffer
  2433. */
  2434. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2435. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2436. }
  2437. /**
  2438. * Bind a specific block at a given index in a specific shader program
  2439. * @param shaderProgram defines the shader program
  2440. * @param blockName defines the block name
  2441. * @param index defines the index where to bind the block
  2442. */
  2443. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2444. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2445. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2446. };
  2447. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2448. if (!this._vaoRecordInProgress) {
  2449. this._unbindVertexArrayObject();
  2450. }
  2451. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2452. }
  2453. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2454. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2455. this._gl.bindBuffer(target, buffer);
  2456. this._currentBoundBuffer[target] = buffer;
  2457. }
  2458. }
  2459. /**
  2460. * update the bound buffer with the given data
  2461. * @param data defines the data to update
  2462. */
  2463. public updateArrayBuffer(data: Float32Array): void {
  2464. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2465. }
  2466. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2467. var pointer = this._currentBufferPointers[indx];
  2468. var changed = false;
  2469. if (!pointer.active) {
  2470. changed = true;
  2471. pointer.active = true;
  2472. pointer.index = indx;
  2473. pointer.size = size;
  2474. pointer.type = type;
  2475. pointer.normalized = normalized;
  2476. pointer.stride = stride;
  2477. pointer.offset = offset;
  2478. pointer.buffer = buffer;
  2479. } else {
  2480. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2481. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2482. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2483. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2484. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2485. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2486. }
  2487. if (changed || this._vaoRecordInProgress) {
  2488. this.bindArrayBuffer(buffer);
  2489. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2490. }
  2491. }
  2492. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2493. if (indexBuffer == null) {
  2494. return;
  2495. }
  2496. if (this._cachedIndexBuffer !== indexBuffer) {
  2497. this._cachedIndexBuffer = indexBuffer;
  2498. this.bindIndexBuffer(indexBuffer);
  2499. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2500. }
  2501. }
  2502. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2503. var attributes = effect.getAttributesNames();
  2504. if (!this._vaoRecordInProgress) {
  2505. this._unbindVertexArrayObject();
  2506. }
  2507. this.unbindAllAttributes();
  2508. for (var index = 0; index < attributes.length; index++) {
  2509. var order = effect.getAttributeLocation(index);
  2510. if (order >= 0) {
  2511. var vertexBuffer = vertexBuffers[attributes[index]];
  2512. if (!vertexBuffer) {
  2513. continue;
  2514. }
  2515. this._gl.enableVertexAttribArray(order);
  2516. if (!this._vaoRecordInProgress) {
  2517. this._vertexAttribArraysEnabled[order] = true;
  2518. }
  2519. var buffer = vertexBuffer.getBuffer();
  2520. if (buffer) {
  2521. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2522. if (vertexBuffer.getIsInstanced()) {
  2523. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2524. if (!this._vaoRecordInProgress) {
  2525. this._currentInstanceLocations.push(order);
  2526. this._currentInstanceBuffers.push(buffer);
  2527. }
  2528. }
  2529. }
  2530. }
  2531. }
  2532. }
  2533. /**
  2534. * Records a vertex array object
  2535. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2536. * @param vertexBuffers defines the list of vertex buffers to store
  2537. * @param indexBuffer defines the index buffer to store
  2538. * @param effect defines the effect to store
  2539. * @returns the new vertex array object
  2540. */
  2541. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2542. var vao = this._gl.createVertexArray();
  2543. this._vaoRecordInProgress = true;
  2544. this._gl.bindVertexArray(vao);
  2545. this._mustWipeVertexAttributes = true;
  2546. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2547. this.bindIndexBuffer(indexBuffer);
  2548. this._vaoRecordInProgress = false;
  2549. this._gl.bindVertexArray(null);
  2550. return vao;
  2551. }
  2552. /**
  2553. * Bind a specific vertex array object
  2554. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2555. * @param vertexArrayObject defines the vertex array object to bind
  2556. * @param indexBuffer defines the index buffer to bind
  2557. */
  2558. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2559. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2560. this._cachedVertexArrayObject = vertexArrayObject;
  2561. this._gl.bindVertexArray(vertexArrayObject);
  2562. this._cachedVertexBuffers = null;
  2563. this._cachedIndexBuffer = null;
  2564. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2565. this._mustWipeVertexAttributes = true;
  2566. }
  2567. }
  2568. /**
  2569. * Bind webGl buffers directly to the webGL context
  2570. * @param vertexBuffer defines the vertex buffer to bind
  2571. * @param indexBuffer defines the index buffer to bind
  2572. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2573. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2574. * @param effect defines the effect associated with the vertex buffer
  2575. */
  2576. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2577. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2578. this._cachedVertexBuffers = vertexBuffer;
  2579. this._cachedEffectForVertexBuffers = effect;
  2580. let attributesCount = effect.getAttributesCount();
  2581. this._unbindVertexArrayObject();
  2582. this.unbindAllAttributes();
  2583. var offset = 0;
  2584. for (var index = 0; index < attributesCount; index++) {
  2585. if (index < vertexDeclaration.length) {
  2586. var order = effect.getAttributeLocation(index);
  2587. if (order >= 0) {
  2588. this._gl.enableVertexAttribArray(order);
  2589. this._vertexAttribArraysEnabled[order] = true;
  2590. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2591. }
  2592. offset += vertexDeclaration[index] * 4;
  2593. }
  2594. }
  2595. }
  2596. this._bindIndexBufferWithCache(indexBuffer);
  2597. }
  2598. private _unbindVertexArrayObject(): void {
  2599. if (!this._cachedVertexArrayObject) {
  2600. return;
  2601. }
  2602. this._cachedVertexArrayObject = null;
  2603. this._gl.bindVertexArray(null);
  2604. }
  2605. /**
  2606. * Bind a list of vertex buffers to the webGL context
  2607. * @param vertexBuffers defines the list of vertex buffers to bind
  2608. * @param indexBuffer defines the index buffer to bind
  2609. * @param effect defines the effect associated with the vertex buffers
  2610. */
  2611. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2612. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2613. this._cachedVertexBuffers = vertexBuffers;
  2614. this._cachedEffectForVertexBuffers = effect;
  2615. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2616. }
  2617. this._bindIndexBufferWithCache(indexBuffer);
  2618. }
  2619. /**
  2620. * Unbind all instance attributes
  2621. */
  2622. public unbindInstanceAttributes() {
  2623. var boundBuffer;
  2624. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2625. var instancesBuffer = this._currentInstanceBuffers[i];
  2626. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2627. boundBuffer = instancesBuffer;
  2628. this.bindArrayBuffer(instancesBuffer);
  2629. }
  2630. var offsetLocation = this._currentInstanceLocations[i];
  2631. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2632. }
  2633. this._currentInstanceBuffers.length = 0;
  2634. this._currentInstanceLocations.length = 0;
  2635. }
  2636. /**
  2637. * Release and free the memory of a vertex array object
  2638. * @param vao defines the vertex array object to delete
  2639. */
  2640. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2641. this._gl.deleteVertexArray(vao);
  2642. }
  2643. /** @ignore */
  2644. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2645. buffer.references--;
  2646. if (buffer.references === 0) {
  2647. this._gl.deleteBuffer(buffer);
  2648. return true;
  2649. }
  2650. return false;
  2651. }
  2652. /**
  2653. * Creates a webGL buffer to use with instanciation
  2654. * @param capacity defines the size of the buffer
  2655. * @returns the webGL buffer
  2656. */
  2657. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2658. var buffer = this._gl.createBuffer();
  2659. if (!buffer) {
  2660. throw new Error("Unable to create instance buffer");
  2661. }
  2662. buffer.capacity = capacity;
  2663. this.bindArrayBuffer(buffer);
  2664. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2665. return buffer;
  2666. }
  2667. /**
  2668. * Delete a webGL buffer used with instanciation
  2669. * @param buffer defines the webGL buffer to delete
  2670. */
  2671. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2672. this._gl.deleteBuffer(buffer);
  2673. }
  2674. /**
  2675. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2676. * @param instancesBuffer defines the webGL buffer to update and bind
  2677. * @param data defines the data to store in the buffer
  2678. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2679. */
  2680. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2681. this.bindArrayBuffer(instancesBuffer);
  2682. if (data) {
  2683. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2684. }
  2685. if ((<any>offsetLocations[0]).index !== undefined) {
  2686. let stride = 0;
  2687. for (let i = 0; i < offsetLocations.length; i++) {
  2688. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2689. stride += ai.attributeSize * 4;
  2690. }
  2691. for (let i = 0; i < offsetLocations.length; i++) {
  2692. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2693. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2694. this._gl.enableVertexAttribArray(ai.index);
  2695. this._vertexAttribArraysEnabled[ai.index] = true;
  2696. }
  2697. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2698. this._gl.vertexAttribDivisor(ai.index, 1);
  2699. this._currentInstanceLocations.push(ai.index);
  2700. this._currentInstanceBuffers.push(instancesBuffer);
  2701. }
  2702. } else {
  2703. for (let index = 0; index < 4; index++) {
  2704. let offsetLocation = <number>offsetLocations[index];
  2705. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2706. this._gl.enableVertexAttribArray(offsetLocation);
  2707. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2708. }
  2709. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2710. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2711. this._currentInstanceLocations.push(offsetLocation);
  2712. this._currentInstanceBuffers.push(instancesBuffer);
  2713. }
  2714. }
  2715. }
  2716. /**
  2717. * Apply all cached states (depth, culling, stencil and alpha)
  2718. */
  2719. public applyStates() {
  2720. this._depthCullingState.apply(this._gl);
  2721. this._stencilState.apply(this._gl);
  2722. this._alphaState.apply(this._gl);
  2723. }
  2724. /**
  2725. * Send a draw order
  2726. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2727. * @param indexStart defines the starting index
  2728. * @param indexCount defines the number of index to draw
  2729. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2730. */
  2731. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2732. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2733. }
  2734. /**
  2735. * Draw a list of points
  2736. * @param verticesStart defines the index of first vertex to draw
  2737. * @param verticesCount defines the count of vertices to draw
  2738. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2739. */
  2740. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2741. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2742. }
  2743. /**
  2744. * Draw a list of unindexed primitives
  2745. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2746. * @param verticesStart defines the index of first vertex to draw
  2747. * @param verticesCount defines the count of vertices to draw
  2748. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2749. */
  2750. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2751. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2752. }
  2753. /**
  2754. * Draw a list of indexed primitives
  2755. * @param fillMode defines the primitive to use
  2756. * @param indexStart defines the starting index
  2757. * @param indexCount defines the number of index to draw
  2758. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2759. */
  2760. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2761. // Apply states
  2762. this.applyStates();
  2763. this._drawCalls.addCount(1, false);
  2764. // Render
  2765. const drawMode = this._drawMode(fillMode);
  2766. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2767. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2768. if (instancesCount) {
  2769. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2770. } else {
  2771. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2772. }
  2773. }
  2774. /**
  2775. * Draw a list of unindexed primitives
  2776. * @param fillMode defines the primitive to use
  2777. * @param verticesStart defines the index of first vertex to draw
  2778. * @param verticesCount defines the count of vertices to draw
  2779. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2780. */
  2781. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2782. // Apply states
  2783. this.applyStates();
  2784. this._drawCalls.addCount(1, false);
  2785. const drawMode = this._drawMode(fillMode);
  2786. if (instancesCount) {
  2787. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2788. } else {
  2789. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2790. }
  2791. }
  2792. private _drawMode(fillMode: number): number {
  2793. switch (fillMode) {
  2794. // Triangle views
  2795. case Material.TriangleFillMode:
  2796. return this._gl.TRIANGLES;
  2797. case Material.PointFillMode:
  2798. return this._gl.POINTS;
  2799. case Material.WireFrameFillMode:
  2800. return this._gl.LINES;
  2801. // Draw modes
  2802. case Material.PointListDrawMode:
  2803. return this._gl.POINTS
  2804. case Material.LineListDrawMode:
  2805. return this._gl.LINES;
  2806. case Material.LineLoopDrawMode:
  2807. return this._gl.LINE_LOOP
  2808. case Material.LineStripDrawMode:
  2809. return this._gl.LINE_STRIP
  2810. case Material.TriangleStripDrawMode:
  2811. return this._gl.TRIANGLE_STRIP
  2812. case Material.TriangleFanDrawMode:
  2813. return this._gl.TRIANGLE_FAN;
  2814. default:
  2815. return this._gl.TRIANGLES;
  2816. }
  2817. }
  2818. // Shaders
  2819. /** @ignore */
  2820. public _releaseEffect(effect: Effect): void {
  2821. if (this._compiledEffects[effect._key]) {
  2822. delete this._compiledEffects[effect._key];
  2823. this._deleteProgram(effect.getProgram());
  2824. }
  2825. }
  2826. /** @ignore */
  2827. public _deleteProgram(program: WebGLProgram): void {
  2828. if (program) {
  2829. program.__SPECTOR_rebuildProgram = null;
  2830. if (program.transformFeedback) {
  2831. this.deleteTransformFeedback(program.transformFeedback);
  2832. program.transformFeedback = null;
  2833. }
  2834. this._gl.deleteProgram(program);
  2835. }
  2836. }
  2837. /**
  2838. * Create a new effect (used to store vertex/fragment shaders)
  2839. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2840. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2841. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2842. * @param samplers defines an array of string used to represent textures
  2843. * @param defines defines the string containing the defines to use to compile the shaders
  2844. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2845. * @param onCompiled defines a function to call when the effect creation is successful
  2846. * @param onError defines a function to call when the effect creation has failed
  2847. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2848. * @returns the new Effect
  2849. */
  2850. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2851. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2852. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2853. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2854. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2855. if (this._compiledEffects[name]) {
  2856. var compiledEffect = <Effect>this._compiledEffects[name];
  2857. if (onCompiled && compiledEffect.isReady()) {
  2858. onCompiled(compiledEffect);
  2859. }
  2860. return compiledEffect;
  2861. }
  2862. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2863. effect._key = name;
  2864. this._compiledEffects[name] = effect;
  2865. return effect;
  2866. }
  2867. /**
  2868. * Create an effect to use with particle systems
  2869. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  2870. * @param uniformsNames defines a list of attribute names
  2871. * @param samplers defines an array of string used to represent textures
  2872. * @param defines defines the string containing the defines to use to compile the shaders
  2873. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2874. * @param onCompiled defines a function to call when the effect creation is successful
  2875. * @param onError defines a function to call when the effect creation has failed
  2876. * @returns the new Effect
  2877. */
  2878. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2879. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2880. return this.createEffect(
  2881. {
  2882. vertex: "particles",
  2883. fragmentElement: fragmentName
  2884. },
  2885. ["position", "color", "options"],
  2886. ["view", "projection"].concat(uniformsNames),
  2887. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2888. }
  2889. /**
  2890. * Directly creates a webGL program
  2891. * @param vertexCode defines the vertex shader code to use
  2892. * @param fragmentCode defines the fragment shader code to use
  2893. * @param context defines the webGL context to use (if not set, the current one will be used)
  2894. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2895. * @returns the new webGL program
  2896. */
  2897. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2898. context = context || this._gl;
  2899. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2900. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2901. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2902. }
  2903. /**
  2904. * Creates a webGL program
  2905. * @param vertexCode defines the vertex shader code to use
  2906. * @param fragmentCode defines the fragment shader code to use
  2907. * @param defines defines the string containing the defines to use to compile the shaders
  2908. * @param context defines the webGL context to use (if not set, the current one will be used)
  2909. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2910. * @returns the new webGL program
  2911. */
  2912. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2913. context = context || this._gl;
  2914. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2915. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2916. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2917. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2918. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2919. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2920. return program;
  2921. }
  2922. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2923. var shaderProgram = context.createProgram();
  2924. if (!shaderProgram) {
  2925. throw new Error("Unable to create program");
  2926. }
  2927. context.attachShader(shaderProgram, vertexShader);
  2928. context.attachShader(shaderProgram, fragmentShader);
  2929. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2930. let transformFeedback = this.createTransformFeedback();
  2931. this.bindTransformFeedback(transformFeedback);
  2932. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2933. shaderProgram.transformFeedback = transformFeedback;
  2934. }
  2935. context.linkProgram(shaderProgram);
  2936. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2937. this.bindTransformFeedback(null);
  2938. }
  2939. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2940. if (!linked) {
  2941. context.validateProgram(shaderProgram);
  2942. var error = context.getProgramInfoLog(shaderProgram);
  2943. if (error) {
  2944. throw new Error(error);
  2945. }
  2946. }
  2947. context.deleteShader(vertexShader);
  2948. context.deleteShader(fragmentShader);
  2949. return shaderProgram;
  2950. }
  2951. /**
  2952. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2953. * @param shaderProgram defines the webGL program to use
  2954. * @param uniformsNames defines the list of uniform names
  2955. * @returns an array of webGL uniform locations
  2956. */
  2957. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2958. var results = new Array<Nullable<WebGLUniformLocation>>();
  2959. for (var index = 0; index < uniformsNames.length; index++) {
  2960. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2961. }
  2962. return results;
  2963. }
  2964. /**
  2965. * Gets the lsit of active attributes for a given webGL program
  2966. * @param shaderProgram defines the webGL program to use
  2967. * @param attributesNames defines the list of attribute names to get
  2968. * @returns an array of indices indicating the offset of each attribute
  2969. */
  2970. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2971. var results = [];
  2972. for (var index = 0; index < attributesNames.length; index++) {
  2973. try {
  2974. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2975. } catch (e) {
  2976. results.push(-1);
  2977. }
  2978. }
  2979. return results;
  2980. }
  2981. /**
  2982. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2983. * @param effect defines the effect to activate
  2984. */
  2985. public enableEffect(effect: Nullable<Effect>): void {
  2986. if (!effect) {
  2987. return;
  2988. }
  2989. // Use program
  2990. this.bindSamplers(effect);
  2991. this._currentEffect = effect;
  2992. if (effect.onBind) {
  2993. effect.onBind(effect);
  2994. }
  2995. effect.onBindObservable.notifyObservers(effect);
  2996. }
  2997. /**
  2998. * Set the value of an uniform to an array of int32
  2999. * @param uniform defines the webGL uniform location where to store the value
  3000. * @param array defines the array of int32 to store
  3001. */
  3002. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3003. if (!uniform)
  3004. return;
  3005. this._gl.uniform1iv(uniform, array);
  3006. }
  3007. /**
  3008. * Set the value of an uniform to an array of int32 (stored as vec2)
  3009. * @param uniform defines the webGL uniform location where to store the value
  3010. * @param array defines the array of int32 to store
  3011. */
  3012. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3013. if (!uniform || array.length % 2 !== 0)
  3014. return;
  3015. this._gl.uniform2iv(uniform, array);
  3016. }
  3017. /**
  3018. * Set the value of an uniform to an array of int32 (stored as vec3)
  3019. * @param uniform defines the webGL uniform location where to store the value
  3020. * @param array defines the array of int32 to store
  3021. */
  3022. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3023. if (!uniform || array.length % 3 !== 0)
  3024. return;
  3025. this._gl.uniform3iv(uniform, array);
  3026. }
  3027. /**
  3028. * Set the value of an uniform to an array of int32 (stored as vec4)
  3029. * @param uniform defines the webGL uniform location where to store the value
  3030. * @param array defines the array of int32 to store
  3031. */
  3032. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3033. if (!uniform || array.length % 4 !== 0)
  3034. return;
  3035. this._gl.uniform4iv(uniform, array);
  3036. }
  3037. /**
  3038. * Set the value of an uniform to an array of float32
  3039. * @param uniform defines the webGL uniform location where to store the value
  3040. * @param array defines the array of float32 to store
  3041. */
  3042. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3043. if (!uniform)
  3044. return;
  3045. this._gl.uniform1fv(uniform, array);
  3046. }
  3047. /**
  3048. * Set the value of an uniform to an array of float32 (stored as vec2)
  3049. * @param uniform defines the webGL uniform location where to store the value
  3050. * @param array defines the array of float32 to store
  3051. */
  3052. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3053. if (!uniform || array.length % 2 !== 0)
  3054. return;
  3055. this._gl.uniform2fv(uniform, array);
  3056. }
  3057. /**
  3058. * Set the value of an uniform to an array of float32 (stored as vec3)
  3059. * @param uniform defines the webGL uniform location where to store the value
  3060. * @param array defines the array of float32 to store
  3061. */
  3062. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3063. if (!uniform || array.length % 3 !== 0)
  3064. return;
  3065. this._gl.uniform3fv(uniform, array);
  3066. }
  3067. /**
  3068. * Set the value of an uniform to an array of float32 (stored as vec4)
  3069. * @param uniform defines the webGL uniform location where to store the value
  3070. * @param array defines the array of float32 to store
  3071. */
  3072. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3073. if (!uniform || array.length % 4 !== 0)
  3074. return;
  3075. this._gl.uniform4fv(uniform, array);
  3076. }
  3077. /**
  3078. * Set the value of an uniform to an array of number
  3079. * @param uniform defines the webGL uniform location where to store the value
  3080. * @param array defines the array of number to store
  3081. */
  3082. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3083. if (!uniform)
  3084. return;
  3085. this._gl.uniform1fv(uniform, <any>array);
  3086. }
  3087. /**
  3088. * Set the value of an uniform to an array of number (stored as vec2)
  3089. * @param uniform defines the webGL uniform location where to store the value
  3090. * @param array defines the array of number to store
  3091. */
  3092. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3093. if (!uniform || array.length % 2 !== 0)
  3094. return;
  3095. this._gl.uniform2fv(uniform, <any>array);
  3096. }
  3097. /**
  3098. * Set the value of an uniform to an array of number (stored as vec3)
  3099. * @param uniform defines the webGL uniform location where to store the value
  3100. * @param array defines the array of number to store
  3101. */
  3102. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3103. if (!uniform || array.length % 3 !== 0)
  3104. return;
  3105. this._gl.uniform3fv(uniform, <any>array);
  3106. }
  3107. /**
  3108. * Set the value of an uniform to an array of number (stored as vec4)
  3109. * @param uniform defines the webGL uniform location where to store the value
  3110. * @param array defines the array of number to store
  3111. */
  3112. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3113. if (!uniform || array.length % 4 !== 0)
  3114. return;
  3115. this._gl.uniform4fv(uniform, <any>array);
  3116. }
  3117. /**
  3118. * Set the value of an uniform to an array of float32 (stored as matrices)
  3119. * @param uniform defines the webGL uniform location where to store the value
  3120. * @param matrices defines the array of float32 to store
  3121. */
  3122. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  3123. if (!uniform)
  3124. return;
  3125. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3126. }
  3127. /**
  3128. * Set the value of an uniform to a matrix
  3129. * @param uniform defines the webGL uniform location where to store the value
  3130. * @param matrix defines the matrix to store
  3131. */
  3132. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  3133. if (!uniform)
  3134. return;
  3135. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3136. }
  3137. /**
  3138. * Set the value of an uniform to a matrix (3x3)
  3139. * @param uniform defines the webGL uniform location where to store the value
  3140. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  3141. */
  3142. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3143. if (!uniform)
  3144. return;
  3145. this._gl.uniformMatrix3fv(uniform, false, matrix);
  3146. }
  3147. /**
  3148. * Set the value of an uniform to a matrix (2x2)
  3149. * @param uniform defines the webGL uniform location where to store the value
  3150. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  3151. */
  3152. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3153. if (!uniform)
  3154. return;
  3155. this._gl.uniformMatrix2fv(uniform, false, matrix);
  3156. }
  3157. /**
  3158. * Set the value of an uniform to a number (int)
  3159. * @param uniform defines the webGL uniform location where to store the value
  3160. * @param value defines the int number to store
  3161. */
  3162. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3163. if (!uniform)
  3164. return;
  3165. this._gl.uniform1i(uniform, value);
  3166. }
  3167. /**
  3168. * Set the value of an uniform to a number (float)
  3169. * @param uniform defines the webGL uniform location where to store the value
  3170. * @param value defines the float number to store
  3171. */
  3172. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3173. if (!uniform)
  3174. return;
  3175. this._gl.uniform1f(uniform, value);
  3176. }
  3177. /**
  3178. * Set the value of an uniform to a vec2
  3179. * @param uniform defines the webGL uniform location where to store the value
  3180. * @param x defines the 1st component of the value
  3181. * @param y defines the 2nd component of the value
  3182. */
  3183. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3184. if (!uniform)
  3185. return;
  3186. this._gl.uniform2f(uniform, x, y);
  3187. }
  3188. /**
  3189. * Set the value of an uniform to a vec3
  3190. * @param uniform defines the webGL uniform location where to store the value
  3191. * @param x defines the 1st component of the value
  3192. * @param y defines the 2nd component of the value
  3193. * @param z defines the 3rd component of the value
  3194. */
  3195. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3196. if (!uniform)
  3197. return;
  3198. this._gl.uniform3f(uniform, x, y, z);
  3199. }
  3200. /**
  3201. * Set the value of an uniform to a boolean
  3202. * @param uniform defines the webGL uniform location where to store the value
  3203. * @param bool defines the boolean to store
  3204. */
  3205. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3206. if (!uniform)
  3207. return;
  3208. this._gl.uniform1i(uniform, bool);
  3209. }
  3210. /**
  3211. * Set the value of an uniform to a vec4
  3212. * @param uniform defines the webGL uniform location where to store the value
  3213. * @param x defines the 1st component of the value
  3214. * @param y defines the 2nd component of the value
  3215. * @param z defines the 3rd component of the value
  3216. * @param w defines the 4th component of the value
  3217. */
  3218. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3219. if (!uniform)
  3220. return;
  3221. this._gl.uniform4f(uniform, x, y, z, w);
  3222. }
  3223. /**
  3224. * Set the value of an uniform to a Color3
  3225. * @param uniform defines the webGL uniform location where to store the value
  3226. * @param color3 defines the color to store
  3227. */
  3228. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3229. if (!uniform)
  3230. return;
  3231. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3232. }
  3233. /**
  3234. * Set the value of an uniform to a Color3 and an alpha value
  3235. * @param uniform defines the webGL uniform location where to store the value
  3236. * @param color3 defines the color to store
  3237. * @param alpha defines the alpha component to store
  3238. */
  3239. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3240. if (!uniform)
  3241. return;
  3242. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3243. }
  3244. /**
  3245. * Sets a Color4 on a uniform variable
  3246. * @param uniform defines the uniform location
  3247. * @param color4 defines the value to be set
  3248. */
  3249. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3250. if (!uniform)
  3251. return;
  3252. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3253. }
  3254. // States
  3255. /**
  3256. * Set various states to the webGL context
  3257. * @param culling defines backface culling state
  3258. * @param zOffset defines the value to apply to zOffset (0 by default)
  3259. * @param force defines if states must be applied even if cache is up to date
  3260. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3261. */
  3262. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3263. // Culling
  3264. if (this._depthCullingState.cull !== culling || force) {
  3265. this._depthCullingState.cull = culling;
  3266. }
  3267. // Cull face
  3268. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3269. if (this._depthCullingState.cullFace !== cullFace || force) {
  3270. this._depthCullingState.cullFace = cullFace;
  3271. }
  3272. // Z offset
  3273. this.setZOffset(zOffset);
  3274. // Front face
  3275. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3276. if (this._depthCullingState.frontFace !== frontFace || force) {
  3277. this._depthCullingState.frontFace = frontFace;
  3278. }
  3279. }
  3280. /**
  3281. * Set the z offset to apply to current rendering
  3282. * @param value defines the offset to apply
  3283. */
  3284. public setZOffset(value: number): void {
  3285. this._depthCullingState.zOffset = value;
  3286. }
  3287. /**
  3288. * Gets the current value of the zOffset
  3289. * @returns the current zOffset state
  3290. */
  3291. public getZOffset(): number {
  3292. return this._depthCullingState.zOffset;
  3293. }
  3294. /**
  3295. * Enable or disable depth buffering
  3296. * @param enable defines the state to set
  3297. */
  3298. public setDepthBuffer(enable: boolean): void {
  3299. this._depthCullingState.depthTest = enable;
  3300. }
  3301. /**
  3302. * Gets a boolean indicating if depth writing is enabled
  3303. * @returns the current depth writing state
  3304. */
  3305. public getDepthWrite(): boolean {
  3306. return this._depthCullingState.depthMask;
  3307. }
  3308. /**
  3309. * Enable or disable depth writing
  3310. * @param enable defines the state to set
  3311. */
  3312. public setDepthWrite(enable: boolean): void {
  3313. this._depthCullingState.depthMask = enable;
  3314. }
  3315. /**
  3316. * Enable or disable color writing
  3317. * @param enable defines the state to set
  3318. */
  3319. public setColorWrite(enable: boolean): void {
  3320. this._gl.colorMask(enable, enable, enable, enable);
  3321. this._colorWrite = enable;
  3322. }
  3323. /**
  3324. * Gets a boolean indicating if color writing is enabled
  3325. * @returns the current color writing state
  3326. */
  3327. public getColorWrite(): boolean {
  3328. return this._colorWrite;
  3329. }
  3330. /**
  3331. * Sets alpha constants used by some alpha blending modes
  3332. * @param r defines the red component
  3333. * @param g defines the green component
  3334. * @param b defines the blue component
  3335. * @param a defines the alpha component
  3336. */
  3337. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3338. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3339. }
  3340. /**
  3341. * Sets the current alpha mode
  3342. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  3343. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3344. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3345. */
  3346. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3347. if (this._alphaMode === mode) {
  3348. return;
  3349. }
  3350. switch (mode) {
  3351. case Engine.ALPHA_DISABLE:
  3352. this._alphaState.alphaBlend = false;
  3353. break;
  3354. case Engine.ALPHA_PREMULTIPLIED:
  3355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3356. this._alphaState.alphaBlend = true;
  3357. break;
  3358. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3359. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3360. this._alphaState.alphaBlend = true;
  3361. break;
  3362. case Engine.ALPHA_COMBINE:
  3363. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3364. this._alphaState.alphaBlend = true;
  3365. break;
  3366. case Engine.ALPHA_ONEONE:
  3367. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3368. this._alphaState.alphaBlend = true;
  3369. break;
  3370. case Engine.ALPHA_ADD:
  3371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3372. this._alphaState.alphaBlend = true;
  3373. break;
  3374. case Engine.ALPHA_SUBTRACT:
  3375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3376. this._alphaState.alphaBlend = true;
  3377. break;
  3378. case Engine.ALPHA_MULTIPLY:
  3379. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3380. this._alphaState.alphaBlend = true;
  3381. break;
  3382. case Engine.ALPHA_MAXIMIZED:
  3383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3384. this._alphaState.alphaBlend = true;
  3385. break;
  3386. case Engine.ALPHA_INTERPOLATE:
  3387. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3388. this._alphaState.alphaBlend = true;
  3389. break;
  3390. case Engine.ALPHA_SCREENMODE:
  3391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3392. this._alphaState.alphaBlend = true;
  3393. break;
  3394. }
  3395. if (!noDepthWriteChange) {
  3396. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3397. }
  3398. this._alphaMode = mode;
  3399. }
  3400. /**
  3401. * Gets the current alpha mode
  3402. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3403. * @returns the current alpha mode
  3404. */
  3405. public getAlphaMode(): number {
  3406. return this._alphaMode;
  3407. }
  3408. // Textures
  3409. /**
  3410. * Force the entire cache to be cleared
  3411. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3412. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3413. */
  3414. public wipeCaches(bruteForce?: boolean): void {
  3415. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3416. return;
  3417. }
  3418. this._currentEffect = null;
  3419. if (bruteForce) {
  3420. this.resetTextureCache();
  3421. this._currentProgram = null;
  3422. this._stencilState.reset();
  3423. this._depthCullingState.reset();
  3424. this.setDepthFunctionToLessOrEqual();
  3425. this._alphaState.reset();
  3426. }
  3427. this._resetVertexBufferBinding();
  3428. this._cachedIndexBuffer = null;
  3429. this._cachedEffectForVertexBuffers = null;
  3430. this._unbindVertexArrayObject();
  3431. this.bindIndexBuffer(null);
  3432. }
  3433. /**
  3434. * Set the compressed texture format to use, based on the formats you have, and the formats
  3435. * supported by the hardware / browser.
  3436. *
  3437. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3438. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3439. * to API arguments needed to compressed textures. This puts the burden on the container
  3440. * generator to house the arcane code for determining these for current & future formats.
  3441. *
  3442. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3443. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3444. *
  3445. * Note: The result of this call is not taken into account when a texture is base64.
  3446. *
  3447. * @param formatsAvailable defines the list of those format families you have created
  3448. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3449. *
  3450. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3451. * @returns The extension selected.
  3452. */
  3453. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3454. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3455. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3456. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3457. return this._textureFormatInUse = this._texturesSupported[i];
  3458. }
  3459. }
  3460. }
  3461. // actively set format to nothing, to allow this to be called more than once
  3462. // and possibly fail the 2nd time
  3463. this._textureFormatInUse = null;
  3464. return null;
  3465. }
  3466. /** @ignore */
  3467. public _createTexture(): WebGLTexture {
  3468. let texture = this._gl.createTexture();
  3469. if (!texture) {
  3470. throw new Error("Unable to create texture");
  3471. }
  3472. return texture;
  3473. }
  3474. /**
  3475. * Usually called from BABYLON.Texture.ts.
  3476. * Passed information to create a WebGLTexture
  3477. * @param urlArg defines a value which contains one of the following:
  3478. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3479. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3480. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3481. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3482. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  3483. * @param scene needed for loading to the correct scene
  3484. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  3485. * @param onLoad optional callback to be called upon successful completion
  3486. * @param onError optional callback to be called upon failure
  3487. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  3488. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3489. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3490. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3491. */
  3492. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  3493. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3494. buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  3495. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3496. var fromData = url.substr(0, 5) === "data:";
  3497. var fromBlob = url.substr(0, 5) === "blob:";
  3498. var isBase64 = fromData && url.indexOf("base64") !== -1;
  3499. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3500. // establish the file extension, if possible
  3501. var lastDot = url.lastIndexOf('.');
  3502. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  3503. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  3504. var isTGA = (extension.indexOf(".tga") === 0);
  3505. // determine if a ktx file should be substituted
  3506. var isKTX = false;
  3507. if (this._textureFormatInUse && !isBase64 && !fallback) {
  3508. url = url.substring(0, lastDot) + this._textureFormatInUse;
  3509. isKTX = true;
  3510. }
  3511. if (scene) {
  3512. scene._addPendingData(texture);
  3513. }
  3514. texture.url = url;
  3515. texture.generateMipMaps = !noMipmap;
  3516. texture.samplingMode = samplingMode;
  3517. texture.invertY = invertY;
  3518. if (!this._doNotHandleContextLost) {
  3519. // Keep a link to the buffer only if we plan to handle context lost
  3520. texture._buffer = buffer;
  3521. }
  3522. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3523. if (onLoad && !fallback) {
  3524. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3525. }
  3526. if (!fallback) this._internalTexturesCache.push(texture);
  3527. var onerror = (message?: string, exception?: any) => {
  3528. if (scene) {
  3529. scene._removePendingData(texture);
  3530. }
  3531. if (onLoadObserver) {
  3532. texture.onLoadedObservable.remove(onLoadObserver);
  3533. }
  3534. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  3535. if (isKTX) {
  3536. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3537. } else if (Tools.UseFallbackTexture) {
  3538. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3539. }
  3540. if (onError) {
  3541. onError(message || "Unknown error", exception);
  3542. }
  3543. };
  3544. var callback: Nullable<(arrayBuffer: any) => void> = null;
  3545. // processing for non-image formats
  3546. if (isKTX || isTGA || isDDS) {
  3547. if (isKTX) {
  3548. callback = (data) => {
  3549. var ktx = new KhronosTextureContainer(data, 1);
  3550. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  3551. ktx.uploadLevels(this._gl, !noMipmap);
  3552. return false;
  3553. }, samplingMode);
  3554. };
  3555. } else if (isTGA) {
  3556. callback = (arrayBuffer) => {
  3557. var data = new Uint8Array(arrayBuffer);
  3558. var header = TGATools.GetTGAHeader(data);
  3559. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  3560. TGATools.UploadContent(this._gl, data);
  3561. return false;
  3562. }, samplingMode);
  3563. };
  3564. } else if (isDDS) {
  3565. callback = (data) => {
  3566. var info = DDSTools.GetDDSInfo(data);
  3567. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  3568. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  3569. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  3570. return false;
  3571. }, samplingMode);
  3572. };
  3573. }
  3574. if (!buffer) {
  3575. this._loadFile(url, data => {
  3576. if (callback) {
  3577. callback(data);
  3578. }
  3579. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3580. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  3581. });
  3582. } else {
  3583. if (callback) {
  3584. callback(buffer);
  3585. }
  3586. }
  3587. // image format processing
  3588. } else {
  3589. var onload = (img: HTMLImageElement) => {
  3590. if (fromBlob && !this._doNotHandleContextLost) {
  3591. // We need to store the image if we need to rebuild the texture
  3592. // in case of a webgl context lost
  3593. texture._buffer = img;
  3594. }
  3595. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3596. let gl = this._gl;
  3597. var isPot = (img.width === potWidth && img.height === potHeight);
  3598. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3599. if (isPot) {
  3600. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3601. return false;
  3602. }
  3603. // Using shaders to rescale because canvas.drawImage is lossy
  3604. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3605. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3606. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3611. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3612. this._releaseTexture(source);
  3613. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3614. continuationCallback();
  3615. });
  3616. return true;
  3617. }, samplingMode);
  3618. };
  3619. if (!fromData || isBase64)
  3620. if (buffer instanceof HTMLImageElement) {
  3621. onload(buffer);
  3622. } else {
  3623. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  3624. }
  3625. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  3626. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  3627. else
  3628. onload(<HTMLImageElement>buffer);
  3629. }
  3630. return texture;
  3631. }
  3632. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3633. let rtt = this.createRenderTargetTexture({
  3634. width: destination.width,
  3635. height: destination.height,
  3636. }, {
  3637. generateMipMaps: false,
  3638. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3639. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  3640. generateDepthBuffer: false,
  3641. generateStencilBuffer: false
  3642. }
  3643. );
  3644. if (!this._rescalePostProcess) {
  3645. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3646. }
  3647. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3648. this._rescalePostProcess.onApply = function (effect) {
  3649. effect._bindTexture("textureSampler", source);
  3650. }
  3651. let hostingScene = scene;
  3652. if (!hostingScene) {
  3653. hostingScene = this.scenes[this.scenes.length - 1];
  3654. }
  3655. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3656. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3657. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3658. this.unBindFramebuffer(rtt);
  3659. this._releaseTexture(rtt);
  3660. if (onComplete) {
  3661. onComplete();
  3662. }
  3663. });
  3664. }
  3665. /**
  3666. * Update a raw texture
  3667. * @param texture defines the texture to update
  3668. * @param data defines the data to store in the texture
  3669. * @param format defines the format of the data
  3670. * @param invertY defines if data must be stored with Y axis inverted
  3671. * @param compression defines the compression used (null by default)
  3672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3673. */
  3674. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void { if (!texture) {
  3675. return;
  3676. }
  3677. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3678. var internalFormat = this._getInternalFormat(format);
  3679. var textureType = this._getWebGLTextureType(type);
  3680. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3681. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3682. if (!this._doNotHandleContextLost) {
  3683. texture._bufferView = data;
  3684. texture.format = format;
  3685. texture.type = type;
  3686. texture.invertY = invertY;
  3687. texture._compression = compression;
  3688. }
  3689. if (texture.width % 4 !== 0) {
  3690. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3691. }
  3692. if (compression && data) {
  3693. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3694. } else {
  3695. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3696. }
  3697. if (texture.generateMipMaps) {
  3698. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3699. }
  3700. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3701. // this.resetTextureCache();
  3702. texture.isReady = true;
  3703. }
  3704. /**
  3705. * Creates a raw texture
  3706. * @param data defines the data to store in the texture
  3707. * @param width defines the width of the texture
  3708. * @param height defines the height of the texture
  3709. * @param format defines the format of the data
  3710. * @param generateMipMaps defines if the engine should generate the mip levels
  3711. * @param invertY defines if data must be stored with Y axis inverted
  3712. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3713. * @param compression defines the compression used (null by default)
  3714. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3715. * @returns the raw texture inside an InternalTexture
  3716. */
  3717. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3718. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3719. texture.baseWidth = width;
  3720. texture.baseHeight = height;
  3721. texture.width = width;
  3722. texture.height = height;
  3723. texture.format = format;
  3724. texture.generateMipMaps = generateMipMaps;
  3725. texture.samplingMode = samplingMode;
  3726. texture.invertY = invertY;
  3727. texture._compression = compression;
  3728. texture.type = type;
  3729. if (!this._doNotHandleContextLost) {
  3730. texture._bufferView = data;
  3731. }
  3732. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3733. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3734. // Filters
  3735. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3736. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3737. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3738. if (generateMipMaps) {
  3739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3740. }
  3741. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3742. this._internalTexturesCache.push(texture);
  3743. return texture;
  3744. }
  3745. /**
  3746. * Creates a dynamic texture
  3747. * @param width defines the width of the texture
  3748. * @param height defines the height of the texture
  3749. * @param generateMipMaps defines if the engine should generate the mip levels
  3750. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3751. * @returns the dynamic texture inside an InternalTexture
  3752. */
  3753. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3754. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  3755. texture.baseWidth = width;
  3756. texture.baseHeight = height;
  3757. if (generateMipMaps) {
  3758. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3759. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3760. }
  3761. // this.resetTextureCache();
  3762. texture.width = width;
  3763. texture.height = height;
  3764. texture.isReady = false;
  3765. texture.generateMipMaps = generateMipMaps;
  3766. texture.samplingMode = samplingMode;
  3767. this.updateTextureSamplingMode(samplingMode, texture);
  3768. this._internalTexturesCache.push(texture);
  3769. return texture;
  3770. }
  3771. /**
  3772. * Update the sampling mode of a given texture
  3773. * @param samplingMode defines the required sampling mode
  3774. * @param texture defines the texture to update
  3775. */
  3776. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3777. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  3778. if (texture.isCube) {
  3779. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3780. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3781. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3782. } else if (texture.is3D) {
  3783. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3784. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3785. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3786. } else {
  3787. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3788. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3790. }
  3791. texture.samplingMode = samplingMode;
  3792. }
  3793. /**
  3794. * Update the content of a dynamic texture
  3795. * @param texture defines the texture to update
  3796. * @param canvas defines the canvas containing the source
  3797. * @param invertY defines if data must be stored with Y axis inverted
  3798. * @param premulAlpha defines if alpha is stored as premultiplied
  3799. * @param format defines the format of the data
  3800. */
  3801. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  3802. if (!texture) {
  3803. return;
  3804. }
  3805. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3806. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3807. if (premulAlpha) {
  3808. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3809. }
  3810. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3811. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3812. if (texture.generateMipMaps) {
  3813. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3814. }
  3815. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3816. if (premulAlpha) {
  3817. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3818. }
  3819. texture.isReady = true;
  3820. }
  3821. /**
  3822. * Update a video texture
  3823. * @param texture defines the texture to update
  3824. * @param video defines the video element to use
  3825. * @param invertY defines if data must be stored with Y axis inverted
  3826. */
  3827. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  3828. if (!texture || texture._isDisabled) {
  3829. return;
  3830. }
  3831. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3832. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  3833. try {
  3834. // Testing video texture support
  3835. if (this._videoTextureSupported === undefined) {
  3836. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3837. if (this._gl.getError() !== 0) {
  3838. this._videoTextureSupported = false;
  3839. } else {
  3840. this._videoTextureSupported = true;
  3841. }
  3842. }
  3843. // Copy video through the current working canvas if video texture is not supported
  3844. if (!this._videoTextureSupported) {
  3845. if (!texture._workingCanvas) {
  3846. texture._workingCanvas = document.createElement("canvas");
  3847. let context = texture._workingCanvas.getContext("2d");
  3848. if (!context) {
  3849. throw new Error("Unable to get 2d context");
  3850. }
  3851. texture._workingContext = context;
  3852. texture._workingCanvas.width = texture.width;
  3853. texture._workingCanvas.height = texture.height;
  3854. }
  3855. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  3856. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3857. } else {
  3858. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3859. }
  3860. if (texture.generateMipMaps) {
  3861. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3862. }
  3863. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3864. // this.resetTextureCache();
  3865. texture.isReady = true;
  3866. } catch (ex) {
  3867. // Something unexpected
  3868. // Let's disable the texture
  3869. texture._isDisabled = true;
  3870. }
  3871. }
  3872. /**
  3873. * Updates a depth texture Comparison Mode and Function.
  3874. * If the comparison Function is equal to 0, the mode will be set to none.
  3875. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  3876. * @param texture The texture to set the comparison function for
  3877. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  3878. */
  3879. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3880. if (this.webGLVersion === 1) {
  3881. Tools.Error("WebGL 1 does not support texture comparison.");
  3882. return;
  3883. }
  3884. var gl = this._gl;
  3885. if (texture.isCube) {
  3886. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3887. if (comparisonFunction === 0) {
  3888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3890. }
  3891. else {
  3892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3894. }
  3895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3896. } else {
  3897. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3898. if (comparisonFunction === 0) {
  3899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3901. }
  3902. else {
  3903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3905. }
  3906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3907. }
  3908. texture._comparisonFunction = comparisonFunction;
  3909. }
  3910. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3911. var width = (<{ width: number, height: number }>size).width || <number>size;
  3912. var height = (<{ width: number, height: number }>size).height || <number>size;
  3913. internalTexture.baseWidth = width;
  3914. internalTexture.baseHeight = height;
  3915. internalTexture.width = width;
  3916. internalTexture.height = height;
  3917. internalTexture.isReady = true;
  3918. internalTexture.samples = 1;
  3919. internalTexture.generateMipMaps = false;
  3920. internalTexture._generateDepthBuffer = true;
  3921. internalTexture._generateStencilBuffer = generateStencil;
  3922. internalTexture.samplingMode = bilinearFiltering ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE;
  3923. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3924. internalTexture._comparisonFunction = comparisonFunction;
  3925. var gl = this._gl;
  3926. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3927. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  3928. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3929. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3930. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3931. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3932. if (comparisonFunction === 0) {
  3933. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3934. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3935. }
  3936. else {
  3937. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3938. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3939. }
  3940. }
  3941. /**
  3942. * Creates a depth stencil texture.
  3943. * This is only available in WebGL 2 or with the depth texture extension available.
  3944. * @param size The size of face edge in the texture.
  3945. * @param options The options defining the texture.
  3946. * @returns The texture
  3947. */
  3948. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3949. if (options.isCube) {
  3950. let width = (<{ width: number, height: number }>size).width || <number>size;
  3951. return this._createDepthStencilCubeTexture(width, options);
  3952. }
  3953. else {
  3954. return this._createDepthStencilTexture(size, options);
  3955. }
  3956. }
  3957. /**
  3958. * Creates a depth stencil texture.
  3959. * This is only available in WebGL 2 or with the depth texture extension available.
  3960. * @param size The size of face edge in the texture.
  3961. * @param options The options defining the texture.
  3962. * @returns The texture
  3963. */
  3964. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3965. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  3966. if (!this._caps.depthTextureExtension) {
  3967. Tools.Error("Depth texture is not supported by your browser or hardware.");
  3968. return internalTexture;
  3969. }
  3970. var internalOptions = {
  3971. bilinearFiltering: false,
  3972. comparisonFunction: 0,
  3973. generateStencil: false,
  3974. ...options
  3975. }
  3976. var gl = this._gl;
  3977. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  3978. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  3979. if (this.webGLVersion > 1) {
  3980. if (internalOptions.generateStencil) {
  3981. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3982. }
  3983. else {
  3984. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3985. }
  3986. }
  3987. else {
  3988. if (internalOptions.generateStencil) {
  3989. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3990. }
  3991. else {
  3992. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3993. }
  3994. }
  3995. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3996. return internalTexture;
  3997. }
  3998. /**
  3999. * Creates a depth stencil cube texture.
  4000. * This is only available in WebGL 2.
  4001. * @param size The size of face edge in the cube texture.
  4002. * @param options The options defining the cube texture.
  4003. * @returns The cube texture
  4004. */
  4005. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  4006. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4007. internalTexture.isCube = true;
  4008. if (this.webGLVersion === 1) {
  4009. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4010. return internalTexture;
  4011. }
  4012. var internalOptions = {
  4013. bilinearFiltering: false,
  4014. comparisonFunction: 0,
  4015. generateStencil: false,
  4016. ...options
  4017. }
  4018. var gl = this._gl;
  4019. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4020. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4021. // Create the depth/stencil buffer
  4022. for (var face = 0; face < 6; face++) {
  4023. if (internalOptions.generateStencil) {
  4024. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4025. }
  4026. else {
  4027. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4028. }
  4029. }
  4030. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4031. return internalTexture;
  4032. }
  4033. /**
  4034. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4035. * @param renderTarget The render target to set the frame buffer for
  4036. */
  4037. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4038. // Create the framebuffer
  4039. var internalTexture = renderTarget.getInternalTexture();
  4040. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4041. return;
  4042. }
  4043. var gl = this._gl;
  4044. var depthStencilTexture = renderTarget.depthStencilTexture;
  4045. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4046. if (depthStencilTexture.isCube) {
  4047. if (depthStencilTexture._generateStencilBuffer) {
  4048. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4049. }
  4050. else {
  4051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4052. }
  4053. }
  4054. else {
  4055. if (depthStencilTexture._generateStencilBuffer) {
  4056. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4057. }
  4058. else {
  4059. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4060. }
  4061. }
  4062. this.bindUnboundFramebuffer(null);
  4063. }
  4064. /**
  4065. * Creates a new render target texture
  4066. * @param size defines the size of the texture
  4067. * @param options defines the options used to create the texture
  4068. * @returns a new render target texture stored in an InternalTexture
  4069. */
  4070. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4071. let fullOptions = new RenderTargetCreationOptions();
  4072. if (options !== undefined && typeof options === "object") {
  4073. fullOptions.generateMipMaps = options.generateMipMaps;
  4074. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4075. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4076. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4077. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4078. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4079. } else {
  4080. fullOptions.generateMipMaps = <boolean>options;
  4081. fullOptions.generateDepthBuffer = true;
  4082. fullOptions.generateStencilBuffer = false;
  4083. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4084. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  4085. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4086. }
  4087. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4088. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4089. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4090. }
  4091. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4092. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4093. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4094. }
  4095. var gl = this._gl;
  4096. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4097. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4098. var width = (<{ width: number, height: number }>size).width || <number>size;
  4099. var height = (<{ width: number, height: number }>size).height || <number>size;
  4100. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  4101. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4102. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4103. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4104. }
  4105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4109. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4110. // Create the framebuffer
  4111. var framebuffer = gl.createFramebuffer();
  4112. this.bindUnboundFramebuffer(framebuffer);
  4113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4114. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4115. if (fullOptions.generateMipMaps) {
  4116. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4117. }
  4118. // Unbind
  4119. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4120. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4121. this.bindUnboundFramebuffer(null);
  4122. texture._framebuffer = framebuffer;
  4123. texture.baseWidth = width;
  4124. texture.baseHeight = height;
  4125. texture.width = width;
  4126. texture.height = height;
  4127. texture.isReady = true;
  4128. texture.samples = 1;
  4129. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4130. texture.samplingMode = fullOptions.samplingMode;
  4131. texture.type = fullOptions.type;
  4132. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4133. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4134. // this.resetTextureCache();
  4135. this._internalTexturesCache.push(texture);
  4136. return texture;
  4137. }
  4138. /**
  4139. * Create a multi render target texture
  4140. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4141. * @param size defines the size of the texture
  4142. * @param options defines the creation options
  4143. * @returns the cube texture as an InternalTexture
  4144. */
  4145. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4146. var generateMipMaps = false;
  4147. var generateDepthBuffer = true;
  4148. var generateStencilBuffer = false;
  4149. var generateDepthTexture = false;
  4150. var textureCount = 1;
  4151. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4152. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  4153. var types = new Array<number>();
  4154. var samplingModes = new Array<number>();
  4155. if (options !== undefined) {
  4156. generateMipMaps = options.generateMipMaps === undefined ? false: options.generateMipMaps;
  4157. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4158. generateStencilBuffer = options.generateStencilBuffer === undefined ? false: options.generateStencilBuffer;
  4159. generateDepthTexture = options.generateDepthTexture === undefined ? false: options.generateDepthTexture;
  4160. textureCount = options.textureCount || 1;
  4161. if (options.types) {
  4162. types = options.types;
  4163. }
  4164. if (options.samplingModes) {
  4165. samplingModes = options.samplingModes;
  4166. }
  4167. }
  4168. var gl = this._gl;
  4169. // Create the framebuffer
  4170. var framebuffer = gl.createFramebuffer();
  4171. this.bindUnboundFramebuffer(framebuffer);
  4172. var width = size.width || size;
  4173. var height = size.height || size;
  4174. var textures = [];
  4175. var attachments = []
  4176. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4177. for (var i = 0; i < textureCount; i++) {
  4178. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4179. var type = types[i] || defaultType;
  4180. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4181. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4182. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4183. }
  4184. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4185. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4186. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4187. }
  4188. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4189. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4190. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4191. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4192. }
  4193. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4194. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4195. textures.push(texture);
  4196. attachments.push(attachment);
  4197. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4198. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4203. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4204. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4205. if (generateMipMaps) {
  4206. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4207. }
  4208. // Unbind
  4209. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4210. texture._framebuffer = framebuffer;
  4211. texture._depthStencilBuffer = depthStencilBuffer;
  4212. texture.baseWidth = width;
  4213. texture.baseHeight = height;
  4214. texture.width = width;
  4215. texture.height = height;
  4216. texture.isReady = true;
  4217. texture.samples = 1;
  4218. texture.generateMipMaps = generateMipMaps;
  4219. texture.samplingMode = samplingMode;
  4220. texture.type = type;
  4221. texture._generateDepthBuffer = generateDepthBuffer;
  4222. texture._generateStencilBuffer = generateStencilBuffer;
  4223. texture._attachments = attachments;
  4224. this._internalTexturesCache.push(texture);
  4225. }
  4226. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4227. // Depth texture
  4228. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4229. gl.activeTexture(gl.TEXTURE0);
  4230. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4231. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4235. gl.texImage2D(
  4236. gl.TEXTURE_2D,
  4237. 0,
  4238. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4239. width,
  4240. height,
  4241. 0,
  4242. gl.DEPTH_COMPONENT,
  4243. gl.UNSIGNED_SHORT,
  4244. null
  4245. );
  4246. gl.framebufferTexture2D(
  4247. gl.FRAMEBUFFER,
  4248. gl.DEPTH_ATTACHMENT,
  4249. gl.TEXTURE_2D,
  4250. depthTexture._webGLTexture,
  4251. 0
  4252. );
  4253. depthTexture._framebuffer = framebuffer;
  4254. depthTexture.baseWidth = width;
  4255. depthTexture.baseHeight = height;
  4256. depthTexture.width = width;
  4257. depthTexture.height = height;
  4258. depthTexture.isReady = true;
  4259. depthTexture.samples = 1;
  4260. depthTexture.generateMipMaps = generateMipMaps;
  4261. depthTexture.samplingMode = gl.NEAREST;
  4262. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4263. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4264. textures.push(depthTexture)
  4265. this._internalTexturesCache.push(depthTexture);
  4266. }
  4267. gl.drawBuffers(attachments);
  4268. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4269. this.bindUnboundFramebuffer(null);
  4270. this.resetTextureCache();
  4271. return textures;
  4272. }
  4273. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4274. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4275. var gl = this._gl;
  4276. // Create the depth/stencil buffer
  4277. if (generateStencilBuffer) {
  4278. depthStencilBuffer = gl.createRenderbuffer();
  4279. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4280. if (samples > 1) {
  4281. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4282. } else {
  4283. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4284. }
  4285. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4286. }
  4287. else if (generateDepthBuffer) {
  4288. depthStencilBuffer = gl.createRenderbuffer();
  4289. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4290. if (samples > 1) {
  4291. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4292. } else {
  4293. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4294. }
  4295. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4296. }
  4297. return depthStencilBuffer;
  4298. }
  4299. /**
  4300. * Updates the sample count of a render target texture
  4301. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4302. * @param texture defines the texture to update
  4303. * @param samples defines the sample count to set
  4304. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4305. */
  4306. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4307. if (this.webGLVersion < 2 || !texture) {
  4308. return 1;
  4309. }
  4310. if (texture.samples === samples) {
  4311. return samples;
  4312. }
  4313. var gl = this._gl;
  4314. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4315. // Dispose previous render buffers
  4316. if (texture._depthStencilBuffer) {
  4317. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4318. texture._depthStencilBuffer = null;
  4319. }
  4320. if (texture._MSAAFramebuffer) {
  4321. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4322. texture._MSAAFramebuffer = null;
  4323. }
  4324. if (texture._MSAARenderBuffer) {
  4325. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4326. texture._MSAARenderBuffer = null;
  4327. }
  4328. if (samples > 1) {
  4329. let framebuffer = gl.createFramebuffer();
  4330. if (!framebuffer) {
  4331. throw new Error("Unable to create multi sampled framebuffer");
  4332. }
  4333. texture._MSAAFramebuffer = framebuffer;
  4334. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4335. var colorRenderbuffer = gl.createRenderbuffer();
  4336. if (!colorRenderbuffer) {
  4337. throw new Error("Unable to create multi sampled framebuffer");
  4338. }
  4339. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4340. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4341. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4342. texture._MSAARenderBuffer = colorRenderbuffer;
  4343. } else {
  4344. this.bindUnboundFramebuffer(texture._framebuffer);
  4345. }
  4346. texture.samples = samples;
  4347. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4348. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4349. this.bindUnboundFramebuffer(null);
  4350. return samples;
  4351. }
  4352. /**
  4353. * Update the sample count for a given multiple render target texture
  4354. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4355. * @param textures defines the textures to update
  4356. * @param samples defines the sample count to set
  4357. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4358. */
  4359. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4360. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4361. return 1;
  4362. }
  4363. if (textures[0].samples === samples) {
  4364. return samples;
  4365. }
  4366. var gl = this._gl;
  4367. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4368. // Dispose previous render buffers
  4369. if (textures[0]._depthStencilBuffer) {
  4370. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4371. textures[0]._depthStencilBuffer = null;
  4372. }
  4373. if (textures[0]._MSAAFramebuffer) {
  4374. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4375. textures[0]._MSAAFramebuffer = null;
  4376. }
  4377. for (var i = 0; i < textures.length; i++) {
  4378. if (textures[i]._MSAARenderBuffer) {
  4379. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4380. textures[i]._MSAARenderBuffer = null;
  4381. }
  4382. }
  4383. if (samples > 1) {
  4384. let framebuffer = gl.createFramebuffer();
  4385. if (!framebuffer) {
  4386. throw new Error("Unable to create multi sampled framebuffer");
  4387. }
  4388. this.bindUnboundFramebuffer(framebuffer);
  4389. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4390. var attachments = [];
  4391. for (var i = 0; i < textures.length; i++) {
  4392. var texture = textures[i];
  4393. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4394. var colorRenderbuffer = gl.createRenderbuffer();
  4395. if (!colorRenderbuffer) {
  4396. throw new Error("Unable to create multi sampled framebuffer");
  4397. }
  4398. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4399. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4400. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4401. texture._MSAAFramebuffer = framebuffer;
  4402. texture._MSAARenderBuffer = colorRenderbuffer;
  4403. texture.samples = samples;
  4404. texture._depthStencilBuffer = depthStencilBuffer;
  4405. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4406. attachments.push(attachment);
  4407. }
  4408. gl.drawBuffers(attachments);
  4409. } else {
  4410. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4411. }
  4412. this.bindUnboundFramebuffer(null);
  4413. return samples;
  4414. }
  4415. /** @ignore */
  4416. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  4417. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  4418. }
  4419. /** @ignore */
  4420. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  4421. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4422. }
  4423. /**
  4424. * Creates a new render target cube texture
  4425. * @param size defines the size of the texture
  4426. * @param options defines the options used to create the texture
  4427. * @returns a new render target cube texture stored in an InternalTexture
  4428. */
  4429. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4430. let fullOptions = {
  4431. generateMipMaps: true,
  4432. generateDepthBuffer: true,
  4433. generateStencilBuffer: false,
  4434. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4435. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  4436. format: Engine.TEXTUREFORMAT_RGBA,
  4437. ...options
  4438. };
  4439. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4440. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4441. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4442. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4443. }
  4444. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4445. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4446. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4447. }
  4448. var gl = this._gl
  4449. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4450. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4451. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  4452. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4453. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4454. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4455. }
  4456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4460. for (var face = 0; face < 6; face++) {
  4461. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4462. }
  4463. // Create the framebuffer
  4464. var framebuffer = gl.createFramebuffer();
  4465. this.bindUnboundFramebuffer(framebuffer);
  4466. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4467. // MipMaps
  4468. if (fullOptions.generateMipMaps) {
  4469. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4470. }
  4471. // Unbind
  4472. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4473. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4474. this.bindUnboundFramebuffer(null);
  4475. texture._framebuffer = framebuffer;
  4476. texture.width = size;
  4477. texture.height = size;
  4478. texture.isReady = true;
  4479. texture.isCube = true;
  4480. texture.samples = 1;
  4481. texture.generateMipMaps = fullOptions.generateMipMaps;
  4482. texture.samplingMode = fullOptions.samplingMode;
  4483. texture.type = fullOptions.type;
  4484. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4485. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4486. this._internalTexturesCache.push(texture);
  4487. return texture;
  4488. }
  4489. /**
  4490. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4491. * @param rootUrl defines the url where the file to load is located
  4492. * @param scene defines the current scene
  4493. * @param scale defines scale to apply to the mip map selection
  4494. * @param offset defines offset to apply to the mip map selection
  4495. * @param onLoad defines an optional callback raised when the texture is loaded
  4496. * @param onError defines an optional callback raised if there is an issue to load the texture
  4497. * @param format defines the format of the data
  4498. * @param forcedExtension defines the extension to use to pick the right loader
  4499. * @returns the cube texture as an InternalTexture
  4500. */
  4501. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  4502. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4503. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  4504. var callback = (loadData: any) => {
  4505. if (!loadData) {
  4506. if (onLoad) {
  4507. onLoad(null);
  4508. }
  4509. return;
  4510. }
  4511. let texture = loadData.texture as InternalTexture;
  4512. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4513. texture._lodGenerationScale = scale;
  4514. texture._lodGenerationOffset = offset;
  4515. if (this._caps.textureLOD) {
  4516. // Do not add extra process if texture lod is supported.
  4517. if (onLoad) {
  4518. onLoad(texture);
  4519. }
  4520. return;
  4521. }
  4522. const mipSlices = 3;
  4523. var gl = this._gl;
  4524. const width = loadData.width;
  4525. if (!width) {
  4526. return;
  4527. }
  4528. const textures: BaseTexture[] = [];
  4529. for (let i = 0; i < mipSlices; i++) {
  4530. //compute LOD from even spacing in smoothness (matching shader calculation)
  4531. let smoothness = i / (mipSlices - 1);
  4532. let roughness = 1 - smoothness;
  4533. let minLODIndex = offset; // roughness = 0
  4534. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  4535. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4536. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4537. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4538. glTextureFromLod.isCube = true;
  4539. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4544. if (loadData.isDDS) {
  4545. var info: DDSInfo = loadData.info;
  4546. var data: any = loadData.data;
  4547. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4548. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  4549. }
  4550. else {
  4551. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  4552. }
  4553. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4554. // Wrap in a base texture for easy binding.
  4555. const lodTexture = new BaseTexture(scene);
  4556. lodTexture.isCube = true;
  4557. lodTexture._texture = glTextureFromLod;
  4558. glTextureFromLod.isReady = true;
  4559. textures.push(lodTexture);
  4560. }
  4561. texture._lodTextureHigh = textures[2];
  4562. texture._lodTextureMid = textures[1];
  4563. texture._lodTextureLow = textures[0];
  4564. if (onLoad) {
  4565. onLoad(texture);
  4566. }
  4567. };
  4568. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  4569. }
  4570. /**
  4571. * Creates a cube texture
  4572. * @param rootUrl defines the url where the files to load is located
  4573. * @param scene defines the current scene
  4574. * @param files defines the list of files to load (1 per face)
  4575. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4576. * @param onLoad defines an optional callback raised when the texture is loaded
  4577. * @param onError defines an optional callback raised if there is an issue to load the texture
  4578. * @param format defines the format of the data
  4579. * @param forcedExtension defines the extension to use to pick the right loader
  4580. * @returns the cube texture as an InternalTexture
  4581. */
  4582. 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 {
  4583. var gl = this._gl;
  4584. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4585. texture.isCube = true;
  4586. texture.url = rootUrl;
  4587. texture.generateMipMaps = !noMipmap;
  4588. if (!this._doNotHandleContextLost) {
  4589. texture._extension = forcedExtension;
  4590. texture._files = files;
  4591. }
  4592. var isKTX = false;
  4593. var isDDS = false;
  4594. var lastDot = rootUrl.lastIndexOf('.');
  4595. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4596. if (this._textureFormatInUse) {
  4597. extension = this._textureFormatInUse;
  4598. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  4599. isKTX = true;
  4600. } else {
  4601. isDDS = (extension === ".dds");
  4602. }
  4603. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  4604. if (onError && request) {
  4605. onError(request.status + " " + request.statusText, exception);
  4606. }
  4607. }
  4608. if (isKTX) {
  4609. this._loadFile(rootUrl, data => {
  4610. var ktx = new KhronosTextureContainer(data, 6);
  4611. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  4612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4613. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4614. ktx.uploadLevels(this._gl, !noMipmap);
  4615. this.setCubeMapTextureParams(gl, loadMipmap);
  4616. texture.width = ktx.pixelWidth;
  4617. texture.height = ktx.pixelHeight;
  4618. texture.isReady = true;
  4619. }, undefined, undefined, true, onerror);
  4620. } else if (isDDS) {
  4621. if (files && files.length === 6) {
  4622. this._cascadeLoadFiles(
  4623. scene,
  4624. imgs => {
  4625. var info: DDSInfo | undefined;
  4626. var loadMipmap: boolean = false;
  4627. var width: number = 0;
  4628. for (let index = 0; index < imgs.length; index++) {
  4629. let data = imgs[index];
  4630. info = DDSTools.GetDDSInfo(data);
  4631. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4632. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4633. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4634. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  4635. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4636. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4637. }
  4638. texture.width = info.width;
  4639. texture.height = info.height;
  4640. texture.type = info.textureType;
  4641. width = info.width;
  4642. }
  4643. this.setCubeMapTextureParams(gl, loadMipmap);
  4644. texture.isReady = true;
  4645. if (onLoad) {
  4646. onLoad({ isDDS: true, width: width, info, imgs, texture });
  4647. }
  4648. },
  4649. files,
  4650. onError);
  4651. } else {
  4652. this._loadFile(rootUrl,
  4653. data => {
  4654. var info = DDSTools.GetDDSInfo(data);
  4655. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4656. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4657. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4658. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  4659. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4660. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4661. }
  4662. this.setCubeMapTextureParams(gl, loadMipmap);
  4663. texture.width = info.width;
  4664. texture.height = info.height;
  4665. texture.isReady = true;
  4666. texture.type = info.textureType;
  4667. if (onLoad) {
  4668. onLoad({ isDDS: true, width: info.width, info, data, texture });
  4669. }
  4670. },
  4671. undefined,
  4672. undefined,
  4673. true,
  4674. onerror);
  4675. }
  4676. } else {
  4677. if (!files) {
  4678. throw new Error("Cannot load cubemap because files were not defined");
  4679. }
  4680. cascadeLoadImgs(rootUrl, scene, imgs => {
  4681. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4682. var height = width;
  4683. this._prepareWorkingCanvas();
  4684. if (!this._workingCanvas || !this._workingContext) {
  4685. return;
  4686. }
  4687. this._workingCanvas.width = width;
  4688. this._workingCanvas.height = height;
  4689. var faces = [
  4690. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4691. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4692. ];
  4693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4694. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4695. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4696. for (var index = 0; index < faces.length; index++) {
  4697. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4698. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4699. }
  4700. if (!noMipmap) {
  4701. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4702. }
  4703. this.setCubeMapTextureParams(gl, !noMipmap);
  4704. texture.width = width;
  4705. texture.height = height;
  4706. texture.isReady = true;
  4707. if (format) {
  4708. texture.format = format;
  4709. }
  4710. texture.onLoadedObservable.notifyObservers(texture);
  4711. texture.onLoadedObservable.clear();
  4712. if (onLoad) {
  4713. onLoad();
  4714. }
  4715. }, files, onError);
  4716. }
  4717. this._internalTexturesCache.push(texture);
  4718. return texture;
  4719. }
  4720. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  4721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4725. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4726. // this.resetTextureCache();
  4727. }
  4728. /**
  4729. * Update a raw cube texture
  4730. * @param texture defines the texture to udpdate
  4731. * @param data defines the data to store
  4732. * @param format defines the data format
  4733. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4734. * @param invertY defines if data must be stored with Y axis inverted
  4735. * @param compression defines the compression used (null by default)
  4736. * @param level defines which level of the texture to update
  4737. */
  4738. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4739. texture._bufferViewArray = data;
  4740. texture.format = format;
  4741. texture.type = type;
  4742. texture.invertY = invertY;
  4743. texture._compression = compression;
  4744. var gl = this._gl;
  4745. var textureType = this._getWebGLTextureType(type);
  4746. var internalFormat = this._getInternalFormat(format);
  4747. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4748. var needConversion = false;
  4749. if (internalFormat === gl.RGB) {
  4750. internalFormat = gl.RGBA;
  4751. needConversion = true;
  4752. }
  4753. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4754. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4755. if (texture.width % 4 !== 0) {
  4756. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4757. }
  4758. // Data are known to be in +X +Y +Z -X -Y -Z
  4759. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4760. let faceData = data[faceIndex];
  4761. if (compression) {
  4762. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4763. } else {
  4764. if (needConversion) {
  4765. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4766. }
  4767. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4768. }
  4769. }
  4770. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4771. if (isPot && texture.generateMipMaps && level === 0) {
  4772. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4773. }
  4774. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4775. // this.resetTextureCache();
  4776. texture.isReady = true;
  4777. }
  4778. /**
  4779. * Creates a new raw cube texture
  4780. * @param data defines the array of data to use to create each face
  4781. * @param size defines the size of the textures
  4782. * @param format defines the format of the data
  4783. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4784. * @param generateMipMaps defines if the engine should generate the mip levels
  4785. * @param invertY defines if data must be stored with Y axis inverted
  4786. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4787. * @param compression defines the compression used (null by default)
  4788. * @returns the cube texture as an InternalTexture
  4789. */
  4790. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4791. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4792. compression: Nullable<string> = null): InternalTexture {
  4793. var gl = this._gl;
  4794. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4795. texture.isCube = true;
  4796. texture.generateMipMaps = generateMipMaps;
  4797. texture.format = format;
  4798. texture.type = type;
  4799. if (!this._doNotHandleContextLost) {
  4800. texture._bufferViewArray = data;
  4801. }
  4802. var textureType = this._getWebGLTextureType(type);
  4803. var internalFormat = this._getInternalFormat(format);
  4804. if (internalFormat === gl.RGB) {
  4805. internalFormat = gl.RGBA;
  4806. }
  4807. var width = size;
  4808. var height = width;
  4809. texture.width = width;
  4810. texture.height = height;
  4811. // Double check on POT to generate Mips.
  4812. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4813. if (!isPot) {
  4814. generateMipMaps = false;
  4815. }
  4816. // Upload data if needed. The texture won't be ready until then.
  4817. if (data) {
  4818. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4819. }
  4820. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4821. // Filters
  4822. if (data && generateMipMaps) {
  4823. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4824. }
  4825. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4828. }
  4829. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4832. }
  4833. else {
  4834. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4837. }
  4838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4841. return texture;
  4842. }
  4843. /**
  4844. * Creates a new raw cube texture from a specified url
  4845. * @param url defines the url where the data is located
  4846. * @param scene defines the current scene
  4847. * @param size defines the size of the textures
  4848. * @param format defines the format of the data
  4849. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4850. * @param noMipmap defines if the engine should avoid generating the mip levels
  4851. * @param callback defines a callback used to extract texture data from loaded data
  4852. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  4853. * @param onLoad defines a callback called when texture is loaded
  4854. * @param onError defines a callback called if there is an error
  4855. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4856. * @param invertY defines if data must be stored with Y axis inverted
  4857. * @returns the cube texture as an InternalTexture
  4858. */
  4859. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  4860. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  4861. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  4862. onLoad: Nullable<() => void> = null,
  4863. onError: Nullable<(message?: string, exception?: any) => void> = null,
  4864. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  4865. invertY = false): InternalTexture {
  4866. var gl = this._gl;
  4867. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  4868. scene._addPendingData(texture);
  4869. texture.url = url;
  4870. this._internalTexturesCache.push(texture);
  4871. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  4872. scene._removePendingData(texture);
  4873. if (onError && request) {
  4874. onError(request.status + " " + request.statusText, exception);
  4875. }
  4876. };
  4877. var internalCallback = (data: any) => {
  4878. var width = texture.width;
  4879. var faceDataArrays = callback(data);
  4880. if (!faceDataArrays) {
  4881. return;
  4882. }
  4883. if (mipmapGenerator) {
  4884. var textureType = this._getWebGLTextureType(type);
  4885. var internalFormat = this._getInternalFormat(format);
  4886. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4887. var needConversion = false;
  4888. if (internalFormat === gl.RGB) {
  4889. internalFormat = gl.RGBA;
  4890. needConversion = true;
  4891. }
  4892. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4893. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4894. var mipData = mipmapGenerator(faceDataArrays);
  4895. for (var level = 0; level < mipData.length; level++) {
  4896. var mipSize = width >> level;
  4897. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  4898. let mipFaceData = mipData[level][faceIndex];
  4899. if (needConversion) {
  4900. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  4901. }
  4902. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  4903. }
  4904. }
  4905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4906. }
  4907. else {
  4908. texture.generateMipMaps = !noMipmap;
  4909. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  4910. }
  4911. texture.isReady = true;
  4912. // this.resetTextureCache();
  4913. scene._removePendingData(texture);
  4914. if (onLoad) {
  4915. onLoad();
  4916. }
  4917. };
  4918. this._loadFile(url, data => {
  4919. internalCallback(data);
  4920. }, undefined, scene.database, true, onerror);
  4921. return texture;
  4922. };
  4923. /**
  4924. * Update a raw 3D texture
  4925. * @param texture defines the texture to update
  4926. * @param data defines the data to store
  4927. * @param format defines the data format
  4928. * @param invertY defines if data must be stored with Y axis inverted
  4929. * @param compression defines the used compression (can be null)
  4930. */
  4931. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  4932. var internalFormat = this._getInternalFormat(format);
  4933. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  4934. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4935. if (!this._doNotHandleContextLost) {
  4936. texture._bufferView = data;
  4937. texture.format = format;
  4938. texture.invertY = invertY;
  4939. texture._compression = compression;
  4940. }
  4941. if (texture.width % 4 !== 0) {
  4942. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  4943. }
  4944. if (compression && data) {
  4945. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  4946. } else {
  4947. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4948. }
  4949. if (texture.generateMipMaps) {
  4950. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  4951. }
  4952. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4953. // this.resetTextureCache();
  4954. texture.isReady = true;
  4955. }
  4956. /**
  4957. * Creates a new raw 3D texture
  4958. * @param data defines the data used to create the texture
  4959. * @param width defines the width of the texture
  4960. * @param height defines the height of the texture
  4961. * @param depth defines the depth of the texture
  4962. * @param format defines the format of the texture
  4963. * @param generateMipMaps defines if the engine must generate mip levels
  4964. * @param invertY defines if data must be stored with Y axis inverted
  4965. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4966. * @param compression defines the compressed used (can be null)
  4967. * @returns a new raw 3D texture (stored in an InternalTexture)
  4968. */
  4969. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  4970. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  4971. texture.baseWidth = width;
  4972. texture.baseHeight = height;
  4973. texture.baseDepth = depth;
  4974. texture.width = width;
  4975. texture.height = height;
  4976. texture.depth = depth;
  4977. texture.format = format;
  4978. texture.generateMipMaps = generateMipMaps;
  4979. texture.samplingMode = samplingMode;
  4980. texture.is3D = true;
  4981. if (!this._doNotHandleContextLost) {
  4982. texture._bufferView = data;
  4983. }
  4984. this.updateRawTexture3D(texture, data, format, invertY, compression);
  4985. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  4986. // Filters
  4987. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4988. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4989. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4990. if (generateMipMaps) {
  4991. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  4992. }
  4993. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4994. this._internalTexturesCache.push(texture);
  4995. return texture;
  4996. }
  4997. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  4998. var gl = this._gl;
  4999. if (!gl) {
  5000. return;
  5001. }
  5002. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5005. if (!noMipmap && !isCompressed) {
  5006. gl.generateMipmap(gl.TEXTURE_2D);
  5007. }
  5008. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5009. // this.resetTextureCache();
  5010. if (scene) {
  5011. scene._removePendingData(texture);
  5012. }
  5013. texture.onLoadedObservable.notifyObservers(texture);
  5014. texture.onLoadedObservable.clear();
  5015. }
  5016. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5017. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  5018. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  5019. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  5020. var gl = this._gl;
  5021. if (!gl) {
  5022. return;
  5023. }
  5024. if (!texture._webGLTexture) {
  5025. // this.resetTextureCache();
  5026. if (scene) {
  5027. scene._removePendingData(texture);
  5028. }
  5029. return;
  5030. }
  5031. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5032. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5033. texture.baseWidth = width;
  5034. texture.baseHeight = height;
  5035. texture.width = potWidth;
  5036. texture.height = potHeight;
  5037. texture.isReady = true;
  5038. if (processFunction(potWidth, potHeight, () => {
  5039. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5040. })) {
  5041. // Returning as texture needs extra async steps
  5042. return;
  5043. }
  5044. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5045. }
  5046. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5047. // Create new RGBA data container.
  5048. var rgbaData: any;
  5049. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5050. rgbaData = new Float32Array(width * height * 4);
  5051. }
  5052. else {
  5053. rgbaData = new Uint32Array(width * height * 4);
  5054. }
  5055. // Convert each pixel.
  5056. for (let x = 0; x < width; x++) {
  5057. for (let y = 0; y < height; y++) {
  5058. let index = (y * width + x) * 3;
  5059. let newIndex = (y * width + x) * 4;
  5060. // Map Old Value to new value.
  5061. rgbaData[newIndex + 0] = rgbData[index + 0];
  5062. rgbaData[newIndex + 1] = rgbData[index + 1];
  5063. rgbaData[newIndex + 2] = rgbData[index + 2];
  5064. // Add fully opaque alpha channel.
  5065. rgbaData[newIndex + 3] = 1;
  5066. }
  5067. }
  5068. return rgbaData;
  5069. }
  5070. /** @ignore */
  5071. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5072. var gl = this._gl;
  5073. if (texture._framebuffer) {
  5074. gl.deleteFramebuffer(texture._framebuffer);
  5075. texture._framebuffer = null;
  5076. }
  5077. if (texture._depthStencilBuffer) {
  5078. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5079. texture._depthStencilBuffer = null;
  5080. }
  5081. if (texture._MSAAFramebuffer) {
  5082. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5083. texture._MSAAFramebuffer = null;
  5084. }
  5085. if (texture._MSAARenderBuffer) {
  5086. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5087. texture._MSAARenderBuffer = null;
  5088. }
  5089. }
  5090. /** @ignore */
  5091. public _releaseTexture(texture: InternalTexture): void {
  5092. var gl = this._gl;
  5093. this._releaseFramebufferObjects(texture);
  5094. gl.deleteTexture(texture._webGLTexture);
  5095. // Unbind channels
  5096. this.unbindAllTextures();
  5097. var index = this._internalTexturesCache.indexOf(texture);
  5098. if (index !== -1) {
  5099. this._internalTexturesCache.splice(index, 1);
  5100. }
  5101. // Integrated fixed lod samplers.
  5102. if (texture._lodTextureHigh) {
  5103. texture._lodTextureHigh.dispose();
  5104. }
  5105. if (texture._lodTextureMid) {
  5106. texture._lodTextureMid.dispose();
  5107. }
  5108. if (texture._lodTextureLow) {
  5109. texture._lodTextureLow.dispose();
  5110. }
  5111. // Set output texture of post process to null if the texture has been released/disposed
  5112. this.scenes.forEach((scene)=>{
  5113. scene.postProcesses.forEach((postProcess)=>{
  5114. if(postProcess._outputTexture == texture){
  5115. postProcess._outputTexture = null;
  5116. }
  5117. });
  5118. scene.cameras.forEach((camera)=>{
  5119. camera._postProcesses.forEach((postProcess)=>{
  5120. if(postProcess){
  5121. if(postProcess._outputTexture == texture){
  5122. postProcess._outputTexture = null;
  5123. }
  5124. }
  5125. });
  5126. });
  5127. })
  5128. }
  5129. private setProgram(program: WebGLProgram): void {
  5130. if (this._currentProgram !== program) {
  5131. this._gl.useProgram(program);
  5132. this._currentProgram = program;
  5133. }
  5134. }
  5135. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5136. /**
  5137. * Binds an effect to the webGL context
  5138. * @param effect defines the effect to bind
  5139. */
  5140. public bindSamplers(effect: Effect): void {
  5141. this.setProgram(effect.getProgram());
  5142. var samplers = effect.getSamplers();
  5143. for (var index = 0; index < samplers.length; index++) {
  5144. var uniform = effect.getUniform(samplers[index]);
  5145. if (uniform) {
  5146. this._boundUniforms[index] = uniform;
  5147. }
  5148. }
  5149. this._currentEffect = null;
  5150. }
  5151. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5152. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5153. return;
  5154. }
  5155. // Remove
  5156. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5157. // Bind last to it
  5158. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5159. // Bind to dummy
  5160. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5161. }
  5162. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5163. if (!internalTexture) {
  5164. return -1;
  5165. }
  5166. internalTexture._initialSlot = channel;
  5167. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5168. if (channel !== internalTexture._designatedSlot) {
  5169. this._textureCollisions.addCount(1, false);
  5170. }
  5171. } else {
  5172. if (channel !== internalTexture._designatedSlot) {
  5173. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5174. return internalTexture._designatedSlot;
  5175. } else {
  5176. // No slot for this texture, let's pick a new one (if we find a free slot)
  5177. if (this._nextFreeTextureSlots.length) {
  5178. return this._nextFreeTextureSlots[0];
  5179. }
  5180. // We need to recycle the oldest bound texture, sorry.
  5181. this._textureCollisions.addCount(1, false);
  5182. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5183. }
  5184. }
  5185. }
  5186. return channel;
  5187. }
  5188. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5189. previous!.next = next;
  5190. next!.previous = previous;
  5191. }
  5192. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5193. let currentSlot = internalTexture._designatedSlot;
  5194. if (currentSlot === -1) {
  5195. return -1;
  5196. }
  5197. internalTexture._designatedSlot = -1;
  5198. if (this.disableTextureBindingOptimization) {
  5199. return -1;
  5200. }
  5201. // Remove from bound list
  5202. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5203. // Free the slot
  5204. this._boundTexturesCache[currentSlot] = null;
  5205. this._nextFreeTextureSlots.push(currentSlot);
  5206. return currentSlot;
  5207. }
  5208. private _activateCurrentTexture() {
  5209. if (this._currentTextureChannel !== this._activeChannel) {
  5210. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5211. this._currentTextureChannel = this._activeChannel;
  5212. }
  5213. }
  5214. /** @ignore */
  5215. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): void {
  5216. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5217. this._activeChannel = texture._designatedSlot;
  5218. }
  5219. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5220. let isTextureForRendering = texture && texture._initialSlot > -1;
  5221. if (currentTextureBound !== texture || force) {
  5222. if (currentTextureBound) {
  5223. this._removeDesignatedSlot(currentTextureBound);
  5224. }
  5225. this._activateCurrentTexture();
  5226. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5227. this._boundTexturesCache[this._activeChannel] = texture;
  5228. if (texture) {
  5229. if (!this.disableTextureBindingOptimization) {
  5230. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5231. if (slotIndex > -1) {
  5232. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5233. }
  5234. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5235. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5236. }
  5237. texture._designatedSlot = this._activeChannel;
  5238. }
  5239. } else if (forTextureDataUpdate) {
  5240. this._activateCurrentTexture();
  5241. }
  5242. if (isTextureForRendering && !forTextureDataUpdate) {
  5243. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5244. }
  5245. }
  5246. /** @ignore */
  5247. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5248. if (channel < 0) {
  5249. return;
  5250. }
  5251. if (texture) {
  5252. channel = this._getCorrectTextureChannel(channel, texture);
  5253. }
  5254. this._activeChannel = channel;
  5255. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5256. }
  5257. /**
  5258. * Sets a texture to the webGL context from a postprocess
  5259. * @param channel defines the channel to use
  5260. * @param postProcess defines the source postprocess
  5261. */
  5262. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5263. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5264. }
  5265. /**
  5266. * Binds the output of the passed in post process to the texture channel specified
  5267. * @param channel The channel the texture should be bound to
  5268. * @param postProcess The post process which's output should be bound
  5269. */
  5270. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5271. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5272. }
  5273. /**
  5274. * Unbind all textures from the webGL context
  5275. */
  5276. public unbindAllTextures(): void {
  5277. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5278. this._activeChannel = channel;
  5279. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5280. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5281. if (this.webGLVersion > 1) {
  5282. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5283. }
  5284. }
  5285. }
  5286. /**
  5287. * Sets a texture to the according uniform.
  5288. * @param channel The texture channel
  5289. * @param uniform The uniform to set
  5290. * @param texture The texture to apply
  5291. */
  5292. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5293. if (channel < 0) {
  5294. return;
  5295. }
  5296. if (uniform) {
  5297. this._boundUniforms[channel] = uniform;
  5298. }
  5299. this._setTexture(channel, texture);
  5300. }
  5301. /**
  5302. * Sets a depth stencil texture from a render target to the according uniform.
  5303. * @param channel The texture channel
  5304. * @param uniform The uniform to set
  5305. * @param texture The render target texture containing the depth stencil texture to apply
  5306. */
  5307. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5308. if (channel < 0) {
  5309. return;
  5310. }
  5311. if (uniform) {
  5312. this._boundUniforms[channel] = uniform;
  5313. }
  5314. if (!texture || !texture.depthStencilTexture) {
  5315. this._setTexture(channel, null);
  5316. }
  5317. else {
  5318. this._setTexture(channel, texture, false, true);
  5319. }
  5320. }
  5321. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5322. let uniform = this._boundUniforms[sourceSlot];
  5323. if (uniform._currentState === destination) {
  5324. return;
  5325. }
  5326. this._gl.uniform1i(uniform, destination);
  5327. uniform._currentState = destination;
  5328. }
  5329. private _getTextureWrapMode(mode: number): number {
  5330. switch(mode) {
  5331. case Texture.WRAP_ADDRESSMODE:
  5332. return this._gl.REPEAT;
  5333. case Texture.CLAMP_ADDRESSMODE:
  5334. return this._gl.CLAMP_TO_EDGE;
  5335. case Texture.MIRROR_ADDRESSMODE:
  5336. return this._gl.MIRRORED_REPEAT;
  5337. }
  5338. return this._gl.REPEAT;
  5339. }
  5340. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5341. // Not ready?
  5342. if (!texture) {
  5343. if (this._boundTexturesCache[channel] != null) {
  5344. this._activeChannel = channel;
  5345. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5346. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5347. if (this.webGLVersion > 1) {
  5348. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5349. }
  5350. }
  5351. return false;
  5352. }
  5353. // Video
  5354. if ((<VideoTexture>texture).video) {
  5355. this._activeChannel = channel;
  5356. (<VideoTexture>texture).update();
  5357. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5358. texture.delayLoad();
  5359. return false;
  5360. }
  5361. let internalTexture: InternalTexture;
  5362. if (depthStencilTexture) {
  5363. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5364. }
  5365. else if (texture.isReady()) {
  5366. internalTexture = <InternalTexture>texture.getInternalTexture();
  5367. }
  5368. else if (texture.isCube) {
  5369. internalTexture = this.emptyCubeTexture;
  5370. }
  5371. else if (texture.is3D) {
  5372. internalTexture = this.emptyTexture3D;
  5373. }
  5374. else {
  5375. internalTexture = this.emptyTexture;
  5376. }
  5377. if (!isPartOfTextureArray) {
  5378. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5379. }
  5380. let needToBind = true;
  5381. if (this._boundTexturesCache[channel] === internalTexture) {
  5382. this._moveBoundTextureOnTop(internalTexture);
  5383. if (!isPartOfTextureArray) {
  5384. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5385. }
  5386. needToBind = false;
  5387. }
  5388. this._activeChannel = channel;
  5389. if (internalTexture && internalTexture.is3D) {
  5390. if (needToBind) {
  5391. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5392. }
  5393. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5394. internalTexture._cachedWrapU = texture.wrapU;
  5395. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5396. }
  5397. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5398. internalTexture._cachedWrapV = texture.wrapV;
  5399. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5400. }
  5401. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5402. internalTexture._cachedWrapR = texture.wrapR;
  5403. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5404. }
  5405. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5406. }
  5407. else if (internalTexture && internalTexture.isCube) {
  5408. if (needToBind) {
  5409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5410. }
  5411. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5412. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5413. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5414. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5415. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5416. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5417. }
  5418. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5419. } else {
  5420. if (needToBind) {
  5421. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5422. }
  5423. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5424. internalTexture._cachedWrapU = texture.wrapU;
  5425. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5426. }
  5427. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5428. internalTexture._cachedWrapV = texture.wrapV;
  5429. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5430. }
  5431. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5432. }
  5433. return true;
  5434. }
  5435. /**
  5436. * Sets an array of texture to the webGL context
  5437. * @param channel defines the channel where the texture array must be set
  5438. * @param uniform defines the associated uniform location
  5439. * @param textures defines the array of textures to bind
  5440. */
  5441. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5442. if (channel < 0 || !uniform) {
  5443. return;
  5444. }
  5445. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5446. this._textureUnits = new Int32Array(textures.length);
  5447. }
  5448. for (let i = 0; i < textures.length; i++) {
  5449. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5450. }
  5451. this._gl.uniform1iv(uniform, this._textureUnits);
  5452. for (var index = 0; index < textures.length; index++) {
  5453. this._setTexture(this._textureUnits[index], textures[index], true);
  5454. }
  5455. }
  5456. /** @ignore */
  5457. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5458. var internalTexture = texture.getInternalTexture();
  5459. if (!internalTexture) {
  5460. return;
  5461. }
  5462. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5463. var value = texture.anisotropicFilteringLevel;
  5464. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  5465. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  5466. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  5467. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5468. }
  5469. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5470. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5471. internalTexture._cachedAnisotropicFilteringLevel = value;
  5472. }
  5473. }
  5474. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5475. this._bindTextureDirectly(target, texture, true, true);
  5476. this._gl.texParameterf(target, parameter, value);
  5477. }
  5478. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5479. if (texture) {
  5480. this._bindTextureDirectly(target, texture, true, true);
  5481. }
  5482. this._gl.texParameteri(target, parameter, value);
  5483. }
  5484. /**
  5485. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5486. * @param x defines the x coordinate of the rectangle where pixels must be read
  5487. * @param y defines the y coordinate of the rectangle where pixels must be read
  5488. * @param width defines the width of the rectangle where pixels must be read
  5489. * @param height defines the height of the rectangle where pixels must be read
  5490. * @returns a Uint8Array containing RGBA colors
  5491. */
  5492. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5493. var data = new Uint8Array(height * width * 4);
  5494. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5495. return data;
  5496. }
  5497. /**
  5498. * Add an externaly attached data from its key.
  5499. * This method call will fail and return false, if such key already exists.
  5500. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5501. * @param key the unique key that identifies the data
  5502. * @param data the data object to associate to the key for this Engine instance
  5503. * @return true if no such key were already present and the data was added successfully, false otherwise
  5504. */
  5505. public addExternalData<T>(key: string, data: T): boolean {
  5506. if (!this._externalData) {
  5507. this._externalData = new StringDictionary<Object>();
  5508. }
  5509. return this._externalData.add(key, data);
  5510. }
  5511. /**
  5512. * Get an externaly attached data from its key
  5513. * @param key the unique key that identifies the data
  5514. * @return the associated data, if present (can be null), or undefined if not present
  5515. */
  5516. public getExternalData<T>(key: string): T {
  5517. if (!this._externalData) {
  5518. this._externalData = new StringDictionary<Object>();
  5519. }
  5520. return <T>this._externalData.get(key);
  5521. }
  5522. /**
  5523. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5524. * @param key the unique key that identifies the data
  5525. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5526. * @return the associated data, can be null if the factory returned null.
  5527. */
  5528. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5529. if (!this._externalData) {
  5530. this._externalData = new StringDictionary<Object>();
  5531. }
  5532. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5533. }
  5534. /**
  5535. * Remove an externaly attached data from the Engine instance
  5536. * @param key the unique key that identifies the data
  5537. * @return true if the data was successfully removed, false if it doesn't exist
  5538. */
  5539. public removeExternalData(key: string): boolean {
  5540. if (!this._externalData) {
  5541. this._externalData = new StringDictionary<Object>();
  5542. }
  5543. return this._externalData.remove(key);
  5544. }
  5545. /**
  5546. * Unbind all vertex attributes from the webGL context
  5547. */
  5548. public unbindAllAttributes() {
  5549. if (this._mustWipeVertexAttributes) {
  5550. this._mustWipeVertexAttributes = false;
  5551. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5552. this._gl.disableVertexAttribArray(i);
  5553. this._vertexAttribArraysEnabled[i] = false;
  5554. this._currentBufferPointers[i].active = false;
  5555. }
  5556. return;
  5557. }
  5558. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5559. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5560. continue;
  5561. }
  5562. this._gl.disableVertexAttribArray(i);
  5563. this._vertexAttribArraysEnabled[i] = false;
  5564. this._currentBufferPointers[i].active = false;
  5565. }
  5566. }
  5567. /**
  5568. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  5569. */
  5570. public releaseEffects() {
  5571. for (var name in this._compiledEffects) {
  5572. this._deleteProgram(this._compiledEffects[name]._program)
  5573. }
  5574. this._compiledEffects = {};
  5575. }
  5576. /**
  5577. * Dispose and release all associated resources
  5578. */
  5579. public dispose(): void {
  5580. this.hideLoadingUI();
  5581. this.stopRenderLoop();
  5582. // Release postProcesses
  5583. while (this.postProcesses.length) {
  5584. this.postProcesses[0].dispose();
  5585. }
  5586. // Empty texture
  5587. if (this._emptyTexture) {
  5588. this._releaseTexture(this._emptyTexture);
  5589. this._emptyTexture = null;
  5590. }
  5591. if (this._emptyCubeTexture) {
  5592. this._releaseTexture(this._emptyCubeTexture);
  5593. this._emptyCubeTexture = null;
  5594. }
  5595. // Rescale PP
  5596. if (this._rescalePostProcess) {
  5597. this._rescalePostProcess.dispose();
  5598. }
  5599. // Release scenes
  5600. while (this.scenes.length) {
  5601. this.scenes[0].dispose();
  5602. }
  5603. // Release audio engine
  5604. if (Engine.audioEngine) {
  5605. Engine.audioEngine.dispose();
  5606. }
  5607. // Release effects
  5608. this.releaseEffects();
  5609. // Unbind
  5610. this.unbindAllAttributes();
  5611. this._boundUniforms = [];
  5612. if (this._dummyFramebuffer) {
  5613. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5614. }
  5615. //WebVR
  5616. this.disableVR();
  5617. // Events
  5618. if (Tools.IsWindowObjectExist()) {
  5619. window.removeEventListener("blur", this._onBlur);
  5620. window.removeEventListener("focus", this._onFocus);
  5621. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5622. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5623. if (this._renderingCanvas) {
  5624. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5625. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5626. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5627. if (!this._doNotHandleContextLost) {
  5628. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5629. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5630. }
  5631. }
  5632. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5633. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5634. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5635. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5636. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5637. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5638. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5639. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5640. if (this._onVrDisplayConnect) {
  5641. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5642. if (this._onVrDisplayDisconnect) {
  5643. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5644. }
  5645. if (this._onVrDisplayPresentChange) {
  5646. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5647. }
  5648. this._onVrDisplayConnect = null;
  5649. this._onVrDisplayDisconnect = null;
  5650. }
  5651. }
  5652. // Remove from Instances
  5653. var index = Engine.Instances.indexOf(this);
  5654. if (index >= 0) {
  5655. Engine.Instances.splice(index, 1);
  5656. }
  5657. this._workingCanvas = null;
  5658. this._workingContext = null;
  5659. this._currentBufferPointers = [];
  5660. this._renderingCanvas = null;
  5661. this._currentProgram = null;
  5662. this._bindedRenderFunction = null;
  5663. this.onResizeObservable.clear();
  5664. this.onCanvasBlurObservable.clear();
  5665. this.onCanvasFocusObservable.clear();
  5666. this.onCanvasPointerOutObservable.clear();
  5667. this.onBeginFrameObservable.clear();
  5668. this.onEndFrameObservable.clear();
  5669. Effect.ResetCache();
  5670. // Abort active requests
  5671. for (let request of this._activeRequests) {
  5672. request.abort();
  5673. }
  5674. }
  5675. // Loading screen
  5676. /**
  5677. * Display the loading screen
  5678. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5679. */
  5680. public displayLoadingUI(): void {
  5681. if (!Tools.IsWindowObjectExist()) {
  5682. return;
  5683. }
  5684. const loadingScreen = this.loadingScreen;
  5685. if (loadingScreen) {
  5686. loadingScreen.displayLoadingUI();
  5687. }
  5688. }
  5689. /**
  5690. * Hide the loading screen
  5691. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5692. */
  5693. public hideLoadingUI(): void {
  5694. if (!Tools.IsWindowObjectExist()) {
  5695. return;
  5696. }
  5697. const loadingScreen = this.loadingScreen;
  5698. if (loadingScreen) {
  5699. loadingScreen.hideLoadingUI();
  5700. }
  5701. }
  5702. /**
  5703. * Gets the current loading screen object
  5704. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5705. */
  5706. public get loadingScreen(): ILoadingScreen {
  5707. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  5708. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  5709. return this._loadingScreen;
  5710. }
  5711. /**
  5712. * Sets the current loading screen object
  5713. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5714. */
  5715. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5716. this._loadingScreen = loadingScreen;
  5717. }
  5718. /**
  5719. * Sets the current loading screen text
  5720. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5721. */
  5722. public set loadingUIText(text: string) {
  5723. this.loadingScreen.loadingUIText = text;
  5724. }
  5725. /**
  5726. * Sets the current loading screen background color
  5727. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5728. */
  5729. public set loadingUIBackgroundColor(color: string) {
  5730. this.loadingScreen.loadingUIBackgroundColor = color;
  5731. }
  5732. /**
  5733. * Attach a new callback raised when context lost event is fired
  5734. * @param callback defines the callback to call
  5735. */
  5736. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5737. if (this._renderingCanvas) {
  5738. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5739. }
  5740. }
  5741. /**
  5742. * Attach a new callback raised when context restored event is fired
  5743. * @param callback defines the callback to call
  5744. */
  5745. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5746. if (this._renderingCanvas) {
  5747. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5748. }
  5749. }
  5750. /**
  5751. * Gets the source code of the vertex shader associated with a specific webGL program
  5752. * @param program defines the program to use
  5753. * @returns a string containing the source code of the vertex shader associated with the program
  5754. */
  5755. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5756. var shaders = this._gl.getAttachedShaders(program);
  5757. if (!shaders) {
  5758. return null;
  5759. }
  5760. return this._gl.getShaderSource(shaders[0]);
  5761. }
  5762. /**
  5763. * Gets the source code of the fragment shader associated with a specific webGL program
  5764. * @param program defines the program to use
  5765. * @returns a string containing the source code of the fragment shader associated with the program
  5766. */
  5767. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5768. var shaders = this._gl.getAttachedShaders(program);
  5769. if (!shaders) {
  5770. return null;
  5771. }
  5772. return this._gl.getShaderSource(shaders[1]);
  5773. }
  5774. /**
  5775. * Get the current error code of the webGL context
  5776. * @returns the error code
  5777. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5778. */
  5779. public getError(): number {
  5780. return this._gl.getError();
  5781. }
  5782. // FPS
  5783. /**
  5784. * Gets the current framerate
  5785. * @returns a number representing the framerate
  5786. */
  5787. public getFps(): number {
  5788. return this._fps;
  5789. }
  5790. /**
  5791. * Gets the time spent between current and previous frame
  5792. * @returns a number representing the delta time in ms
  5793. */
  5794. public getDeltaTime(): number {
  5795. return this._deltaTime;
  5796. }
  5797. private _measureFps(): void {
  5798. this._performanceMonitor.sampleFrame();
  5799. this._fps = this._performanceMonitor.averageFPS;
  5800. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5801. }
  5802. /** @ignore */
  5803. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  5804. let gl = this._gl;
  5805. if (!this._dummyFramebuffer) {
  5806. let dummy = gl.createFramebuffer();
  5807. if (!dummy) {
  5808. throw new Error("Unable to create dummy framebuffer");
  5809. }
  5810. this._dummyFramebuffer = dummy;
  5811. }
  5812. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5813. if (faceIndex > -1) {
  5814. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  5815. } else {
  5816. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  5817. }
  5818. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5819. let buffer: ArrayBufferView;
  5820. switch (readType) {
  5821. case gl.UNSIGNED_BYTE:
  5822. buffer = new Uint8Array(4 * width * height);
  5823. readType = gl.UNSIGNED_BYTE;
  5824. break;
  5825. default:
  5826. buffer = new Float32Array(4 * width * height);
  5827. readType = gl.FLOAT;
  5828. break;
  5829. }
  5830. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  5831. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  5832. return buffer;
  5833. }
  5834. private _canRenderToFloatFramebuffer(): boolean {
  5835. if (this._webGLVersion > 1) {
  5836. return this._caps.colorBufferFloat;
  5837. }
  5838. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  5839. }
  5840. private _canRenderToHalfFloatFramebuffer(): boolean {
  5841. if (this._webGLVersion > 1) {
  5842. return this._caps.colorBufferFloat;
  5843. }
  5844. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  5845. }
  5846. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  5847. private _canRenderToFramebuffer(type: number): boolean {
  5848. let gl = this._gl;
  5849. //clear existing errors
  5850. while (gl.getError() !== gl.NO_ERROR) { }
  5851. let successful = true;
  5852. let texture = gl.createTexture();
  5853. gl.bindTexture(gl.TEXTURE_2D, texture);
  5854. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  5855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5857. let fb = gl.createFramebuffer();
  5858. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  5859. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5860. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  5861. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  5862. successful = successful && (gl.getError() === gl.NO_ERROR);
  5863. //try render by clearing frame buffer's color buffer
  5864. if (successful) {
  5865. gl.clear(gl.COLOR_BUFFER_BIT);
  5866. successful = successful && (gl.getError() === gl.NO_ERROR);
  5867. }
  5868. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  5869. if (successful) {
  5870. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  5871. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5872. let readFormat = gl.RGBA;
  5873. let readType = gl.UNSIGNED_BYTE;
  5874. let buffer = new Uint8Array(4);
  5875. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  5876. successful = successful && (gl.getError() === gl.NO_ERROR);
  5877. }
  5878. //clean up
  5879. gl.deleteTexture(texture);
  5880. gl.deleteFramebuffer(fb);
  5881. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5882. //clear accumulated errors
  5883. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  5884. return successful;
  5885. }
  5886. /** @ignore */
  5887. public _getWebGLTextureType(type: number): number {
  5888. if (type === Engine.TEXTURETYPE_FLOAT) {
  5889. return this._gl.FLOAT;
  5890. }
  5891. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5892. // Add Half Float Constant.
  5893. return this._gl.HALF_FLOAT_OES;
  5894. }
  5895. return this._gl.UNSIGNED_BYTE;
  5896. };
  5897. private _getInternalFormat(format: number): number {
  5898. var internalFormat = this._gl.RGBA;
  5899. switch (format) {
  5900. case Engine.TEXTUREFORMAT_ALPHA:
  5901. internalFormat = this._gl.ALPHA;
  5902. break;
  5903. case Engine.TEXTUREFORMAT_LUMINANCE:
  5904. internalFormat = this._gl.LUMINANCE;
  5905. break;
  5906. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5907. internalFormat = this._gl.LUMINANCE_ALPHA;
  5908. break;
  5909. case Engine.TEXTUREFORMAT_RGB:
  5910. case Engine.TEXTUREFORMAT_RGB32F:
  5911. internalFormat = this._gl.RGB;
  5912. break;
  5913. case Engine.TEXTUREFORMAT_RGBA:
  5914. case Engine.TEXTUREFORMAT_RGBA32F:
  5915. internalFormat = this._gl.RGBA;
  5916. break;
  5917. case Engine.TEXTUREFORMAT_R32F:
  5918. internalFormat = this._gl.RED;
  5919. break;
  5920. case Engine.TEXTUREFORMAT_RG32F:
  5921. internalFormat = this._gl.RG;
  5922. break;
  5923. }
  5924. return internalFormat;
  5925. }
  5926. /** @ignore */
  5927. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  5928. if (this._webGLVersion === 1) {
  5929. if (format) {
  5930. switch(format) {
  5931. case Engine.TEXTUREFORMAT_LUMINANCE:
  5932. return this._gl.LUMINANCE;
  5933. }
  5934. }
  5935. return this._gl.RGBA;
  5936. }
  5937. if (type === Engine.TEXTURETYPE_FLOAT) {
  5938. if (format) {
  5939. switch(format) {
  5940. case Engine.TEXTUREFORMAT_R32F:
  5941. return this._gl.R32F;
  5942. case Engine.TEXTUREFORMAT_RG32F:
  5943. return this._gl.RG32F;
  5944. case Engine.TEXTUREFORMAT_RGB32F:
  5945. return this._gl.RGB32F;
  5946. }
  5947. }
  5948. return this._gl.RGBA32F;
  5949. }
  5950. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5951. return this._gl.RGBA16F;
  5952. }
  5953. if (format) {
  5954. switch(format) {
  5955. case Engine.TEXTUREFORMAT_LUMINANCE:
  5956. return this._gl.LUMINANCE;
  5957. }
  5958. }
  5959. return this._gl.RGBA;
  5960. };
  5961. /** @ignore */
  5962. public _getRGBAMultiSampleBufferFormat(type: number): number {
  5963. if (type === Engine.TEXTURETYPE_FLOAT) {
  5964. return this._gl.RGBA32F;
  5965. }
  5966. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5967. return this._gl.RGBA16F;
  5968. }
  5969. return this._gl.RGBA8;
  5970. };
  5971. /**
  5972. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  5973. * @return the new query
  5974. */
  5975. public createQuery(): WebGLQuery {
  5976. return this._gl.createQuery();
  5977. }
  5978. /**
  5979. * Delete and release a webGL query
  5980. * @param query defines the query to delete
  5981. * @return the current engine
  5982. */
  5983. public deleteQuery(query: WebGLQuery): Engine {
  5984. this._gl.deleteQuery(query);
  5985. return this;
  5986. }
  5987. /**
  5988. * Check if a given query has resolved and got its value
  5989. * @param query defines the query to check
  5990. * @returns true if the query got its value
  5991. */
  5992. public isQueryResultAvailable(query: WebGLQuery): boolean {
  5993. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  5994. }
  5995. /**
  5996. * Gets the value of a given query
  5997. * @param query defines the query to check
  5998. * @returns the value of the query
  5999. */
  6000. public getQueryResult(query: WebGLQuery): number {
  6001. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  6002. }
  6003. /**
  6004. * Initiates an occlusion query
  6005. * @param algorithmType defines the algorithm to use
  6006. * @param query defines the query to use
  6007. * @returns the current engine
  6008. * @see http://doc.babylonjs.com/features/occlusionquery
  6009. */
  6010. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  6011. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  6012. this._gl.beginQuery(glAlgorithm, query);
  6013. return this;
  6014. }
  6015. /**
  6016. * Ends an occlusion query
  6017. * @see http://doc.babylonjs.com/features/occlusionquery
  6018. * @param algorithmType defines the algorithm to use
  6019. * @returns the current engine
  6020. */
  6021. public endOcclusionQuery(algorithmType: number): Engine {
  6022. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  6023. this._gl.endQuery(glAlgorithm);
  6024. return this;
  6025. }
  6026. /* Time queries */
  6027. private _createTimeQuery(): WebGLQuery {
  6028. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6029. if (timerQuery.createQueryEXT) {
  6030. return timerQuery.createQueryEXT();
  6031. }
  6032. return this.createQuery();
  6033. }
  6034. private _deleteTimeQuery(query: WebGLQuery): void {
  6035. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6036. if (timerQuery.deleteQueryEXT) {
  6037. timerQuery.deleteQueryEXT(query);
  6038. return;
  6039. }
  6040. this.deleteQuery(query);
  6041. }
  6042. private _getTimeQueryResult(query: WebGLQuery): any {
  6043. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6044. if (timerQuery.getQueryObjectEXT) {
  6045. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  6046. }
  6047. return this.getQueryResult(query);
  6048. }
  6049. private _getTimeQueryAvailability(query: WebGLQuery): any {
  6050. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6051. if (timerQuery.getQueryObjectEXT) {
  6052. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  6053. }
  6054. return this.isQueryResultAvailable(query);
  6055. }
  6056. private _currentNonTimestampToken: Nullable<_TimeToken>;
  6057. /**
  6058. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  6059. * Please note that only one query can be issued at a time
  6060. * @returns a time token used to track the time span
  6061. */
  6062. public startTimeQuery(): Nullable<_TimeToken> {
  6063. let timerQuery = this._caps.timerQuery;
  6064. if (!timerQuery) {
  6065. return null;
  6066. }
  6067. let token = new _TimeToken();
  6068. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  6069. if (this._caps.canUseTimestampForTimerQuery) {
  6070. token._startTimeQuery = this._createTimeQuery();
  6071. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  6072. } else {
  6073. if (this._currentNonTimestampToken) {
  6074. return this._currentNonTimestampToken;
  6075. }
  6076. token._timeElapsedQuery = this._createTimeQuery();
  6077. if (timerQuery.beginQueryEXT) {
  6078. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  6079. } else {
  6080. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  6081. }
  6082. this._currentNonTimestampToken = token;
  6083. }
  6084. return token;
  6085. }
  6086. /**
  6087. * Ends a time query
  6088. * @param token defines the token used to measure the time span
  6089. * @returns the time spent (in ns)
  6090. */
  6091. public endTimeQuery(token: _TimeToken): int {
  6092. let timerQuery = this._caps.timerQuery;
  6093. if (!timerQuery || !token) {
  6094. return -1;
  6095. }
  6096. if (this._caps.canUseTimestampForTimerQuery) {
  6097. if (!token._startTimeQuery) {
  6098. return -1;
  6099. }
  6100. if (!token._endTimeQuery) {
  6101. token._endTimeQuery = this._createTimeQuery();
  6102. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  6103. }
  6104. } else if (!token._timeElapsedQueryEnded) {
  6105. if (!token._timeElapsedQuery) {
  6106. return -1;
  6107. }
  6108. if (timerQuery.endQueryEXT) {
  6109. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  6110. } else {
  6111. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  6112. }
  6113. token._timeElapsedQueryEnded = true;
  6114. }
  6115. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  6116. let available: boolean = false;
  6117. if (token._endTimeQuery) {
  6118. available = this._getTimeQueryAvailability(token._endTimeQuery);
  6119. } else if (token._timeElapsedQuery) {
  6120. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  6121. }
  6122. if (available && !disjoint) {
  6123. let result = 0;
  6124. if (this._caps.canUseTimestampForTimerQuery) {
  6125. if (!token._startTimeQuery || !token._endTimeQuery) {
  6126. return -1;
  6127. }
  6128. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  6129. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  6130. result = timeEnd - timeStart;
  6131. this._deleteTimeQuery(token._startTimeQuery);
  6132. this._deleteTimeQuery(token._endTimeQuery);
  6133. token._startTimeQuery = null;
  6134. token._endTimeQuery = null;
  6135. } else {
  6136. if (!token._timeElapsedQuery) {
  6137. return -1;
  6138. }
  6139. result = this._getTimeQueryResult(token._timeElapsedQuery);
  6140. this._deleteTimeQuery(token._timeElapsedQuery);
  6141. token._timeElapsedQuery = null;
  6142. token._timeElapsedQueryEnded = false;
  6143. this._currentNonTimestampToken = null;
  6144. }
  6145. return result;
  6146. }
  6147. return -1;
  6148. }
  6149. private getGlAlgorithmType(algorithmType: number): number {
  6150. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  6151. }
  6152. // Transform feedback
  6153. /**
  6154. * Creates a webGL transform feedback object
  6155. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  6156. * @returns the webGL transform feedback object
  6157. */
  6158. public createTransformFeedback(): WebGLTransformFeedback {
  6159. return this._gl.createTransformFeedback();
  6160. }
  6161. /**
  6162. * Delete a webGL transform feedback object
  6163. * @param value defines the webGL transform feedback object to delete
  6164. */
  6165. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  6166. this._gl.deleteTransformFeedback(value);
  6167. }
  6168. /**
  6169. * Bind a webGL transform feedback object to the webgl context
  6170. * @param value defines the webGL transform feedback object to bind
  6171. */
  6172. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  6173. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  6174. }
  6175. /**
  6176. * Begins a transform feedback operation
  6177. * @param usePoints defines if points or triangles must be used
  6178. */
  6179. public beginTransformFeedback(usePoints: boolean = true): void {
  6180. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  6181. }
  6182. /**
  6183. * Ends a transform feedback operation
  6184. */
  6185. public endTransformFeedback(): void {
  6186. this._gl.endTransformFeedback();
  6187. }
  6188. /**
  6189. * Specify the varyings to use with transform feedback
  6190. * @param program defines the associated webGL program
  6191. * @param value defines the list of strings representing the varying names
  6192. */
  6193. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  6194. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  6195. }
  6196. /**
  6197. * Bind a webGL buffer for a transform feedback operation
  6198. * @param value defines the webGL buffer to bind
  6199. */
  6200. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  6201. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  6202. }
  6203. /** @ignore */
  6204. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6205. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  6206. this._activeRequests.push(request);
  6207. request.onCompleteObservable.add(request => {
  6208. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6209. });
  6210. return request;
  6211. }
  6212. /** @ignore */
  6213. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6214. return new Promise((resolve, reject) => {
  6215. this._loadFile(url, (data) => {
  6216. resolve(data);
  6217. }, undefined, database, useArrayBuffer, (request, exception) => {
  6218. reject(exception);
  6219. })
  6220. });
  6221. }
  6222. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6223. var onload = (data: string | ArrayBuffer) => {
  6224. loadedFiles[index] = data;
  6225. (<any>loadedFiles)._internalCount++;
  6226. if ((<any>loadedFiles)._internalCount === 6) {
  6227. onfinish(loadedFiles);
  6228. }
  6229. };
  6230. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6231. if (onErrorCallBack && request) {
  6232. onErrorCallBack(request.status + " " + request.statusText, exception);
  6233. }
  6234. };
  6235. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6236. }
  6237. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6238. var loadedFiles: (string | ArrayBuffer)[] = [];
  6239. (<any>loadedFiles)._internalCount = 0;
  6240. for (let index = 0; index < 6; index++) {
  6241. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6242. }
  6243. }
  6244. // Statics
  6245. /**
  6246. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6247. * @returns true if the engine can be created
  6248. * @ignoreNaming
  6249. */
  6250. public static isSupported(): boolean {
  6251. try {
  6252. var tempcanvas = document.createElement("canvas");
  6253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6254. return gl != null && !!window.WebGLRenderingContext;
  6255. } catch (e) {
  6256. return false;
  6257. }
  6258. }
  6259. }
  6260. }