engine.ts 307 KB

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