engine.ts 307 KB

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