babylon.engine.ts 326 KB

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