engine.ts 258 KB

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