babylon.engine.ts 232 KB

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