babylon.engine.ts 225 KB

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