babylon.engine.ts 218 KB

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