babylon.engine.ts 244 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader => {
  3. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  4. };
  5. var compileRawShader = (gl: WebGLRenderingContext, source: string, type: string): WebGLShader => {
  6. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7. gl.shaderSource(shader, source);
  8. gl.compileShader(shader);
  9. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10. let log = gl.getShaderInfoLog(shader);
  11. if (log) {
  12. throw new Error(log);
  13. }
  14. }
  15. if (!shader) {
  16. throw new Error("Something went wrong while compile the shader.");
  17. }
  18. return shader;
  19. };
  20. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  21. var magFilter = gl.NEAREST;
  22. var minFilter = gl.NEAREST;
  23. switch (samplingMode) {
  24. case Texture.BILINEAR_SAMPLINGMODE:
  25. magFilter = gl.LINEAR;
  26. if (generateMipMaps) {
  27. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  28. } else {
  29. minFilter = gl.LINEAR;
  30. }
  31. break;
  32. case Texture.TRILINEAR_SAMPLINGMODE:
  33. magFilter = gl.LINEAR;
  34. if (generateMipMaps) {
  35. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  36. } else {
  37. minFilter = gl.LINEAR;
  38. }
  39. break;
  40. case Texture.NEAREST_SAMPLINGMODE:
  41. magFilter = gl.NEAREST;
  42. if (generateMipMaps) {
  43. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  44. } else {
  45. minFilter = gl.NEAREST;
  46. }
  47. break;
  48. case Texture.NEAREST_NEAREST_MIPNEAREST:
  49. magFilter = gl.NEAREST;
  50. if (generateMipMaps) {
  51. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  52. } else {
  53. minFilter = gl.NEAREST;
  54. }
  55. break;
  56. case Texture.NEAREST_LINEAR_MIPNEAREST:
  57. magFilter = gl.NEAREST;
  58. if (generateMipMaps) {
  59. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  60. } else {
  61. minFilter = gl.LINEAR;
  62. }
  63. break;
  64. case Texture.NEAREST_LINEAR_MIPLINEAR:
  65. magFilter = gl.NEAREST;
  66. if (generateMipMaps) {
  67. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  68. } else {
  69. minFilter = gl.LINEAR;
  70. }
  71. break;
  72. case Texture.NEAREST_LINEAR:
  73. magFilter = gl.NEAREST;
  74. minFilter = gl.LINEAR;
  75. break;
  76. case Texture.NEAREST_NEAREST:
  77. magFilter = gl.NEAREST;
  78. minFilter = gl.NEAREST;
  79. break;
  80. case Texture.LINEAR_NEAREST_MIPNEAREST:
  81. magFilter = gl.LINEAR;
  82. if (generateMipMaps) {
  83. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  84. } else {
  85. minFilter = gl.NEAREST;
  86. }
  87. break;
  88. case Texture.LINEAR_NEAREST_MIPLINEAR:
  89. magFilter = gl.LINEAR;
  90. if (generateMipMaps) {
  91. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  92. } else {
  93. minFilter = gl.NEAREST;
  94. }
  95. break;
  96. case Texture.LINEAR_LINEAR:
  97. magFilter = gl.LINEAR;
  98. minFilter = gl.LINEAR;
  99. break;
  100. case Texture.LINEAR_NEAREST:
  101. magFilter = gl.LINEAR;
  102. minFilter = gl.NEAREST;
  103. break;
  104. }
  105. return {
  106. min: minFilter,
  107. mag: magFilter
  108. }
  109. }
  110. var partialLoadImg = (url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  111. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) => {
  112. var img: HTMLImageElement;
  113. var onload = () => {
  114. loadedImages[index] = img;
  115. (<any>loadedImages)._internalCount++;
  116. if (scene) {
  117. scene._removePendingData(img);
  118. }
  119. if ((<any>loadedImages)._internalCount === 6) {
  120. onfinish(loadedImages);
  121. }
  122. };
  123. var onerror = (message?: string, exception?: any) => {
  124. if (scene) {
  125. scene._removePendingData(img);
  126. }
  127. if (onErrorCallBack) {
  128. onErrorCallBack(message, exception);
  129. }
  130. };
  131. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  132. if (scene) {
  133. scene._addPendingData(img);
  134. }
  135. }
  136. var cascadeLoadImgs = (rootUrl: string, scene: Nullable<Scene>,
  137. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) => {
  138. var loadedImages: HTMLImageElement[] = [];
  139. (<any>loadedImages)._internalCount = 0;
  140. for (let index = 0; index < 6; index++) {
  141. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  142. }
  143. };
  144. class BufferPointer {
  145. public active: boolean;
  146. public index: number;
  147. public size: number;
  148. public type: number;
  149. public normalized: boolean;
  150. public stride: number;
  151. public offset: number;
  152. public buffer: WebGLBuffer;
  153. }
  154. export class InstancingAttributeInfo {
  155. /**
  156. * Index/offset of the attribute in the vertex shader
  157. */
  158. index: number;
  159. /**
  160. * size of the attribute, 1, 2, 3 or 4
  161. */
  162. attributeSize: number;
  163. /**
  164. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  165. * default is FLOAT
  166. */
  167. attribyteType: number;
  168. /**
  169. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  170. */
  171. normalized: boolean;
  172. /**
  173. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  174. */
  175. offset: number;
  176. /**
  177. * Name of the GLSL attribute, for debugging purpose only
  178. */
  179. attributeName: string;
  180. }
  181. /**
  182. * Define options used to create a render target texture
  183. */
  184. export class RenderTargetCreationOptions {
  185. generateMipMaps?: boolean;
  186. generateDepthBuffer?: boolean;
  187. generateStencilBuffer?: boolean;
  188. type?: number;
  189. samplingMode?: number;
  190. }
  191. /**
  192. * Regroup several parameters relative to the browser in use
  193. */
  194. export class EngineCapabilities {
  195. /** The maximum textures image */
  196. public maxTexturesImageUnits: number;
  197. public maxVertexTextureImageUnits: number;
  198. public maxCombinedTexturesImageUnits: number;
  199. /** The maximum texture size */
  200. public maxTextureSize: number;
  201. public maxCubemapTextureSize: number;
  202. public maxRenderTextureSize: number;
  203. public maxVertexAttribs: number;
  204. public maxVaryingVectors: number;
  205. public maxVertexUniformVectors: number;
  206. public maxFragmentUniformVectors: number;
  207. public standardDerivatives: boolean;
  208. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  209. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  210. public etc1: any; //WEBGL_compressed_texture_etc1;
  211. public etc2: any; //WEBGL_compressed_texture_etc;
  212. public astc: any; //WEBGL_compressed_texture_astc;
  213. public textureFloat: boolean;
  214. public vertexArrayObject: boolean;
  215. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  216. public maxAnisotropy: number;
  217. public instancedArrays: boolean;
  218. public uintIndices: boolean;
  219. public highPrecisionShaderSupported: boolean;
  220. public fragmentDepthSupported: boolean;
  221. public textureFloatLinearFiltering: boolean;
  222. public textureFloatRender: boolean;
  223. public textureHalfFloat: boolean;
  224. public textureHalfFloatLinearFiltering: boolean;
  225. public textureHalfFloatRender: boolean;
  226. public textureLOD: boolean;
  227. public drawBuffersExtension: boolean;
  228. public depthTextureExtension: boolean;
  229. public colorBufferFloat: boolean;
  230. public timerQuery: EXT_disjoint_timer_query;
  231. public canUseTimestampForTimerQuery: boolean;
  232. }
  233. export interface EngineOptions extends WebGLContextAttributes {
  234. limitDeviceRatio?: number;
  235. autoEnableWebVR?: boolean;
  236. disableWebGL2Support?: boolean;
  237. audioEngine?: boolean;
  238. deterministicLockstep?: boolean;
  239. lockstepMaxSteps?: number;
  240. doNotHandleContextLost?: boolean;
  241. }
  242. export interface IDisplayChangedEventArgs {
  243. vrDisplay: any;
  244. vrSupported: boolean;
  245. }
  246. /**
  247. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  248. */
  249. export class Engine {
  250. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  251. public static ExceptionList = [
  252. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  253. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  254. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  255. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  256. ];
  257. public static Instances = new Array<Engine>();
  258. public static get LastCreatedEngine(): Nullable<Engine> {
  259. if (Engine.Instances.length === 0) {
  260. return null;
  261. }
  262. return Engine.Instances[Engine.Instances.length - 1];
  263. }
  264. public static get LastCreatedScene(): Nullable<Scene> {
  265. var lastCreatedEngine = Engine.LastCreatedEngine;
  266. if (!lastCreatedEngine) {
  267. return null;
  268. }
  269. if (lastCreatedEngine.scenes.length === 0) {
  270. return null;
  271. }
  272. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  273. }
  274. /**
  275. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  276. */
  277. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  278. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  279. var engine = Engine.Instances[engineIndex];
  280. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  281. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  282. }
  283. }
  284. }
  285. // Const statics
  286. private static _ALPHA_DISABLE = 0;
  287. private static _ALPHA_ADD = 1;
  288. private static _ALPHA_COMBINE = 2;
  289. private static _ALPHA_SUBTRACT = 3;
  290. private static _ALPHA_MULTIPLY = 4;
  291. private static _ALPHA_MAXIMIZED = 5;
  292. private static _ALPHA_ONEONE = 6;
  293. private static _ALPHA_PREMULTIPLIED = 7;
  294. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  295. private static _ALPHA_INTERPOLATE = 9;
  296. private static _ALPHA_SCREENMODE = 10;
  297. private static _DELAYLOADSTATE_NONE = 0;
  298. private static _DELAYLOADSTATE_LOADED = 1;
  299. private static _DELAYLOADSTATE_LOADING = 2;
  300. private static _DELAYLOADSTATE_NOTLOADED = 4;
  301. private static _TEXTUREFORMAT_ALPHA = 0;
  302. private static _TEXTUREFORMAT_LUMINANCE = 1;
  303. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  304. private static _TEXTUREFORMAT_RGB = 4;
  305. private static _TEXTUREFORMAT_RGBA = 5;
  306. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  307. private static _TEXTURETYPE_FLOAT = 1;
  308. private static _TEXTURETYPE_HALF_FLOAT = 2;
  309. // Depht or Stencil test Constants.
  310. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  311. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  312. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  313. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  314. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  315. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  316. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  317. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  318. public static get NEVER(): number {
  319. return Engine._NEVER;
  320. }
  321. public static get ALWAYS(): number {
  322. return Engine._ALWAYS;
  323. }
  324. public static get LESS(): number {
  325. return Engine._LESS;
  326. }
  327. public static get EQUAL(): number {
  328. return Engine._EQUAL;
  329. }
  330. public static get LEQUAL(): number {
  331. return Engine._LEQUAL;
  332. }
  333. public static get GREATER(): number {
  334. return Engine._GREATER;
  335. }
  336. public static get GEQUAL(): number {
  337. return Engine._GEQUAL;
  338. }
  339. public static get NOTEQUAL(): number {
  340. return Engine._NOTEQUAL;
  341. }
  342. // Stencil Actions Constants.
  343. private static _KEEP = 0x1E00;
  344. private static _REPLACE = 0x1E01;
  345. private static _INCR = 0x1E02;
  346. private static _DECR = 0x1E03;
  347. private static _INVERT = 0x150A;
  348. private static _INCR_WRAP = 0x8507;
  349. private static _DECR_WRAP = 0x8508;
  350. public static get KEEP(): number {
  351. return Engine._KEEP;
  352. }
  353. public static get REPLACE(): number {
  354. return Engine._REPLACE;
  355. }
  356. public static get INCR(): number {
  357. return Engine._INCR;
  358. }
  359. public static get DECR(): number {
  360. return Engine._DECR;
  361. }
  362. public static get INVERT(): number {
  363. return Engine._INVERT;
  364. }
  365. public static get INCR_WRAP(): number {
  366. return Engine._INCR_WRAP;
  367. }
  368. public static get DECR_WRAP(): number {
  369. return Engine._DECR_WRAP;
  370. }
  371. public static get ALPHA_DISABLE(): number {
  372. return Engine._ALPHA_DISABLE;
  373. }
  374. public static get ALPHA_ONEONE(): number {
  375. return Engine._ALPHA_ONEONE;
  376. }
  377. public static get ALPHA_ADD(): number {
  378. return Engine._ALPHA_ADD;
  379. }
  380. public static get ALPHA_COMBINE(): number {
  381. return Engine._ALPHA_COMBINE;
  382. }
  383. public static get ALPHA_SUBTRACT(): number {
  384. return Engine._ALPHA_SUBTRACT;
  385. }
  386. public static get ALPHA_MULTIPLY(): number {
  387. return Engine._ALPHA_MULTIPLY;
  388. }
  389. public static get ALPHA_MAXIMIZED(): number {
  390. return Engine._ALPHA_MAXIMIZED;
  391. }
  392. public static get ALPHA_PREMULTIPLIED(): number {
  393. return Engine._ALPHA_PREMULTIPLIED;
  394. }
  395. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  396. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  397. }
  398. public static get ALPHA_INTERPOLATE(): number {
  399. return Engine._ALPHA_INTERPOLATE;
  400. }
  401. public static get ALPHA_SCREENMODE(): number {
  402. return Engine._ALPHA_SCREENMODE;
  403. }
  404. public static get DELAYLOADSTATE_NONE(): number {
  405. return Engine._DELAYLOADSTATE_NONE;
  406. }
  407. public static get DELAYLOADSTATE_LOADED(): number {
  408. return Engine._DELAYLOADSTATE_LOADED;
  409. }
  410. public static get DELAYLOADSTATE_LOADING(): number {
  411. return Engine._DELAYLOADSTATE_LOADING;
  412. }
  413. public static get DELAYLOADSTATE_NOTLOADED(): number {
  414. return Engine._DELAYLOADSTATE_NOTLOADED;
  415. }
  416. public static get TEXTUREFORMAT_ALPHA(): number {
  417. return Engine._TEXTUREFORMAT_ALPHA;
  418. }
  419. public static get TEXTUREFORMAT_LUMINANCE(): number {
  420. return Engine._TEXTUREFORMAT_LUMINANCE;
  421. }
  422. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  423. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  424. }
  425. public static get TEXTUREFORMAT_RGB(): number {
  426. return Engine._TEXTUREFORMAT_RGB;
  427. }
  428. public static get TEXTUREFORMAT_RGBA(): number {
  429. return Engine._TEXTUREFORMAT_RGBA;
  430. }
  431. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  432. return Engine._TEXTURETYPE_UNSIGNED_INT;
  433. }
  434. public static get TEXTURETYPE_FLOAT(): number {
  435. return Engine._TEXTURETYPE_FLOAT;
  436. }
  437. public static get TEXTURETYPE_HALF_FLOAT(): number {
  438. return Engine._TEXTURETYPE_HALF_FLOAT;
  439. }
  440. // Texture rescaling mode
  441. private static _SCALEMODE_FLOOR = 1;
  442. private static _SCALEMODE_NEAREST = 2;
  443. private static _SCALEMODE_CEILING = 3;
  444. public static get SCALEMODE_FLOOR(): number {
  445. return Engine._SCALEMODE_FLOOR;
  446. }
  447. public static get SCALEMODE_NEAREST(): number {
  448. return Engine._SCALEMODE_NEAREST;
  449. }
  450. public static get SCALEMODE_CEILING(): number {
  451. return Engine._SCALEMODE_CEILING;
  452. }
  453. public static get Version(): string {
  454. return "3.2.0-alpha7";
  455. }
  456. // Updatable statics so stick with vars here
  457. public static CollisionsEpsilon = 0.001;
  458. public static CodeRepository = "src/";
  459. public static ShadersRepository = "src/Shaders/";
  460. // Public members
  461. public forcePOTTextures = false;
  462. public isFullscreen = false;
  463. public isPointerLock = false;
  464. public cullBackFaces = true;
  465. public renderEvenInBackground = true;
  466. public preventCacheWipeBetweenFrames = false;
  467. // To enable/disable IDB support and avoid XHR on .manifest
  468. public enableOfflineSupport = false;
  469. public scenes = new Array<Scene>();
  470. public postProcesses = new Array<PostProcess>();
  471. // Observables
  472. /**
  473. * Observable event triggered each time the rendering canvas is resized
  474. */
  475. public onResizeObservable = new Observable<Engine>();
  476. /**
  477. * Observable event triggered each time the canvas loses focus
  478. */
  479. public onCanvasBlurObservable = new Observable<Engine>();
  480. /**
  481. * Observable event triggered each time the canvas gains focus
  482. */
  483. public onCanvasFocusObservable = new Observable<Engine>();
  484. /**
  485. * Observable event triggered each time the canvas receives pointerout event
  486. */
  487. public onCanvasPointerOutObservable = new Observable<Engine>();
  488. /**
  489. * Observable event triggered before each texture is initialized
  490. */
  491. public onBeforeTextureInitObservable = new Observable<Texture>();
  492. //WebVR
  493. private _vrDisplay: any = undefined;
  494. private _vrSupported: boolean = false;
  495. private _oldSize: Size;
  496. private _oldHardwareScaleFactor: number;
  497. private _vrExclusivePointerMode = false;
  498. public get isInVRExclusivePointerMode(): boolean {
  499. return this._vrExclusivePointerMode;
  500. }
  501. // Uniform buffers list
  502. public disableUniformBuffers = false;
  503. public _uniformBuffers = new Array<UniformBuffer>();
  504. public get supportsUniformBuffers(): boolean {
  505. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  506. }
  507. // Observables
  508. /**
  509. * Observable raised when the engine begins a new frame
  510. */
  511. public onBeginFrameObservable = new Observable<Engine>();
  512. /**
  513. * Observable raised when the engine ends the current frame
  514. */
  515. public onEndFrameObservable = new Observable<Engine>();
  516. /**
  517. * Observable raised when the engine is about to compile a shader
  518. */
  519. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  520. /**
  521. * Observable raised when the engine has jsut compiled a shader
  522. */
  523. public onAfterShaderCompilationObservable = new Observable<Engine>();
  524. // Private Members
  525. private _gl: WebGLRenderingContext;
  526. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  527. private _windowIsBackground = false;
  528. private _webGLVersion = 1.0;
  529. public get needPOTTextures(): boolean {
  530. return this._webGLVersion < 2 || this.forcePOTTextures;
  531. }
  532. private _badOS = false;
  533. public get badOS(): boolean {
  534. return this._badOS;
  535. }
  536. private _badDesktopOS = false;
  537. public get badDesktopOS(): boolean {
  538. return this._badDesktopOS;
  539. }
  540. /**
  541. * Gets or sets a value indicating if we want to disable texture binding optmization.
  542. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  543. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  544. */
  545. public disableTextureBindingOptimization = false;
  546. public static audioEngine: AudioEngine;
  547. // Focus
  548. private _onFocus: () => void;
  549. private _onBlur: () => void;
  550. private _onCanvasPointerOut: () => void;
  551. private _onCanvasBlur: () => void;
  552. private _onCanvasFocus: () => void;
  553. private _onFullscreenChange: () => void;
  554. private _onPointerLockChange: () => void;
  555. private _onVRDisplayPointerRestricted: () => void;
  556. private _onVRDisplayPointerUnrestricted: () => void;
  557. // VRDisplay connection
  558. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  559. private _onVrDisplayDisconnect: Nullable<() => void>;
  560. private _onVrDisplayPresentChange: Nullable<() => void>;
  561. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  562. public onVRRequestPresentComplete = new Observable<boolean>();
  563. public onVRRequestPresentStart = new Observable<Engine>();
  564. private _hardwareScalingLevel: number;
  565. protected _caps: EngineCapabilities;
  566. private _pointerLockRequested: boolean;
  567. private _isStencilEnable: boolean;
  568. private _colorWrite = true;
  569. private _loadingScreen: ILoadingScreen;
  570. public _drawCalls = new PerfCounter();
  571. public _textureCollisions = new PerfCounter();
  572. private _glVersion: string;
  573. private _glRenderer: string;
  574. private _glVendor: string;
  575. private _videoTextureSupported: boolean;
  576. private _renderingQueueLaunched = false;
  577. private _activeRenderLoops = new Array<() => void>();
  578. // Deterministic lockstepMaxSteps
  579. private _deterministicLockstep: boolean = false;
  580. private _lockstepMaxSteps: number = 4;
  581. // Lost context
  582. public onContextLostObservable = new Observable<Engine>();
  583. public onContextRestoredObservable = new Observable<Engine>();
  584. private _onContextLost: (evt: Event) => void;
  585. private _onContextRestored: (evt: Event) => void;
  586. private _contextWasLost = false;
  587. private _doNotHandleContextLost = false;
  588. // FPS
  589. private _performanceMonitor = new PerformanceMonitor();
  590. private _fps = 60;
  591. private _deltaTime = 0;
  592. /**
  593. * Turn this value on if you want to pause FPS computation when in background
  594. */
  595. public disablePerformanceMonitorInBackground = false;
  596. public get performanceMonitor(): PerformanceMonitor {
  597. return this._performanceMonitor;
  598. }
  599. // States
  600. protected _depthCullingState = new _DepthCullingState();
  601. protected _stencilState = new _StencilState();
  602. protected _alphaState = new _AlphaState();
  603. protected _alphaMode = Engine.ALPHA_DISABLE;
  604. // Cache
  605. private _internalTexturesCache = new Array<InternalTexture>();
  606. protected _activeChannel = 0;
  607. private _currentTextureChannel = -1;
  608. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  609. protected _currentEffect: Nullable<Effect>;
  610. protected _currentProgram: Nullable<WebGLProgram>;
  611. private _compiledEffects: { [key: string]: Effect } = {}
  612. private _vertexAttribArraysEnabled: boolean[] = [];
  613. protected _cachedViewport: Nullable<Viewport>;
  614. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  615. protected _cachedVertexBuffers: any;
  616. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  617. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  618. protected _currentRenderTarget: Nullable<InternalTexture>;
  619. private _uintIndicesCurrentlySet = false;
  620. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  621. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  622. private _currentBufferPointers = new Array<BufferPointer>();
  623. private _currentInstanceLocations = new Array<number>();
  624. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  625. private _textureUnits: Int32Array;
  626. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  627. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  628. private _workingCanvas: Nullable<HTMLCanvasElement>;
  629. private _workingContext: Nullable<CanvasRenderingContext2D>;
  630. private _rescalePostProcess: PassPostProcess;
  631. private _dummyFramebuffer: WebGLFramebuffer;
  632. private _externalData: StringDictionary<Object>;
  633. private _bindedRenderFunction: any;
  634. private _vaoRecordInProgress = false;
  635. private _mustWipeVertexAttributes = false;
  636. private _emptyTexture: Nullable<InternalTexture>;
  637. private _emptyCubeTexture: Nullable<InternalTexture>;
  638. private _emptyTexture3D: Nullable<InternalTexture>;
  639. private _frameHandler: number;
  640. private _nextFreeTextureSlots = new Array<number>();
  641. private _maxSimultaneousTextures = 0;
  642. private _activeRequests = new Array<IFileRequest>();
  643. // Hardware supported Compressed Textures
  644. private _texturesSupported = new Array<string>();
  645. private _textureFormatInUse: Nullable<string>;
  646. public get texturesSupported(): Array<string> {
  647. return this._texturesSupported;
  648. }
  649. public get textureFormatInUse(): Nullable<string> {
  650. return this._textureFormatInUse;
  651. }
  652. public get currentViewport(): Nullable<Viewport> {
  653. return this._cachedViewport;
  654. }
  655. // Empty texture
  656. public get emptyTexture(): InternalTexture {
  657. if (!this._emptyTexture) {
  658. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  659. }
  660. return this._emptyTexture;
  661. }
  662. public get emptyTexture3D(): InternalTexture {
  663. if (!this._emptyTexture3D) {
  664. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  665. }
  666. return this._emptyTexture3D;
  667. }
  668. public get emptyCubeTexture(): InternalTexture {
  669. if (!this._emptyCubeTexture) {
  670. var faceData = new Uint8Array(4);
  671. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  672. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  673. }
  674. return this._emptyCubeTexture;
  675. }
  676. /**
  677. * @constructor
  678. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  679. * @param antialias defines enable antialiasing (default: false)
  680. * @param options defines further options to be sent to the getContext() function
  681. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  682. */
  683. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  684. // Register promises
  685. PromisePolyfill.Apply();
  686. let canvas: Nullable<HTMLCanvasElement> = null;
  687. Engine.Instances.push(this);
  688. if (!canvasOrContext) {
  689. return;
  690. }
  691. options = options || {};
  692. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  693. canvas = <HTMLCanvasElement>canvasOrContext;
  694. this._renderingCanvas = canvas;
  695. if (antialias != null) {
  696. options.antialias = antialias;
  697. }
  698. if (options.deterministicLockstep === undefined) {
  699. options.deterministicLockstep = false;
  700. }
  701. if (options.lockstepMaxSteps === undefined) {
  702. options.lockstepMaxSteps = 4;
  703. }
  704. if (options.preserveDrawingBuffer === undefined) {
  705. options.preserveDrawingBuffer = false;
  706. }
  707. if (options.audioEngine === undefined) {
  708. options.audioEngine = true;
  709. }
  710. if (options.stencil === undefined) {
  711. options.stencil = true;
  712. }
  713. this._deterministicLockstep = options.deterministicLockstep;
  714. this._lockstepMaxSteps = options.lockstepMaxSteps;
  715. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  716. // Exceptions
  717. if (navigator && navigator.userAgent) {
  718. let ua = navigator.userAgent;
  719. for (var exception of Engine.ExceptionList) {
  720. let key = exception.key;
  721. let targets = exception.targets;
  722. if (ua.indexOf(key) > -1) {
  723. if (exception.capture && exception.captureConstraint) {
  724. let capture = exception.capture;
  725. let constraint = exception.captureConstraint;
  726. let regex = new RegExp(capture);
  727. let matches = regex.exec(ua);
  728. if (matches && matches.length > 0) {
  729. let capturedValue = parseInt(matches[matches.length - 1]);
  730. if (capturedValue >= constraint) {
  731. continue;
  732. }
  733. }
  734. }
  735. for (var target of targets) {
  736. switch (target) {
  737. case "uniformBuffer":
  738. this.disableUniformBuffers = true;
  739. break;
  740. case "textureBindingOptimization":
  741. this.disableTextureBindingOptimization = true;
  742. break;
  743. }
  744. }
  745. break;
  746. }
  747. }
  748. }
  749. // GL
  750. if (!options.disableWebGL2Support) {
  751. try {
  752. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  753. if (this._gl) {
  754. this._webGLVersion = 2.0;
  755. }
  756. } catch (e) {
  757. // Do nothing
  758. }
  759. }
  760. if (!this._gl) {
  761. if (!canvas) {
  762. throw new Error("The provided canvas is null or undefined.");
  763. }
  764. try {
  765. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  766. } catch (e) {
  767. throw new Error("WebGL not supported");
  768. }
  769. }
  770. if (!this._gl) {
  771. throw new Error("WebGL not supported");
  772. }
  773. this._onCanvasFocus = () => {
  774. this.onCanvasFocusObservable.notifyObservers(this);
  775. }
  776. this._onCanvasBlur = () => {
  777. this.onCanvasBlurObservable.notifyObservers(this);
  778. }
  779. canvas.addEventListener("focus", this._onCanvasFocus);
  780. canvas.addEventListener("blur", this._onCanvasBlur);
  781. this._onBlur = () => {
  782. if (this.disablePerformanceMonitorInBackground) {
  783. this._performanceMonitor.disable();
  784. }
  785. this._windowIsBackground = true;
  786. };
  787. this._onFocus = () => {
  788. if (this.disablePerformanceMonitorInBackground) {
  789. this._performanceMonitor.enable();
  790. }
  791. this._windowIsBackground = false;
  792. };
  793. this._onCanvasPointerOut = () => {
  794. this.onCanvasPointerOutObservable.notifyObservers(this);
  795. };
  796. window.addEventListener("blur", this._onBlur);
  797. window.addEventListener("focus", this._onFocus);
  798. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  799. // Context lost
  800. if (!this._doNotHandleContextLost) {
  801. this._onContextLost = (evt: Event) => {
  802. evt.preventDefault();
  803. this._contextWasLost = true;
  804. Tools.Warn("WebGL context lost.");
  805. this.onContextLostObservable.notifyObservers(this);
  806. };
  807. this._onContextRestored = (evt: Event) => {
  808. // Adding a timeout to avoid race condition at browser level
  809. setTimeout(() => {
  810. // Rebuild gl context
  811. this._initGLContext();
  812. // Rebuild effects
  813. this._rebuildEffects();
  814. // Rebuild textures
  815. this._rebuildInternalTextures();
  816. // Rebuild buffers
  817. this._rebuildBuffers();
  818. // Cache
  819. this.wipeCaches(true);
  820. Tools.Warn("WebGL context successfully restored.");
  821. this.onContextRestoredObservable.notifyObservers(this);
  822. this._contextWasLost = false;
  823. }, 0);
  824. };
  825. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  826. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  827. }
  828. } else {
  829. this._gl = <WebGLRenderingContext>canvasOrContext;
  830. this._renderingCanvas = this._gl.canvas
  831. if (this._gl.renderbufferStorageMultisample) {
  832. this._webGLVersion = 2.0;
  833. }
  834. options.stencil = this._gl.getContextAttributes().stencil;
  835. }
  836. // Viewport
  837. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  838. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  839. this.resize();
  840. this._isStencilEnable = options.stencil ? true : false;
  841. this._initGLContext();
  842. if (canvas) {
  843. // Fullscreen
  844. this._onFullscreenChange = () => {
  845. if (document.fullscreen !== undefined) {
  846. this.isFullscreen = document.fullscreen;
  847. } else if (document.mozFullScreen !== undefined) {
  848. this.isFullscreen = document.mozFullScreen;
  849. } else if (document.webkitIsFullScreen !== undefined) {
  850. this.isFullscreen = document.webkitIsFullScreen;
  851. } else if (document.msIsFullScreen !== undefined) {
  852. this.isFullscreen = document.msIsFullScreen;
  853. }
  854. // Pointer lock
  855. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  856. canvas.requestPointerLock = canvas.requestPointerLock ||
  857. canvas.msRequestPointerLock ||
  858. canvas.mozRequestPointerLock ||
  859. canvas.webkitRequestPointerLock;
  860. if (canvas.requestPointerLock) {
  861. canvas.requestPointerLock();
  862. }
  863. }
  864. };
  865. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  866. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  867. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  868. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  869. // Pointer lock
  870. this._onPointerLockChange = () => {
  871. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  872. document.webkitPointerLockElement === canvas ||
  873. document.msPointerLockElement === canvas ||
  874. document.pointerLockElement === canvas
  875. );
  876. };
  877. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  878. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  879. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  880. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  881. this._onVRDisplayPointerRestricted = () => {
  882. if (canvas) {
  883. canvas.requestPointerLock();
  884. }
  885. }
  886. this._onVRDisplayPointerUnrestricted = () => {
  887. document.exitPointerLock();
  888. }
  889. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  890. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  891. }
  892. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  893. Engine.audioEngine = new AudioEngine();
  894. }
  895. // Prepare buffer pointers
  896. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  897. this._currentBufferPointers[i] = new BufferPointer();
  898. }
  899. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  900. // Load WebVR Devices
  901. if (options.autoEnableWebVR) {
  902. this.initWebVR();
  903. }
  904. // Detect if we are running on a faulty buggy OS.
  905. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  906. // Detect if we are running on a faulty buggy desktop OS.
  907. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  908. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  909. this.enableOfflineSupport = (Database !== undefined);
  910. }
  911. private _rebuildInternalTextures(): void {
  912. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  913. for (var internalTexture of currentState) {
  914. internalTexture._rebuild();
  915. }
  916. }
  917. private _rebuildEffects(): void {
  918. for (var key in this._compiledEffects) {
  919. let effect = <Effect>this._compiledEffects[key];
  920. effect._prepareEffect();
  921. }
  922. Effect.ResetCache();
  923. }
  924. private _rebuildBuffers(): void {
  925. // Index / Vertex
  926. for (var scene of this.scenes) {
  927. scene.resetCachedMaterial();
  928. scene._rebuildGeometries();
  929. scene._rebuildTextures();
  930. }
  931. // Uniforms
  932. for (var uniformBuffer of this._uniformBuffers) {
  933. uniformBuffer._rebuild();
  934. }
  935. }
  936. private _initGLContext(): void {
  937. // Caps
  938. this._caps = new EngineCapabilities();
  939. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  940. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  941. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  942. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  943. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  944. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  945. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  946. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  947. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  948. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  949. // Infos
  950. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  951. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  952. if (rendererInfo != null) {
  953. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  954. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  955. }
  956. if (!this._glVendor) {
  957. this._glVendor = "Unknown vendor";
  958. }
  959. if (!this._glRenderer) {
  960. this._glRenderer = "Unknown renderer";
  961. }
  962. // Constants
  963. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  964. if (this._gl.RGBA16F !== 0x881A) {
  965. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  966. }
  967. if (this._gl.RGBA32F !== 0x8814) {
  968. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  969. }
  970. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  971. this._gl.DEPTH24_STENCIL8 = 35056;
  972. }
  973. // Extensions
  974. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  975. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  976. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  977. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  978. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  979. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  980. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  981. 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');
  982. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  983. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  984. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  985. this._caps.highPrecisionShaderSupported = true;
  986. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  987. if (this._caps.timerQuery) {
  988. if (this._webGLVersion === 1) {
  989. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  990. }
  991. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  992. }
  993. // Checks if some of the format renders first to allow the use of webgl inspector.
  994. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  995. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  996. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  997. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  998. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  999. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  1000. if (this._webGLVersion > 1) {
  1001. this._gl.HALF_FLOAT_OES = 0x140B;
  1002. }
  1003. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1004. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  1005. // Draw buffers
  1006. if (this._webGLVersion > 1) {
  1007. this._caps.drawBuffersExtension = true;
  1008. } else {
  1009. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1010. if (drawBuffersExtension !== null) {
  1011. this._caps.drawBuffersExtension = true;
  1012. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1013. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1014. for (var i = 0; i < 16; i++) {
  1015. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1016. }
  1017. } else {
  1018. this._caps.drawBuffersExtension = false;
  1019. }
  1020. }
  1021. // Depth Texture
  1022. if (this._webGLVersion > 1) {
  1023. this._caps.depthTextureExtension = true;
  1024. } else {
  1025. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1026. if (depthTextureExtension != null) {
  1027. this._caps.depthTextureExtension = true;
  1028. }
  1029. }
  1030. // Vertex array object
  1031. if (this._webGLVersion > 1) {
  1032. this._caps.vertexArrayObject = true;
  1033. } else {
  1034. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1035. if (vertexArrayObjectExtension != null) {
  1036. this._caps.vertexArrayObject = true;
  1037. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1038. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1039. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1040. } else {
  1041. this._caps.vertexArrayObject = false;
  1042. }
  1043. }
  1044. // Instances count
  1045. if (this._webGLVersion > 1) {
  1046. this._caps.instancedArrays = true;
  1047. } else {
  1048. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1049. if (instanceExtension != null) {
  1050. this._caps.instancedArrays = true;
  1051. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1052. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1053. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1054. } else {
  1055. this._caps.instancedArrays = false;
  1056. }
  1057. }
  1058. // Intelligently add supported compressed formats in order to check for.
  1059. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1060. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1061. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1062. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1063. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1064. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1065. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1066. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1067. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1068. if (this._gl.getShaderPrecisionFormat) {
  1069. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1070. if (highp) {
  1071. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1072. }
  1073. }
  1074. // Depth buffer
  1075. this.setDepthBuffer(true);
  1076. this.setDepthFunctionToLessOrEqual();
  1077. this.setDepthWrite(true);
  1078. // Texture maps
  1079. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1080. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1081. this._nextFreeTextureSlots.push(slot);
  1082. }
  1083. }
  1084. public get webGLVersion(): number {
  1085. return this._webGLVersion;
  1086. }
  1087. /**
  1088. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1089. */
  1090. public get isStencilEnable(): boolean {
  1091. return this._isStencilEnable;
  1092. }
  1093. private _prepareWorkingCanvas(): void {
  1094. if (this._workingCanvas) {
  1095. return;
  1096. }
  1097. this._workingCanvas = document.createElement("canvas");
  1098. let context = this._workingCanvas.getContext("2d");
  1099. if (context) {
  1100. this._workingContext = context;
  1101. }
  1102. }
  1103. public resetTextureCache() {
  1104. for (var key in this._boundTexturesCache) {
  1105. let boundTexture = this._boundTexturesCache[key];
  1106. if (boundTexture) {
  1107. this._removeDesignatedSlot(boundTexture);
  1108. }
  1109. this._boundTexturesCache[key] = null;
  1110. }
  1111. if (!this.disableTextureBindingOptimization) {
  1112. this._nextFreeTextureSlots = [];
  1113. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1114. this._nextFreeTextureSlots.push(slot);
  1115. }
  1116. }
  1117. this._currentTextureChannel = -1;
  1118. }
  1119. public isDeterministicLockStep(): boolean {
  1120. return this._deterministicLockstep;
  1121. }
  1122. public getLockstepMaxSteps(): number {
  1123. return this._lockstepMaxSteps;
  1124. }
  1125. public getGlInfo() {
  1126. return {
  1127. vendor: this._glVendor,
  1128. renderer: this._glRenderer,
  1129. version: this._glVersion
  1130. }
  1131. }
  1132. public getAspectRatio(camera: Camera, useScreen = false): number {
  1133. var viewport = camera.viewport;
  1134. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1135. }
  1136. public getRenderWidth(useScreen = false): number {
  1137. if (!useScreen && this._currentRenderTarget) {
  1138. return this._currentRenderTarget.width;
  1139. }
  1140. return this._gl.drawingBufferWidth;
  1141. }
  1142. public getRenderHeight(useScreen = false): number {
  1143. if (!useScreen && this._currentRenderTarget) {
  1144. return this._currentRenderTarget.height;
  1145. }
  1146. return this._gl.drawingBufferHeight;
  1147. }
  1148. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1149. return this._renderingCanvas;
  1150. }
  1151. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1152. if (!this._renderingCanvas) {
  1153. return null;
  1154. }
  1155. return this._renderingCanvas.getBoundingClientRect();
  1156. }
  1157. public setHardwareScalingLevel(level: number): void {
  1158. this._hardwareScalingLevel = level;
  1159. this.resize();
  1160. }
  1161. public getHardwareScalingLevel(): number {
  1162. return this._hardwareScalingLevel;
  1163. }
  1164. public getLoadedTexturesCache(): InternalTexture[] {
  1165. return this._internalTexturesCache;
  1166. }
  1167. public getCaps(): EngineCapabilities {
  1168. return this._caps;
  1169. }
  1170. /** The number of draw calls submitted last frame */
  1171. public get drawCalls(): number {
  1172. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1173. return 0;
  1174. }
  1175. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1176. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1177. return null;
  1178. }
  1179. public getDepthFunction(): Nullable<number> {
  1180. return this._depthCullingState.depthFunc;
  1181. }
  1182. public setDepthFunction(depthFunc: number) {
  1183. this._depthCullingState.depthFunc = depthFunc;
  1184. }
  1185. public setDepthFunctionToGreater(): void {
  1186. this._depthCullingState.depthFunc = this._gl.GREATER;
  1187. }
  1188. public setDepthFunctionToGreaterOrEqual(): void {
  1189. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1190. }
  1191. public setDepthFunctionToLess(): void {
  1192. this._depthCullingState.depthFunc = this._gl.LESS;
  1193. }
  1194. public setDepthFunctionToLessOrEqual(): void {
  1195. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1196. }
  1197. public getStencilBuffer(): boolean {
  1198. return this._stencilState.stencilTest;
  1199. }
  1200. public setStencilBuffer(enable: boolean): void {
  1201. this._stencilState.stencilTest = enable;
  1202. }
  1203. public getStencilMask(): number {
  1204. return this._stencilState.stencilMask;
  1205. }
  1206. public setStencilMask(mask: number): void {
  1207. this._stencilState.stencilMask = mask;
  1208. }
  1209. public getStencilFunction(): number {
  1210. return this._stencilState.stencilFunc;
  1211. }
  1212. public getStencilFunctionReference(): number {
  1213. return this._stencilState.stencilFuncRef;
  1214. }
  1215. public getStencilFunctionMask(): number {
  1216. return this._stencilState.stencilFuncMask;
  1217. }
  1218. public setStencilFunction(stencilFunc: number) {
  1219. this._stencilState.stencilFunc = stencilFunc;
  1220. }
  1221. public setStencilFunctionReference(reference: number) {
  1222. this._stencilState.stencilFuncRef = reference;
  1223. }
  1224. public setStencilFunctionMask(mask: number) {
  1225. this._stencilState.stencilFuncMask = mask;
  1226. }
  1227. public getStencilOperationFail(): number {
  1228. return this._stencilState.stencilOpStencilFail;
  1229. }
  1230. public getStencilOperationDepthFail(): number {
  1231. return this._stencilState.stencilOpDepthFail;
  1232. }
  1233. public getStencilOperationPass(): number {
  1234. return this._stencilState.stencilOpStencilDepthPass;
  1235. }
  1236. public setStencilOperationFail(operation: number): void {
  1237. this._stencilState.stencilOpStencilFail = operation;
  1238. }
  1239. public setStencilOperationDepthFail(operation: number): void {
  1240. this._stencilState.stencilOpDepthFail = operation;
  1241. }
  1242. public setStencilOperationPass(operation: number): void {
  1243. this._stencilState.stencilOpStencilDepthPass = operation;
  1244. }
  1245. public setDitheringState(value: boolean): void {
  1246. if (value) {
  1247. this._gl.enable(this._gl.DITHER);
  1248. } else {
  1249. this._gl.disable(this._gl.DITHER);
  1250. }
  1251. }
  1252. public setRasterizerState(value: boolean): void {
  1253. if (value) {
  1254. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1255. } else {
  1256. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1257. }
  1258. }
  1259. /**
  1260. * stop executing a render loop function and remove it from the execution array
  1261. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1262. */
  1263. public stopRenderLoop(renderFunction?: () => void): void {
  1264. if (!renderFunction) {
  1265. this._activeRenderLoops = [];
  1266. return;
  1267. }
  1268. var index = this._activeRenderLoops.indexOf(renderFunction);
  1269. if (index >= 0) {
  1270. this._activeRenderLoops.splice(index, 1);
  1271. }
  1272. }
  1273. public _renderLoop(): void {
  1274. if (!this._contextWasLost) {
  1275. var shouldRender = true;
  1276. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1277. shouldRender = false;
  1278. }
  1279. if (shouldRender) {
  1280. // Start new frame
  1281. this.beginFrame();
  1282. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1283. var renderFunction = this._activeRenderLoops[index];
  1284. renderFunction();
  1285. }
  1286. // Present
  1287. this.endFrame();
  1288. }
  1289. }
  1290. if (this._activeRenderLoops.length > 0) {
  1291. // Register new frame
  1292. var requester = null;
  1293. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1294. requester = this._vrDisplay;
  1295. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1296. } else {
  1297. this._renderingQueueLaunched = false;
  1298. }
  1299. }
  1300. /**
  1301. * Register and execute a render loop. The engine can have more than one render function.
  1302. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1303. * @example
  1304. * engine.runRenderLoop(function () {
  1305. * scene.render()
  1306. * })
  1307. */
  1308. public runRenderLoop(renderFunction: () => void): void {
  1309. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1310. return;
  1311. }
  1312. this._activeRenderLoops.push(renderFunction);
  1313. if (!this._renderingQueueLaunched) {
  1314. this._renderingQueueLaunched = true;
  1315. this._bindedRenderFunction = this._renderLoop.bind(this);
  1316. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1317. }
  1318. }
  1319. /**
  1320. * Toggle full screen mode.
  1321. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1322. * @param {any} options - an options object to be sent to the requestFullscreen function
  1323. */
  1324. public switchFullscreen(requestPointerLock: boolean): void {
  1325. if (this.isFullscreen) {
  1326. Tools.ExitFullscreen();
  1327. } else {
  1328. this._pointerLockRequested = requestPointerLock;
  1329. if (this._renderingCanvas) {
  1330. Tools.RequestFullscreen(this._renderingCanvas);
  1331. }
  1332. }
  1333. }
  1334. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1335. this.applyStates();
  1336. var mode = 0;
  1337. if (backBuffer && color) {
  1338. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1339. mode |= this._gl.COLOR_BUFFER_BIT;
  1340. }
  1341. if (depth) {
  1342. this._gl.clearDepth(1.0);
  1343. mode |= this._gl.DEPTH_BUFFER_BIT;
  1344. }
  1345. if (stencil) {
  1346. this._gl.clearStencil(0);
  1347. mode |= this._gl.STENCIL_BUFFER_BIT;
  1348. }
  1349. this._gl.clear(mode);
  1350. }
  1351. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1352. let gl = this._gl;
  1353. // Save state
  1354. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1355. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1356. // Change state
  1357. gl.enable(gl.SCISSOR_TEST);
  1358. gl.scissor(x, y, width, height);
  1359. // Clear
  1360. this.clear(clearColor, true, true, true);
  1361. // Restore state
  1362. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1363. if (curScissor === true) {
  1364. gl.enable(gl.SCISSOR_TEST);
  1365. } else {
  1366. gl.disable(gl.SCISSOR_TEST);
  1367. }
  1368. }
  1369. /**
  1370. * Set the WebGL's viewport
  1371. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1372. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1373. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1374. */
  1375. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1376. var width = requiredWidth || this.getRenderWidth();
  1377. var height = requiredHeight || this.getRenderHeight();
  1378. var x = viewport.x || 0;
  1379. var y = viewport.y || 0;
  1380. this._cachedViewport = viewport;
  1381. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1382. }
  1383. /**
  1384. * Directly set the WebGL Viewport
  1385. * The x, y, width & height are directly passed to the WebGL call
  1386. * @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.
  1387. */
  1388. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1389. let currentViewport = this._cachedViewport;
  1390. this._cachedViewport = null;
  1391. this._gl.viewport(x, y, width, height);
  1392. return currentViewport;
  1393. }
  1394. public beginFrame(): void {
  1395. this.onBeginFrameObservable.notifyObservers(this);
  1396. this._measureFps();
  1397. }
  1398. public endFrame(): void {
  1399. //force a flush in case we are using a bad OS.
  1400. if (this._badOS) {
  1401. this.flushFramebuffer();
  1402. }
  1403. //submit frame to the vr device, if enabled
  1404. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1405. // TODO: We should only submit the frame if we read frameData successfully.
  1406. this._vrDisplay.submitFrame();
  1407. }
  1408. this.onEndFrameObservable.notifyObservers(this);
  1409. }
  1410. /**
  1411. * resize the view according to the canvas' size.
  1412. * @example
  1413. * window.addEventListener("resize", function () {
  1414. * engine.resize();
  1415. * });
  1416. */
  1417. public resize(): void {
  1418. // We're not resizing the size of the canvas while in VR mode & presenting
  1419. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1420. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1421. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1422. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1423. }
  1424. }
  1425. /**
  1426. * force a specific size of the canvas
  1427. * @param {number} width - the new canvas' width
  1428. * @param {number} height - the new canvas' height
  1429. */
  1430. public setSize(width: number, height: number): void {
  1431. if (!this._renderingCanvas) {
  1432. return;
  1433. }
  1434. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1435. return;
  1436. }
  1437. this._renderingCanvas.width = width;
  1438. this._renderingCanvas.height = height;
  1439. for (var index = 0; index < this.scenes.length; index++) {
  1440. var scene = this.scenes[index];
  1441. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1442. var cam = scene.cameras[camIndex];
  1443. cam._currentRenderId = 0;
  1444. }
  1445. }
  1446. if (this.onResizeObservable.hasObservers) {
  1447. this.onResizeObservable.notifyObservers(this);
  1448. }
  1449. }
  1450. // WebVR functions
  1451. public isVRDevicePresent(): boolean {
  1452. return !!this._vrDisplay;
  1453. }
  1454. public getVRDevice(): any {
  1455. return this._vrDisplay;
  1456. }
  1457. public initWebVR(): Observable<{ vrDisplay: any, vrSupported: any }> {
  1458. var notifyObservers = () => {
  1459. var eventArgs = {
  1460. vrDisplay: this._vrDisplay,
  1461. vrSupported: this._vrSupported
  1462. };
  1463. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1464. }
  1465. if (!this._onVrDisplayConnect) {
  1466. this._onVrDisplayConnect = (event) => {
  1467. this._vrDisplay = event.display;
  1468. notifyObservers();
  1469. };
  1470. this._onVrDisplayDisconnect = () => {
  1471. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1472. this._vrDisplay = undefined;
  1473. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1474. notifyObservers();
  1475. };
  1476. this._onVrDisplayPresentChange = () => {
  1477. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1478. }
  1479. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1480. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1481. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1482. }
  1483. this._getVRDisplays(notifyObservers);
  1484. return this.onVRDisplayChangedObservable;
  1485. }
  1486. public enableVR() {
  1487. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1488. var onResolved = () => {
  1489. this.onVRRequestPresentComplete.notifyObservers(true);
  1490. this._onVRFullScreenTriggered();
  1491. };
  1492. var onRejected = () => {
  1493. this.onVRRequestPresentComplete.notifyObservers(false);
  1494. };
  1495. this.onVRRequestPresentStart.notifyObservers(this);
  1496. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1497. }
  1498. }
  1499. public disableVR() {
  1500. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1501. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1502. }
  1503. }
  1504. private _onVRFullScreenTriggered = () => {
  1505. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1506. //get the old size before we change
  1507. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1508. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1509. //get the width and height, change the render size
  1510. var leftEye = this._vrDisplay.getEyeParameters('left');
  1511. this.setHardwareScalingLevel(1);
  1512. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1513. } else {
  1514. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1515. this.setSize(this._oldSize.width, this._oldSize.height);
  1516. }
  1517. }
  1518. private _getVRDisplays(callback: () => void) {
  1519. var getWebVRDevices = (devices: Array<any>) => {
  1520. this._vrSupported = true;
  1521. // note that devices may actually be an empty array. This is fine;
  1522. // we expect this._vrDisplay to be undefined in this case.
  1523. return this._vrDisplay = devices[0];
  1524. }
  1525. if (navigator.getVRDisplays) {
  1526. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch((error: () => void) => {
  1527. // TODO: System CANNOT support WebVR, despite API presence.
  1528. this._vrSupported = false;
  1529. callback();
  1530. });
  1531. } else {
  1532. // TODO: Browser does not support WebVR
  1533. this._vrDisplay = undefined;
  1534. this._vrSupported = false;
  1535. callback();
  1536. }
  1537. }
  1538. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1539. if (this._currentRenderTarget) {
  1540. this.unBindFramebuffer(this._currentRenderTarget);
  1541. }
  1542. this._currentRenderTarget = texture;
  1543. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1544. var gl = this._gl;
  1545. if (texture.isCube) {
  1546. if (faceIndex === undefined) {
  1547. faceIndex = 0;
  1548. }
  1549. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1550. }
  1551. if (this._cachedViewport && !forceFullscreenViewport) {
  1552. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1553. } else {
  1554. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1555. }
  1556. this.wipeCaches();
  1557. }
  1558. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1559. if (this._currentFramebuffer !== framebuffer) {
  1560. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1561. this._currentFramebuffer = framebuffer;
  1562. }
  1563. }
  1564. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1565. this._currentRenderTarget = null;
  1566. // If MSAA, we need to bitblt back to main texture
  1567. var gl = this._gl;
  1568. if (texture._MSAAFramebuffer) {
  1569. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1570. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1571. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1572. 0, 0, texture.width, texture.height,
  1573. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1574. }
  1575. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1576. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1577. gl.generateMipmap(gl.TEXTURE_2D);
  1578. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1579. }
  1580. if (onBeforeUnbind) {
  1581. if (texture._MSAAFramebuffer) {
  1582. // Bind the correct framebuffer
  1583. this.bindUnboundFramebuffer(texture._framebuffer);
  1584. }
  1585. onBeforeUnbind();
  1586. }
  1587. this.bindUnboundFramebuffer(null);
  1588. }
  1589. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1590. this._currentRenderTarget = null;
  1591. // If MSAA, we need to bitblt back to main texture
  1592. var gl = this._gl;
  1593. if (textures[0]._MSAAFramebuffer) {
  1594. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1595. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1596. var attachments = textures[0]._attachments;
  1597. if (!attachments) {
  1598. attachments = new Array(textures.length);
  1599. textures[0]._attachments = attachments;
  1600. }
  1601. for (var i = 0; i < textures.length; i++) {
  1602. var texture = textures[i];
  1603. for (var j = 0; j < attachments.length; j++) {
  1604. attachments[j] = gl.NONE;
  1605. }
  1606. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1607. gl.readBuffer(attachments[i]);
  1608. gl.drawBuffers(attachments);
  1609. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1610. 0, 0, texture.width, texture.height,
  1611. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1612. }
  1613. for (var i = 0; i < attachments.length; i++) {
  1614. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1615. }
  1616. gl.drawBuffers(attachments);
  1617. }
  1618. for (var i = 0; i < textures.length; i++) {
  1619. var texture = textures[i];
  1620. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1621. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1622. gl.generateMipmap(gl.TEXTURE_2D);
  1623. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1624. }
  1625. }
  1626. if (onBeforeUnbind) {
  1627. if (textures[0]._MSAAFramebuffer) {
  1628. // Bind the correct framebuffer
  1629. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  1630. }
  1631. onBeforeUnbind();
  1632. }
  1633. this.bindUnboundFramebuffer(null);
  1634. }
  1635. public generateMipMapsForCubemap(texture: InternalTexture) {
  1636. if (texture.generateMipMaps) {
  1637. var gl = this._gl;
  1638. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  1639. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1640. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1641. }
  1642. }
  1643. public flushFramebuffer(): void {
  1644. this._gl.flush();
  1645. }
  1646. public restoreDefaultFramebuffer(): void {
  1647. if (this._currentRenderTarget) {
  1648. this.unBindFramebuffer(this._currentRenderTarget);
  1649. } else {
  1650. this.bindUnboundFramebuffer(null);
  1651. }
  1652. if (this._cachedViewport) {
  1653. this.setViewport(this._cachedViewport);
  1654. }
  1655. this.wipeCaches();
  1656. }
  1657. // UBOs
  1658. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  1659. var ubo = this._gl.createBuffer();
  1660. if (!ubo) {
  1661. throw new Error("Unable to create uniform buffer");
  1662. }
  1663. this.bindUniformBuffer(ubo);
  1664. if (elements instanceof Float32Array) {
  1665. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1666. } else {
  1667. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1668. }
  1669. this.bindUniformBuffer(null);
  1670. ubo.references = 1;
  1671. return ubo;
  1672. }
  1673. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  1674. var ubo = this._gl.createBuffer();
  1675. if (!ubo) {
  1676. throw new Error("Unable to create dynamic uniform buffer");
  1677. }
  1678. this.bindUniformBuffer(ubo);
  1679. if (elements instanceof Float32Array) {
  1680. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1681. } else {
  1682. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1683. }
  1684. this.bindUniformBuffer(null);
  1685. ubo.references = 1;
  1686. return ubo;
  1687. }
  1688. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  1689. this.bindUniformBuffer(uniformBuffer);
  1690. if (offset === undefined) {
  1691. offset = 0;
  1692. }
  1693. if (count === undefined) {
  1694. if (elements instanceof Float32Array) {
  1695. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1696. } else {
  1697. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1698. }
  1699. } else {
  1700. if (elements instanceof Float32Array) {
  1701. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1702. } else {
  1703. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1704. }
  1705. }
  1706. this.bindUniformBuffer(null);
  1707. }
  1708. // VBOs
  1709. private _resetVertexBufferBinding(): void {
  1710. this.bindArrayBuffer(null);
  1711. this._cachedVertexBuffers = null;
  1712. }
  1713. public createVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1714. var vbo = this._gl.createBuffer();
  1715. if (!vbo) {
  1716. throw new Error("Unable to create vertex buffer");
  1717. }
  1718. this.bindArrayBuffer(vbo);
  1719. if (vertices instanceof Float32Array) {
  1720. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1721. } else {
  1722. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1723. }
  1724. this._resetVertexBufferBinding();
  1725. vbo.references = 1;
  1726. return vbo;
  1727. }
  1728. public createDynamicVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1729. var vbo = this._gl.createBuffer();
  1730. if (!vbo) {
  1731. throw new Error("Unable to create dynamic vertex buffer");
  1732. }
  1733. this.bindArrayBuffer(vbo);
  1734. if (vertices instanceof Float32Array) {
  1735. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1736. } else {
  1737. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1738. }
  1739. this._resetVertexBufferBinding();
  1740. vbo.references = 1;
  1741. return vbo;
  1742. }
  1743. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  1744. // Force cache update
  1745. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  1746. this.bindIndexBuffer(indexBuffer);
  1747. var arrayBuffer;
  1748. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  1749. arrayBuffer = indices;
  1750. } else {
  1751. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1752. }
  1753. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  1754. this._resetIndexBufferBinding();
  1755. }
  1756. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: FloatArray, offset?: number, count?: number): void {
  1757. this.bindArrayBuffer(vertexBuffer);
  1758. if (offset === undefined) {
  1759. offset = 0;
  1760. }
  1761. if (count === undefined) {
  1762. if (vertices instanceof Float32Array) {
  1763. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1764. } else {
  1765. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1766. }
  1767. } else {
  1768. if (vertices instanceof Float32Array) {
  1769. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1770. } else {
  1771. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1772. }
  1773. }
  1774. this._resetVertexBufferBinding();
  1775. }
  1776. private _resetIndexBufferBinding(): void {
  1777. this.bindIndexBuffer(null);
  1778. this._cachedIndexBuffer = null;
  1779. }
  1780. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  1781. var vbo = this._gl.createBuffer();
  1782. if (!vbo) {
  1783. throw new Error("Unable to create index buffer");
  1784. }
  1785. this.bindIndexBuffer(vbo);
  1786. // Check for 32 bits indices
  1787. var arrayBuffer;
  1788. var need32Bits = false;
  1789. if (indices instanceof Uint16Array) {
  1790. arrayBuffer = indices;
  1791. } else {
  1792. //check 32 bit support
  1793. if (this._caps.uintIndices) {
  1794. if (indices instanceof Uint32Array) {
  1795. arrayBuffer = indices;
  1796. need32Bits = true;
  1797. } else {
  1798. //number[] or Int32Array, check if 32 bit is necessary
  1799. for (var index = 0; index < indices.length; index++) {
  1800. if (indices[index] > 65535) {
  1801. need32Bits = true;
  1802. break;
  1803. }
  1804. }
  1805. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1806. }
  1807. } else {
  1808. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1809. arrayBuffer = new Uint16Array(indices);
  1810. }
  1811. }
  1812. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1813. this._resetIndexBufferBinding();
  1814. vbo.references = 1;
  1815. vbo.is32Bits = need32Bits;
  1816. return vbo;
  1817. }
  1818. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  1819. if (!this._vaoRecordInProgress) {
  1820. this._unbindVertexArrayObject();
  1821. }
  1822. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1823. }
  1824. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  1825. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1826. }
  1827. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1828. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1829. }
  1830. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1831. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1832. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1833. };
  1834. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  1835. if (!this._vaoRecordInProgress) {
  1836. this._unbindVertexArrayObject();
  1837. }
  1838. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1839. }
  1840. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  1841. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1842. this._gl.bindBuffer(target, buffer);
  1843. this._currentBoundBuffer[target] = buffer;
  1844. }
  1845. }
  1846. public updateArrayBuffer(data: Float32Array): void {
  1847. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1848. }
  1849. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1850. var pointer = this._currentBufferPointers[indx];
  1851. var changed = false;
  1852. if (!pointer.active) {
  1853. changed = true;
  1854. pointer.active = true;
  1855. pointer.index = indx;
  1856. pointer.size = size;
  1857. pointer.type = type;
  1858. pointer.normalized = normalized;
  1859. pointer.stride = stride;
  1860. pointer.offset = offset;
  1861. pointer.buffer = buffer;
  1862. } else {
  1863. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1864. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1865. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1866. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1867. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1868. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1869. }
  1870. if (changed || this._vaoRecordInProgress) {
  1871. this.bindArrayBuffer(buffer);
  1872. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1873. }
  1874. }
  1875. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  1876. if (indexBuffer == null) {
  1877. return;
  1878. }
  1879. if (this._cachedIndexBuffer !== indexBuffer) {
  1880. this._cachedIndexBuffer = indexBuffer;
  1881. this.bindIndexBuffer(indexBuffer);
  1882. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1883. }
  1884. }
  1885. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1886. var attributes = effect.getAttributesNames();
  1887. if (!this._vaoRecordInProgress) {
  1888. this._unbindVertexArrayObject();
  1889. }
  1890. this.unbindAllAttributes();
  1891. for (var index = 0; index < attributes.length; index++) {
  1892. var order = effect.getAttributeLocation(index);
  1893. if (order >= 0) {
  1894. var vertexBuffer = vertexBuffers[attributes[index]];
  1895. if (!vertexBuffer) {
  1896. continue;
  1897. }
  1898. this._gl.enableVertexAttribArray(order);
  1899. if (!this._vaoRecordInProgress) {
  1900. this._vertexAttribArraysEnabled[order] = true;
  1901. }
  1902. var buffer = vertexBuffer.getBuffer();
  1903. if (buffer) {
  1904. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1905. if (vertexBuffer.getIsInstanced()) {
  1906. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1907. if (!this._vaoRecordInProgress) {
  1908. this._currentInstanceLocations.push(order);
  1909. this._currentInstanceBuffers.push(buffer);
  1910. }
  1911. }
  1912. }
  1913. }
  1914. }
  1915. }
  1916. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  1917. var vao = this._gl.createVertexArray();
  1918. this._vaoRecordInProgress = true;
  1919. this._gl.bindVertexArray(vao);
  1920. this._mustWipeVertexAttributes = true;
  1921. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1922. this.bindIndexBuffer(indexBuffer);
  1923. this._vaoRecordInProgress = false;
  1924. this._gl.bindVertexArray(null);
  1925. return vao;
  1926. }
  1927. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  1928. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1929. this._cachedVertexArrayObject = vertexArrayObject;
  1930. this._gl.bindVertexArray(vertexArrayObject);
  1931. this._cachedVertexBuffers = null;
  1932. this._cachedIndexBuffer = null;
  1933. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1934. this._mustWipeVertexAttributes = true;
  1935. }
  1936. }
  1937. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1938. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1939. this._cachedVertexBuffers = vertexBuffer;
  1940. this._cachedEffectForVertexBuffers = effect;
  1941. let attributesCount = effect.getAttributesCount();
  1942. this._unbindVertexArrayObject();
  1943. this.unbindAllAttributes();
  1944. var offset = 0;
  1945. for (var index = 0; index < attributesCount; index++) {
  1946. if (index < vertexDeclaration.length) {
  1947. var order = effect.getAttributeLocation(index);
  1948. if (order >= 0) {
  1949. this._gl.enableVertexAttribArray(order);
  1950. this._vertexAttribArraysEnabled[order] = true;
  1951. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1952. }
  1953. offset += vertexDeclaration[index] * 4;
  1954. }
  1955. }
  1956. }
  1957. this._bindIndexBufferWithCache(indexBuffer);
  1958. }
  1959. private _unbindVertexArrayObject(): void {
  1960. if (!this._cachedVertexArrayObject) {
  1961. return;
  1962. }
  1963. this._cachedVertexArrayObject = null;
  1964. this._gl.bindVertexArray(null);
  1965. }
  1966. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  1967. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1968. this._cachedVertexBuffers = vertexBuffers;
  1969. this._cachedEffectForVertexBuffers = effect;
  1970. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1971. }
  1972. this._bindIndexBufferWithCache(indexBuffer);
  1973. }
  1974. public unbindInstanceAttributes() {
  1975. var boundBuffer;
  1976. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1977. var instancesBuffer = this._currentInstanceBuffers[i];
  1978. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1979. boundBuffer = instancesBuffer;
  1980. this.bindArrayBuffer(instancesBuffer);
  1981. }
  1982. var offsetLocation = this._currentInstanceLocations[i];
  1983. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1984. }
  1985. this._currentInstanceBuffers.length = 0;
  1986. this._currentInstanceLocations.length = 0;
  1987. }
  1988. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1989. this._gl.deleteVertexArray(vao);
  1990. }
  1991. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1992. buffer.references--;
  1993. if (buffer.references === 0) {
  1994. this._gl.deleteBuffer(buffer);
  1995. return true;
  1996. }
  1997. return false;
  1998. }
  1999. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2000. var buffer = this._gl.createBuffer();
  2001. if (!buffer) {
  2002. throw new Error("Unable to create instance buffer");
  2003. }
  2004. buffer.capacity = capacity;
  2005. this.bindArrayBuffer(buffer);
  2006. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2007. return buffer;
  2008. }
  2009. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2010. this._gl.deleteBuffer(buffer);
  2011. }
  2012. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2013. this.bindArrayBuffer(instancesBuffer);
  2014. if (data) {
  2015. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2016. }
  2017. if ((<any>offsetLocations[0]).index !== undefined) {
  2018. let stride = 0;
  2019. for (let i = 0; i < offsetLocations.length; i++) {
  2020. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2021. stride += ai.attributeSize * 4;
  2022. }
  2023. for (let i = 0; i < offsetLocations.length; i++) {
  2024. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2025. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2026. this._gl.enableVertexAttribArray(ai.index);
  2027. this._vertexAttribArraysEnabled[ai.index] = true;
  2028. }
  2029. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2030. this._gl.vertexAttribDivisor(ai.index, 1);
  2031. this._currentInstanceLocations.push(ai.index);
  2032. this._currentInstanceBuffers.push(instancesBuffer);
  2033. }
  2034. } else {
  2035. for (let index = 0; index < 4; index++) {
  2036. let offsetLocation = <number>offsetLocations[index];
  2037. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2038. this._gl.enableVertexAttribArray(offsetLocation);
  2039. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2040. }
  2041. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2042. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2043. this._currentInstanceLocations.push(offsetLocation);
  2044. this._currentInstanceBuffers.push(instancesBuffer);
  2045. }
  2046. }
  2047. }
  2048. public applyStates() {
  2049. this._depthCullingState.apply(this._gl);
  2050. this._stencilState.apply(this._gl);
  2051. this._alphaState.apply(this._gl);
  2052. }
  2053. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2054. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2055. }
  2056. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2057. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2058. }
  2059. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2060. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2061. }
  2062. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2063. // Apply states
  2064. this.applyStates();
  2065. this._drawCalls.addCount(1, false);
  2066. // Render
  2067. const drawMode = this.DrawMode(fillMode);
  2068. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2069. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2070. if (instancesCount) {
  2071. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2072. } else {
  2073. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2074. }
  2075. }
  2076. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2077. // Apply states
  2078. this.applyStates();
  2079. this._drawCalls.addCount(1, false);
  2080. const drawMode = this.DrawMode(fillMode);
  2081. if (instancesCount) {
  2082. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2083. } else {
  2084. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2085. }
  2086. }
  2087. private DrawMode(fillMode: number): number {
  2088. switch (fillMode) {
  2089. // Triangle views
  2090. case Material.TriangleFillMode:
  2091. return this._gl.TRIANGLES;
  2092. case Material.PointFillMode:
  2093. return this._gl.POINTS;
  2094. case Material.WireFrameFillMode:
  2095. return this._gl.LINES;
  2096. // Draw modes
  2097. case Material.PointListDrawMode:
  2098. return this._gl.POINTS
  2099. case Material.LineListDrawMode:
  2100. return this._gl.LINES;
  2101. case Material.LineLoopDrawMode:
  2102. return this._gl.LINE_LOOP
  2103. case Material.LineStripDrawMode:
  2104. return this._gl.LINE_STRIP
  2105. case Material.TriangleStripDrawMode:
  2106. return this._gl.TRIANGLE_STRIP
  2107. case Material.TriangleFanDrawMode:
  2108. return this._gl.TRIANGLE_FAN;
  2109. default:
  2110. return this._gl.TRIANGLES;
  2111. }
  2112. }
  2113. // Shaders
  2114. public _releaseEffect(effect: Effect): void {
  2115. if (this._compiledEffects[effect._key]) {
  2116. delete this._compiledEffects[effect._key];
  2117. this._deleteProgram(effect.getProgram());
  2118. }
  2119. }
  2120. public _deleteProgram(program: WebGLProgram): void {
  2121. if (program) {
  2122. program.__SPECTOR_rebuildProgram = null;
  2123. if (program.transformFeedback) {
  2124. this.deleteTransformFeedback(program.transformFeedback);
  2125. program.transformFeedback = null;
  2126. }
  2127. this._gl.deleteProgram(program);
  2128. }
  2129. }
  2130. /**
  2131. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2132. * @param samplers An array of string used to represent textures
  2133. */
  2134. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2135. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2136. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2137. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2138. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2139. if (this._compiledEffects[name]) {
  2140. var compiledEffect = <Effect>this._compiledEffects[name];
  2141. if (onCompiled && compiledEffect.isReady()) {
  2142. onCompiled(compiledEffect);
  2143. }
  2144. return compiledEffect;
  2145. }
  2146. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2147. effect._key = name;
  2148. this._compiledEffects[name] = effect;
  2149. return effect;
  2150. }
  2151. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2152. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2153. return this.createEffect(
  2154. {
  2155. vertex: "particles",
  2156. fragmentElement: fragmentName
  2157. },
  2158. ["position", "color", "options"],
  2159. ["view", "projection"].concat(uniformsNames),
  2160. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2161. }
  2162. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2163. context = context || this._gl;
  2164. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2165. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2166. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2167. }
  2168. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2169. context = context || this._gl;
  2170. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2171. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  2172. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2173. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2174. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2175. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2176. return program;
  2177. }
  2178. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2179. var shaderProgram = context.createProgram();
  2180. if (!shaderProgram) {
  2181. throw new Error("Unable to create program");
  2182. }
  2183. context.attachShader(shaderProgram, vertexShader);
  2184. context.attachShader(shaderProgram, fragmentShader);
  2185. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2186. let transformFeedback = this.createTransformFeedback();
  2187. this.bindTransformFeedback(transformFeedback);
  2188. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2189. shaderProgram.transformFeedback = transformFeedback;
  2190. }
  2191. context.linkProgram(shaderProgram);
  2192. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2193. this.bindTransformFeedback(null);
  2194. }
  2195. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2196. if (!linked) {
  2197. context.validateProgram(shaderProgram);
  2198. var error = context.getProgramInfoLog(shaderProgram);
  2199. if (error) {
  2200. throw new Error(error);
  2201. }
  2202. }
  2203. context.deleteShader(vertexShader);
  2204. context.deleteShader(fragmentShader);
  2205. return shaderProgram;
  2206. }
  2207. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2208. var results = new Array<Nullable<WebGLUniformLocation>>();
  2209. for (var index = 0; index < uniformsNames.length; index++) {
  2210. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2211. }
  2212. return results;
  2213. }
  2214. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2215. var results = [];
  2216. for (var index = 0; index < attributesNames.length; index++) {
  2217. try {
  2218. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2219. } catch (e) {
  2220. results.push(-1);
  2221. }
  2222. }
  2223. return results;
  2224. }
  2225. public enableEffect(effect: Nullable<Effect>): void {
  2226. if (!effect) {
  2227. return;
  2228. }
  2229. // Use program
  2230. this.bindSamplers(effect);
  2231. this._currentEffect = effect;
  2232. if (effect.onBind) {
  2233. effect.onBind(effect);
  2234. }
  2235. effect.onBindObservable.notifyObservers(effect);
  2236. }
  2237. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2238. if (!uniform)
  2239. return;
  2240. this._gl.uniform1iv(uniform, array);
  2241. }
  2242. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2243. if (!uniform || array.length % 2 !== 0)
  2244. return;
  2245. this._gl.uniform2iv(uniform, array);
  2246. }
  2247. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2248. if (!uniform || array.length % 3 !== 0)
  2249. return;
  2250. this._gl.uniform3iv(uniform, array);
  2251. }
  2252. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2253. if (!uniform || array.length % 4 !== 0)
  2254. return;
  2255. this._gl.uniform4iv(uniform, array);
  2256. }
  2257. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2258. if (!uniform)
  2259. return;
  2260. this._gl.uniform1fv(uniform, array);
  2261. }
  2262. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2263. if (!uniform || array.length % 2 !== 0)
  2264. return;
  2265. this._gl.uniform2fv(uniform, array);
  2266. }
  2267. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2268. if (!uniform || array.length % 3 !== 0)
  2269. return;
  2270. this._gl.uniform3fv(uniform, array);
  2271. }
  2272. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2273. if (!uniform || array.length % 4 !== 0)
  2274. return;
  2275. this._gl.uniform4fv(uniform, array);
  2276. }
  2277. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2278. if (!uniform)
  2279. return;
  2280. this._gl.uniform1fv(uniform, <any>array);
  2281. }
  2282. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2283. if (!uniform || array.length % 2 !== 0)
  2284. return;
  2285. this._gl.uniform2fv(uniform, <any>array);
  2286. }
  2287. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2288. if (!uniform || array.length % 3 !== 0)
  2289. return;
  2290. this._gl.uniform3fv(uniform, <any>array);
  2291. }
  2292. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2293. if (!uniform || array.length % 4 !== 0)
  2294. return;
  2295. this._gl.uniform4fv(uniform, <any>array);
  2296. }
  2297. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2298. if (!uniform)
  2299. return;
  2300. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2301. }
  2302. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  2303. if (!uniform)
  2304. return;
  2305. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2306. }
  2307. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2308. if (!uniform)
  2309. return;
  2310. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2311. }
  2312. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2313. if (!uniform)
  2314. return;
  2315. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2316. }
  2317. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2318. if (!uniform)
  2319. return;
  2320. this._gl.uniform1i(uniform, value);
  2321. }
  2322. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2323. if (!uniform)
  2324. return;
  2325. this._gl.uniform1f(uniform, value);
  2326. }
  2327. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2328. if (!uniform)
  2329. return;
  2330. this._gl.uniform2f(uniform, x, y);
  2331. }
  2332. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2333. if (!uniform)
  2334. return;
  2335. this._gl.uniform3f(uniform, x, y, z);
  2336. }
  2337. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  2338. if (!uniform)
  2339. return;
  2340. this._gl.uniform1i(uniform, bool);
  2341. }
  2342. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2343. if (!uniform)
  2344. return;
  2345. this._gl.uniform4f(uniform, x, y, z, w);
  2346. }
  2347. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  2348. if (!uniform)
  2349. return;
  2350. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2351. }
  2352. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  2353. if (!uniform)
  2354. return;
  2355. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2356. }
  2357. // States
  2358. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2359. // Culling
  2360. if (this._depthCullingState.cull !== culling || force) {
  2361. this._depthCullingState.cull = culling;
  2362. }
  2363. // Cull face
  2364. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2365. if (this._depthCullingState.cullFace !== cullFace || force) {
  2366. this._depthCullingState.cullFace = cullFace;
  2367. }
  2368. // Z offset
  2369. this.setZOffset(zOffset);
  2370. // Front face
  2371. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2372. if (this._depthCullingState.frontFace !== frontFace || force) {
  2373. this._depthCullingState.frontFace = frontFace;
  2374. }
  2375. }
  2376. public setZOffset(value: number): void {
  2377. this._depthCullingState.zOffset = value;
  2378. }
  2379. public getZOffset(): number {
  2380. return this._depthCullingState.zOffset;
  2381. }
  2382. public setDepthBuffer(enable: boolean): void {
  2383. this._depthCullingState.depthTest = enable;
  2384. }
  2385. public getDepthWrite(): boolean {
  2386. return this._depthCullingState.depthMask;
  2387. }
  2388. public setDepthWrite(enable: boolean): void {
  2389. this._depthCullingState.depthMask = enable;
  2390. }
  2391. public setColorWrite(enable: boolean): void {
  2392. this._gl.colorMask(enable, enable, enable, enable);
  2393. this._colorWrite = enable;
  2394. }
  2395. public getColorWrite(): boolean {
  2396. return this._colorWrite;
  2397. }
  2398. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2399. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2400. }
  2401. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2402. if (this._alphaMode === mode) {
  2403. return;
  2404. }
  2405. switch (mode) {
  2406. case Engine.ALPHA_DISABLE:
  2407. this._alphaState.alphaBlend = false;
  2408. break;
  2409. case Engine.ALPHA_PREMULTIPLIED:
  2410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2411. this._alphaState.alphaBlend = true;
  2412. break;
  2413. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2415. this._alphaState.alphaBlend = true;
  2416. break;
  2417. case Engine.ALPHA_COMBINE:
  2418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2419. this._alphaState.alphaBlend = true;
  2420. break;
  2421. case Engine.ALPHA_ONEONE:
  2422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2423. this._alphaState.alphaBlend = true;
  2424. break;
  2425. case Engine.ALPHA_ADD:
  2426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2427. this._alphaState.alphaBlend = true;
  2428. break;
  2429. case Engine.ALPHA_SUBTRACT:
  2430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2431. this._alphaState.alphaBlend = true;
  2432. break;
  2433. case Engine.ALPHA_MULTIPLY:
  2434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2435. this._alphaState.alphaBlend = true;
  2436. break;
  2437. case Engine.ALPHA_MAXIMIZED:
  2438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2439. this._alphaState.alphaBlend = true;
  2440. break;
  2441. case Engine.ALPHA_INTERPOLATE:
  2442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2443. this._alphaState.alphaBlend = true;
  2444. break;
  2445. case Engine.ALPHA_SCREENMODE:
  2446. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2447. this._alphaState.alphaBlend = true;
  2448. break;
  2449. }
  2450. if (!noDepthWriteChange) {
  2451. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2452. }
  2453. this._alphaMode = mode;
  2454. }
  2455. public getAlphaMode(): number {
  2456. return this._alphaMode;
  2457. }
  2458. // Textures
  2459. public wipeCaches(bruteForce?: boolean): void {
  2460. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2461. return;
  2462. }
  2463. this._currentEffect = null;
  2464. // 6/8/2017: deltakosh: Should not be required anymore.
  2465. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  2466. if (bruteForce) {
  2467. this.resetTextureCache();
  2468. this._currentProgram = null;
  2469. this._stencilState.reset();
  2470. this._depthCullingState.reset();
  2471. this.setDepthFunctionToLessOrEqual();
  2472. this._alphaState.reset();
  2473. }
  2474. this._resetVertexBufferBinding();
  2475. this._cachedIndexBuffer = null;
  2476. this._cachedEffectForVertexBuffers = null;
  2477. this._unbindVertexArrayObject();
  2478. this.bindIndexBuffer(null);
  2479. }
  2480. /**
  2481. * Set the compressed texture format to use, based on the formats you have, and the formats
  2482. * supported by the hardware / browser.
  2483. *
  2484. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2485. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2486. * to API arguments needed to compressed textures. This puts the burden on the container
  2487. * generator to house the arcane code for determining these for current & future formats.
  2488. *
  2489. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2490. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2491. *
  2492. * Note: The result of this call is not taken into account when a texture is base64.
  2493. *
  2494. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2495. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2496. *
  2497. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2498. * @returns The extension selected.
  2499. */
  2500. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  2501. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2502. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2503. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2504. return this._textureFormatInUse = this._texturesSupported[i];
  2505. }
  2506. }
  2507. }
  2508. // actively set format to nothing, to allow this to be called more than once
  2509. // and possibly fail the 2nd time
  2510. this._textureFormatInUse = null;
  2511. return null;
  2512. }
  2513. public _createTexture(): WebGLTexture {
  2514. let texture = this._gl.createTexture();
  2515. if (!texture) {
  2516. throw new Error("Unable to create texture");
  2517. }
  2518. return texture;
  2519. }
  2520. /**
  2521. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2522. * @param {string} urlArg- This contains one of the following:
  2523. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2524. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2525. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2526. *
  2527. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2528. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2529. * @param {Scene} scene- Needed for loading to the correct scene.
  2530. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2531. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2532. * @param {callback} onError- Optional callback to be called upon failure.
  2533. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2534. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2535. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2536. *
  2537. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2538. */
  2539. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  2540. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2541. buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  2542. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2543. var fromData = url.substr(0, 5) === "data:";
  2544. var fromBlob = url.substr(0, 5) === "blob:";
  2545. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2546. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2547. // establish the file extension, if possible
  2548. var lastDot = url.lastIndexOf('.');
  2549. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2550. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  2551. var isTGA = (extension.indexOf(".tga") === 0);
  2552. // determine if a ktx file should be substituted
  2553. var isKTX = false;
  2554. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2555. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2556. isKTX = true;
  2557. }
  2558. if (scene) {
  2559. scene._addPendingData(texture);
  2560. }
  2561. texture.url = url;
  2562. texture.generateMipMaps = !noMipmap;
  2563. texture.samplingMode = samplingMode;
  2564. texture.invertY = invertY;
  2565. if (!this._doNotHandleContextLost) {
  2566. // Keep a link to the buffer only if we plan to handle context lost
  2567. texture._buffer = buffer;
  2568. }
  2569. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2570. if (onLoad && !fallBack) {
  2571. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2572. }
  2573. if (!fallBack) this._internalTexturesCache.push(texture);
  2574. var onerror = (message?: string, exception?: any) => {
  2575. if (scene) {
  2576. scene._removePendingData(texture);
  2577. }
  2578. if (onLoadObserver) {
  2579. texture.onLoadedObservable.remove(onLoadObserver);
  2580. }
  2581. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2582. if (isKTX) {
  2583. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2584. } else if (Tools.UseFallbackTexture) {
  2585. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2586. }
  2587. if (onError) {
  2588. onError(message || "Unknown error", exception);
  2589. }
  2590. };
  2591. var callback: Nullable<(arrayBuffer: any) => void> = null;
  2592. // processing for non-image formats
  2593. if (isKTX || isTGA || isDDS) {
  2594. if (isKTX) {
  2595. callback = (data) => {
  2596. var ktx = new KhronosTextureContainer(data, 1);
  2597. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2598. ktx.uploadLevels(this._gl, !noMipmap);
  2599. return false;
  2600. }, samplingMode);
  2601. };
  2602. } else if (isTGA) {
  2603. callback = (arrayBuffer) => {
  2604. var data = new Uint8Array(arrayBuffer);
  2605. var header = TGATools.GetTGAHeader(data);
  2606. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2607. TGATools.UploadContent(this._gl, data);
  2608. return false;
  2609. }, samplingMode);
  2610. };
  2611. } else if (isDDS) {
  2612. callback = (data) => {
  2613. var info = DDSTools.GetDDSInfo(data);
  2614. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2615. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2616. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2617. return false;
  2618. }, samplingMode);
  2619. };
  2620. }
  2621. if (!buffer) {
  2622. this._loadFile(url, data => {
  2623. if (callback) {
  2624. callback(data);
  2625. }
  2626. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  2627. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  2628. });
  2629. } else {
  2630. if (callback) {
  2631. callback(buffer);
  2632. }
  2633. }
  2634. // image format processing
  2635. } else {
  2636. var onload = (img: HTMLImageElement) => {
  2637. if (fromBlob && !this._doNotHandleContextLost) {
  2638. // We need to store the image if we need to rebuild the texture
  2639. // in case of a webgl context lost
  2640. texture._buffer = img;
  2641. }
  2642. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2643. let gl = this._gl;
  2644. var isPot = (img.width === potWidth && img.height === potHeight);
  2645. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2646. if (isPot) {
  2647. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2648. return false;
  2649. }
  2650. // Using shaders to rescale because canvas.drawImage is lossy
  2651. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2652. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2653. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2657. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2658. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2659. this._releaseTexture(source);
  2660. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2661. continuationCallback();
  2662. });
  2663. return true;
  2664. }, samplingMode);
  2665. };
  2666. if (!fromData || isBase64)
  2667. if (buffer instanceof HTMLImageElement) {
  2668. onload(buffer);
  2669. } else {
  2670. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2671. }
  2672. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  2673. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2674. else
  2675. onload(<HTMLImageElement>buffer);
  2676. }
  2677. return texture;
  2678. }
  2679. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  2680. let rtt = this.createRenderTargetTexture({
  2681. width: destination.width,
  2682. height: destination.height,
  2683. }, {
  2684. generateMipMaps: false,
  2685. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2686. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2687. generateDepthBuffer: false,
  2688. generateStencilBuffer: false
  2689. }
  2690. );
  2691. if (!this._rescalePostProcess) {
  2692. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2693. }
  2694. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2695. this._rescalePostProcess.onApply = function (effect) {
  2696. effect._bindTexture("textureSampler", source);
  2697. }
  2698. let hostingScene = scene;
  2699. if (!hostingScene) {
  2700. hostingScene = this.scenes[this.scenes.length - 1];
  2701. }
  2702. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  2703. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  2704. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2705. this.unBindFramebuffer(rtt);
  2706. this._releaseTexture(rtt);
  2707. if (onComplete) {
  2708. onComplete();
  2709. }
  2710. });
  2711. }
  2712. private _getInternalFormat(format: number): number {
  2713. var internalFormat = this._gl.RGBA;
  2714. switch (format) {
  2715. case Engine.TEXTUREFORMAT_ALPHA:
  2716. internalFormat = this._gl.ALPHA;
  2717. break;
  2718. case Engine.TEXTUREFORMAT_LUMINANCE:
  2719. internalFormat = this._gl.LUMINANCE;
  2720. break;
  2721. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2722. internalFormat = this._gl.LUMINANCE_ALPHA;
  2723. break;
  2724. case Engine.TEXTUREFORMAT_RGB:
  2725. internalFormat = this._gl.RGB;
  2726. break;
  2727. case Engine.TEXTUREFORMAT_RGBA:
  2728. internalFormat = this._gl.RGBA;
  2729. break;
  2730. }
  2731. return internalFormat;
  2732. }
  2733. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  2734. if (!texture) {
  2735. return;
  2736. }
  2737. var internalFormat = this._getInternalFormat(format);
  2738. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2739. var textureType = this._getWebGLTextureType(type);
  2740. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2741. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2742. if (!this._doNotHandleContextLost) {
  2743. texture._bufferView = data;
  2744. texture.format = format;
  2745. texture.type = type;
  2746. texture.invertY = invertY;
  2747. texture._compression = compression;
  2748. }
  2749. if (texture.width % 4 !== 0) {
  2750. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2751. }
  2752. if (compression && data) {
  2753. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, data);
  2754. } else {
  2755. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  2756. }
  2757. if (texture.generateMipMaps) {
  2758. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2759. }
  2760. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2761. // this.resetTextureCache();
  2762. texture.isReady = true;
  2763. }
  2764. 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 {
  2765. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2766. texture.baseWidth = width;
  2767. texture.baseHeight = height;
  2768. texture.width = width;
  2769. texture.height = height;
  2770. texture.format = format;
  2771. texture.generateMipMaps = generateMipMaps;
  2772. texture.samplingMode = samplingMode;
  2773. texture.invertY = invertY;
  2774. texture._compression = compression;
  2775. texture.type = type;
  2776. if (!this._doNotHandleContextLost) {
  2777. texture._bufferView = data;
  2778. }
  2779. this.updateRawTexture(texture, data, format, invertY, compression, type);
  2780. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2781. // Filters
  2782. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2783. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2784. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2785. if (generateMipMaps) {
  2786. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2787. }
  2788. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2789. this._internalTexturesCache.push(texture);
  2790. return texture;
  2791. }
  2792. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2793. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2794. texture.baseWidth = width;
  2795. texture.baseHeight = height;
  2796. if (generateMipMaps) {
  2797. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2798. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2799. }
  2800. // this.resetTextureCache();
  2801. texture.width = width;
  2802. texture.height = height;
  2803. texture.isReady = false;
  2804. texture.generateMipMaps = generateMipMaps;
  2805. texture.samplingMode = samplingMode;
  2806. this.updateTextureSamplingMode(samplingMode, texture);
  2807. this._internalTexturesCache.push(texture);
  2808. return texture;
  2809. }
  2810. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2811. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2812. if (texture.isCube) {
  2813. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  2814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2816. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2817. } else if (texture.is3D) {
  2818. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  2819. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2820. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2821. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2822. } else {
  2823. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2824. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2827. }
  2828. texture.samplingMode = samplingMode;
  2829. }
  2830. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2831. if (!texture) {
  2832. return;
  2833. }
  2834. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2835. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2836. if (premulAlpha) {
  2837. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2838. }
  2839. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2840. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2841. if (texture.generateMipMaps) {
  2842. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2843. }
  2844. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2845. if (premulAlpha) {
  2846. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2847. }
  2848. texture.isReady = true;
  2849. }
  2850. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  2851. if (!texture || texture._isDisabled) {
  2852. return;
  2853. }
  2854. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2855. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2856. try {
  2857. // Testing video texture support
  2858. if (this._videoTextureSupported === undefined) {
  2859. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2860. if (this._gl.getError() !== 0) {
  2861. this._videoTextureSupported = false;
  2862. } else {
  2863. this._videoTextureSupported = true;
  2864. }
  2865. }
  2866. // Copy video through the current working canvas if video texture is not supported
  2867. if (!this._videoTextureSupported) {
  2868. if (!texture._workingCanvas) {
  2869. texture._workingCanvas = document.createElement("canvas");
  2870. let context = texture._workingCanvas.getContext("2d");
  2871. if (!context) {
  2872. throw new Error("Unable to get 2d context");
  2873. }
  2874. texture._workingContext = context;
  2875. texture._workingCanvas.width = texture.width;
  2876. texture._workingCanvas.height = texture.height;
  2877. }
  2878. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2879. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2880. } else {
  2881. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2882. }
  2883. if (texture.generateMipMaps) {
  2884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2885. }
  2886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2887. // this.resetTextureCache();
  2888. texture.isReady = true;
  2889. } catch (ex) {
  2890. // Something unexpected
  2891. // Let's disable the texture
  2892. texture._isDisabled = true;
  2893. }
  2894. }
  2895. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2896. let fullOptions = new RenderTargetCreationOptions();
  2897. if (options !== undefined && typeof options === "object") {
  2898. fullOptions.generateMipMaps = options.generateMipMaps;
  2899. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2900. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2901. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2902. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2903. } else {
  2904. fullOptions.generateMipMaps = <boolean>options;
  2905. fullOptions.generateDepthBuffer = true;
  2906. fullOptions.generateStencilBuffer = false;
  2907. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2908. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2909. }
  2910. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2911. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2912. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2913. }
  2914. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2915. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2916. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2917. }
  2918. var gl = this._gl;
  2919. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2920. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2921. var width = (<{ width: number, height: number }>size).width || <number>size;
  2922. var height = (<{ width: number, height: number }>size).height || <number>size;
  2923. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  2924. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2925. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2926. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2927. }
  2928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2931. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2932. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  2933. // Create the framebuffer
  2934. var framebuffer = gl.createFramebuffer();
  2935. this.bindUnboundFramebuffer(framebuffer);
  2936. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2937. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  2938. if (fullOptions.generateMipMaps) {
  2939. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2940. }
  2941. // Unbind
  2942. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2944. this.bindUnboundFramebuffer(null);
  2945. texture._framebuffer = framebuffer;
  2946. texture.baseWidth = width;
  2947. texture.baseHeight = height;
  2948. texture.width = width;
  2949. texture.height = height;
  2950. texture.isReady = true;
  2951. texture.samples = 1;
  2952. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  2953. texture.samplingMode = fullOptions.samplingMode;
  2954. texture.type = fullOptions.type;
  2955. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2956. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  2957. // this.resetTextureCache();
  2958. this._internalTexturesCache.push(texture);
  2959. return texture;
  2960. }
  2961. public createMultipleRenderTarget(size: any, options: any): InternalTexture[] {
  2962. var generateMipMaps = false;
  2963. var generateDepthBuffer = true;
  2964. var generateStencilBuffer = false;
  2965. var generateDepthTexture = false;
  2966. var textureCount = 1;
  2967. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2968. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2969. var types = [], samplingModes = [];
  2970. if (options !== undefined) {
  2971. generateMipMaps = options.generateMipMaps;
  2972. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2973. generateStencilBuffer = options.generateStencilBuffer;
  2974. generateDepthTexture = options.generateDepthTexture;
  2975. textureCount = options.textureCount || 1;
  2976. if (options.types) {
  2977. types = options.types;
  2978. }
  2979. if (options.samplingModes) {
  2980. samplingModes = options.samplingModes;
  2981. }
  2982. }
  2983. var gl = this._gl;
  2984. // Create the framebuffer
  2985. var framebuffer = gl.createFramebuffer();
  2986. this.bindUnboundFramebuffer(framebuffer);
  2987. var width = size.width || size;
  2988. var height = size.height || size;
  2989. var textures = [];
  2990. var attachments = []
  2991. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2992. for (var i = 0; i < textureCount; i++) {
  2993. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2994. var type = types[i] || defaultType;
  2995. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2996. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2997. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2998. }
  2999. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3000. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3001. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3002. }
  3003. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3004. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3005. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3006. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  3007. }
  3008. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3009. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3010. textures.push(texture);
  3011. attachments.push(attachment);
  3012. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  3013. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  3014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3018. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3019. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3020. if (generateMipMaps) {
  3021. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3022. }
  3023. // Unbind
  3024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3025. texture._framebuffer = framebuffer;
  3026. texture._depthStencilBuffer = depthStencilBuffer;
  3027. texture.baseWidth = width;
  3028. texture.baseHeight = height;
  3029. texture.width = width;
  3030. texture.height = height;
  3031. texture.isReady = true;
  3032. texture.samples = 1;
  3033. texture.generateMipMaps = generateMipMaps;
  3034. texture.samplingMode = samplingMode;
  3035. texture.type = type;
  3036. texture._generateDepthBuffer = generateDepthBuffer;
  3037. texture._generateStencilBuffer = generateStencilBuffer;
  3038. texture._attachments = attachments;
  3039. this._internalTexturesCache.push(texture);
  3040. }
  3041. if (generateDepthTexture && this._caps.depthTextureExtension) {
  3042. // Depth texture
  3043. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3044. gl.activeTexture(gl.TEXTURE0);
  3045. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  3046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3050. gl.texImage2D(
  3051. gl.TEXTURE_2D,
  3052. 0,
  3053. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  3054. width,
  3055. height,
  3056. 0,
  3057. gl.DEPTH_COMPONENT,
  3058. gl.UNSIGNED_SHORT,
  3059. null
  3060. );
  3061. gl.framebufferTexture2D(
  3062. gl.FRAMEBUFFER,
  3063. gl.DEPTH_ATTACHMENT,
  3064. gl.TEXTURE_2D,
  3065. depthTexture._webGLTexture,
  3066. 0
  3067. );
  3068. depthTexture._framebuffer = framebuffer;
  3069. depthTexture.baseWidth = width;
  3070. depthTexture.baseHeight = height;
  3071. depthTexture.width = width;
  3072. depthTexture.height = height;
  3073. depthTexture.isReady = true;
  3074. depthTexture.samples = 1;
  3075. depthTexture.generateMipMaps = generateMipMaps;
  3076. depthTexture.samplingMode = gl.NEAREST;
  3077. depthTexture._generateDepthBuffer = generateDepthBuffer;
  3078. depthTexture._generateStencilBuffer = generateStencilBuffer;
  3079. textures.push(depthTexture)
  3080. this._internalTexturesCache.push(depthTexture);
  3081. }
  3082. gl.drawBuffers(attachments);
  3083. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3084. this.bindUnboundFramebuffer(null);
  3085. this.resetTextureCache();
  3086. return textures;
  3087. }
  3088. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  3089. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  3090. var gl = this._gl;
  3091. // Create the depth/stencil buffer
  3092. if (generateStencilBuffer) {
  3093. depthStencilBuffer = gl.createRenderbuffer();
  3094. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3095. if (samples > 1) {
  3096. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  3097. } else {
  3098. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  3099. }
  3100. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3101. }
  3102. else if (generateDepthBuffer) {
  3103. depthStencilBuffer = gl.createRenderbuffer();
  3104. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3105. if (samples > 1) {
  3106. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  3107. } else {
  3108. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3109. }
  3110. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3111. }
  3112. return depthStencilBuffer;
  3113. }
  3114. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  3115. if (this.webGLVersion < 2 || !texture) {
  3116. return 1;
  3117. }
  3118. if (texture.samples === samples) {
  3119. return samples;
  3120. }
  3121. var gl = this._gl;
  3122. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3123. // Dispose previous render buffers
  3124. if (texture._depthStencilBuffer) {
  3125. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3126. texture._depthStencilBuffer = null;
  3127. }
  3128. if (texture._MSAAFramebuffer) {
  3129. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3130. texture._MSAAFramebuffer = null;
  3131. }
  3132. if (texture._MSAARenderBuffer) {
  3133. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3134. texture._MSAARenderBuffer = null;
  3135. }
  3136. if (samples > 1) {
  3137. let framebuffer = gl.createFramebuffer();
  3138. if (!framebuffer) {
  3139. throw new Error("Unable to create multi sampled framebuffer");
  3140. }
  3141. texture._MSAAFramebuffer = framebuffer;
  3142. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  3143. var colorRenderbuffer = gl.createRenderbuffer();
  3144. if (!colorRenderbuffer) {
  3145. throw new Error("Unable to create multi sampled framebuffer");
  3146. }
  3147. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3148. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3149. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  3150. texture._MSAARenderBuffer = colorRenderbuffer;
  3151. } else {
  3152. this.bindUnboundFramebuffer(texture._framebuffer);
  3153. }
  3154. texture.samples = samples;
  3155. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  3156. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3157. this.bindUnboundFramebuffer(null);
  3158. return samples;
  3159. }
  3160. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  3161. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  3162. return 1;
  3163. }
  3164. if (textures[0].samples === samples) {
  3165. return samples;
  3166. }
  3167. var gl = this._gl;
  3168. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3169. // Dispose previous render buffers
  3170. if (textures[0]._depthStencilBuffer) {
  3171. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  3172. textures[0]._depthStencilBuffer = null;
  3173. }
  3174. if (textures[0]._MSAAFramebuffer) {
  3175. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  3176. textures[0]._MSAAFramebuffer = null;
  3177. }
  3178. for (var i = 0; i < textures.length; i++) {
  3179. if (textures[i]._MSAARenderBuffer) {
  3180. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  3181. textures[i]._MSAARenderBuffer = null;
  3182. }
  3183. }
  3184. if (samples > 1) {
  3185. let framebuffer = gl.createFramebuffer();
  3186. if (!framebuffer) {
  3187. throw new Error("Unable to create multi sampled framebuffer");
  3188. }
  3189. this.bindUnboundFramebuffer(framebuffer);
  3190. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  3191. var attachments = [];
  3192. for (var i = 0; i < textures.length; i++) {
  3193. var texture = textures[i];
  3194. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3195. var colorRenderbuffer = gl.createRenderbuffer();
  3196. if (!colorRenderbuffer) {
  3197. throw new Error("Unable to create multi sampled framebuffer");
  3198. }
  3199. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3200. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3201. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  3202. texture._MSAAFramebuffer = framebuffer;
  3203. texture._MSAARenderBuffer = colorRenderbuffer;
  3204. texture.samples = samples;
  3205. texture._depthStencilBuffer = depthStencilBuffer;
  3206. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3207. attachments.push(attachment);
  3208. }
  3209. gl.drawBuffers(attachments);
  3210. } else {
  3211. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  3212. }
  3213. this.bindUnboundFramebuffer(null);
  3214. return samples;
  3215. }
  3216. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  3217. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  3218. }
  3219. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  3220. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  3221. }
  3222. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  3223. let fullOptions = {
  3224. generateMipMaps: true,
  3225. generateDepthBuffer: true,
  3226. generateStencilBuffer: false,
  3227. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3228. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  3229. ...options
  3230. };
  3231. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  3232. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3233. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3234. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3235. }
  3236. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3237. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3238. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3239. }
  3240. var gl = this._gl
  3241. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  3242. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3243. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  3244. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3245. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3246. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  3247. }
  3248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3252. for (var face = 0; face < 6; face++) {
  3253. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  3254. }
  3255. // Create the framebuffer
  3256. var framebuffer = gl.createFramebuffer();
  3257. this.bindUnboundFramebuffer(framebuffer);
  3258. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  3259. // MipMaps
  3260. if (fullOptions.generateMipMaps) {
  3261. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3262. }
  3263. // Unbind
  3264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3265. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3266. this.bindUnboundFramebuffer(null);
  3267. texture._framebuffer = framebuffer;
  3268. texture.width = size;
  3269. texture.height = size;
  3270. texture.isReady = true;
  3271. texture.isCube = true;
  3272. texture.samples = 1;
  3273. texture.generateMipMaps = fullOptions.generateMipMaps;
  3274. texture.samplingMode = fullOptions.samplingMode;
  3275. texture.type = fullOptions.type;
  3276. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  3277. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  3278. this._internalTexturesCache.push(texture);
  3279. return texture;
  3280. }
  3281. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  3282. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  3283. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3284. var callback = (loadData: any) => {
  3285. if (!loadData) {
  3286. if (onLoad) {
  3287. onLoad(null);
  3288. }
  3289. return;
  3290. }
  3291. let texture = loadData.texture as InternalTexture;
  3292. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  3293. texture._lodGenerationScale = scale;
  3294. texture._lodGenerationOffset = offset;
  3295. if (this._caps.textureLOD) {
  3296. // Do not add extra process if texture lod is supported.
  3297. if (onLoad) {
  3298. onLoad(texture);
  3299. }
  3300. return;
  3301. }
  3302. const mipSlices = 3;
  3303. var gl = this._gl;
  3304. const width = loadData.width;
  3305. if (!width) {
  3306. return;
  3307. }
  3308. const textures: BaseTexture[] = [];
  3309. for (let i = 0; i < mipSlices; i++) {
  3310. //compute LOD from even spacing in smoothness (matching shader calculation)
  3311. let smoothness = i / (mipSlices - 1);
  3312. let roughness = 1 - smoothness;
  3313. let minLODIndex = offset; // roughness = 0
  3314. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  3315. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  3316. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  3317. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3318. glTextureFromLod.isCube = true;
  3319. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  3320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3324. if (loadData.isDDS) {
  3325. var info: DDSInfo = loadData.info;
  3326. var data: any = loadData.data;
  3327. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3328. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  3329. }
  3330. else {
  3331. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  3332. }
  3333. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3334. // Wrap in a base texture for easy binding.
  3335. const lodTexture = new BaseTexture(scene);
  3336. lodTexture.isCube = true;
  3337. lodTexture._texture = glTextureFromLod;
  3338. glTextureFromLod.isReady = true;
  3339. textures.push(lodTexture);
  3340. }
  3341. texture._lodTextureHigh = textures[2];
  3342. texture._lodTextureMid = textures[1];
  3343. texture._lodTextureLow = textures[0];
  3344. if (onLoad) {
  3345. onLoad(texture);
  3346. }
  3347. };
  3348. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  3349. }
  3350. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3351. var gl = this._gl;
  3352. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  3353. texture.isCube = true;
  3354. texture.url = rootUrl;
  3355. texture.generateMipMaps = !noMipmap;
  3356. if (!this._doNotHandleContextLost) {
  3357. texture._extension = forcedExtension;
  3358. texture._files = files;
  3359. }
  3360. var isKTX = false;
  3361. var isDDS = false;
  3362. var lastDot = rootUrl.lastIndexOf('.');
  3363. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  3364. if (this._textureFormatInUse) {
  3365. extension = this._textureFormatInUse;
  3366. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  3367. isKTX = true;
  3368. } else {
  3369. isDDS = (extension === ".dds");
  3370. }
  3371. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  3372. if (onError && request) {
  3373. onError(request.status + " " + request.statusText, exception);
  3374. }
  3375. }
  3376. if (isKTX) {
  3377. this._loadFile(rootUrl, data => {
  3378. var ktx = new KhronosTextureContainer(data, 6);
  3379. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  3380. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3381. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3382. ktx.uploadLevels(this._gl, !noMipmap);
  3383. this.setCubeMapTextureParams(gl, loadMipmap);
  3384. texture.width = ktx.pixelWidth;
  3385. texture.height = ktx.pixelHeight;
  3386. texture.isReady = true;
  3387. }, undefined, undefined, true, onerror);
  3388. } else if (isDDS) {
  3389. if (files && files.length === 6) {
  3390. this._cascadeLoadFiles(rootUrl,
  3391. scene,
  3392. imgs => {
  3393. var info: DDSInfo | undefined;
  3394. var loadMipmap: boolean = false;
  3395. var width: number = 0;
  3396. for (let index = 0; index < imgs.length; index++) {
  3397. let data = imgs[index];
  3398. info = DDSTools.GetDDSInfo(data);
  3399. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3401. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3402. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  3403. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3404. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3405. }
  3406. texture.width = info.width;
  3407. texture.height = info.height;
  3408. texture.type = info.textureType;
  3409. width = info.width;
  3410. }
  3411. this.setCubeMapTextureParams(gl, loadMipmap);
  3412. texture.isReady = true;
  3413. if (onLoad) {
  3414. onLoad({ isDDS: true, width: width, info, imgs, texture });
  3415. }
  3416. },
  3417. files,
  3418. onError);
  3419. } else {
  3420. this._loadFile(rootUrl,
  3421. data => {
  3422. var info = DDSTools.GetDDSInfo(data);
  3423. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3424. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3426. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  3427. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3428. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3429. }
  3430. this.setCubeMapTextureParams(gl, loadMipmap);
  3431. texture.width = info.width;
  3432. texture.height = info.height;
  3433. texture.isReady = true;
  3434. texture.type = info.textureType;
  3435. if (onLoad) {
  3436. onLoad({ isDDS: true, width: info.width, info, data, texture });
  3437. }
  3438. },
  3439. undefined,
  3440. undefined,
  3441. true,
  3442. onerror);
  3443. }
  3444. } else {
  3445. if (!files) {
  3446. throw new Error("Cannot load cubemap because files were not defined");
  3447. }
  3448. cascadeLoadImgs(rootUrl, scene, imgs => {
  3449. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  3450. var height = width;
  3451. this._prepareWorkingCanvas();
  3452. if (!this._workingCanvas || !this._workingContext) {
  3453. return;
  3454. }
  3455. this._workingCanvas.width = width;
  3456. this._workingCanvas.height = height;
  3457. var faces = [
  3458. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3459. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3460. ];
  3461. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3462. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3463. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3464. for (var index = 0; index < faces.length; index++) {
  3465. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3466. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3467. }
  3468. if (!noMipmap) {
  3469. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3470. }
  3471. this.setCubeMapTextureParams(gl, !noMipmap);
  3472. texture.width = width;
  3473. texture.height = height;
  3474. texture.isReady = true;
  3475. if (format) {
  3476. texture.format = format;
  3477. }
  3478. texture.onLoadedObservable.notifyObservers(texture);
  3479. texture.onLoadedObservable.clear();
  3480. if (onLoad) {
  3481. onLoad();
  3482. }
  3483. }, files, onError);
  3484. }
  3485. this._internalTexturesCache.push(texture);
  3486. return texture;
  3487. }
  3488. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  3489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3493. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3494. // this.resetTextureCache();
  3495. }
  3496. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  3497. texture._bufferViewArray = data;
  3498. texture.format = format;
  3499. texture.type = type;
  3500. texture.invertY = invertY;
  3501. texture._compression = compression;
  3502. var gl = this._gl;
  3503. var textureType = this._getWebGLTextureType(type);
  3504. var internalFormat = this._getInternalFormat(format);
  3505. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3506. var needConversion = false;
  3507. if (internalFormat === gl.RGB) {
  3508. internalFormat = gl.RGBA;
  3509. needConversion = true;
  3510. }
  3511. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3512. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3513. if (texture.width % 4 !== 0) {
  3514. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3515. }
  3516. // Data are known to be in +X +Y +Z -X -Y -Z
  3517. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3518. let faceData = data[faceIndex];
  3519. if (compression) {
  3520. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, faceData);
  3521. } else {
  3522. if (needConversion) {
  3523. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3524. }
  3525. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3526. }
  3527. }
  3528. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3529. if (isPot && texture.generateMipMaps && level === 0) {
  3530. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3531. }
  3532. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3533. // this.resetTextureCache();
  3534. texture.isReady = true;
  3535. }
  3536. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3537. var gl = this._gl;
  3538. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3539. texture.isCube = true;
  3540. texture.generateMipMaps = generateMipMaps;
  3541. texture.format = format;
  3542. texture.type = type;
  3543. if (!this._doNotHandleContextLost) {
  3544. texture._bufferViewArray = data;
  3545. }
  3546. var textureType = this._getWebGLTextureType(type);
  3547. var internalFormat = this._getInternalFormat(format);
  3548. if (internalFormat === gl.RGB) {
  3549. internalFormat = gl.RGBA;
  3550. }
  3551. var width = size;
  3552. var height = width;
  3553. texture.width = width;
  3554. texture.height = height;
  3555. // Double check on POT to generate Mips.
  3556. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3557. if (!isPot) {
  3558. generateMipMaps = false;
  3559. }
  3560. // Upload data if needed. The texture won't be ready until then.
  3561. if (data) {
  3562. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3563. }
  3564. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3565. // Filters
  3566. if (data && generateMipMaps) {
  3567. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3568. }
  3569. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3572. }
  3573. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3576. }
  3577. else {
  3578. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3581. }
  3582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3584. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3585. return texture;
  3586. }
  3587. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3588. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  3589. mipmmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  3590. onLoad: Nullable<() => void> = null,
  3591. onError: Nullable<(message?: string, exception?: any) => void> = null,
  3592. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3593. invertY = false): InternalTexture {
  3594. var gl = this._gl;
  3595. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3596. scene._addPendingData(texture);
  3597. texture.url = url;
  3598. this._internalTexturesCache.push(texture);
  3599. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  3600. scene._removePendingData(texture);
  3601. if (onError && request) {
  3602. onError(request.status + " " + request.statusText, exception);
  3603. }
  3604. };
  3605. var internalCallback = (data: any) => {
  3606. var width = texture.width;
  3607. var faceDataArrays = callback(data);
  3608. if (!faceDataArrays) {
  3609. return;
  3610. }
  3611. if (mipmmapGenerator) {
  3612. var textureType = this._getWebGLTextureType(type);
  3613. var internalFormat = this._getInternalFormat(format);
  3614. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3615. var needConversion = false;
  3616. if (internalFormat === gl.RGB) {
  3617. internalFormat = gl.RGBA;
  3618. needConversion = true;
  3619. }
  3620. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3621. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3622. var mipData = mipmmapGenerator(faceDataArrays);
  3623. for (var level = 0; level < mipData.length; level++) {
  3624. var mipSize = width >> level;
  3625. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3626. let mipFaceData = mipData[level][faceIndex];
  3627. if (needConversion) {
  3628. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3629. }
  3630. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3631. }
  3632. }
  3633. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3634. }
  3635. else {
  3636. texture.generateMipMaps = !noMipmap;
  3637. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3638. }
  3639. texture.isReady = true;
  3640. // this.resetTextureCache();
  3641. scene._removePendingData(texture);
  3642. if (onLoad) {
  3643. onLoad();
  3644. }
  3645. };
  3646. this._loadFile(url, data => {
  3647. internalCallback(data);
  3648. }, undefined, scene.database, true, onerror);
  3649. return texture;
  3650. };
  3651. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  3652. var internalFormat = this._getInternalFormat(format);
  3653. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3654. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3655. if (!this._doNotHandleContextLost) {
  3656. texture._bufferView = data;
  3657. texture.format = format;
  3658. texture.invertY = invertY;
  3659. texture._compression = compression;
  3660. }
  3661. if (texture.width % 4 !== 0) {
  3662. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3663. }
  3664. if (compression && data) {
  3665. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  3666. } else {
  3667. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  3668. }
  3669. if (texture.generateMipMaps) {
  3670. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3671. }
  3672. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3673. // this.resetTextureCache();
  3674. texture.isReady = true;
  3675. }
  3676. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3677. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  3678. texture.baseWidth = width;
  3679. texture.baseHeight = height;
  3680. texture.baseDepth = depth;
  3681. texture.width = width;
  3682. texture.height = height;
  3683. texture.depth = depth;
  3684. texture.format = format;
  3685. texture.generateMipMaps = generateMipMaps;
  3686. texture.samplingMode = samplingMode;
  3687. texture.is3D = true;
  3688. if (!this._doNotHandleContextLost) {
  3689. texture._bufferView = data;
  3690. }
  3691. this.updateRawTexture3D(texture, data, format, invertY, compression);
  3692. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3693. // Filters
  3694. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3695. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3696. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3697. if (generateMipMaps) {
  3698. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3699. }
  3700. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3701. this._internalTexturesCache.push(texture);
  3702. return texture;
  3703. }
  3704. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3705. var gl = this._gl;
  3706. if (!gl) {
  3707. return;
  3708. }
  3709. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3712. if (!noMipmap && !isCompressed) {
  3713. gl.generateMipmap(gl.TEXTURE_2D);
  3714. }
  3715. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3716. // this.resetTextureCache();
  3717. if (scene) {
  3718. scene._removePendingData(texture);
  3719. }
  3720. texture.onLoadedObservable.notifyObservers(texture);
  3721. texture.onLoadedObservable.clear();
  3722. }
  3723. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3724. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3725. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3726. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3727. var gl = this._gl;
  3728. if (!gl) {
  3729. return;
  3730. }
  3731. if (!texture._webGLTexture) {
  3732. // this.resetTextureCache();
  3733. if (scene) {
  3734. scene._removePendingData(texture);
  3735. }
  3736. return;
  3737. }
  3738. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3740. texture.baseWidth = width;
  3741. texture.baseHeight = height;
  3742. texture.width = potWidth;
  3743. texture.height = potHeight;
  3744. texture.isReady = true;
  3745. if (processFunction(potWidth, potHeight, () => {
  3746. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3747. })) {
  3748. // Returning as texture needs extra async steps
  3749. return;
  3750. }
  3751. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3752. }
  3753. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  3754. // Create new RGBA data container.
  3755. var rgbaData: any;
  3756. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3757. rgbaData = new Float32Array(width * height * 4);
  3758. }
  3759. else {
  3760. rgbaData = new Uint32Array(width * height * 4);
  3761. }
  3762. // Convert each pixel.
  3763. for (let x = 0; x < width; x++) {
  3764. for (let y = 0; y < height; y++) {
  3765. let index = (y * width + x) * 3;
  3766. let newIndex = (y * width + x) * 4;
  3767. // Map Old Value to new value.
  3768. rgbaData[newIndex + 0] = rgbData[index + 0];
  3769. rgbaData[newIndex + 1] = rgbData[index + 1];
  3770. rgbaData[newIndex + 2] = rgbData[index + 2];
  3771. // Add fully opaque alpha channel.
  3772. rgbaData[newIndex + 3] = 1;
  3773. }
  3774. }
  3775. return rgbaData;
  3776. }
  3777. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3778. var gl = this._gl;
  3779. if (texture._framebuffer) {
  3780. gl.deleteFramebuffer(texture._framebuffer);
  3781. texture._framebuffer = null;
  3782. }
  3783. if (texture._depthStencilBuffer) {
  3784. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3785. texture._depthStencilBuffer = null;
  3786. }
  3787. if (texture._MSAAFramebuffer) {
  3788. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3789. texture._MSAAFramebuffer = null;
  3790. }
  3791. if (texture._MSAARenderBuffer) {
  3792. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3793. texture._MSAARenderBuffer = null;
  3794. }
  3795. }
  3796. public _releaseTexture(texture: InternalTexture): void {
  3797. var gl = this._gl;
  3798. this._releaseFramebufferObjects(texture);
  3799. gl.deleteTexture(texture._webGLTexture);
  3800. // Unbind channels
  3801. this.unbindAllTextures();
  3802. var index = this._internalTexturesCache.indexOf(texture);
  3803. if (index !== -1) {
  3804. this._internalTexturesCache.splice(index, 1);
  3805. }
  3806. // Integrated fixed lod samplers.
  3807. if (texture._lodTextureHigh) {
  3808. texture._lodTextureHigh.dispose();
  3809. }
  3810. if (texture._lodTextureMid) {
  3811. texture._lodTextureMid.dispose();
  3812. }
  3813. if (texture._lodTextureLow) {
  3814. texture._lodTextureLow.dispose();
  3815. }
  3816. }
  3817. private setProgram(program: WebGLProgram): void {
  3818. if (this._currentProgram !== program) {
  3819. this._gl.useProgram(program);
  3820. this._currentProgram = program;
  3821. }
  3822. }
  3823. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  3824. public bindSamplers(effect: Effect): void {
  3825. this.setProgram(effect.getProgram());
  3826. var samplers = effect.getSamplers();
  3827. for (var index = 0; index < samplers.length; index++) {
  3828. var uniform = effect.getUniform(samplers[index]);
  3829. if (uniform) {
  3830. this._boundUniforms[index] = uniform;
  3831. }
  3832. }
  3833. this._currentEffect = null;
  3834. }
  3835. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  3836. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  3837. return;
  3838. }
  3839. // Remove
  3840. this._linkTrackers(internalTexture.previous, internalTexture.next);
  3841. // Bind last to it
  3842. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  3843. // Bind to dummy
  3844. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  3845. }
  3846. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  3847. if (!internalTexture) {
  3848. return -1;
  3849. }
  3850. internalTexture._initialSlot = channel;
  3851. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  3852. if (channel !== internalTexture._designatedSlot) {
  3853. this._textureCollisions.addCount(1, false);
  3854. }
  3855. } else {
  3856. if (channel !== internalTexture._designatedSlot) {
  3857. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  3858. return internalTexture._designatedSlot;
  3859. } else {
  3860. // No slot for this texture, let's pick a new one (if we find a free slot)
  3861. if (this._nextFreeTextureSlots.length) {
  3862. return this._nextFreeTextureSlots[0];
  3863. }
  3864. // We need to recycle the oldest bound texture, sorry.
  3865. this._textureCollisions.addCount(1, false);
  3866. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  3867. }
  3868. }
  3869. }
  3870. return channel;
  3871. }
  3872. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  3873. previous!.next = next;
  3874. next!.previous = previous;
  3875. }
  3876. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  3877. let currentSlot = internalTexture._designatedSlot;
  3878. if (currentSlot === -1) {
  3879. return -1;
  3880. }
  3881. internalTexture._designatedSlot = -1;
  3882. if (this.disableTextureBindingOptimization) {
  3883. return -1;
  3884. }
  3885. // Remove from bound list
  3886. this._linkTrackers(internalTexture.previous, internalTexture.next);
  3887. // Free the slot
  3888. this._boundTexturesCache[currentSlot] = null;
  3889. this._nextFreeTextureSlots.push(currentSlot);
  3890. return currentSlot;
  3891. }
  3892. private _activateCurrentTexture() {
  3893. if (this._currentTextureChannel !== this._activeChannel) {
  3894. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  3895. this._currentTextureChannel = this._activeChannel;
  3896. }
  3897. }
  3898. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false): void {
  3899. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  3900. this._activeChannel = texture._designatedSlot;
  3901. }
  3902. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  3903. let isTextureForRendering = texture && texture._initialSlot > -1;
  3904. if (currentTextureBound !== texture) {
  3905. if (currentTextureBound) {
  3906. this._removeDesignatedSlot(currentTextureBound);
  3907. }
  3908. this._activateCurrentTexture();
  3909. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3910. this._boundTexturesCache[this._activeChannel] = texture;
  3911. if (texture) {
  3912. if (!this.disableTextureBindingOptimization) {
  3913. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  3914. if (slotIndex > -1) {
  3915. this._nextFreeTextureSlots.splice(slotIndex, 1);
  3916. }
  3917. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  3918. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  3919. }
  3920. texture._designatedSlot = this._activeChannel;
  3921. }
  3922. } else if (forTextureDataUpdate) {
  3923. this._activateCurrentTexture();
  3924. }
  3925. if (isTextureForRendering && !forTextureDataUpdate) {
  3926. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  3927. }
  3928. }
  3929. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  3930. if (channel < 0) {
  3931. return;
  3932. }
  3933. if (texture) {
  3934. channel = this._getCorrectTextureChannel(channel, texture);
  3935. }
  3936. this._activeChannel = channel;
  3937. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3938. }
  3939. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  3940. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  3941. }
  3942. public unbindAllTextures(): void {
  3943. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  3944. this._activeChannel = channel;
  3945. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3946. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3947. if (this.webGLVersion > 1) {
  3948. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3949. }
  3950. }
  3951. }
  3952. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  3953. if (channel < 0) {
  3954. return;
  3955. }
  3956. if (uniform) {
  3957. this._boundUniforms[channel] = uniform;
  3958. }
  3959. this._setTexture(channel, texture);
  3960. }
  3961. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  3962. let uniform = this._boundUniforms[sourceSlot];
  3963. if (uniform._currentState === destination) {
  3964. return;
  3965. }
  3966. this._gl.uniform1i(uniform, destination);
  3967. uniform._currentState = destination;
  3968. }
  3969. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false): boolean {
  3970. // Not ready?
  3971. if (!texture) {
  3972. if (this._boundTexturesCache[channel] != null) {
  3973. this._activeChannel = channel;
  3974. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3975. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3976. if (this.webGLVersion > 1) {
  3977. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3978. }
  3979. }
  3980. return false;
  3981. }
  3982. // Video
  3983. if ((<VideoTexture>texture).video) {
  3984. this._activeChannel = channel;
  3985. (<VideoTexture>texture).update();
  3986. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3987. texture.delayLoad();
  3988. return false;
  3989. }
  3990. let internalTexture: InternalTexture;
  3991. if (texture.isReady()) {
  3992. internalTexture = <InternalTexture>texture.getInternalTexture();
  3993. }
  3994. else if (texture.isCube) {
  3995. internalTexture = this.emptyCubeTexture;
  3996. }
  3997. else if (texture.is3D) {
  3998. internalTexture = this.emptyTexture3D;
  3999. }
  4000. else {
  4001. internalTexture = this.emptyTexture;
  4002. }
  4003. if (!isPartOfTextureArray) {
  4004. channel = this._getCorrectTextureChannel(channel, internalTexture);
  4005. }
  4006. if (this._boundTexturesCache[channel] === internalTexture) {
  4007. this._moveBoundTextureOnTop(internalTexture);
  4008. if (!isPartOfTextureArray) {
  4009. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  4010. }
  4011. return false;
  4012. }
  4013. this._activeChannel = channel;
  4014. if (internalTexture && internalTexture.is3D) {
  4015. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  4016. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4017. internalTexture._cachedWrapU = texture.wrapU;
  4018. switch (texture.wrapU) {
  4019. case Texture.WRAP_ADDRESSMODE:
  4020. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4021. break;
  4022. case Texture.CLAMP_ADDRESSMODE:
  4023. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4024. break;
  4025. case Texture.MIRROR_ADDRESSMODE:
  4026. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4027. break;
  4028. }
  4029. }
  4030. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4031. internalTexture._cachedWrapV = texture.wrapV;
  4032. switch (texture.wrapV) {
  4033. case Texture.WRAP_ADDRESSMODE:
  4034. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4035. break;
  4036. case Texture.CLAMP_ADDRESSMODE:
  4037. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4038. break;
  4039. case Texture.MIRROR_ADDRESSMODE:
  4040. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4041. break;
  4042. }
  4043. }
  4044. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  4045. internalTexture._cachedWrapR = texture.wrapR;
  4046. switch (texture.wrapR) {
  4047. case Texture.WRAP_ADDRESSMODE:
  4048. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  4049. break;
  4050. case Texture.CLAMP_ADDRESSMODE:
  4051. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  4052. break;
  4053. case Texture.MIRROR_ADDRESSMODE:
  4054. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  4055. break;
  4056. }
  4057. }
  4058. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  4059. }
  4060. else if (internalTexture && internalTexture.isCube) {
  4061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  4062. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4063. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4064. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4065. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4066. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4067. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4068. }
  4069. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4070. } else {
  4071. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  4072. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4073. internalTexture._cachedWrapU = texture.wrapU;
  4074. switch (texture.wrapU) {
  4075. case Texture.WRAP_ADDRESSMODE:
  4076. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4077. break;
  4078. case Texture.CLAMP_ADDRESSMODE:
  4079. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4080. break;
  4081. case Texture.MIRROR_ADDRESSMODE:
  4082. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4083. break;
  4084. }
  4085. }
  4086. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4087. internalTexture._cachedWrapV = texture.wrapV;
  4088. switch (texture.wrapV) {
  4089. case Texture.WRAP_ADDRESSMODE:
  4090. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4091. break;
  4092. case Texture.CLAMP_ADDRESSMODE:
  4093. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4094. break;
  4095. case Texture.MIRROR_ADDRESSMODE:
  4096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4097. break;
  4098. }
  4099. }
  4100. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4101. }
  4102. return true;
  4103. }
  4104. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  4105. if (channel < 0 || !uniform) {
  4106. return;
  4107. }
  4108. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  4109. this._textureUnits = new Int32Array(textures.length);
  4110. }
  4111. for (let i = 0; i < textures.length; i++) {
  4112. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  4113. }
  4114. this._gl.uniform1iv(uniform, this._textureUnits);
  4115. for (var index = 0; index < textures.length; index++) {
  4116. this._setTexture(this._textureUnits[index], textures[index], true);
  4117. }
  4118. }
  4119. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  4120. var internalTexture = texture.getInternalTexture();
  4121. if (!internalTexture) {
  4122. return;
  4123. }
  4124. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4125. var value = texture.anisotropicFilteringLevel;
  4126. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  4127. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  4128. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  4129. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  4130. }
  4131. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  4132. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  4133. internalTexture._cachedAnisotropicFilteringLevel = value;
  4134. }
  4135. }
  4136. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  4137. var data = new Uint8Array(height * width * 4);
  4138. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4139. return data;
  4140. }
  4141. /**
  4142. * Add an externaly attached data from its key.
  4143. * This method call will fail and return false, if such key already exists.
  4144. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4145. * @param key the unique key that identifies the data
  4146. * @param data the data object to associate to the key for this Engine instance
  4147. * @return true if no such key were already present and the data was added successfully, false otherwise
  4148. */
  4149. public addExternalData<T>(key: string, data: T): boolean {
  4150. if (!this._externalData) {
  4151. this._externalData = new StringDictionary<Object>();
  4152. }
  4153. return this._externalData.add(key, data);
  4154. }
  4155. /**
  4156. * Get an externaly attached data from its key
  4157. * @param key the unique key that identifies the data
  4158. * @return the associated data, if present (can be null), or undefined if not present
  4159. */
  4160. public getExternalData<T>(key: string): T {
  4161. if (!this._externalData) {
  4162. this._externalData = new StringDictionary<Object>();
  4163. }
  4164. return <T>this._externalData.get(key);
  4165. }
  4166. /**
  4167. * Get an externaly attached data from its key, create it using a factory if it's not already present
  4168. * @param key the unique key that identifies the data
  4169. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4170. * @return the associated data, can be null if the factory returned null.
  4171. */
  4172. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  4173. if (!this._externalData) {
  4174. this._externalData = new StringDictionary<Object>();
  4175. }
  4176. return <T>this._externalData.getOrAddWithFactory(key, factory);
  4177. }
  4178. /**
  4179. * Remove an externaly attached data from the Engine instance
  4180. * @param key the unique key that identifies the data
  4181. * @return true if the data was successfully removed, false if it doesn't exist
  4182. */
  4183. public removeExternalData(key: string): boolean {
  4184. if (!this._externalData) {
  4185. this._externalData = new StringDictionary<Object>();
  4186. }
  4187. return this._externalData.remove(key);
  4188. }
  4189. public unbindAllAttributes() {
  4190. if (this._mustWipeVertexAttributes) {
  4191. this._mustWipeVertexAttributes = false;
  4192. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  4193. this._gl.disableVertexAttribArray(i);
  4194. this._vertexAttribArraysEnabled[i] = false;
  4195. this._currentBufferPointers[i].active = false;
  4196. }
  4197. return;
  4198. }
  4199. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  4200. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  4201. continue;
  4202. }
  4203. this._gl.disableVertexAttribArray(i);
  4204. this._vertexAttribArraysEnabled[i] = false;
  4205. this._currentBufferPointers[i].active = false;
  4206. }
  4207. }
  4208. public releaseEffects() {
  4209. for (var name in this._compiledEffects) {
  4210. this._deleteProgram(this._compiledEffects[name]._program)
  4211. }
  4212. this._compiledEffects = {};
  4213. }
  4214. // Dispose
  4215. public dispose(): void {
  4216. this.hideLoadingUI();
  4217. this.stopRenderLoop();
  4218. // Release postProcesses
  4219. while (this.postProcesses.length) {
  4220. this.postProcesses[0].dispose();
  4221. }
  4222. // Empty texture
  4223. if (this._emptyTexture) {
  4224. this._releaseTexture(this._emptyTexture);
  4225. this._emptyTexture = null;
  4226. }
  4227. if (this._emptyCubeTexture) {
  4228. this._releaseTexture(this._emptyCubeTexture);
  4229. this._emptyCubeTexture = null;
  4230. }
  4231. // Rescale PP
  4232. if (this._rescalePostProcess) {
  4233. this._rescalePostProcess.dispose();
  4234. }
  4235. // Release scenes
  4236. while (this.scenes.length) {
  4237. this.scenes[0].dispose();
  4238. }
  4239. // Release audio engine
  4240. if (Engine.audioEngine) {
  4241. Engine.audioEngine.dispose();
  4242. }
  4243. // Release effects
  4244. this.releaseEffects();
  4245. // Unbind
  4246. this.unbindAllAttributes();
  4247. if (this._dummyFramebuffer) {
  4248. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  4249. }
  4250. //WebVR
  4251. this.disableVR();
  4252. // Events
  4253. if (Tools.IsWindowObjectExist()) {
  4254. window.removeEventListener("blur", this._onBlur);
  4255. window.removeEventListener("focus", this._onFocus);
  4256. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  4257. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  4258. if (this._renderingCanvas) {
  4259. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  4260. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  4261. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  4262. if (!this._doNotHandleContextLost) {
  4263. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  4264. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  4265. }
  4266. }
  4267. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4268. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4269. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4270. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4271. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4272. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4273. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4274. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4275. if (this._onVrDisplayConnect) {
  4276. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  4277. if (this._onVrDisplayDisconnect) {
  4278. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  4279. }
  4280. if (this._onVrDisplayPresentChange) {
  4281. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  4282. }
  4283. this._onVrDisplayConnect = null;
  4284. this._onVrDisplayDisconnect = null;
  4285. }
  4286. }
  4287. // Remove from Instances
  4288. var index = Engine.Instances.indexOf(this);
  4289. if (index >= 0) {
  4290. Engine.Instances.splice(index, 1);
  4291. }
  4292. this._workingCanvas = null;
  4293. this._workingContext = null;
  4294. this._currentBufferPointers = [];
  4295. this._renderingCanvas = null;
  4296. this._currentProgram = null;
  4297. this.onResizeObservable.clear();
  4298. this.onCanvasBlurObservable.clear();
  4299. this.onCanvasFocusObservable.clear();
  4300. this.onCanvasPointerOutObservable.clear();
  4301. this.onBeginFrameObservable.clear();
  4302. this.onEndFrameObservable.clear();
  4303. Effect.ResetCache();
  4304. // Abort active requests
  4305. for (let request of this._activeRequests) {
  4306. request.abort();
  4307. }
  4308. }
  4309. // Loading screen
  4310. public displayLoadingUI(): void {
  4311. if (!Tools.IsWindowObjectExist()) {
  4312. return;
  4313. }
  4314. const loadingScreen = this.loadingScreen;
  4315. if (loadingScreen) {
  4316. loadingScreen.displayLoadingUI();
  4317. }
  4318. }
  4319. public hideLoadingUI(): void {
  4320. if (!Tools.IsWindowObjectExist()) {
  4321. return;
  4322. }
  4323. const loadingScreen = this.loadingScreen;
  4324. if (loadingScreen) {
  4325. loadingScreen.hideLoadingUI();
  4326. }
  4327. }
  4328. public get loadingScreen(): ILoadingScreen {
  4329. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  4330. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  4331. return this._loadingScreen;
  4332. }
  4333. public set loadingScreen(loadingScreen: ILoadingScreen) {
  4334. this._loadingScreen = loadingScreen;
  4335. }
  4336. public set loadingUIText(text: string) {
  4337. this.loadingScreen.loadingUIText = text;
  4338. }
  4339. public set loadingUIBackgroundColor(color: string) {
  4340. this.loadingScreen.loadingUIBackgroundColor = color;
  4341. }
  4342. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4343. if (this._renderingCanvas) {
  4344. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  4345. }
  4346. }
  4347. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4348. if (this._renderingCanvas) {
  4349. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  4350. }
  4351. }
  4352. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  4353. var shaders = this._gl.getAttachedShaders(program);
  4354. if (!shaders) {
  4355. return null;
  4356. }
  4357. return this._gl.getShaderSource(shaders[0]);
  4358. }
  4359. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  4360. var shaders = this._gl.getAttachedShaders(program);
  4361. if (!shaders) {
  4362. return null;
  4363. }
  4364. return this._gl.getShaderSource(shaders[1]);
  4365. }
  4366. public getError(): number {
  4367. return this._gl.getError();
  4368. }
  4369. // FPS
  4370. public getFps(): number {
  4371. return this._fps;
  4372. }
  4373. public getDeltaTime(): number {
  4374. return this._deltaTime;
  4375. }
  4376. private _measureFps(): void {
  4377. this._performanceMonitor.sampleFrame();
  4378. this._fps = this._performanceMonitor.averageFPS;
  4379. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  4380. }
  4381. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  4382. let gl = this._gl;
  4383. if (!this._dummyFramebuffer) {
  4384. let dummy = gl.createFramebuffer();
  4385. if (!dummy) {
  4386. throw new Error("Unable to create dummy framebuffer");
  4387. }
  4388. this._dummyFramebuffer = dummy;
  4389. }
  4390. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  4391. if (faceIndex > -1) {
  4392. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  4393. } else {
  4394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4395. }
  4396. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  4397. let buffer: ArrayBufferView;
  4398. switch (readType) {
  4399. case gl.UNSIGNED_BYTE:
  4400. buffer = new Uint8Array(4 * width * height);
  4401. readType = gl.UNSIGNED_BYTE;
  4402. break;
  4403. default:
  4404. buffer = new Float32Array(4 * width * height);
  4405. readType = gl.FLOAT;
  4406. break;
  4407. }
  4408. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  4409. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  4410. return buffer;
  4411. }
  4412. private _canRenderToFloatFramebuffer(): boolean {
  4413. if (this._webGLVersion > 1) {
  4414. return this._caps.colorBufferFloat;
  4415. }
  4416. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  4417. }
  4418. private _canRenderToHalfFloatFramebuffer(): boolean {
  4419. if (this._webGLVersion > 1) {
  4420. return this._caps.colorBufferFloat;
  4421. }
  4422. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  4423. }
  4424. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  4425. private _canRenderToFramebuffer(type: number): boolean {
  4426. let gl = this._gl;
  4427. //clear existing errors
  4428. while (gl.getError() !== gl.NO_ERROR) { }
  4429. let successful = true;
  4430. let texture = gl.createTexture();
  4431. gl.bindTexture(gl.TEXTURE_2D, texture);
  4432. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4435. let fb = gl.createFramebuffer();
  4436. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  4437. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4438. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  4439. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  4440. successful = successful && (gl.getError() === gl.NO_ERROR);
  4441. //try render by clearing frame buffer's color buffer
  4442. if (successful) {
  4443. gl.clear(gl.COLOR_BUFFER_BIT);
  4444. successful = successful && (gl.getError() === gl.NO_ERROR);
  4445. }
  4446. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  4447. if (successful) {
  4448. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  4449. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4450. let readFormat = gl.RGBA;
  4451. let readType = gl.UNSIGNED_BYTE;
  4452. let buffer = new Uint8Array(4);
  4453. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  4454. successful = successful && (gl.getError() === gl.NO_ERROR);
  4455. }
  4456. //clean up
  4457. gl.deleteTexture(texture);
  4458. gl.deleteFramebuffer(fb);
  4459. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4460. //clear accumulated errors
  4461. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  4462. return successful;
  4463. }
  4464. public _getWebGLTextureType(type: number): number {
  4465. if (type === Engine.TEXTURETYPE_FLOAT) {
  4466. return this._gl.FLOAT;
  4467. }
  4468. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4469. // Add Half Float Constant.
  4470. return this._gl.HALF_FLOAT_OES;
  4471. }
  4472. return this._gl.UNSIGNED_BYTE;
  4473. };
  4474. public _getRGBABufferInternalSizedFormat(type: number): number {
  4475. if (this._webGLVersion === 1) {
  4476. return this._gl.RGBA;
  4477. }
  4478. if (type === Engine.TEXTURETYPE_FLOAT) {
  4479. return this._gl.RGBA32F;
  4480. }
  4481. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4482. return this._gl.RGBA16F;
  4483. }
  4484. return this._gl.RGBA;
  4485. };
  4486. public _getRGBAMultiSampleBufferFormat(type: number): number {
  4487. if (type === Engine.TEXTURETYPE_FLOAT) {
  4488. return this._gl.RGBA32F;
  4489. }
  4490. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4491. return this._gl.RGBA16F;
  4492. }
  4493. return this._gl.RGBA8;
  4494. };
  4495. public createQuery(): WebGLQuery {
  4496. return this._gl.createQuery();
  4497. }
  4498. public deleteQuery(query: WebGLQuery): Engine {
  4499. this._gl.deleteQuery(query);
  4500. return this;
  4501. }
  4502. public isQueryResultAvailable(query: WebGLQuery): boolean {
  4503. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  4504. }
  4505. public getQueryResult(query: WebGLQuery): number {
  4506. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  4507. }
  4508. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  4509. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4510. this._gl.beginQuery(glAlgorithm, query);
  4511. return this;
  4512. }
  4513. public endOcclusionQuery(algorithmType: number): Engine {
  4514. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4515. this._gl.endQuery(glAlgorithm);
  4516. return this;
  4517. }
  4518. /* Time queries */
  4519. private _createTimeQuery(): WebGLQuery {
  4520. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4521. if (timerQuery.createQueryEXT) {
  4522. return timerQuery.createQueryEXT();
  4523. }
  4524. return this.createQuery();
  4525. }
  4526. private _deleteTimeQuery(query: WebGLQuery): void {
  4527. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4528. if (timerQuery.deleteQueryEXT) {
  4529. timerQuery.deleteQueryEXT(query);
  4530. return;
  4531. }
  4532. this.deleteQuery(query);
  4533. }
  4534. private _getTimeQueryResult(query: WebGLQuery): any {
  4535. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4536. if (timerQuery.getQueryObjectEXT) {
  4537. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  4538. }
  4539. return this.getQueryResult(query);
  4540. }
  4541. private _getTimeQueryAvailability(query: WebGLQuery): any {
  4542. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4543. if (timerQuery.getQueryObjectEXT) {
  4544. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  4545. }
  4546. return this.isQueryResultAvailable(query);
  4547. }
  4548. private _currentNonTimestampToken: Nullable<_TimeToken>;
  4549. public startTimeQuery(): Nullable<_TimeToken> {
  4550. let timerQuery = this._caps.timerQuery;
  4551. if (!timerQuery) {
  4552. return null;
  4553. }
  4554. let token = new _TimeToken();
  4555. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4556. if (this._caps.canUseTimestampForTimerQuery) {
  4557. token._startTimeQuery = this._createTimeQuery();
  4558. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  4559. } else {
  4560. if (this._currentNonTimestampToken) {
  4561. return this._currentNonTimestampToken;
  4562. }
  4563. token._timeElapsedQuery = this._createTimeQuery();
  4564. if (timerQuery.beginQueryEXT) {
  4565. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4566. } else {
  4567. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4568. }
  4569. this._currentNonTimestampToken = token;
  4570. }
  4571. return token;
  4572. }
  4573. public endTimeQuery(token: _TimeToken): int {
  4574. let timerQuery = this._caps.timerQuery;
  4575. if (!timerQuery || !token) {
  4576. return -1;
  4577. }
  4578. if (this._caps.canUseTimestampForTimerQuery) {
  4579. if (!token._startTimeQuery) {
  4580. return -1;
  4581. }
  4582. if (!token._endTimeQuery) {
  4583. token._endTimeQuery = this._createTimeQuery();
  4584. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  4585. }
  4586. } else if (!token._timeElapsedQueryEnded) {
  4587. if (!token._timeElapsedQuery) {
  4588. return -1;
  4589. }
  4590. if (timerQuery.endQueryEXT) {
  4591. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  4592. } else {
  4593. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  4594. }
  4595. token._timeElapsedQueryEnded = true;
  4596. }
  4597. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4598. let available: boolean = false;
  4599. if (token._endTimeQuery) {
  4600. available = this._getTimeQueryAvailability(token._endTimeQuery);
  4601. } else if (token._timeElapsedQuery) {
  4602. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  4603. }
  4604. if (available && !disjoint) {
  4605. let result = 0;
  4606. if (this._caps.canUseTimestampForTimerQuery) {
  4607. if (!token._startTimeQuery || !token._endTimeQuery) {
  4608. return -1;
  4609. }
  4610. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  4611. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  4612. result = timeEnd - timeStart;
  4613. this._deleteTimeQuery(token._startTimeQuery);
  4614. this._deleteTimeQuery(token._endTimeQuery);
  4615. token._startTimeQuery = null;
  4616. token._endTimeQuery = null;
  4617. } else {
  4618. if (!token._timeElapsedQuery) {
  4619. return -1;
  4620. }
  4621. result = this._getTimeQueryResult(token._timeElapsedQuery);
  4622. this._deleteTimeQuery(token._timeElapsedQuery);
  4623. token._timeElapsedQuery = null;
  4624. token._timeElapsedQueryEnded = false;
  4625. this._currentNonTimestampToken = null;
  4626. }
  4627. return result;
  4628. }
  4629. return -1;
  4630. }
  4631. private getGlAlgorithmType(algorithmType: number): number {
  4632. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  4633. }
  4634. // Transform feedback
  4635. public createTransformFeedback(): WebGLTransformFeedback {
  4636. return this._gl.createTransformFeedback();
  4637. }
  4638. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  4639. this._gl.deleteTransformFeedback(value);
  4640. }
  4641. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  4642. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  4643. }
  4644. public beginTransformFeedback(usePoints: boolean = true): void {
  4645. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  4646. }
  4647. public endTransformFeedback(): void {
  4648. this._gl.endTransformFeedback();
  4649. }
  4650. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  4651. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  4652. }
  4653. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  4654. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  4655. }
  4656. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  4657. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  4658. this._activeRequests.push(request);
  4659. request.onCompleteObservable.add(request => {
  4660. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4661. });
  4662. return request;
  4663. }
  4664. /** @ignore */
  4665. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4666. return new Promise((resolve, reject) => {
  4667. this._loadFile(url, (data) => {
  4668. resolve(data);
  4669. }, undefined, database, useArrayBuffer, (request, exception) => {
  4670. reject(exception);
  4671. })
  4672. });
  4673. }
  4674. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  4675. var onload = (data: string | ArrayBuffer) => {
  4676. loadedFiles[index] = data;
  4677. (<any>loadedFiles)._internalCount++;
  4678. if ((<any>loadedFiles)._internalCount === 6) {
  4679. onfinish(loadedFiles);
  4680. }
  4681. };
  4682. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  4683. if (onErrorCallBack && request) {
  4684. onErrorCallBack(request.status + " " + request.statusText, exception);
  4685. }
  4686. };
  4687. this._loadFile(url, onload, undefined, undefined, true, onerror);
  4688. }
  4689. private _cascadeLoadFiles(rootUrl: string, scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  4690. var loadedFiles: (string | ArrayBuffer)[] = [];
  4691. (<any>loadedFiles)._internalCount = 0;
  4692. for (let index = 0; index < 6; index++) {
  4693. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  4694. }
  4695. }
  4696. // Statics
  4697. public static isSupported(): boolean {
  4698. try {
  4699. var tempcanvas = document.createElement("canvas");
  4700. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4701. return gl != null && !!window.WebGLRenderingContext;
  4702. } catch (e) {
  4703. return false;
  4704. }
  4705. }
  4706. }
  4707. }