renderer_gl.cpp 184 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. namespace bgfx { namespace gl
  11. {
  12. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  13. struct PrimInfo
  14. {
  15. GLenum m_type;
  16. uint32_t m_min;
  17. uint32_t m_div;
  18. uint32_t m_sub;
  19. };
  20. static const PrimInfo s_primInfo[] =
  21. {
  22. { GL_TRIANGLES, 3, 3, 0 },
  23. { GL_TRIANGLE_STRIP, 3, 1, 2 },
  24. { GL_LINES, 2, 2, 0 },
  25. { GL_LINE_STRIP, 2, 1, 1 },
  26. { GL_POINTS, 1, 1, 0 },
  27. };
  28. static const char* s_primName[] =
  29. {
  30. "TriList",
  31. "TriStrip",
  32. "Line",
  33. "LineStrip",
  34. "Point",
  35. };
  36. static const char* s_attribName[] =
  37. {
  38. "a_position",
  39. "a_normal",
  40. "a_tangent",
  41. "a_bitangent",
  42. "a_color0",
  43. "a_color1",
  44. "a_indices",
  45. "a_weight",
  46. "a_texcoord0",
  47. "a_texcoord1",
  48. "a_texcoord2",
  49. "a_texcoord3",
  50. "a_texcoord4",
  51. "a_texcoord5",
  52. "a_texcoord6",
  53. "a_texcoord7",
  54. };
  55. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  56. static const char* s_instanceDataName[] =
  57. {
  58. "i_data0",
  59. "i_data1",
  60. "i_data2",
  61. "i_data3",
  62. "i_data4",
  63. };
  64. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  65. static const GLenum s_access[] =
  66. {
  67. GL_READ_ONLY,
  68. GL_WRITE_ONLY,
  69. GL_READ_WRITE,
  70. };
  71. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  72. static const GLenum s_attribType[] =
  73. {
  74. GL_UNSIGNED_BYTE, // Uint8
  75. GL_UNSIGNED_INT_10_10_10_2, // Uint10
  76. GL_SHORT, // Int16
  77. GL_HALF_FLOAT, // Half
  78. GL_FLOAT, // Float
  79. };
  80. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  81. struct Blend
  82. {
  83. GLenum m_src;
  84. GLenum m_dst;
  85. bool m_factor;
  86. };
  87. static const Blend s_blendFactor[] =
  88. {
  89. { 0, 0, false }, // ignored
  90. { GL_ZERO, GL_ZERO, false }, // ZERO
  91. { GL_ONE, GL_ONE, false }, // ONE
  92. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  93. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  94. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  95. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  96. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  97. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  98. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  99. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  100. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  101. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  102. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  103. };
  104. static const GLenum s_blendEquation[] =
  105. {
  106. GL_FUNC_ADD,
  107. GL_FUNC_SUBTRACT,
  108. GL_FUNC_REVERSE_SUBTRACT,
  109. GL_MIN,
  110. GL_MAX,
  111. };
  112. static const GLenum s_cmpFunc[] =
  113. {
  114. 0, // ignored
  115. GL_LESS,
  116. GL_LEQUAL,
  117. GL_EQUAL,
  118. GL_GEQUAL,
  119. GL_GREATER,
  120. GL_NOTEQUAL,
  121. GL_NEVER,
  122. GL_ALWAYS,
  123. };
  124. static const GLenum s_stencilOp[] =
  125. {
  126. GL_ZERO,
  127. GL_KEEP,
  128. GL_REPLACE,
  129. GL_INCR_WRAP,
  130. GL_INCR,
  131. GL_DECR_WRAP,
  132. GL_DECR,
  133. GL_INVERT,
  134. };
  135. static const GLenum s_stencilFace[] =
  136. {
  137. GL_FRONT_AND_BACK,
  138. GL_FRONT,
  139. GL_BACK,
  140. };
  141. static const GLenum s_textureAddress[] =
  142. {
  143. GL_REPEAT,
  144. GL_MIRRORED_REPEAT,
  145. GL_CLAMP_TO_EDGE,
  146. };
  147. static const GLenum s_textureFilterMag[] =
  148. {
  149. GL_LINEAR,
  150. GL_NEAREST,
  151. GL_LINEAR,
  152. };
  153. static const GLenum s_textureFilterMin[][3] =
  154. {
  155. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  156. { GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_NEAREST },
  157. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  158. };
  159. struct TextureFormatInfo
  160. {
  161. GLenum m_internalFmt;
  162. GLenum m_internalFmtSrgb;
  163. GLenum m_fmt;
  164. GLenum m_type;
  165. bool m_supported;
  166. };
  167. static TextureFormatInfo s_textureFormat[] =
  168. {
  169. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  170. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  171. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  172. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  173. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  174. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  175. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  176. { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  177. { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  178. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  179. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  180. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  181. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  182. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  183. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  184. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  185. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  186. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown
  187. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1
  188. { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8
  189. { GL_R8_SNORM, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S
  190. { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16
  191. { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F
  192. { GL_R16_SNORM, GL_ZERO, GL_RED, GL_SHORT, false }, // R16S
  193. { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32
  194. { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F
  195. { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8
  196. { GL_RG8_SNORM, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8S
  197. { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  198. { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F
  199. { GL_RG16_SNORM, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16S
  200. { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32
  201. { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F
  202. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8
  203. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8
  204. { GL_RGBA8_SNORM, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8S
  205. { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16
  206. { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F
  207. { GL_RGBA16_SNORM, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16S
  208. { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32
  209. { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F
  210. { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5
  211. { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, false }, // RGBA4
  212. { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, false }, // RGB5A1
  213. { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2
  214. { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // R11G11B10F
  215. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth
  216. { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  217. { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  218. { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  219. { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  220. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  221. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  222. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  223. { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  224. };
  225. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  226. static bool s_textureFilter[TextureFormat::Count+1];
  227. static GLenum s_rboFormat[] =
  228. {
  229. GL_ZERO, // BC1
  230. GL_ZERO, // BC2
  231. GL_ZERO, // BC3
  232. GL_ZERO, // BC4
  233. GL_ZERO, // BC5
  234. GL_ZERO, // BC6H
  235. GL_ZERO, // BC7
  236. GL_ZERO, // ETC1
  237. GL_ZERO, // ETC2
  238. GL_ZERO, // ETC2A
  239. GL_ZERO, // ETC2A1
  240. GL_ZERO, // PTC12
  241. GL_ZERO, // PTC14
  242. GL_ZERO, // PTC12A
  243. GL_ZERO, // PTC14A
  244. GL_ZERO, // PTC22
  245. GL_ZERO, // PTC24
  246. GL_ZERO, // Unknown
  247. GL_ZERO, // R1
  248. GL_R8, // R8
  249. GL_R8_SNORM, // R8S
  250. GL_R16, // R16
  251. GL_R16F, // R16F
  252. GL_R16_SNORM, // R16S
  253. GL_R32UI, // R32
  254. GL_R32F, // R32F
  255. GL_RG8, // RG8
  256. GL_RG8_SNORM, // RG8S
  257. GL_RG16, // RG16
  258. GL_RG16F, // RG16F
  259. GL_RG16_SNORM, // RG16S
  260. GL_RG32UI, // RG32
  261. GL_RG32F, // RG32F
  262. GL_RGBA8, // BGRA8
  263. GL_RGBA8, // RGBA8
  264. GL_RGBA8_SNORM, // RGBA8S
  265. GL_RGBA16, // RGBA16
  266. GL_RGBA16F, // RGBA16F
  267. GL_RGBA16_SNORM, // RGBA16S
  268. GL_RGBA32UI, // RGBA32
  269. GL_RGBA32F, // RGBA32F
  270. GL_RGB565, // R5G6B5
  271. GL_RGBA4, // RGBA4
  272. GL_RGB5_A1, // RGB5A1
  273. GL_RGB10_A2, // RGB10A2
  274. GL_R11F_G11F_B10F, // R11G11B10F
  275. GL_ZERO, // UnknownDepth
  276. GL_DEPTH_COMPONENT16, // D16
  277. GL_DEPTH_COMPONENT24, // D24
  278. GL_DEPTH24_STENCIL8, // D24S8
  279. GL_DEPTH_COMPONENT32, // D32
  280. GL_DEPTH_COMPONENT32F, // D16F
  281. GL_DEPTH_COMPONENT32F, // D24F
  282. GL_DEPTH_COMPONENT32F, // D32F
  283. GL_STENCIL_INDEX8, // D0S8
  284. };
  285. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  286. static GLenum s_imageFormat[] =
  287. {
  288. GL_ZERO, // BC1
  289. GL_ZERO, // BC2
  290. GL_ZERO, // BC3
  291. GL_ZERO, // BC4
  292. GL_ZERO, // BC5
  293. GL_ZERO, // BC6H
  294. GL_ZERO, // BC7
  295. GL_ZERO, // ETC1
  296. GL_ZERO, // ETC2
  297. GL_ZERO, // ETC2A
  298. GL_ZERO, // ETC2A1
  299. GL_ZERO, // PTC12
  300. GL_ZERO, // PTC14
  301. GL_ZERO, // PTC12A
  302. GL_ZERO, // PTC14A
  303. GL_ZERO, // PTC22
  304. GL_ZERO, // PTC24
  305. GL_ZERO, // Unknown
  306. GL_ZERO, // R1
  307. GL_R8, // R8
  308. GL_R8_SNORM, // R8S
  309. GL_R16, // R16
  310. GL_R16F, // R16F
  311. GL_R16_SNORM, // R16S
  312. GL_R32UI, // R32
  313. GL_R32F, // R32F
  314. GL_RG8, // RG8
  315. GL_RG8_SNORM, // RG8S
  316. GL_RG16, // RG16
  317. GL_RG16F, // RG16F
  318. GL_RG16_SNORM, // RG16S
  319. GL_RG32UI, // RG32
  320. GL_RG32F, // RG32F
  321. GL_RGBA8, // BGRA8
  322. GL_RGBA8, // RGBA8
  323. GL_RGBA8_SNORM, // RGBA8S
  324. GL_RGBA16, // RGBA16
  325. GL_RGBA16F, // RGBA16F
  326. GL_RGBA16_SNORM, // RGBA16S
  327. GL_RGBA32UI, // RGBA32
  328. GL_RGBA32F, // RGBA32F
  329. GL_RGB565, // R5G6B5
  330. GL_RGBA4, // RGBA4
  331. GL_RGB5_A1, // RGB5A1
  332. GL_RGB10_A2, // RGB10A2
  333. GL_R11F_G11F_B10F, // R11G11B10F
  334. GL_ZERO, // UnknownDepth
  335. GL_ZERO, // D16
  336. GL_ZERO, // D24
  337. GL_ZERO, // D24S8
  338. GL_ZERO, // D32
  339. GL_ZERO, // D16F
  340. GL_ZERO, // D24F
  341. GL_ZERO, // D32F
  342. GL_ZERO, // D0S8
  343. };
  344. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  345. struct Extension
  346. {
  347. enum Enum
  348. {
  349. AMD_conservative_depth,
  350. AMD_multi_draw_indirect,
  351. ANGLE_depth_texture,
  352. ANGLE_framebuffer_blit,
  353. ANGLE_framebuffer_multisample,
  354. ANGLE_instanced_arrays,
  355. ANGLE_texture_compression_dxt1,
  356. ANGLE_texture_compression_dxt3,
  357. ANGLE_texture_compression_dxt5,
  358. ANGLE_timer_query,
  359. ANGLE_translated_shader_source,
  360. APPLE_texture_format_BGRA8888,
  361. APPLE_texture_max_level,
  362. ARB_compute_shader,
  363. ARB_conservative_depth,
  364. ARB_debug_label,
  365. ARB_debug_output,
  366. ARB_depth_buffer_float,
  367. ARB_depth_clamp,
  368. ARB_draw_buffers_blend,
  369. ARB_draw_indirect,
  370. ARB_draw_instanced,
  371. ARB_ES3_compatibility,
  372. ARB_framebuffer_object,
  373. ARB_framebuffer_sRGB,
  374. ARB_get_program_binary,
  375. ARB_half_float_pixel,
  376. ARB_half_float_vertex,
  377. ARB_instanced_arrays,
  378. ARB_invalidate_subdata,
  379. ARB_map_buffer_range,
  380. ARB_multi_draw_indirect,
  381. ARB_multisample,
  382. ARB_occlusion_query,
  383. ARB_occlusion_query2,
  384. ARB_program_interface_query,
  385. ARB_sampler_objects,
  386. ARB_seamless_cube_map,
  387. ARB_shader_bit_encoding,
  388. ARB_shader_image_load_store,
  389. ARB_shader_storage_buffer_object,
  390. ARB_shader_texture_lod,
  391. ARB_texture_compression_bptc,
  392. ARB_texture_compression_rgtc,
  393. ARB_texture_float,
  394. ARB_texture_multisample,
  395. ARB_texture_rg,
  396. ARB_texture_rgb10_a2ui,
  397. ARB_texture_stencil8,
  398. ARB_texture_storage,
  399. ARB_texture_swizzle,
  400. ARB_timer_query,
  401. ARB_uniform_buffer_object,
  402. ARB_vertex_array_object,
  403. ARB_vertex_type_2_10_10_10_rev,
  404. ATI_meminfo,
  405. CHROMIUM_color_buffer_float_rgb,
  406. CHROMIUM_color_buffer_float_rgba,
  407. CHROMIUM_depth_texture,
  408. CHROMIUM_framebuffer_multisample,
  409. CHROMIUM_texture_compression_dxt3,
  410. CHROMIUM_texture_compression_dxt5,
  411. EXT_bgra,
  412. EXT_blend_color,
  413. EXT_blend_minmax,
  414. EXT_blend_subtract,
  415. EXT_color_buffer_half_float,
  416. EXT_color_buffer_float,
  417. EXT_compressed_ETC1_RGB8_sub_texture,
  418. EXT_debug_label,
  419. EXT_debug_marker,
  420. EXT_debug_tool,
  421. EXT_discard_framebuffer,
  422. EXT_disjoint_timer_query,
  423. EXT_draw_buffers,
  424. EXT_frag_depth,
  425. EXT_framebuffer_blit,
  426. EXT_framebuffer_object,
  427. EXT_framebuffer_sRGB,
  428. EXT_multi_draw_indirect,
  429. EXT_occlusion_query_boolean,
  430. EXT_packed_float,
  431. EXT_read_format_bgra,
  432. EXT_shader_image_load_store,
  433. EXT_shader_texture_lod,
  434. EXT_shadow_samplers,
  435. EXT_texture_array,
  436. EXT_texture_compression_dxt1,
  437. EXT_texture_compression_latc,
  438. EXT_texture_compression_rgtc,
  439. EXT_texture_compression_s3tc,
  440. EXT_texture_filter_anisotropic,
  441. EXT_texture_format_BGRA8888,
  442. EXT_texture_rg,
  443. EXT_texture_snorm,
  444. EXT_texture_sRGB,
  445. EXT_texture_storage,
  446. EXT_texture_swizzle,
  447. EXT_texture_type_2_10_10_10_REV,
  448. EXT_timer_query,
  449. EXT_unpack_subimage,
  450. GOOGLE_depth_texture,
  451. GREMEDY_string_marker,
  452. GREMEDY_frame_terminator,
  453. IMG_multisampled_render_to_texture,
  454. IMG_read_format,
  455. IMG_shader_binary,
  456. IMG_texture_compression_pvrtc,
  457. IMG_texture_compression_pvrtc2,
  458. IMG_texture_format_BGRA8888,
  459. INTEL_fragment_shader_ordering,
  460. KHR_debug,
  461. KHR_no_error,
  462. MOZ_WEBGL_compressed_texture_s3tc,
  463. MOZ_WEBGL_depth_texture,
  464. NV_draw_buffers,
  465. NVX_gpu_memory_info,
  466. OES_compressed_ETC1_RGB8_texture,
  467. OES_depth24,
  468. OES_depth32,
  469. OES_depth_texture,
  470. OES_element_index_uint,
  471. OES_fragment_precision_high,
  472. OES_get_program_binary,
  473. OES_required_internalformat,
  474. OES_packed_depth_stencil,
  475. OES_read_format,
  476. OES_rgb8_rgba8,
  477. OES_standard_derivatives,
  478. OES_texture_3D,
  479. OES_texture_float,
  480. OES_texture_float_linear,
  481. OES_texture_npot,
  482. OES_texture_half_float,
  483. OES_texture_half_float_linear,
  484. OES_texture_stencil8,
  485. OES_vertex_array_object,
  486. OES_vertex_half_float,
  487. OES_vertex_type_10_10_10_2,
  488. WEBGL_color_buffer_float,
  489. WEBGL_compressed_texture_etc1,
  490. WEBGL_compressed_texture_s3tc,
  491. WEBGL_compressed_texture_pvrtc,
  492. WEBGL_depth_texture,
  493. WEBGL_draw_buffers,
  494. WEBKIT_EXT_texture_filter_anisotropic,
  495. WEBKIT_WEBGL_compressed_texture_s3tc,
  496. WEBKIT_WEBGL_depth_texture,
  497. Count
  498. };
  499. const char* m_name;
  500. bool m_supported;
  501. bool m_initialize;
  502. };
  503. // Extension registry
  504. //
  505. // ANGLE:
  506. // https://github.com/google/angle/tree/master/extensions
  507. //
  508. // CHROMIUM:
  509. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  510. //
  511. // EGL:
  512. // https://www.khronos.org/registry/egl/extensions/
  513. //
  514. // GL:
  515. // https://www.opengl.org/registry/
  516. //
  517. // GLES:
  518. // https://www.khronos.org/registry/gles/extensions/
  519. //
  520. // WEBGL:
  521. // https://www.khronos.org/registry/webgl/extensions/
  522. //
  523. static Extension s_extension[] =
  524. {
  525. { "AMD_conservative_depth", false, true },
  526. { "AMD_multi_draw_indirect", false, true },
  527. { "ANGLE_depth_texture", false, true },
  528. { "ANGLE_framebuffer_blit", false, true },
  529. { "ANGLE_framebuffer_multisample", false, false },
  530. { "ANGLE_instanced_arrays", false, true },
  531. { "ANGLE_texture_compression_dxt1", false, true },
  532. { "ANGLE_texture_compression_dxt3", false, true },
  533. { "ANGLE_texture_compression_dxt5", false, true },
  534. { "ANGLE_timer_query", false, true },
  535. { "ANGLE_translated_shader_source", false, true },
  536. { "APPLE_texture_format_BGRA8888", false, true },
  537. { "APPLE_texture_max_level", false, true },
  538. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  539. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  540. { "ARB_debug_label", false, true },
  541. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  542. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  543. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  544. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  545. { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  546. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  547. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  548. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  549. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  550. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  551. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  552. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  553. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  554. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  555. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  556. { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  557. { "ARB_multisample", false, true },
  558. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  559. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  560. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  561. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  562. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  563. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  564. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  565. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  566. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  567. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  568. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  569. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  570. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  571. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  572. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  573. { "ARB_texture_stencil8", false, true },
  574. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  575. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  576. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  577. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  578. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  579. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  580. { "ATI_meminfo", false, true },
  581. { "CHROMIUM_color_buffer_float_rgb", false, true },
  582. { "CHROMIUM_color_buffer_float_rgba", false, true },
  583. { "CHROMIUM_depth_texture", false, true },
  584. { "CHROMIUM_framebuffer_multisample", false, true },
  585. { "CHROMIUM_texture_compression_dxt3", false, true },
  586. { "CHROMIUM_texture_compression_dxt5", false, true },
  587. { "EXT_bgra", false, true },
  588. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  589. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  590. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  591. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  592. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  593. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  594. { "EXT_debug_label", false, true },
  595. { "EXT_debug_marker", false, true },
  596. { "EXT_debug_tool", false, true }, // RenderDoc extension.
  597. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  598. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  599. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  600. { "EXT_frag_depth", false, true }, // GLES2 extension.
  601. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  602. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  603. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  604. { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension.
  605. { "EXT_occlusion_query_boolean", false, true },
  606. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  607. { "EXT_read_format_bgra", false, true },
  608. { "EXT_shader_image_load_store", false, true },
  609. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  610. { "EXT_shadow_samplers", false, true },
  611. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  612. { "EXT_texture_compression_dxt1", false, true },
  613. { "EXT_texture_compression_latc", false, true },
  614. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  615. { "EXT_texture_compression_s3tc", false, true },
  616. { "EXT_texture_filter_anisotropic", false, true },
  617. { "EXT_texture_format_BGRA8888", false, true },
  618. { "EXT_texture_rg", false, true }, // GLES2 extension.
  619. { "EXT_texture_snorm", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  620. { "EXT_texture_sRGB", false, true },
  621. { "EXT_texture_storage", false, true },
  622. { "EXT_texture_swizzle", false, true },
  623. { "EXT_texture_type_2_10_10_10_REV", false, true },
  624. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  625. { "EXT_unpack_subimage", false, true },
  626. { "GOOGLE_depth_texture", false, true },
  627. { "GREMEDY_string_marker", false, true },
  628. { "GREMEDY_frame_terminator", false, true },
  629. { "IMG_multisampled_render_to_texture", false, true },
  630. { "IMG_read_format", false, true },
  631. { "IMG_shader_binary", false, true },
  632. { "IMG_texture_compression_pvrtc", false, true },
  633. { "IMG_texture_compression_pvrtc2", false, true },
  634. { "IMG_texture_format_BGRA8888", false, true },
  635. { "INTEL_fragment_shader_ordering", false, true },
  636. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  637. { "KHR_no_error", false, true },
  638. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  639. { "MOZ_WEBGL_depth_texture", false, true },
  640. { "NV_draw_buffers", false, true }, // GLES2 extension.
  641. { "NVX_gpu_memory_info", false, true },
  642. { "OES_compressed_ETC1_RGB8_texture", false, true },
  643. { "OES_depth24", false, true },
  644. { "OES_depth32", false, true },
  645. { "OES_depth_texture", false, true },
  646. { "OES_element_index_uint", false, true },
  647. { "OES_fragment_precision_high", false, true },
  648. { "OES_get_program_binary", false, true },
  649. { "OES_required_internalformat", false, true },
  650. { "OES_packed_depth_stencil", false, true },
  651. { "OES_read_format", false, true },
  652. { "OES_rgb8_rgba8", false, true },
  653. { "OES_standard_derivatives", false, true },
  654. { "OES_texture_3D", false, true },
  655. { "OES_texture_float", false, true },
  656. { "OES_texture_float_linear", false, true },
  657. { "OES_texture_npot", false, true },
  658. { "OES_texture_half_float", false, true },
  659. { "OES_texture_half_float_linear", false, true },
  660. { "OES_texture_stencil8", false, true },
  661. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  662. { "OES_vertex_half_float", false, true },
  663. { "OES_vertex_type_10_10_10_2", false, true },
  664. { "WEBGL_color_buffer_float", false, true },
  665. { "WEBGL_compressed_texture_etc1", false, true },
  666. { "WEBGL_compressed_texture_s3tc", false, true },
  667. { "WEBGL_compressed_texture_pvrtc", false, true },
  668. { "WEBGL_depth_texture", false, true },
  669. { "WEBGL_draw_buffers", false, true },
  670. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  671. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  672. { "WEBKIT_WEBGL_depth_texture", false, true },
  673. };
  674. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  675. static const char* s_ARB_shader_texture_lod[] =
  676. {
  677. "texture2DLod",
  678. "texture2DProjLod",
  679. "texture3DLod",
  680. "texture3DProjLod",
  681. "textureCubeLod",
  682. "shadow2DLod",
  683. "shadow2DProjLod",
  684. NULL
  685. // "texture1DLod",
  686. // "texture1DProjLod",
  687. // "shadow1DLod",
  688. // "shadow1DProjLod",
  689. };
  690. static const char* s_EXT_shader_texture_lod[] =
  691. {
  692. "texture2DLod",
  693. "texture2DProjLod",
  694. "textureCubeLod",
  695. NULL
  696. // "texture2DGrad",
  697. // "texture2DProjGrad",
  698. // "textureCubeGrad",
  699. };
  700. static const char* s_EXT_shadow_samplers[] =
  701. {
  702. "shadow2D",
  703. "shadow2DProj",
  704. NULL
  705. };
  706. static const char* s_OES_standard_derivatives[] =
  707. {
  708. "dFdx",
  709. "dFdy",
  710. "fwidth",
  711. NULL
  712. };
  713. static const char* s_OES_texture_3D[] =
  714. {
  715. "texture3D",
  716. "texture3DProj",
  717. "texture3DLod",
  718. "texture3DProjLod",
  719. NULL
  720. };
  721. static const char* s_uisamplers[] =
  722. {
  723. "isampler2D",
  724. "usampler2D",
  725. "isampler3D",
  726. "usampler3D",
  727. "isamplerCube",
  728. "usamplerCube",
  729. NULL
  730. };
  731. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  732. {
  733. }
  734. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  735. {
  736. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  737. }
  738. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  739. {
  740. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  741. }
  742. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  743. {
  744. }
  745. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  746. {
  747. }
  748. static void GL_APIENTRY stubInsertEventMarkerGREMEDY(GLsizei _length, const char* _marker)
  749. {
  750. // If <marker> is a null-terminated string then <length> should not
  751. // include the terminator.
  752. //
  753. // If <length> is 0 then <marker> is assumed to be null-terminated.
  754. uint32_t size = (0 == _length ? (uint32_t)strlen(_marker) : _length) + 1;
  755. size *= sizeof(wchar_t);
  756. wchar_t* name = (wchar_t*)alloca(size);
  757. mbstowcs(name, _marker, size-2);
  758. GL_CHECK(glStringMarkerGREMEDY(_length, _marker) );
  759. }
  760. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  761. {
  762. }
  763. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  764. {
  765. }
  766. static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  767. {
  768. const uint8_t* args = (const uint8_t*)_indirect;
  769. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  770. {
  771. GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) );
  772. args += _stride;
  773. }
  774. }
  775. static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  776. {
  777. const uint8_t* args = (const uint8_t*)_indirect;
  778. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  779. {
  780. GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) );
  781. args += _stride;
  782. }
  783. }
  784. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  785. static const char* getGLString(GLenum _name)
  786. {
  787. const char* str = (const char*)glGetString(_name);
  788. glGetError(); // ignore error if glGetString returns NULL.
  789. if (NULL != str)
  790. {
  791. return str;
  792. }
  793. return "<unknown>";
  794. }
  795. static uint32_t getGLStringHash(GLenum _name)
  796. {
  797. const char* str = (const char*)glGetString(_name);
  798. glGetError(); // ignore error if glGetString returns NULL.
  799. if (NULL != str)
  800. {
  801. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  802. }
  803. return 0;
  804. }
  805. void dumpExtensions(const char* _extensions)
  806. {
  807. if (NULL != _extensions)
  808. {
  809. char name[1024];
  810. const char* pos = _extensions;
  811. const char* end = _extensions + strlen(_extensions);
  812. while (pos < end)
  813. {
  814. uint32_t len;
  815. const char* space = strchr(pos, ' ');
  816. if (NULL != space)
  817. {
  818. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  819. }
  820. else
  821. {
  822. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  823. }
  824. strncpy(name, pos, len);
  825. name[len] = '\0';
  826. BX_TRACE("\t%s", name);
  827. pos += len+1;
  828. }
  829. }
  830. }
  831. const char* toString(GLenum _enum)
  832. {
  833. switch (_enum)
  834. {
  835. case GL_DEBUG_SOURCE_API: return "API";
  836. case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys";
  837. case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader";
  838. case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty";
  839. case GL_DEBUG_SOURCE_APPLICATION: return "Application";
  840. case GL_DEBUG_SOURCE_OTHER: return "Other";
  841. case GL_DEBUG_TYPE_ERROR: return "Error";
  842. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior";
  843. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior";
  844. case GL_DEBUG_TYPE_PORTABILITY: return "Portability";
  845. case GL_DEBUG_TYPE_PERFORMANCE: return "Performance";
  846. case GL_DEBUG_TYPE_OTHER: return "Other";
  847. case GL_DEBUG_SEVERITY_HIGH: return "High";
  848. case GL_DEBUG_SEVERITY_MEDIUM: return "Medium";
  849. case GL_DEBUG_SEVERITY_LOW: return "Low";
  850. default:
  851. break;
  852. }
  853. return "<unknown>";
  854. }
  855. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  856. {
  857. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  858. , toString(_source)
  859. , toString(_type)
  860. , _id
  861. , toString(_severity)
  862. , _message
  863. );
  864. BX_UNUSED(_source, _type, _id, _severity, _message);
  865. }
  866. GLint glGet(GLenum _pname)
  867. {
  868. GLint result = 0;
  869. glGetIntegerv(_pname, &result);
  870. GLenum err = glGetError();
  871. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  872. return 0 == err ? result : 0;
  873. }
  874. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  875. {
  876. TextureFormatInfo& tfi = s_textureFormat[_format];
  877. tfi.m_internalFmt = _internalFmt;
  878. tfi.m_fmt = _fmt;
  879. tfi.m_type = _type;
  880. }
  881. void initTestTexture(TextureFormat::Enum _format, bool srgb = false)
  882. {
  883. const TextureFormatInfo& tfi = s_textureFormat[_format];
  884. GLenum internalFmt = srgb
  885. ? tfi.m_internalFmtSrgb
  886. : tfi.m_internalFmt
  887. ;
  888. GLsizei size = (16*16*getBitsPerPixel(_format) )/8;
  889. void* data = alloca(size);
  890. if (isCompressed(_format) )
  891. {
  892. glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, size, data);
  893. }
  894. else
  895. {
  896. glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, tfi.m_fmt, tfi.m_type, data);
  897. }
  898. }
  899. static bool isTextureFormatValid(TextureFormat::Enum _format, bool srgb = false)
  900. {
  901. const TextureFormatInfo& tfi = s_textureFormat[_format];
  902. GLenum internalFmt = srgb
  903. ? tfi.m_internalFmtSrgb
  904. : tfi.m_internalFmt
  905. ;
  906. if (!s_textureFormat[_format].m_supported
  907. || GL_ZERO == internalFmt)
  908. {
  909. return false;
  910. }
  911. GLuint id;
  912. GL_CHECK(glGenTextures(1, &id) );
  913. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  914. initTestTexture(_format);
  915. GLenum err = glGetError();
  916. BX_WARN(0 == err, "TextureFormat::%s is not supported (%x: %s).", getName(_format), err, glEnumName(err) );
  917. GL_CHECK(glDeleteTextures(1, &id) );
  918. return 0 == err;
  919. }
  920. static bool isImageFormatValid(TextureFormat::Enum _format)
  921. {
  922. if (GL_ZERO == s_imageFormat[_format])
  923. {
  924. return false;
  925. }
  926. GLuint id;
  927. GL_CHECK(glGenTextures(1, &id) );
  928. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  929. GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], 16, 16) );
  930. glBindImageTexture(0
  931. , id
  932. , 0
  933. , GL_FALSE
  934. , 0
  935. , GL_READ_WRITE
  936. , s_imageFormat[_format]
  937. );
  938. GLenum err = glGetError();
  939. GL_CHECK(glDeleteTextures(1, &id) );
  940. return 0 == err;
  941. }
  942. static bool isFramebufferFormatValid(TextureFormat::Enum _format, bool srgb = false)
  943. {
  944. const TextureFormatInfo& tfi = s_textureFormat[_format];
  945. GLenum internalFmt = srgb
  946. ? tfi.m_internalFmtSrgb
  947. : tfi.m_internalFmt
  948. ;
  949. if (GL_ZERO == internalFmt
  950. || !tfi.m_supported)
  951. {
  952. return false;
  953. }
  954. GLuint fbo;
  955. GL_CHECK(glGenFramebuffers(1, &fbo) );
  956. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
  957. GLuint id;
  958. GL_CHECK(glGenTextures(1, &id) );
  959. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  960. initTestTexture(_format);
  961. GLenum err = glGetError();
  962. GLenum attachment;
  963. if (isDepth(_format) )
  964. {
  965. const ImageBlockInfo& info = getBlockInfo(_format);
  966. if (0 == info.depthBits)
  967. {
  968. attachment = GL_STENCIL_ATTACHMENT;
  969. }
  970. else if (0 == info.stencilBits)
  971. {
  972. attachment = GL_DEPTH_ATTACHMENT;
  973. }
  974. else
  975. {
  976. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  977. }
  978. }
  979. else
  980. {
  981. attachment = GL_COLOR_ATTACHMENT0;
  982. }
  983. glFramebufferTexture2D(GL_FRAMEBUFFER
  984. , attachment
  985. , GL_TEXTURE_2D
  986. , id
  987. , 0
  988. );
  989. err = glGetError();
  990. if (0 == err)
  991. {
  992. err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  993. }
  994. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  995. GL_CHECK(glDeleteFramebuffers(1, &fbo) );
  996. GL_CHECK(glDeleteTextures(1, &id) );
  997. return GL_FRAMEBUFFER_COMPLETE == err;
  998. }
  999. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  1000. {
  1001. const uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  1002. const uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  1003. const uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  1004. _magFilter = s_textureFilterMag[mag];
  1005. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  1006. }
  1007. struct RendererContextGL : public RendererContextI
  1008. {
  1009. RendererContextGL()
  1010. : m_numWindows(1)
  1011. , m_rtMsaa(false)
  1012. , m_fbDiscard(BGFX_CLEAR_NONE)
  1013. , m_capture(NULL)
  1014. , m_captureSize(0)
  1015. , m_maxAnisotropy(0.0f)
  1016. , m_maxAnisotropyDefault(0.0f)
  1017. , m_maxMsaa(0)
  1018. , m_vao(0)
  1019. , m_vaoSupport(false)
  1020. , m_samplerObjectSupport(false)
  1021. , m_shadowSamplersSupport(false)
  1022. , m_programBinarySupport(false)
  1023. , m_textureSwizzleSupport(false)
  1024. , m_depthTextureSupport(false)
  1025. , m_timerQuerySupport(false)
  1026. , m_flip(false)
  1027. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1028. , m_backBufferFbo(0)
  1029. , m_msaaBackBufferFbo(0)
  1030. , m_ovrFbo(0)
  1031. {
  1032. memset(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  1033. }
  1034. ~RendererContextGL()
  1035. {
  1036. }
  1037. void init()
  1038. {
  1039. m_renderdocdll = loadRenderDoc();
  1040. m_fbh.idx = invalidHandle;
  1041. memset(m_uniforms, 0, sizeof(m_uniforms) );
  1042. memset(&m_resolution, 0, sizeof(m_resolution) );
  1043. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  1044. // Must be after context is initialized?!
  1045. m_ovr.init();
  1046. m_vendor = getGLString(GL_VENDOR);
  1047. m_renderer = getGLString(GL_RENDERER);
  1048. m_version = getGLString(GL_VERSION);
  1049. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  1050. GLint numCmpFormats = 0;
  1051. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1052. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1053. GLint* cmpFormat = NULL;
  1054. if (0 < numCmpFormats)
  1055. {
  1056. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  1057. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1058. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  1059. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1060. {
  1061. GLint internalFmt = cmpFormat[ii];
  1062. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  1063. for (uint32_t jj = 0; jj < fmt; ++jj)
  1064. {
  1065. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  1066. {
  1067. s_textureFormat[jj].m_supported = true;
  1068. fmt = jj;
  1069. }
  1070. }
  1071. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  1072. }
  1073. }
  1074. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1075. {
  1076. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1077. BX_TRACE("Defaults:");
  1078. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1079. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1080. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1081. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1082. #else
  1083. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1084. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1085. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1086. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1087. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1088. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1089. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1090. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1091. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1092. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1093. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1094. GL_GET(GL_MAX_COLOR_ATTACHMENTS, 1);
  1095. GL_GET(GL_MAX_DRAW_BUFFERS, 1);
  1096. #undef GL_GET
  1097. BX_TRACE(" Vendor: %s", m_vendor);
  1098. BX_TRACE(" Renderer: %s", m_renderer);
  1099. BX_TRACE(" Version: %s", m_version);
  1100. BX_TRACE("GLSL version: %s", m_glslVersion);
  1101. }
  1102. // Initial binary shader hash depends on driver version.
  1103. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1104. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1105. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1106. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1107. ;
  1108. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  1109. {
  1110. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1111. glGetError(); // ignore error if glGetString returns NULL.
  1112. if (NULL != extensions)
  1113. {
  1114. char name[1024];
  1115. const char* pos = extensions;
  1116. const char* end = extensions + strlen(extensions);
  1117. uint32_t index = 0;
  1118. while (pos < end)
  1119. {
  1120. uint32_t len;
  1121. const char* space = strchr(pos, ' ');
  1122. if (NULL != space)
  1123. {
  1124. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  1125. }
  1126. else
  1127. {
  1128. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  1129. }
  1130. strncpy(name, pos, len);
  1131. name[len] = '\0';
  1132. bool supported = false;
  1133. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1134. {
  1135. Extension& extension = s_extension[ii];
  1136. if (!extension.m_supported
  1137. && extension.m_initialize)
  1138. {
  1139. const char* ext = name;
  1140. if (0 == strncmp(ext, "GL_", 3) ) // skip GL_
  1141. {
  1142. ext += 3;
  1143. }
  1144. if (0 == strcmp(ext, extension.m_name) )
  1145. {
  1146. extension.m_supported = true;
  1147. supported = true;
  1148. break;
  1149. }
  1150. }
  1151. }
  1152. BX_TRACE("GL_EXTENSION %3d%s: %s", index, supported ? " (supported)" : "", name);
  1153. BX_UNUSED(supported);
  1154. pos += len+1;
  1155. ++index;
  1156. }
  1157. BX_TRACE("Supported extensions:");
  1158. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1159. {
  1160. if (s_extension[ii].m_supported)
  1161. {
  1162. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1163. }
  1164. }
  1165. }
  1166. }
  1167. // Allow all texture filters.
  1168. memset(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1169. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1170. {
  1171. s_textureFormat[ii].m_supported = true
  1172. && TextureFormat::Unknown != ii
  1173. && TextureFormat::UnknownDepth != ii
  1174. ;
  1175. }
  1176. bool bc123Supported = 0
  1177. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1178. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1179. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1180. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1181. ;
  1182. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1183. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1184. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1185. ;
  1186. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1187. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1188. {
  1189. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1190. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1191. {
  1192. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1193. {
  1194. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1195. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1201. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1202. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1203. ;
  1204. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1205. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1206. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1207. ;
  1208. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1209. {
  1210. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1211. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1212. }
  1213. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1214. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1215. {
  1216. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1217. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1218. }
  1219. bool etc1Supported = 0
  1220. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1221. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1222. ;
  1223. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1224. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1225. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1226. ;
  1227. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1228. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1229. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1230. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1231. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1232. {
  1233. // When ETC2 is supported override ETC1 texture format settings.
  1234. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1235. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1236. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1237. }
  1238. bool ptc1Supported = 0
  1239. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1240. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1241. ;
  1242. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1243. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1244. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1245. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1246. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1247. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1248. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1249. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1250. {
  1251. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1252. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1253. {
  1254. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1255. // internalFormat and format must match:
  1256. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml
  1257. setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1258. setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5);
  1259. setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4);
  1260. setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1);
  1261. if (s_extension[Extension::OES_texture_half_float].m_supported
  1262. || s_extension[Extension::OES_texture_float ].m_supported)
  1263. {
  1264. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1265. // When half/float is available via extensions texture will be marked as
  1266. // incomplete if it uses anything other than nearest filter.
  1267. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1268. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1269. s_textureFilter[TextureFormat::R16F] = linear16F;
  1270. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1271. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1272. s_textureFilter[TextureFormat::R32F] = linear32F;
  1273. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1274. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1275. }
  1276. if (BX_ENABLED(BX_PLATFORM_IOS) )
  1277. {
  1278. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1279. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1280. }
  1281. }
  1282. }
  1283. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1284. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1285. {
  1286. setTextureFormat(TextureFormat::R16, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1287. setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1288. setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1289. setTextureFormat(TextureFormat::R32, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1290. setTextureFormat(TextureFormat::RG32, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1291. setTextureFormat(TextureFormat::RGBA32, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1292. }
  1293. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1294. || s_extension[Extension::EXT_bgra ].m_supported
  1295. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1296. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1297. {
  1298. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1299. {
  1300. m_readPixelsFmt = GL_BGRA;
  1301. }
  1302. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1303. // APPLE_texture_format_BGRA8888 wants
  1304. // format to be BGRA but internal format to stay RGBA, but
  1305. // EXT_texture_format_BGRA8888 wants both format and internal
  1306. // format to be BGRA.
  1307. //
  1308. // Reference:
  1309. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1310. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  1311. // https://www.khronos.org/registry/gles/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1312. if (!s_extension[Extension::EXT_bgra ].m_supported
  1313. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1314. {
  1315. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1316. }
  1317. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1318. {
  1319. // Revert back to RGBA if texture can't be created.
  1320. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE);
  1321. }
  1322. }
  1323. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  1324. || !isTextureFormatValid(TextureFormat::R8) )
  1325. {
  1326. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1327. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1328. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1329. }
  1330. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1331. {
  1332. if (TextureFormat::Unknown != ii
  1333. && TextureFormat::UnknownDepth != ii)
  1334. {
  1335. s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) );
  1336. }
  1337. }
  1338. if (BX_ENABLED(0) )
  1339. {
  1340. // Disable all compressed texture formats. For testing only.
  1341. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  1342. {
  1343. s_textureFormat[ii].m_supported = false;
  1344. }
  1345. }
  1346. const bool computeSupport = false
  1347. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1348. || s_extension[Extension::ARB_compute_shader].m_supported
  1349. ;
  1350. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1351. {
  1352. uint8_t supported = 0;
  1353. supported |= s_textureFormat[ii].m_supported
  1354. ? BGFX_CAPS_FORMAT_TEXTURE_COLOR
  1355. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1356. ;
  1357. supported |= isTextureFormatValid(TextureFormat::Enum(ii), true)
  1358. ? BGFX_CAPS_FORMAT_TEXTURE_COLOR_SRGB
  1359. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1360. ;
  1361. supported |= computeSupport
  1362. && isImageFormatValid(TextureFormat::Enum(ii) )
  1363. ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE
  1364. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1365. ;
  1366. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii) )
  1367. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1368. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1369. ;
  1370. g_caps.formats[ii] = supported;
  1371. }
  1372. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1373. || s_extension[Extension::OES_texture_3D].m_supported
  1374. ? BGFX_CAPS_TEXTURE_3D
  1375. : 0
  1376. ;
  1377. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1378. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1379. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  1380. : 0
  1381. ;
  1382. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1383. || s_extension[Extension::OES_vertex_half_float].m_supported
  1384. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  1385. : 0
  1386. ;
  1387. g_caps.supported |= false
  1388. || s_extension[Extension::ARB_vertex_type_2_10_10_10_rev].m_supported
  1389. || s_extension[Extension::OES_vertex_type_10_10_10_2].m_supported
  1390. ? BGFX_CAPS_VERTEX_ATTRIB_UINT10
  1391. : 0
  1392. ;
  1393. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1394. || s_extension[Extension::EXT_frag_depth].m_supported
  1395. ? BGFX_CAPS_FRAGMENT_DEPTH
  1396. : 0
  1397. ;
  1398. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  1399. ? BGFX_CAPS_BLEND_INDEPENDENT
  1400. : 0
  1401. ;
  1402. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  1403. ? BGFX_CAPS_FRAGMENT_ORDERING
  1404. : 0
  1405. ;
  1406. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1407. || s_extension[Extension::OES_element_index_uint].m_supported
  1408. ? BGFX_CAPS_INDEX32
  1409. : 0
  1410. ;
  1411. const bool drawIndirectSupported = false
  1412. || s_extension[Extension::AMD_multi_draw_indirect].m_supported
  1413. || s_extension[Extension::ARB_draw_indirect ].m_supported
  1414. || s_extension[Extension::ARB_multi_draw_indirect].m_supported
  1415. || s_extension[Extension::EXT_multi_draw_indirect].m_supported
  1416. ;
  1417. if (drawIndirectSupported)
  1418. {
  1419. if (NULL == glMultiDrawArraysIndirect
  1420. || NULL == glMultiDrawElementsIndirect)
  1421. {
  1422. glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect;
  1423. glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect;
  1424. }
  1425. }
  1426. g_caps.supported |= drawIndirectSupported
  1427. ? BGFX_CAPS_DRAW_INDIRECT
  1428. : 0
  1429. ;
  1430. g_caps.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) );
  1431. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1432. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1433. || s_extension[Extension::EXT_draw_buffers ].m_supported
  1434. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  1435. {
  1436. g_caps.maxFBAttachments = uint8_t(bx::uint32_min(glGet(GL_MAX_DRAW_BUFFERS)
  1437. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS)
  1438. );
  1439. }
  1440. m_vaoSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1441. || s_extension[Extension::ARB_vertex_array_object].m_supported
  1442. || s_extension[Extension::OES_vertex_array_object].m_supported
  1443. ;
  1444. if (BX_ENABLED(BX_PLATFORM_NACL) )
  1445. {
  1446. m_vaoSupport &= true
  1447. && NULL != glGenVertexArrays
  1448. && NULL != glDeleteVertexArrays
  1449. && NULL != glBindVertexArray
  1450. ;
  1451. }
  1452. if (m_vaoSupport)
  1453. {
  1454. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  1455. }
  1456. m_samplerObjectSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1457. || s_extension[Extension::ARB_sampler_objects].m_supported
  1458. ;
  1459. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1460. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1461. ;
  1462. m_programBinarySupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1463. || s_extension[Extension::ARB_get_program_binary].m_supported
  1464. || s_extension[Extension::OES_get_program_binary].m_supported
  1465. || s_extension[Extension::IMG_shader_binary ].m_supported
  1466. ;
  1467. m_textureSwizzleSupport = false
  1468. || s_extension[Extension::ARB_texture_swizzle].m_supported
  1469. || s_extension[Extension::EXT_texture_swizzle].m_supported
  1470. ;
  1471. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1472. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  1473. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  1474. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  1475. || s_extension[Extension::OES_depth_texture ].m_supported
  1476. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  1477. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  1478. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  1479. ;
  1480. m_timerQuerySupport = false
  1481. || s_extension[Extension::ANGLE_timer_query ].m_supported
  1482. || s_extension[Extension::ARB_timer_query ].m_supported
  1483. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  1484. || s_extension[Extension::EXT_timer_query ].m_supported
  1485. ;
  1486. m_timerQuerySupport &= true
  1487. && NULL != glGetQueryObjectiv
  1488. && NULL != glGetQueryObjectui64v
  1489. ;
  1490. g_caps.supported |= m_depthTextureSupport
  1491. ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  1492. : 0
  1493. ;
  1494. g_caps.supported |= computeSupport
  1495. ? BGFX_CAPS_COMPUTE
  1496. : 0
  1497. ;
  1498. g_caps.supported |= m_glctx.getCaps();
  1499. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  1500. {
  1501. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  1502. }
  1503. if (s_extension[Extension::ARB_texture_multisample].m_supported
  1504. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  1505. {
  1506. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  1507. }
  1508. if (s_extension[Extension::OES_read_format].m_supported
  1509. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  1510. {
  1511. m_readPixelsFmt = GL_BGRA;
  1512. }
  1513. else
  1514. {
  1515. m_readPixelsFmt = GL_RGBA;
  1516. }
  1517. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1518. {
  1519. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1520. }
  1521. else
  1522. {
  1523. if (!BX_ENABLED(BX_PLATFORM_IOS) )
  1524. {
  1525. if (s_extension[Extension::ARB_instanced_arrays].m_supported
  1526. || s_extension[Extension::ANGLE_instanced_arrays].m_supported)
  1527. {
  1528. if (NULL != glVertexAttribDivisor
  1529. && NULL != glDrawArraysInstanced
  1530. && NULL != glDrawElementsInstanced)
  1531. {
  1532. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1533. }
  1534. }
  1535. }
  1536. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  1537. {
  1538. glVertexAttribDivisor = stubVertexAttribDivisor;
  1539. glDrawArraysInstanced = stubDrawArraysInstanced;
  1540. glDrawElementsInstanced = stubDrawElementsInstanced;
  1541. }
  1542. }
  1543. if (s_extension[Extension::ARB_debug_output].m_supported
  1544. || s_extension[Extension::KHR_debug].m_supported)
  1545. {
  1546. if (NULL != glDebugMessageControl
  1547. && NULL != glDebugMessageInsert
  1548. && NULL != glDebugMessageCallback
  1549. && NULL != glGetDebugMessageLog)
  1550. {
  1551. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  1552. GL_CHECK(glDebugMessageControl(GL_DONT_CARE
  1553. , GL_DONT_CARE
  1554. , GL_DEBUG_SEVERITY_MEDIUM
  1555. , 0
  1556. , NULL
  1557. , GL_TRUE
  1558. ) );
  1559. }
  1560. }
  1561. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  1562. {
  1563. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  1564. }
  1565. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  1566. {
  1567. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  1568. }
  1569. if (NULL == glFrameTerminatorGREMEDY
  1570. || !s_extension[Extension::GREMEDY_frame_terminator].m_supported)
  1571. {
  1572. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  1573. }
  1574. if (NULL == glInsertEventMarker
  1575. || !s_extension[Extension::EXT_debug_marker].m_supported)
  1576. {
  1577. glInsertEventMarker = (NULL != glStringMarkerGREMEDY && s_extension[Extension::GREMEDY_string_marker].m_supported)
  1578. ? stubInsertEventMarkerGREMEDY
  1579. : stubInsertEventMarker
  1580. ;
  1581. }
  1582. setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported);
  1583. if (NULL == glObjectLabel)
  1584. {
  1585. glObjectLabel = stubObjectLabel;
  1586. }
  1587. if (NULL == glInvalidateFramebuffer)
  1588. {
  1589. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  1590. }
  1591. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1592. && m_timerQuerySupport)
  1593. {
  1594. m_gpuTimer.create();
  1595. }
  1596. // Init reserved part of view name.
  1597. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1598. {
  1599. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  1600. }
  1601. ovrPostReset();
  1602. }
  1603. void shutdown()
  1604. {
  1605. ovrPreReset();
  1606. m_ovr.shutdown();
  1607. if (m_vaoSupport)
  1608. {
  1609. GL_CHECK(glBindVertexArray(0) );
  1610. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  1611. m_vao = 0;
  1612. }
  1613. captureFinish();
  1614. invalidateCache();
  1615. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1616. && m_timerQuerySupport)
  1617. {
  1618. m_gpuTimer.destroy();
  1619. }
  1620. destroyMsaaFbo();
  1621. m_glctx.destroy();
  1622. m_flip = false;
  1623. unloadRenderDoc(m_renderdocdll);
  1624. }
  1625. RendererType::Enum getRendererType() const BX_OVERRIDE
  1626. {
  1627. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1628. {
  1629. return RendererType::OpenGL;
  1630. }
  1631. return RendererType::OpenGLES;
  1632. }
  1633. const char* getRendererName() const BX_OVERRIDE
  1634. {
  1635. return BGFX_RENDERER_OPENGL_NAME;
  1636. }
  1637. void flip(HMD& _hmd)
  1638. {
  1639. if (m_flip)
  1640. {
  1641. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  1642. {
  1643. m_glctx.swap(m_frameBuffers[m_windows[ii].idx].m_swapChain);
  1644. }
  1645. if (!m_ovr.swap(_hmd) )
  1646. {
  1647. m_glctx.swap();
  1648. }
  1649. }
  1650. }
  1651. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  1652. {
  1653. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  1654. }
  1655. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1656. {
  1657. m_indexBuffers[_handle.idx].destroy();
  1658. }
  1659. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  1660. {
  1661. VertexDecl& decl = m_vertexDecls[_handle.idx];
  1662. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  1663. dump(decl);
  1664. }
  1665. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  1666. {
  1667. }
  1668. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) BX_OVERRIDE
  1669. {
  1670. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  1671. }
  1672. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1673. {
  1674. m_vertexBuffers[_handle.idx].destroy();
  1675. }
  1676. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1677. {
  1678. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  1679. }
  1680. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1681. {
  1682. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1683. }
  1684. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1685. {
  1686. m_indexBuffers[_handle.idx].destroy();
  1687. }
  1688. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1689. {
  1690. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1691. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  1692. }
  1693. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1694. {
  1695. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1696. }
  1697. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1698. {
  1699. m_vertexBuffers[_handle.idx].destroy();
  1700. }
  1701. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  1702. {
  1703. m_shaders[_handle.idx].create(_mem);
  1704. }
  1705. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  1706. {
  1707. m_shaders[_handle.idx].destroy();
  1708. }
  1709. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  1710. {
  1711. ShaderGL dummyFragmentShader;
  1712. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  1713. }
  1714. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  1715. {
  1716. m_program[_handle.idx].destroy();
  1717. }
  1718. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  1719. {
  1720. m_textures[_handle.idx].create(_mem, _flags, _skip);
  1721. }
  1722. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  1723. {
  1724. }
  1725. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  1726. {
  1727. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1728. }
  1729. void updateTextureEnd() BX_OVERRIDE
  1730. {
  1731. }
  1732. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height) BX_OVERRIDE
  1733. {
  1734. TextureGL& texture = m_textures[_handle.idx];
  1735. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  1736. const Memory* mem = alloc(size);
  1737. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  1738. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  1739. bx::write(&writer, magic);
  1740. TextureCreate tc;
  1741. tc.m_flags = texture.m_flags;
  1742. tc.m_width = _width;
  1743. tc.m_height = _height;
  1744. tc.m_sides = 0;
  1745. tc.m_depth = 0;
  1746. tc.m_numMips = 1;
  1747. tc.m_format = texture.m_requestedFormat;
  1748. tc.m_cubeMap = false;
  1749. tc.m_mem = NULL;
  1750. bx::write(&writer, tc);
  1751. texture.destroy();
  1752. texture.create(mem, tc.m_flags, 0);
  1753. release(mem);
  1754. }
  1755. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  1756. {
  1757. m_textures[_handle.idx].destroy();
  1758. }
  1759. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const TextureHandle* _textureHandles) BX_OVERRIDE
  1760. {
  1761. m_frameBuffers[_handle.idx].create(_num, _textureHandles);
  1762. }
  1763. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  1764. {
  1765. uint16_t denseIdx = m_numWindows++;
  1766. m_windows[denseIdx] = _handle;
  1767. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  1768. }
  1769. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  1770. {
  1771. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  1772. if (UINT16_MAX != denseIdx)
  1773. {
  1774. --m_numWindows;
  1775. if (m_numWindows > 1)
  1776. {
  1777. FrameBufferHandle handle = m_windows[m_numWindows];
  1778. m_windows[denseIdx] = handle;
  1779. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  1780. }
  1781. }
  1782. }
  1783. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  1784. {
  1785. if (NULL != m_uniforms[_handle.idx])
  1786. {
  1787. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1788. }
  1789. uint32_t size = g_uniformTypeSize[_type]*_num;
  1790. void* data = BX_ALLOC(g_allocator, size);
  1791. memset(data, 0, size);
  1792. m_uniforms[_handle.idx] = data;
  1793. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  1794. }
  1795. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  1796. {
  1797. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1798. m_uniforms[_handle.idx] = NULL;
  1799. }
  1800. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  1801. {
  1802. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  1803. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  1804. uint32_t width = m_resolution.m_width;
  1805. uint32_t height = m_resolution.m_height;
  1806. GL_CHECK(glReadPixels(0
  1807. , 0
  1808. , width
  1809. , height
  1810. , m_readPixelsFmt
  1811. , GL_UNSIGNED_BYTE
  1812. , data
  1813. ) );
  1814. if (GL_RGBA == m_readPixelsFmt)
  1815. {
  1816. imageSwizzleBgra8(width, height, width*4, data, data);
  1817. }
  1818. g_callback->screenShot(_filePath
  1819. , width
  1820. , height
  1821. , width*4
  1822. , data
  1823. , length
  1824. , true
  1825. );
  1826. BX_FREE(g_allocator, data);
  1827. }
  1828. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  1829. {
  1830. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  1831. {
  1832. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  1833. , _name
  1834. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  1835. );
  1836. }
  1837. }
  1838. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  1839. {
  1840. memcpy(m_uniforms[_loc], _data, _size);
  1841. }
  1842. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  1843. {
  1844. GL_CHECK(glInsertEventMarker(_size, _marker) );
  1845. }
  1846. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  1847. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  1848. {
  1849. if (0 != m_vao)
  1850. {
  1851. GL_CHECK(glBindVertexArray(m_vao) );
  1852. }
  1853. uint32_t width = m_resolution.m_width;
  1854. uint32_t height = m_resolution.m_height;
  1855. if (m_ovr.isEnabled() )
  1856. {
  1857. m_ovr.getSize(width, height);
  1858. }
  1859. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  1860. GL_CHECK(glViewport(0, 0, width, height) );
  1861. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1862. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1863. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1864. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1865. GL_CHECK(glDisable(GL_CULL_FACE) );
  1866. GL_CHECK(glDisable(GL_BLEND) );
  1867. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1868. ProgramGL& program = m_program[_blitter.m_program.idx];
  1869. GL_CHECK(glUseProgram(program.m_id) );
  1870. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  1871. float proj[16];
  1872. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1873. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  1874. , 1
  1875. , GL_FALSE
  1876. , proj
  1877. ) );
  1878. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1879. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  1880. }
  1881. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  1882. {
  1883. const uint32_t numVertices = _numIndices*4/6;
  1884. if (0 < numVertices)
  1885. {
  1886. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  1887. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  1888. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1889. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1890. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  1891. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1892. ProgramGL& program = m_program[_blitter.m_program.idx];
  1893. program.bindAttributes(_blitter.m_decl, 0);
  1894. GL_CHECK(glDrawElements(GL_TRIANGLES
  1895. , _numIndices
  1896. , GL_UNSIGNED_SHORT
  1897. , (void*)0
  1898. ) );
  1899. }
  1900. }
  1901. void updateResolution(const Resolution& _resolution)
  1902. {
  1903. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  1904. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  1905. ? m_maxAnisotropyDefault
  1906. : 0.0f
  1907. ;
  1908. uint32_t flags = _resolution.m_flags & ~(BGFX_RESET_HMD_RECENTER | BGFX_RESET_MAXANISOTROPY);
  1909. if (m_resolution.m_width != _resolution.m_width
  1910. || m_resolution.m_height != _resolution.m_height
  1911. || m_resolution.m_flags != flags)
  1912. {
  1913. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  1914. m_textVideoMem.clear();
  1915. m_resolution = _resolution;
  1916. m_resolution.m_flags = flags;
  1917. if ( (flags & BGFX_RESET_HMD)
  1918. && m_ovr.isInitialized() )
  1919. {
  1920. flags &= ~BGFX_RESET_MSAA_MASK;
  1921. }
  1922. setRenderContextSize(m_resolution.m_width
  1923. , m_resolution.m_height
  1924. , flags
  1925. );
  1926. updateCapture();
  1927. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1928. {
  1929. m_frameBuffers[ii].postReset();
  1930. }
  1931. ovrPreReset();
  1932. ovrPostReset();
  1933. }
  1934. if (recenter)
  1935. {
  1936. m_ovr.recenter();
  1937. }
  1938. }
  1939. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1940. {
  1941. GL_CHECK(glUniform4fv(_regIndex
  1942. , _numRegs
  1943. , (const GLfloat*)_val
  1944. ) );
  1945. }
  1946. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1947. {
  1948. GL_CHECK(glUniformMatrix4fv(_regIndex
  1949. , _numRegs
  1950. , GL_FALSE
  1951. , (const GLfloat*)_val
  1952. ) );
  1953. }
  1954. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  1955. {
  1956. if (isValid(m_fbh)
  1957. && m_fbh.idx != _fbh.idx
  1958. && (BGFX_CLEAR_NONE != m_fbDiscard || m_rtMsaa) )
  1959. {
  1960. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  1961. if (m_rtMsaa)
  1962. {
  1963. frameBuffer.resolve();
  1964. }
  1965. if (BGFX_CLEAR_NONE != m_fbDiscard)
  1966. {
  1967. frameBuffer.discard(m_fbDiscard);
  1968. }
  1969. m_fbDiscard = BGFX_CLEAR_NONE;
  1970. }
  1971. m_glctx.makeCurrent(NULL);
  1972. if (!isValid(_fbh) )
  1973. {
  1974. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1975. }
  1976. else
  1977. {
  1978. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  1979. _height = frameBuffer.m_height;
  1980. if (UINT16_MAX != frameBuffer.m_denseIdx)
  1981. {
  1982. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  1983. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1984. }
  1985. else
  1986. {
  1987. m_glctx.makeCurrent(NULL);
  1988. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  1989. }
  1990. }
  1991. m_fbh = _fbh;
  1992. m_fbDiscard = _discard;
  1993. m_rtMsaa = _msaa;
  1994. return _height;
  1995. }
  1996. uint32_t getNumRt() const
  1997. {
  1998. if (isValid(m_fbh) )
  1999. {
  2000. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2001. return frameBuffer.m_num;
  2002. }
  2003. return 1;
  2004. }
  2005. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  2006. {
  2007. if (0 == m_msaaBackBufferFbo // iOS
  2008. && 1 < _msaa)
  2009. {
  2010. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2011. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2012. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2013. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2014. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  2015. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2016. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  2017. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2018. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2019. ? GL_DEPTH_STENCIL_ATTACHMENT
  2020. : GL_DEPTH_ATTACHMENT
  2021. ;
  2022. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2023. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2024. , "glCheckFramebufferStatus failed 0x%08x"
  2025. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2026. );
  2027. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2028. }
  2029. }
  2030. void destroyMsaaFbo()
  2031. {
  2032. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2033. && 0 != m_msaaBackBufferFbo)
  2034. {
  2035. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2036. m_msaaBackBufferFbo = 0;
  2037. if (0 != m_msaaBackBufferRbos[0])
  2038. {
  2039. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2040. m_msaaBackBufferRbos[0] = 0;
  2041. m_msaaBackBufferRbos[1] = 0;
  2042. }
  2043. }
  2044. }
  2045. void blitMsaaFbo()
  2046. {
  2047. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2048. && 0 != m_msaaBackBufferFbo)
  2049. {
  2050. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2051. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2052. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2053. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2054. uint32_t width = m_resolution.m_width;
  2055. uint32_t height = m_resolution.m_height;
  2056. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2057. ? GL_NEAREST
  2058. : GL_LINEAR
  2059. ;
  2060. GL_CHECK(glBlitFramebuffer(0
  2061. , 0
  2062. , width
  2063. , height
  2064. , 0
  2065. , 0
  2066. , width
  2067. , height
  2068. , GL_COLOR_BUFFER_BIT
  2069. , filter
  2070. ) );
  2071. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2072. }
  2073. }
  2074. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2075. {
  2076. if (_width != 0
  2077. || _height != 0)
  2078. {
  2079. if (!m_glctx.isValid() )
  2080. {
  2081. m_glctx.create(_width, _height);
  2082. #if BX_PLATFORM_IOS
  2083. // iOS: need to figure out how to deal with FBO created by context.
  2084. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2085. #endif // BX_PLATFORM_IOS
  2086. }
  2087. else
  2088. {
  2089. destroyMsaaFbo();
  2090. m_glctx.resize(_width, _height, _flags);
  2091. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2092. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2093. createMsaaFbo(_width, _height, msaa);
  2094. }
  2095. }
  2096. m_flip = true;
  2097. }
  2098. void invalidateCache()
  2099. {
  2100. if (m_vaoSupport)
  2101. {
  2102. m_vaoStateCache.invalidate();
  2103. }
  2104. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2105. && m_samplerObjectSupport)
  2106. {
  2107. m_samplerStateCache.invalidate();
  2108. }
  2109. }
  2110. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags)
  2111. {
  2112. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2113. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2114. {
  2115. if (0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) )
  2116. {
  2117. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  2118. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  2119. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  2120. GLuint sampler = m_samplerStateCache.find(_flags);
  2121. if (UINT32_MAX == sampler)
  2122. {
  2123. sampler = m_samplerStateCache.add(_flags);
  2124. GL_CHECK(glSamplerParameteri(sampler
  2125. , GL_TEXTURE_WRAP_S
  2126. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  2127. ) );
  2128. GL_CHECK(glSamplerParameteri(sampler
  2129. , GL_TEXTURE_WRAP_T
  2130. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  2131. ) );
  2132. GL_CHECK(glSamplerParameteri(sampler
  2133. , GL_TEXTURE_WRAP_R
  2134. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  2135. ) );
  2136. GLenum minFilter;
  2137. GLenum magFilter;
  2138. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  2139. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  2140. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  2141. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  2142. && 0.0f < m_maxAnisotropy)
  2143. {
  2144. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  2145. }
  2146. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2147. || m_shadowSamplersSupport)
  2148. {
  2149. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  2150. if (0 == cmpFunc)
  2151. {
  2152. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  2153. }
  2154. else
  2155. {
  2156. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  2157. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  2158. }
  2159. }
  2160. }
  2161. GL_CHECK(glBindSampler(_stage, sampler) );
  2162. }
  2163. else
  2164. {
  2165. GL_CHECK(glBindSampler(_stage, 0) );
  2166. }
  2167. }
  2168. }
  2169. void ovrPostReset()
  2170. {
  2171. #if BGFX_CONFIG_USE_OVR
  2172. if (m_resolution.m_flags & (BGFX_RESET_HMD|BGFX_RESET_HMD_DEBUG) )
  2173. {
  2174. ovrGLConfig config;
  2175. config.OGL.Header.API = ovrRenderAPI_OpenGL;
  2176. # if OVR_VERSION > OVR_VERSION_043
  2177. config.OGL.Header.BackBufferSize.w = m_resolution.m_width;
  2178. config.OGL.Header.BackBufferSize.h = m_resolution.m_height;
  2179. # else
  2180. config.OGL.Header.RTSize.w = m_resolution.m_width;
  2181. config.OGL.Header.RTSize.h = m_resolution.m_height;
  2182. # endif // OVR_VERSION > OVR_VERSION_043
  2183. config.OGL.Header.Multisample = 0;
  2184. config.OGL.Window = (HWND)g_platformData.nwh;
  2185. config.OGL.DC = GetDC(config.OGL.Window);
  2186. if (m_ovr.postReset(g_platformData.nwh, &config.Config, !!(m_resolution.m_flags & BGFX_RESET_HMD_DEBUG) ) )
  2187. {
  2188. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  2189. const Memory* mem = alloc(size);
  2190. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2191. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2192. bx::write(&writer, magic);
  2193. TextureCreate tc;
  2194. tc.m_flags = BGFX_TEXTURE_RT|( ((m_resolution.m_flags & BGFX_RESET_MSAA_MASK) >> BGFX_RESET_MSAA_SHIFT) << BGFX_TEXTURE_RT_MSAA_SHIFT);;
  2195. tc.m_width = m_ovr.m_rtSize.w;
  2196. tc.m_height = m_ovr.m_rtSize.h;
  2197. tc.m_sides = 0;
  2198. tc.m_depth = 0;
  2199. tc.m_numMips = 1;
  2200. tc.m_format = uint8_t(bgfx::TextureFormat::BGRA8);
  2201. tc.m_cubeMap = false;
  2202. tc.m_mem = NULL;
  2203. bx::write(&writer, tc);
  2204. m_ovrRT.create(mem, tc.m_flags, 0);
  2205. release(mem);
  2206. m_ovrFbo = m_msaaBackBufferFbo;
  2207. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2208. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2209. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  2210. , GL_COLOR_ATTACHMENT0
  2211. , GL_TEXTURE_2D
  2212. , m_ovrRT.m_id
  2213. , 0
  2214. ) );
  2215. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_ovrFbo) );
  2216. ovrGLTexture texture;
  2217. texture.OGL.Header.API = ovrRenderAPI_OpenGL;
  2218. texture.OGL.Header.TextureSize = m_ovr.m_rtSize;
  2219. texture.OGL.TexId = m_ovrRT.m_id;
  2220. m_ovr.postReset(texture.Texture);
  2221. }
  2222. }
  2223. #endif // BGFX_CONFIG_USE_OVR
  2224. }
  2225. void ovrPreReset()
  2226. {
  2227. #if BGFX_CONFIG_USE_OVR
  2228. m_ovr.preReset();
  2229. if (m_ovr.isEnabled() )
  2230. {
  2231. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  2232. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2233. m_msaaBackBufferFbo = m_ovrFbo;
  2234. m_ovrFbo = 0;
  2235. m_ovrRT.destroy();
  2236. }
  2237. #endif // BGFX_CONFIG_USE_OVR
  2238. }
  2239. void updateCapture()
  2240. {
  2241. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  2242. {
  2243. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  2244. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  2245. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  2246. }
  2247. else
  2248. {
  2249. captureFinish();
  2250. }
  2251. }
  2252. void capture()
  2253. {
  2254. if (NULL != m_capture)
  2255. {
  2256. GL_CHECK(glReadPixels(0
  2257. , 0
  2258. , m_resolution.m_width
  2259. , m_resolution.m_height
  2260. , m_readPixelsFmt
  2261. , GL_UNSIGNED_BYTE
  2262. , m_capture
  2263. ) );
  2264. g_callback->captureFrame(m_capture, m_captureSize);
  2265. }
  2266. }
  2267. void captureFinish()
  2268. {
  2269. if (NULL != m_capture)
  2270. {
  2271. g_callback->captureEnd();
  2272. BX_FREE(g_allocator, m_capture);
  2273. m_capture = NULL;
  2274. m_captureSize = 0;
  2275. }
  2276. }
  2277. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2278. {
  2279. _id ^= m_hash;
  2280. bool cached = false;
  2281. if (m_programBinarySupport)
  2282. {
  2283. uint32_t length = g_callback->cacheReadSize(_id);
  2284. cached = length > 0;
  2285. if (cached)
  2286. {
  2287. void* data = BX_ALLOC(g_allocator, length);
  2288. if (g_callback->cacheRead(_id, data, length) )
  2289. {
  2290. bx::MemoryReader reader(data, length);
  2291. GLenum format;
  2292. bx::read(&reader, format);
  2293. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2294. }
  2295. BX_FREE(g_allocator, data);
  2296. }
  2297. #if BGFX_CONFIG_RENDERER_OPENGL
  2298. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2299. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2300. }
  2301. return cached;
  2302. }
  2303. void programCache(GLuint programId, uint64_t _id)
  2304. {
  2305. _id ^= m_hash;
  2306. if (m_programBinarySupport)
  2307. {
  2308. GLint programLength;
  2309. GLenum format;
  2310. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2311. if (0 < programLength)
  2312. {
  2313. uint32_t length = programLength + 4;
  2314. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2315. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2316. *(uint32_t*)data = format;
  2317. g_callback->cacheWrite(_id, data, length);
  2318. BX_FREE(g_allocator, data);
  2319. }
  2320. }
  2321. }
  2322. void commit(ConstantBuffer& _constantBuffer)
  2323. {
  2324. _constantBuffer.reset();
  2325. for (;;)
  2326. {
  2327. uint32_t opcode = _constantBuffer.read();
  2328. if (UniformType::End == opcode)
  2329. {
  2330. break;
  2331. }
  2332. UniformType::Enum type;
  2333. uint16_t ignore;
  2334. uint16_t num;
  2335. uint16_t copy;
  2336. ConstantBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2337. const char* data;
  2338. if (copy)
  2339. {
  2340. data = _constantBuffer.read(g_uniformTypeSize[type]*num);
  2341. }
  2342. else
  2343. {
  2344. UniformHandle handle;
  2345. memcpy(&handle, _constantBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2346. data = (const char*)m_uniforms[handle.idx];
  2347. }
  2348. uint32_t loc = _constantBuffer.read();
  2349. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2350. case UniformType::_uniform: \
  2351. { \
  2352. _type* value = (_type*)data; \
  2353. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2354. } \
  2355. break;
  2356. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2357. case UniformType::_uniform: \
  2358. { \
  2359. _type* value = (_type*)data; \
  2360. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2361. } \
  2362. break;
  2363. switch (type)
  2364. {
  2365. // case ConstantType::Int1:
  2366. // {
  2367. // int* value = (int*)data;
  2368. // BX_TRACE("Int1 sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2369. // GL_CHECK(glUniform1iv(loc, num, value) );
  2370. // }
  2371. // break;
  2372. CASE_IMPLEMENT_UNIFORM(Int1, 1iv, I, int);
  2373. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  2374. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  2375. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  2376. case UniformType::End:
  2377. break;
  2378. default:
  2379. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _constantBuffer.getPos(), opcode, type, loc, num, copy);
  2380. break;
  2381. }
  2382. #undef CASE_IMPLEMENT_UNIFORM
  2383. #undef CASE_IMPLEMENT_UNIFORM_T
  2384. }
  2385. }
  2386. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2387. {
  2388. uint32_t numMrt = 1;
  2389. FrameBufferHandle fbh = m_fbh;
  2390. if (isValid(fbh) )
  2391. {
  2392. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2393. numMrt = bx::uint32_max(1, fb.m_num);
  2394. }
  2395. if (1 == numMrt)
  2396. {
  2397. GLuint flags = 0;
  2398. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2399. {
  2400. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2401. {
  2402. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[0]);
  2403. const float* rgba = _palette[index];
  2404. const float rr = rgba[0];
  2405. const float gg = rgba[1];
  2406. const float bb = rgba[2];
  2407. const float aa = rgba[3];
  2408. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2409. }
  2410. else
  2411. {
  2412. float rr = _clear.m_index[0]*1.0f/255.0f;
  2413. float gg = _clear.m_index[1]*1.0f/255.0f;
  2414. float bb = _clear.m_index[2]*1.0f/255.0f;
  2415. float aa = _clear.m_index[3]*1.0f/255.0f;
  2416. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2417. }
  2418. flags |= GL_COLOR_BUFFER_BIT;
  2419. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2420. }
  2421. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2422. {
  2423. flags |= GL_DEPTH_BUFFER_BIT;
  2424. GL_CHECK(glClearDepth(_clear.m_depth) );
  2425. GL_CHECK(glDepthMask(GL_TRUE) );
  2426. }
  2427. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2428. {
  2429. flags |= GL_STENCIL_BUFFER_BIT;
  2430. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2431. }
  2432. if (0 != flags)
  2433. {
  2434. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2435. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2436. GL_CHECK(glClear(flags) );
  2437. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2438. }
  2439. }
  2440. else
  2441. {
  2442. const GLuint defaultVao = m_vao;
  2443. if (0 != defaultVao)
  2444. {
  2445. GL_CHECK(glBindVertexArray(defaultVao) );
  2446. }
  2447. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2448. GL_CHECK(glDisable(GL_CULL_FACE) );
  2449. GL_CHECK(glDisable(GL_BLEND) );
  2450. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2451. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2452. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2453. {
  2454. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2455. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2456. GL_CHECK(glDepthMask(GL_TRUE) );
  2457. }
  2458. else
  2459. {
  2460. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2461. }
  2462. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2463. {
  2464. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2465. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2466. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2467. }
  2468. else
  2469. {
  2470. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2471. }
  2472. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2473. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2474. {
  2475. struct Vertex
  2476. {
  2477. float m_x;
  2478. float m_y;
  2479. float m_z;
  2480. };
  2481. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2482. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2483. const float depth = _clear.m_depth * 2.0f - 1.0f;
  2484. vertex->m_x = -1.0f;
  2485. vertex->m_y = -1.0f;
  2486. vertex->m_z = depth;
  2487. vertex++;
  2488. vertex->m_x = 1.0f;
  2489. vertex->m_y = -1.0f;
  2490. vertex->m_z = depth;
  2491. vertex++;
  2492. vertex->m_x = -1.0f;
  2493. vertex->m_y = 1.0f;
  2494. vertex->m_z = depth;
  2495. vertex++;
  2496. vertex->m_x = 1.0f;
  2497. vertex->m_y = 1.0f;
  2498. vertex->m_z = depth;
  2499. }
  2500. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2501. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2502. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2503. GL_CHECK(glUseProgram(program.m_id) );
  2504. program.bindAttributes(vertexDecl, 0);
  2505. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2506. {
  2507. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2508. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2509. {
  2510. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[ii]);
  2511. memcpy(mrtClear[ii], _palette[index], 16);
  2512. }
  2513. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  2514. }
  2515. else
  2516. {
  2517. float rgba[4] =
  2518. {
  2519. _clear.m_index[0]*1.0f/255.0f,
  2520. _clear.m_index[1]*1.0f/255.0f,
  2521. _clear.m_index[2]*1.0f/255.0f,
  2522. _clear.m_index[3]*1.0f/255.0f,
  2523. };
  2524. GL_CHECK(glUniform4fv(0, 1, rgba) );
  2525. }
  2526. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  2527. , 0
  2528. , 4
  2529. ) );
  2530. }
  2531. }
  2532. void* m_renderdocdll;
  2533. uint16_t m_numWindows;
  2534. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2535. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  2536. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  2537. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  2538. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  2539. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  2540. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  2541. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2542. UniformRegistry m_uniformReg;
  2543. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  2544. TimerQueryGL m_gpuTimer;
  2545. VaoStateCache m_vaoStateCache;
  2546. SamplerStateCache m_samplerStateCache;
  2547. TextVideoMem m_textVideoMem;
  2548. bool m_rtMsaa;
  2549. FrameBufferHandle m_fbh;
  2550. uint16_t m_fbDiscard;
  2551. Resolution m_resolution;
  2552. void* m_capture;
  2553. uint32_t m_captureSize;
  2554. float m_maxAnisotropy;
  2555. float m_maxAnisotropyDefault;
  2556. int32_t m_maxMsaa;
  2557. GLuint m_vao;
  2558. bool m_vaoSupport;
  2559. bool m_samplerObjectSupport;
  2560. bool m_shadowSamplersSupport;
  2561. bool m_programBinarySupport;
  2562. bool m_textureSwizzleSupport;
  2563. bool m_depthTextureSupport;
  2564. bool m_timerQuerySupport;
  2565. bool m_flip;
  2566. uint64_t m_hash;
  2567. GLenum m_readPixelsFmt;
  2568. GLuint m_backBufferFbo;
  2569. GLuint m_msaaBackBufferFbo;
  2570. GLuint m_msaaBackBufferRbos[2];
  2571. GlContext m_glctx;
  2572. const char* m_vendor;
  2573. const char* m_renderer;
  2574. const char* m_version;
  2575. const char* m_glslVersion;
  2576. OVR m_ovr;
  2577. TextureGL m_ovrRT;
  2578. GLint m_ovrFbo;
  2579. };
  2580. RendererContextGL* s_renderGL;
  2581. RendererContextI* rendererCreate()
  2582. {
  2583. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  2584. s_renderGL->init();
  2585. return s_renderGL;
  2586. }
  2587. void rendererDestroy()
  2588. {
  2589. s_renderGL->shutdown();
  2590. BX_DELETE(g_allocator, s_renderGL);
  2591. s_renderGL = NULL;
  2592. }
  2593. const char* glslTypeName(GLuint _type)
  2594. {
  2595. #define GLSL_TYPE(_ty) case _ty: return #_ty
  2596. switch (_type)
  2597. {
  2598. GLSL_TYPE(GL_INT);
  2599. GLSL_TYPE(GL_INT_VEC2);
  2600. GLSL_TYPE(GL_INT_VEC3);
  2601. GLSL_TYPE(GL_INT_VEC4);
  2602. GLSL_TYPE(GL_UNSIGNED_INT);
  2603. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  2604. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  2605. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  2606. GLSL_TYPE(GL_FLOAT);
  2607. GLSL_TYPE(GL_FLOAT_VEC2);
  2608. GLSL_TYPE(GL_FLOAT_VEC3);
  2609. GLSL_TYPE(GL_FLOAT_VEC4);
  2610. GLSL_TYPE(GL_FLOAT_MAT2);
  2611. GLSL_TYPE(GL_FLOAT_MAT3);
  2612. GLSL_TYPE(GL_FLOAT_MAT4);
  2613. GLSL_TYPE(GL_SAMPLER_2D);
  2614. GLSL_TYPE(GL_INT_SAMPLER_2D);
  2615. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  2616. GLSL_TYPE(GL_SAMPLER_3D);
  2617. GLSL_TYPE(GL_INT_SAMPLER_3D);
  2618. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  2619. GLSL_TYPE(GL_SAMPLER_CUBE);
  2620. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  2621. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  2622. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  2623. GLSL_TYPE(GL_IMAGE_1D);
  2624. GLSL_TYPE(GL_INT_IMAGE_1D);
  2625. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  2626. GLSL_TYPE(GL_IMAGE_2D);
  2627. GLSL_TYPE(GL_INT_IMAGE_2D);
  2628. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  2629. GLSL_TYPE(GL_IMAGE_3D);
  2630. GLSL_TYPE(GL_INT_IMAGE_3D);
  2631. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  2632. GLSL_TYPE(GL_IMAGE_CUBE);
  2633. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  2634. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  2635. }
  2636. #undef GLSL_TYPE
  2637. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  2638. return "UNKNOWN GLSL TYPE!";
  2639. }
  2640. const char* glEnumName(GLenum _enum)
  2641. {
  2642. #define GLENUM(_ty) case _ty: return #_ty
  2643. switch (_enum)
  2644. {
  2645. GLENUM(GL_TEXTURE);
  2646. GLENUM(GL_RENDERBUFFER);
  2647. GLENUM(GL_INVALID_ENUM);
  2648. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  2649. GLENUM(GL_INVALID_VALUE);
  2650. GLENUM(GL_INVALID_OPERATION);
  2651. GLENUM(GL_OUT_OF_MEMORY);
  2652. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  2653. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  2654. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  2655. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  2656. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  2657. }
  2658. #undef GLENUM
  2659. BX_WARN(false, "Unknown enum? %x", _enum);
  2660. return "<GLenum?>";
  2661. }
  2662. UniformType::Enum convertGlType(GLenum _type)
  2663. {
  2664. switch (_type)
  2665. {
  2666. case GL_INT:
  2667. case GL_UNSIGNED_INT:
  2668. return UniformType::Int1;
  2669. case GL_FLOAT:
  2670. case GL_FLOAT_VEC2:
  2671. case GL_FLOAT_VEC3:
  2672. case GL_FLOAT_VEC4:
  2673. return UniformType::Vec4;
  2674. case GL_FLOAT_MAT2:
  2675. break;
  2676. case GL_FLOAT_MAT3:
  2677. return UniformType::Mat3;
  2678. case GL_FLOAT_MAT4:
  2679. return UniformType::Mat4;
  2680. case GL_SAMPLER_2D:
  2681. case GL_INT_SAMPLER_2D:
  2682. case GL_UNSIGNED_INT_SAMPLER_2D:
  2683. case GL_SAMPLER_3D:
  2684. case GL_INT_SAMPLER_3D:
  2685. case GL_UNSIGNED_INT_SAMPLER_3D:
  2686. case GL_SAMPLER_CUBE:
  2687. case GL_INT_SAMPLER_CUBE:
  2688. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2689. case GL_SAMPLER_2D_SHADOW:
  2690. case GL_IMAGE_1D:
  2691. case GL_INT_IMAGE_1D:
  2692. case GL_UNSIGNED_INT_IMAGE_1D:
  2693. case GL_IMAGE_2D:
  2694. case GL_INT_IMAGE_2D:
  2695. case GL_UNSIGNED_INT_IMAGE_2D:
  2696. case GL_IMAGE_3D:
  2697. case GL_INT_IMAGE_3D:
  2698. case GL_UNSIGNED_INT_IMAGE_3D:
  2699. case GL_IMAGE_CUBE:
  2700. case GL_INT_IMAGE_CUBE:
  2701. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2702. return UniformType::Int1;
  2703. };
  2704. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  2705. return UniformType::End;
  2706. }
  2707. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  2708. {
  2709. m_id = glCreateProgram();
  2710. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  2711. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  2712. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  2713. if (!cached)
  2714. {
  2715. GLint linked = 0;
  2716. if (0 != _vsh.m_id)
  2717. {
  2718. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  2719. if (0 != _fsh.m_id)
  2720. {
  2721. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  2722. }
  2723. GL_CHECK(glLinkProgram(m_id) );
  2724. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  2725. if (0 == linked)
  2726. {
  2727. char log[1024];
  2728. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  2729. BX_TRACE("%d: %s", linked, log);
  2730. }
  2731. }
  2732. if (0 == linked)
  2733. {
  2734. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  2735. GL_CHECK(glDeleteProgram(m_id) );
  2736. m_used[0] = Attrib::Count;
  2737. m_id = 0;
  2738. return;
  2739. }
  2740. s_renderGL->programCache(m_id, id);
  2741. }
  2742. init();
  2743. if (!cached)
  2744. {
  2745. // Must be after init, otherwise init might fail to lookup shader
  2746. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  2747. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  2748. if (0 != _fsh.m_id)
  2749. {
  2750. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  2751. }
  2752. }
  2753. }
  2754. void ProgramGL::destroy()
  2755. {
  2756. if (NULL != m_constantBuffer)
  2757. {
  2758. ConstantBuffer::destroy(m_constantBuffer);
  2759. m_constantBuffer = NULL;
  2760. }
  2761. m_numPredefined = 0;
  2762. if (0 != m_id)
  2763. {
  2764. GL_CHECK(glUseProgram(0) );
  2765. GL_CHECK(glDeleteProgram(m_id) );
  2766. m_id = 0;
  2767. }
  2768. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  2769. }
  2770. void ProgramGL::init()
  2771. {
  2772. GLint activeAttribs = 0;
  2773. GLint activeUniforms = 0;
  2774. GLint activeBuffers = 0;
  2775. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  2776. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  2777. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  2778. bool piqSupported = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) || (true
  2779. && s_extension[Extension::ARB_program_interface_query].m_supported
  2780. && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported
  2781. );
  2782. if (piqSupported)
  2783. {
  2784. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  2785. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  2786. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  2787. }
  2788. else
  2789. {
  2790. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  2791. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  2792. }
  2793. GLint max0, max1;
  2794. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  2795. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  2796. uint32_t maxLength = bx::uint32_max(max0, max1);
  2797. char* name = (char*)alloca(maxLength + 1);
  2798. BX_TRACE("Program %d", m_id);
  2799. BX_TRACE("Attributes (%d):", activeAttribs);
  2800. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  2801. {
  2802. GLint size;
  2803. GLenum type;
  2804. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  2805. BX_TRACE("\t%s %s is at location %d"
  2806. , glslTypeName(type)
  2807. , name
  2808. , glGetAttribLocation(m_id, name)
  2809. );
  2810. }
  2811. m_numPredefined = 0;
  2812. m_numSamplers = 0;
  2813. BX_TRACE("Uniforms (%d):", activeUniforms);
  2814. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  2815. {
  2816. struct VariableInfo
  2817. {
  2818. GLenum type;
  2819. GLint loc;
  2820. GLint num;
  2821. };
  2822. VariableInfo vi;
  2823. GLenum props[] ={ GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  2824. GLenum gltype;
  2825. GLint num;
  2826. GLint loc;
  2827. if (piqSupported)
  2828. {
  2829. GL_CHECK(glGetProgramResourceiv(m_id
  2830. , GL_UNIFORM
  2831. , ii
  2832. , BX_COUNTOF(props)
  2833. , props
  2834. , BX_COUNTOF(props)
  2835. , NULL
  2836. , (GLint*)&vi
  2837. ) );
  2838. GL_CHECK(glGetProgramResourceName(m_id
  2839. , GL_UNIFORM
  2840. , ii
  2841. , maxLength + 1
  2842. , NULL
  2843. , name
  2844. ) );
  2845. gltype = vi.type;
  2846. loc = vi.loc;
  2847. num = vi.num;
  2848. }
  2849. else
  2850. {
  2851. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  2852. loc = glGetUniformLocation(m_id, name);
  2853. }
  2854. num = bx::uint32_max(num, 1);
  2855. int offset = 0;
  2856. char* array = strchr(name, '[');
  2857. if (NULL != array)
  2858. {
  2859. BX_TRACE("--- %s", name);
  2860. *array = '\0';
  2861. array++;
  2862. char* end = strchr(array, ']');
  2863. if (NULL != end)
  2864. { // Some devices (Amazon Fire) might not return terminating brace.
  2865. *end = '\0';
  2866. offset = atoi(array);
  2867. }
  2868. }
  2869. switch (gltype)
  2870. {
  2871. case GL_SAMPLER_2D:
  2872. case GL_INT_SAMPLER_2D:
  2873. case GL_UNSIGNED_INT_SAMPLER_2D:
  2874. case GL_SAMPLER_3D:
  2875. case GL_INT_SAMPLER_3D:
  2876. case GL_UNSIGNED_INT_SAMPLER_3D:
  2877. case GL_SAMPLER_CUBE:
  2878. case GL_INT_SAMPLER_CUBE:
  2879. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2880. case GL_SAMPLER_2D_SHADOW:
  2881. case GL_IMAGE_1D:
  2882. case GL_INT_IMAGE_1D:
  2883. case GL_UNSIGNED_INT_IMAGE_1D:
  2884. case GL_IMAGE_2D:
  2885. case GL_INT_IMAGE_2D:
  2886. case GL_UNSIGNED_INT_IMAGE_2D:
  2887. case GL_IMAGE_3D:
  2888. case GL_INT_IMAGE_3D:
  2889. case GL_UNSIGNED_INT_IMAGE_3D:
  2890. case GL_IMAGE_CUBE:
  2891. case GL_INT_IMAGE_CUBE:
  2892. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2893. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  2894. m_sampler[m_numSamplers] = loc;
  2895. m_numSamplers++;
  2896. break;
  2897. default:
  2898. break;
  2899. }
  2900. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2901. if (PredefinedUniform::Count != predefined)
  2902. {
  2903. m_predefined[m_numPredefined].m_loc = loc;
  2904. m_predefined[m_numPredefined].m_count = uint16_t(num);
  2905. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  2906. m_numPredefined++;
  2907. }
  2908. else
  2909. {
  2910. const UniformInfo* info = s_renderGL->m_uniformReg.find(name);
  2911. if (NULL != info)
  2912. {
  2913. if (NULL == m_constantBuffer)
  2914. {
  2915. m_constantBuffer = ConstantBuffer::create(1024);
  2916. }
  2917. UniformType::Enum type = convertGlType(gltype);
  2918. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  2919. m_constantBuffer->write(loc);
  2920. BX_TRACE("store %s %d", name, info->m_handle);
  2921. }
  2922. }
  2923. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  2924. , glslTypeName(gltype)
  2925. , name
  2926. , PredefinedUniform::Count != predefined ? "*" : ""
  2927. , loc
  2928. , num
  2929. , offset
  2930. );
  2931. BX_UNUSED(offset);
  2932. }
  2933. if (NULL != m_constantBuffer)
  2934. {
  2935. m_constantBuffer->finish();
  2936. }
  2937. if (piqSupported)
  2938. {
  2939. struct VariableInfo
  2940. {
  2941. GLenum type;
  2942. };
  2943. VariableInfo vi;
  2944. GLenum props[] = { GL_TYPE };
  2945. BX_TRACE("Buffers (%d):", activeBuffers);
  2946. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  2947. {
  2948. GL_CHECK(glGetProgramResourceiv(m_id
  2949. , GL_BUFFER_VARIABLE
  2950. , ii
  2951. , BX_COUNTOF(props)
  2952. , props
  2953. , BX_COUNTOF(props)
  2954. , NULL
  2955. , (GLint*)&vi
  2956. ) );
  2957. GL_CHECK(glGetProgramResourceName(m_id
  2958. , GL_BUFFER_VARIABLE
  2959. , ii
  2960. , maxLength + 1
  2961. , NULL
  2962. , name
  2963. ) );
  2964. BX_TRACE("\t%s %s at %d"
  2965. , glslTypeName(vi.type)
  2966. , name
  2967. , 0 //vi.loc
  2968. );
  2969. }
  2970. }
  2971. memset(m_attributes, 0xff, sizeof(m_attributes) );
  2972. uint32_t used = 0;
  2973. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  2974. {
  2975. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  2976. if (-1 != loc)
  2977. {
  2978. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  2979. m_attributes[ii] = loc;
  2980. m_used[used++] = ii;
  2981. }
  2982. }
  2983. BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d."
  2984. , used
  2985. , BX_COUNTOF(m_used)
  2986. );
  2987. m_used[used] = Attrib::Count;
  2988. used = 0;
  2989. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  2990. {
  2991. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  2992. if (GLuint(-1) != loc )
  2993. {
  2994. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  2995. m_instanceData[used++] = loc;
  2996. }
  2997. }
  2998. BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d."
  2999. , used
  3000. , BX_COUNTOF(m_instanceData)
  3001. );
  3002. m_instanceData[used] = 0xffff;
  3003. }
  3004. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  3005. {
  3006. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  3007. {
  3008. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3009. GLint loc = m_attributes[attr];
  3010. uint8_t num;
  3011. AttribType::Enum type;
  3012. bool normalized;
  3013. bool asInt;
  3014. _vertexDecl.decode(attr, num, type, normalized, asInt);
  3015. if (-1 != loc)
  3016. {
  3017. if (UINT16_MAX != _vertexDecl.m_attributes[attr])
  3018. {
  3019. GL_CHECK(glEnableVertexAttribArray(loc) );
  3020. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  3021. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  3022. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  3023. }
  3024. else
  3025. {
  3026. GL_CHECK(glDisableVertexAttribArray(loc) );
  3027. }
  3028. }
  3029. }
  3030. }
  3031. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  3032. {
  3033. uint32_t baseVertex = _baseVertex;
  3034. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3035. {
  3036. GLint loc = m_instanceData[ii];
  3037. GL_CHECK(glEnableVertexAttribArray(loc) );
  3038. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  3039. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  3040. baseVertex += 16;
  3041. }
  3042. }
  3043. void IndexBufferGL::destroy()
  3044. {
  3045. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  3046. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3047. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3048. }
  3049. void VertexBufferGL::destroy()
  3050. {
  3051. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  3052. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3053. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3054. }
  3055. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _data)
  3056. {
  3057. if (_target == GL_TEXTURE_3D)
  3058. {
  3059. GL_CHECK(glTexImage3D(_target, _level, _internalFormat, _width, _height, _depth, _border, _format, _type, _data) );
  3060. }
  3061. else
  3062. {
  3063. BX_UNUSED(_depth);
  3064. GL_CHECK(glTexImage2D(_target, _level, _internalFormat, _width, _height, _border, _format, _type, _data) );
  3065. }
  3066. }
  3067. static void texSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLenum _type, const GLvoid* _data)
  3068. {
  3069. if (_target == GL_TEXTURE_3D)
  3070. {
  3071. GL_CHECK(glTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _type, _data) );
  3072. }
  3073. else
  3074. {
  3075. BX_UNUSED(_zoffset, _depth);
  3076. GL_CHECK(glTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _type, _data) );
  3077. }
  3078. }
  3079. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  3080. {
  3081. if (_target == GL_TEXTURE_3D)
  3082. {
  3083. GL_CHECK(glCompressedTexImage3D(_target, _level, _internalformat, _width, _height, _depth, _border, _imageSize, _data) );
  3084. }
  3085. else
  3086. {
  3087. BX_UNUSED(_depth);
  3088. GL_CHECK(glCompressedTexImage2D(_target, _level, _internalformat, _width, _height, _border, _imageSize, _data) );
  3089. }
  3090. }
  3091. static void compressedTexSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLsizei _imageSize, const GLvoid* _data)
  3092. {
  3093. if (_target == GL_TEXTURE_3D)
  3094. {
  3095. GL_CHECK(glCompressedTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _imageSize, _data) );
  3096. }
  3097. else
  3098. {
  3099. BX_UNUSED(_zoffset, _depth);
  3100. GL_CHECK(glCompressedTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _imageSize, _data) );
  3101. }
  3102. }
  3103. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _format, uint8_t _numMips, uint32_t _flags)
  3104. {
  3105. m_target = _target;
  3106. m_numMips = _numMips;
  3107. m_flags = _flags;
  3108. m_width = _width;
  3109. m_height = _height;
  3110. m_depth = _depth;
  3111. m_currentFlags = UINT32_MAX;
  3112. m_requestedFormat = _format;
  3113. m_textureFormat = _format;
  3114. const bool bufferOnly = 0 != (m_flags&BGFX_TEXTURE_RT_BUFFER_ONLY);
  3115. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  3116. if (!bufferOnly)
  3117. {
  3118. GL_CHECK(glGenTextures(1, &m_id) );
  3119. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  3120. GL_CHECK(glBindTexture(_target, m_id) );
  3121. const TextureFormatInfo& tfi = s_textureFormat[_format];
  3122. m_fmt = tfi.m_fmt;
  3123. m_type = tfi.m_type;
  3124. const bool swizzle = true
  3125. && TextureFormat::BGRA8 == m_requestedFormat
  3126. && !s_textureFormat[m_requestedFormat].m_supported
  3127. && !s_renderGL->m_textureSwizzleSupport
  3128. ;
  3129. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3130. const bool convert = false
  3131. || (compressed && m_textureFormat != m_requestedFormat)
  3132. || swizzle
  3133. || !s_textureFormat[m_requestedFormat].m_supported
  3134. ;
  3135. if (convert)
  3136. {
  3137. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  3138. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  3139. m_fmt = tfiRgba8.m_fmt;
  3140. m_type = tfiRgba8.m_type;
  3141. }
  3142. if (computeWrite)
  3143. {
  3144. if (_target == GL_TEXTURE_3D)
  3145. {
  3146. GL_CHECK(glTexStorage3D(_target
  3147. , _numMips
  3148. , s_textureFormat[m_textureFormat].m_internalFmt
  3149. , m_width
  3150. , m_height
  3151. , _depth
  3152. ) );
  3153. }
  3154. else
  3155. {
  3156. GL_CHECK(glTexStorage2D(_target
  3157. , _numMips
  3158. , s_textureFormat[m_textureFormat].m_internalFmt
  3159. , m_width
  3160. , m_height
  3161. ) );
  3162. }
  3163. }
  3164. setSamplerState(_flags);
  3165. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3166. && TextureFormat::BGRA8 == m_requestedFormat
  3167. && !s_textureFormat[m_requestedFormat].m_supported
  3168. && s_renderGL->m_textureSwizzleSupport)
  3169. {
  3170. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  3171. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  3172. }
  3173. }
  3174. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  3175. if (renderTarget)
  3176. {
  3177. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  3178. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  3179. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  3180. if (0 != msaaQuality
  3181. || bufferOnly)
  3182. {
  3183. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  3184. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  3185. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  3186. if (0 == msaaQuality)
  3187. {
  3188. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  3189. , s_rboFormat[m_textureFormat]
  3190. , _width
  3191. , _height
  3192. ) );
  3193. }
  3194. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3195. {
  3196. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  3197. , msaaQuality
  3198. , s_rboFormat[m_textureFormat]
  3199. , _width
  3200. , _height
  3201. ) );
  3202. }
  3203. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  3204. if (bufferOnly)
  3205. {
  3206. // This is render buffer, there is no sampling, no need
  3207. // to create texture.
  3208. return false;
  3209. }
  3210. }
  3211. }
  3212. return true;
  3213. }
  3214. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  3215. {
  3216. ImageContainer imageContainer;
  3217. if (imageParse(imageContainer, _mem->data, _mem->size) )
  3218. {
  3219. uint8_t numMips = imageContainer.m_numMips;
  3220. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  3221. numMips -= startLod;
  3222. uint32_t textureWidth;
  3223. uint32_t textureHeight;
  3224. uint32_t textureDepth;
  3225. {
  3226. const ImageBlockInfo& ibi = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  3227. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  3228. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  3229. textureDepth = imageContainer.m_depth;
  3230. }
  3231. GLenum target = GL_TEXTURE_2D;
  3232. if (imageContainer.m_cubeMap)
  3233. {
  3234. target = GL_TEXTURE_CUBE_MAP;
  3235. }
  3236. else if (imageContainer.m_depth > 1)
  3237. {
  3238. target = GL_TEXTURE_3D;
  3239. }
  3240. if (!init(target
  3241. , textureWidth
  3242. , textureHeight
  3243. , textureDepth
  3244. , imageContainer.m_format
  3245. , numMips
  3246. , _flags
  3247. ) )
  3248. {
  3249. return;
  3250. }
  3251. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  3252. const bool srgb = 0 != (m_flags&BGFX_TEXTURE_SRGB);
  3253. target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3254. const GLenum internalFmt = srgb
  3255. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  3256. : s_textureFormat[m_textureFormat].m_internalFmt
  3257. ;
  3258. const bool swizzle = true
  3259. && TextureFormat::BGRA8 == m_requestedFormat
  3260. && !s_textureFormat[m_requestedFormat].m_supported
  3261. && !s_renderGL->m_textureSwizzleSupport
  3262. ;
  3263. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3264. const bool convert = false
  3265. || m_textureFormat != m_requestedFormat
  3266. || swizzle
  3267. ;
  3268. BX_TRACE("Texture%-4s %3d: %s (requested: %s), %dx%dx%d%s."
  3269. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  3270. , this - s_renderGL->m_textures
  3271. , getName( (TextureFormat::Enum)m_textureFormat)
  3272. , getName( (TextureFormat::Enum)m_requestedFormat)
  3273. , textureWidth
  3274. , textureHeight
  3275. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  3276. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  3277. );
  3278. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  3279. , swizzle ? "swizzle" : ""
  3280. , swizzle&&convert ? " and " : ""
  3281. , convert ? "convert" : ""
  3282. , getName( (TextureFormat::Enum)m_requestedFormat)
  3283. , getName( (TextureFormat::Enum)m_textureFormat)
  3284. );
  3285. uint8_t* temp = NULL;
  3286. if (convert)
  3287. {
  3288. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  3289. }
  3290. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  3291. {
  3292. uint32_t width = textureWidth;
  3293. uint32_t height = textureHeight;
  3294. uint32_t depth = imageContainer.m_depth;
  3295. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  3296. {
  3297. width = bx::uint32_max(1, width);
  3298. height = bx::uint32_max(1, height);
  3299. depth = bx::uint32_max(1, depth);
  3300. ImageMip mip;
  3301. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  3302. {
  3303. if (compressed
  3304. && !convert)
  3305. {
  3306. compressedTexImage(target+side
  3307. , lod
  3308. , internalFmt
  3309. , width
  3310. , height
  3311. , depth
  3312. , 0
  3313. , mip.m_size
  3314. , mip.m_data
  3315. );
  3316. }
  3317. else
  3318. {
  3319. const uint8_t* data = mip.m_data;
  3320. if (convert)
  3321. {
  3322. imageDecodeToRgba8(temp
  3323. , mip.m_data
  3324. , mip.m_width
  3325. , mip.m_height
  3326. , mip.m_width*4
  3327. , mip.m_format
  3328. );
  3329. data = temp;
  3330. }
  3331. texImage(target+side
  3332. , lod
  3333. , internalFmt
  3334. , width
  3335. , height
  3336. , depth
  3337. , 0
  3338. , m_fmt
  3339. , m_type
  3340. , data
  3341. );
  3342. }
  3343. }
  3344. else if (!computeWrite)
  3345. {
  3346. if (compressed)
  3347. {
  3348. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  3349. * bx::uint32_max(1, (height + 3)>>2)
  3350. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  3351. ;
  3352. compressedTexImage(target+side
  3353. , lod
  3354. , internalFmt
  3355. , width
  3356. , height
  3357. , depth
  3358. , 0
  3359. , size
  3360. , NULL
  3361. );
  3362. }
  3363. else
  3364. {
  3365. texImage(target+side
  3366. , lod
  3367. , internalFmt
  3368. , width
  3369. , height
  3370. , depth
  3371. , 0
  3372. , m_fmt
  3373. , m_type
  3374. , NULL
  3375. );
  3376. }
  3377. }
  3378. width >>= 1;
  3379. height >>= 1;
  3380. depth >>= 1;
  3381. }
  3382. }
  3383. if (NULL != temp)
  3384. {
  3385. BX_FREE(g_allocator, temp);
  3386. }
  3387. }
  3388. GL_CHECK(glBindTexture(m_target, 0) );
  3389. }
  3390. void TextureGL::destroy()
  3391. {
  3392. if (0 != m_id)
  3393. {
  3394. GL_CHECK(glBindTexture(m_target, 0) );
  3395. GL_CHECK(glDeleteTextures(1, &m_id) );
  3396. m_id = 0;
  3397. }
  3398. if (0 != m_rbo)
  3399. {
  3400. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  3401. m_rbo = 0;
  3402. }
  3403. }
  3404. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  3405. {
  3406. BX_UNUSED(_z, _depth);
  3407. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  3408. const uint32_t rectpitch = _rect.m_width*bpp/8;
  3409. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  3410. GL_CHECK(glBindTexture(m_target, m_id) );
  3411. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  3412. GLenum target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3413. const bool swizzle = true
  3414. && TextureFormat::BGRA8 == m_requestedFormat
  3415. && !s_textureFormat[m_requestedFormat].m_supported
  3416. && !s_renderGL->m_textureSwizzleSupport
  3417. ;
  3418. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  3419. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3420. const bool convert = false
  3421. || (compressed && m_textureFormat != m_requestedFormat)
  3422. || swizzle
  3423. ;
  3424. const uint32_t width = _rect.m_width;
  3425. const uint32_t height = _rect.m_height;
  3426. uint8_t* temp = NULL;
  3427. if (convert
  3428. || !unpackRowLength)
  3429. {
  3430. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  3431. }
  3432. else if (unpackRowLength)
  3433. {
  3434. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  3435. }
  3436. if (compressed)
  3437. {
  3438. const uint8_t* data = _mem->data;
  3439. if (!unpackRowLength)
  3440. {
  3441. imageCopy(width, height, bpp, srcpitch, data, temp);
  3442. data = temp;
  3443. }
  3444. GL_CHECK(compressedTexSubImage(target+_side
  3445. , _mip
  3446. , _rect.m_x
  3447. , _rect.m_y
  3448. , _z
  3449. , _rect.m_width
  3450. , _rect.m_height
  3451. , _depth
  3452. , m_fmt
  3453. , _mem->size
  3454. , data
  3455. ) );
  3456. }
  3457. else
  3458. {
  3459. const uint8_t* data = _mem->data;
  3460. if (convert)
  3461. {
  3462. imageDecodeToRgba8(temp, data, width, height, srcpitch, m_requestedFormat);
  3463. data = temp;
  3464. srcpitch = rectpitch;
  3465. }
  3466. if (!unpackRowLength
  3467. && !convert)
  3468. {
  3469. imageCopy(width, height, bpp, srcpitch, data, temp);
  3470. data = temp;
  3471. }
  3472. GL_CHECK(texSubImage(target+_side
  3473. , _mip
  3474. , _rect.m_x
  3475. , _rect.m_y
  3476. , _z
  3477. , _rect.m_width
  3478. , _rect.m_height
  3479. , _depth
  3480. , m_fmt
  3481. , m_type
  3482. , data
  3483. ) );
  3484. }
  3485. if (!convert
  3486. && unpackRowLength)
  3487. {
  3488. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  3489. }
  3490. if (NULL != temp)
  3491. {
  3492. BX_FREE(g_allocator, temp);
  3493. }
  3494. }
  3495. void TextureGL::setSamplerState(uint32_t _flags)
  3496. {
  3497. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  3498. && !s_textureFilter[m_textureFormat])
  3499. {
  3500. // Force point sampling when texture format doesn't support linear sampling.
  3501. _flags &= 0
  3502. | BGFX_TEXTURE_MIN_MASK
  3503. | BGFX_TEXTURE_MAG_MASK
  3504. | BGFX_TEXTURE_MIP_MASK
  3505. ;
  3506. _flags |= 0
  3507. | BGFX_TEXTURE_MIN_POINT
  3508. | BGFX_TEXTURE_MAG_POINT
  3509. | BGFX_TEXTURE_MIP_POINT
  3510. ;
  3511. }
  3512. const uint32_t flags = (0 != (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  3513. if (flags != m_currentFlags)
  3514. {
  3515. const GLenum target = m_target;
  3516. const uint8_t numMips = m_numMips;
  3517. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  3518. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  3519. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3520. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  3521. {
  3522. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  3523. }
  3524. if (target == GL_TEXTURE_3D)
  3525. {
  3526. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  3527. }
  3528. GLenum magFilter;
  3529. GLenum minFilter;
  3530. getFilters(flags, 1 < numMips, magFilter, minFilter);
  3531. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  3532. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  3533. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  3534. && 0.0f < s_renderGL->m_maxAnisotropy)
  3535. {
  3536. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  3537. }
  3538. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3539. || s_renderGL->m_shadowSamplersSupport)
  3540. {
  3541. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  3542. if (0 == cmpFunc)
  3543. {
  3544. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  3545. }
  3546. else
  3547. {
  3548. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  3549. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  3550. }
  3551. }
  3552. m_currentFlags = flags;
  3553. }
  3554. }
  3555. void TextureGL::commit(uint32_t _stage, uint32_t _flags)
  3556. {
  3557. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  3558. GL_CHECK(glBindTexture(m_target, m_id) );
  3559. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3560. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3561. {
  3562. // GLES2 doesn't have support for sampler object.
  3563. setSamplerState(_flags);
  3564. }
  3565. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3566. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  3567. {
  3568. // In case that GL 2.1 sampler object is supported via extension.
  3569. if (s_renderGL->m_samplerObjectSupport)
  3570. {
  3571. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3572. }
  3573. else
  3574. {
  3575. setSamplerState(_flags);
  3576. }
  3577. }
  3578. else
  3579. {
  3580. // Everything else has sampler object.
  3581. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3582. }
  3583. }
  3584. void writeString(bx::WriterI* _writer, const char* _str)
  3585. {
  3586. bx::write(_writer, _str, (int32_t)strlen(_str) );
  3587. }
  3588. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  3589. {
  3590. char temp[512];
  3591. va_list argList;
  3592. va_start(argList, _format);
  3593. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  3594. va_end(argList);
  3595. bx::write(_writer, temp, len);
  3596. }
  3597. void strins(char* _str, const char* _insert)
  3598. {
  3599. size_t len = strlen(_insert);
  3600. memmove(&_str[len], _str, strlen(_str)+1);
  3601. memcpy(_str, _insert, len);
  3602. }
  3603. void ShaderGL::create(Memory* _mem)
  3604. {
  3605. bx::MemoryReader reader(_mem->data, _mem->size);
  3606. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  3607. uint32_t magic;
  3608. bx::read(&reader, magic);
  3609. switch (magic)
  3610. {
  3611. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  3612. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  3613. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  3614. default:
  3615. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  3616. break;
  3617. }
  3618. uint32_t iohash;
  3619. bx::read(&reader, iohash);
  3620. uint16_t count;
  3621. bx::read(&reader, count);
  3622. BX_TRACE("%s Shader consts %d"
  3623. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  3624. , count
  3625. );
  3626. for (uint32_t ii = 0; ii < count; ++ii)
  3627. {
  3628. uint8_t nameSize;
  3629. bx::read(&reader, nameSize);
  3630. char name[256];
  3631. bx::read(&reader, &name, nameSize);
  3632. name[nameSize] = '\0';
  3633. uint8_t type;
  3634. bx::read(&reader, type);
  3635. uint8_t num;
  3636. bx::read(&reader, num);
  3637. uint16_t regIndex;
  3638. bx::read(&reader, regIndex);
  3639. uint16_t regCount;
  3640. bx::read(&reader, regCount);
  3641. }
  3642. uint32_t shaderSize;
  3643. bx::read(&reader, shaderSize);
  3644. m_id = glCreateShader(m_type);
  3645. BX_WARN(0 != m_id, "Failed to create %s shader."
  3646. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  3647. );
  3648. const char* code = (const char*)reader.getDataPtr();
  3649. if (0 != m_id)
  3650. {
  3651. if (GL_COMPUTE_SHADER != m_type)
  3652. {
  3653. int32_t codeLen = (int32_t)strlen(code);
  3654. int32_t tempLen = codeLen + (4<<10);
  3655. char* temp = (char*)alloca(tempLen);
  3656. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  3657. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3658. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3659. {
  3660. writeString(&writer
  3661. , "#define flat\n"
  3662. "#define smooth\n"
  3663. "#define noperspective\n"
  3664. );
  3665. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  3666. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  3667. ;
  3668. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  3669. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  3670. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  3671. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  3672. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  3673. ;
  3674. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  3675. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  3676. if (usesDerivatives)
  3677. {
  3678. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  3679. }
  3680. if (usesFragData)
  3681. {
  3682. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  3683. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  3684. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  3685. );
  3686. writeString(&writer
  3687. , "#extension GL_EXT_draw_buffers : enable\n"
  3688. );
  3689. }
  3690. bool insertFragDepth = false;
  3691. if (usesFragDepth)
  3692. {
  3693. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  3694. if (s_extension[Extension::EXT_frag_depth].m_supported)
  3695. {
  3696. writeString(&writer
  3697. , "#extension GL_EXT_frag_depth : enable\n"
  3698. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  3699. );
  3700. char str[128];
  3701. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  3702. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  3703. );
  3704. writeString(&writer, str);
  3705. }
  3706. else
  3707. {
  3708. insertFragDepth = true;
  3709. }
  3710. }
  3711. if (usesShadowSamplers)
  3712. {
  3713. if (s_renderGL->m_shadowSamplersSupport)
  3714. {
  3715. writeString(&writer
  3716. , "#extension GL_EXT_shadow_samplers : enable\n"
  3717. "#define shadow2D shadow2DEXT\n"
  3718. "#define shadow2DProj shadow2DProjEXT\n"
  3719. );
  3720. }
  3721. else
  3722. {
  3723. writeString(&writer
  3724. , "#define sampler2DShadow sampler2D\n"
  3725. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  3726. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  3727. );
  3728. }
  3729. }
  3730. if (usesTexture3D)
  3731. {
  3732. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  3733. }
  3734. if (usesTextureLod)
  3735. {
  3736. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  3737. if (s_extension[Extension::EXT_shader_texture_lod].m_supported
  3738. /*&& GL_VERTEX_SHADER == m_type*/)
  3739. {
  3740. writeString(&writer
  3741. , "#extension GL_EXT_shader_texture_lod : enable\n"
  3742. "#define texture2DLod texture2DLodEXT\n"
  3743. "#define texture2DProjLod texture2DProjLodEXT\n"
  3744. "#define textureCubeLod textureCubeLodEXT\n"
  3745. );
  3746. }
  3747. else
  3748. {
  3749. writeString(&writer
  3750. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  3751. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  3752. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  3753. );
  3754. }
  3755. }
  3756. if (usesFragmentOrdering)
  3757. {
  3758. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3759. {
  3760. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3761. }
  3762. else
  3763. {
  3764. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3765. }
  3766. }
  3767. writeStringf(&writer, "precision %s float;\n"
  3768. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  3769. );
  3770. bx::write(&writer, code, codeLen);
  3771. bx::write(&writer, '\0');
  3772. if (insertFragDepth)
  3773. {
  3774. char* entry = strstr(temp, "void main ()");
  3775. if (NULL != entry)
  3776. {
  3777. char* brace = strstr(entry, "{");
  3778. if (NULL != brace)
  3779. {
  3780. const char* end = bx::strmb(brace, '{', '}');
  3781. if (NULL != end)
  3782. {
  3783. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  3784. }
  3785. }
  3786. }
  3787. }
  3788. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  3789. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  3790. {
  3791. char* insert = const_cast<char*>(fragDepth);
  3792. strins(insert, "bg");
  3793. memcpy(insert + 2, "fx", 2);
  3794. }
  3795. }
  3796. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3797. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  3798. {
  3799. bool usesTextureLod = true
  3800. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  3801. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  3802. ;
  3803. bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  3804. uint32_t version = usesIUsamplers
  3805. ? 130
  3806. : (usesTextureLod ? 120 : 0)
  3807. ;
  3808. if (0 != version)
  3809. {
  3810. writeStringf(&writer, "#version %d\n", version);
  3811. }
  3812. if (usesTextureLod)
  3813. {
  3814. if (m_type == GL_FRAGMENT_SHADER)
  3815. {
  3816. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  3817. }
  3818. }
  3819. if (130 <= version)
  3820. {
  3821. if (m_type == GL_FRAGMENT_SHADER)
  3822. {
  3823. writeString(&writer, "#define varying in\n");
  3824. }
  3825. else
  3826. {
  3827. writeString(&writer, "#define attribute in\n");
  3828. writeString(&writer, "#define varying out\n");
  3829. }
  3830. uint32_t fragData = 0;
  3831. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  3832. {
  3833. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  3834. {
  3835. char tmpFragData[16];
  3836. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  3837. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  3838. }
  3839. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  3840. }
  3841. if (0 != fragData)
  3842. {
  3843. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  3844. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  3845. }
  3846. else
  3847. {
  3848. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  3849. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  3850. }
  3851. }
  3852. writeString(&writer
  3853. , "#define lowp\n"
  3854. "#define mediump\n"
  3855. "#define highp\n"
  3856. "#define flat\n"
  3857. "#define smooth\n"
  3858. "#define noperspective\n"
  3859. );
  3860. bx::write(&writer, code, codeLen);
  3861. bx::write(&writer, '\0');
  3862. }
  3863. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  3864. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3865. {
  3866. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3867. {
  3868. writeString(&writer
  3869. , "#version 300 es\n"
  3870. "precision mediump float;\n"
  3871. );
  3872. }
  3873. else
  3874. {
  3875. writeString(&writer, "#version 140\n");
  3876. }
  3877. writeString(&writer, "#define texture2DLod textureLod\n");
  3878. writeString(&writer, "#define texture3DLod textureLod\n");
  3879. writeString(&writer, "#define textureCubeLod textureLod\n");
  3880. if (m_type == GL_FRAGMENT_SHADER)
  3881. {
  3882. writeString(&writer, "#define varying in\n");
  3883. writeString(&writer, "#define texture2D texture\n");
  3884. writeString(&writer, "#define texture2DProj textureProj\n");
  3885. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  3886. {
  3887. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3888. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  3889. }
  3890. else
  3891. {
  3892. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3893. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  3894. }
  3895. writeString(&writer, "#define texture3D texture\n");
  3896. writeString(&writer, "#define textureCube texture\n");
  3897. uint32_t fragData = 0;
  3898. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  3899. {
  3900. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  3901. {
  3902. char tmpFragData[16];
  3903. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  3904. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  3905. }
  3906. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  3907. }
  3908. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  3909. {
  3910. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3911. {
  3912. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3913. }
  3914. else
  3915. {
  3916. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3917. }
  3918. }
  3919. if (0 != fragData)
  3920. {
  3921. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  3922. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  3923. }
  3924. else
  3925. {
  3926. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  3927. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  3928. }
  3929. }
  3930. else
  3931. {
  3932. writeString(&writer, "#define attribute in\n");
  3933. writeString(&writer, "#define varying out\n");
  3934. }
  3935. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3936. {
  3937. writeString(&writer
  3938. , "#define lowp\n"
  3939. "#define mediump\n"
  3940. "#define highp\n"
  3941. );
  3942. }
  3943. bx::write(&writer, code, codeLen);
  3944. bx::write(&writer, '\0');
  3945. }
  3946. code = temp;
  3947. }
  3948. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  3949. GL_CHECK(glCompileShader(m_id) );
  3950. GLint compiled = 0;
  3951. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  3952. if (0 == compiled)
  3953. {
  3954. BX_TRACE("\n####\n%s\n####", code);
  3955. GLsizei len;
  3956. char log[1024];
  3957. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  3958. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  3959. GL_CHECK(glDeleteShader(m_id) );
  3960. m_id = 0;
  3961. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  3962. }
  3963. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3964. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  3965. && NULL != glGetTranslatedShaderSourceANGLE)
  3966. {
  3967. GLsizei len;
  3968. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  3969. char* source = (char*)alloca(len);
  3970. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  3971. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  3972. }
  3973. }
  3974. }
  3975. void ShaderGL::destroy()
  3976. {
  3977. if (0 != m_id)
  3978. {
  3979. GL_CHECK(glDeleteShader(m_id) );
  3980. m_id = 0;
  3981. }
  3982. }
  3983. static void frameBufferValidate()
  3984. {
  3985. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3986. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  3987. , "glCheckFramebufferStatus failed 0x%08x: %s"
  3988. , complete
  3989. , glEnumName(complete)
  3990. );
  3991. BX_UNUSED(complete);
  3992. }
  3993. void FrameBufferGL::create(uint8_t _num, const TextureHandle* _handles)
  3994. {
  3995. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  3996. m_numTh = _num;
  3997. memcpy(m_th, _handles, _num*sizeof(TextureHandle) );
  3998. postReset();
  3999. }
  4000. void FrameBufferGL::postReset()
  4001. {
  4002. if (0 != m_fbo[0])
  4003. {
  4004. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  4005. bool needResolve = false;
  4006. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  4007. uint32_t colorIdx = 0;
  4008. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  4009. {
  4010. TextureHandle handle = m_th[ii];
  4011. if (isValid(handle) )
  4012. {
  4013. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  4014. if (0 == colorIdx)
  4015. {
  4016. m_width = texture.m_width;
  4017. m_height = texture.m_height;
  4018. }
  4019. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  4020. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  4021. if (isDepth(format) )
  4022. {
  4023. const ImageBlockInfo& info = getBlockInfo(format);
  4024. if (0 < info.stencilBits)
  4025. {
  4026. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  4027. }
  4028. else if (0 == info.depthBits)
  4029. {
  4030. attachment = GL_STENCIL_ATTACHMENT;
  4031. }
  4032. else
  4033. {
  4034. attachment = GL_DEPTH_ATTACHMENT;
  4035. }
  4036. }
  4037. else
  4038. {
  4039. buffers[colorIdx] = attachment;
  4040. ++colorIdx;
  4041. }
  4042. if (0 != texture.m_rbo)
  4043. {
  4044. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  4045. , attachment
  4046. , GL_RENDERBUFFER
  4047. , texture.m_rbo
  4048. ) );
  4049. }
  4050. else
  4051. {
  4052. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4053. , attachment
  4054. , texture.m_target
  4055. , texture.m_id
  4056. , 0
  4057. ) );
  4058. }
  4059. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  4060. }
  4061. }
  4062. m_num = uint8_t(colorIdx);
  4063. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  4064. {
  4065. if (0 == colorIdx)
  4066. {
  4067. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4068. {
  4069. // When only depth is attached disable draw buffer to avoid
  4070. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  4071. GL_CHECK(glDrawBuffer(GL_NONE) );
  4072. }
  4073. }
  4074. else
  4075. {
  4076. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  4077. }
  4078. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  4079. GL_CHECK(glReadBuffer(GL_NONE) );
  4080. }
  4081. frameBufferValidate();
  4082. if (needResolve)
  4083. {
  4084. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  4085. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  4086. colorIdx = 0;
  4087. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  4088. {
  4089. TextureHandle handle = m_th[ii];
  4090. if (isValid(handle) )
  4091. {
  4092. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  4093. if (0 != texture.m_id)
  4094. {
  4095. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  4096. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  4097. {
  4098. ++colorIdx;
  4099. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4100. , attachment
  4101. , texture.m_target
  4102. , texture.m_id
  4103. , 0
  4104. ) );
  4105. }
  4106. }
  4107. }
  4108. }
  4109. frameBufferValidate();
  4110. }
  4111. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4112. }
  4113. }
  4114. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  4115. {
  4116. BX_UNUSED(_depthFormat);
  4117. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  4118. m_width = _width;
  4119. m_height = _height;
  4120. m_denseIdx = _denseIdx;
  4121. }
  4122. uint16_t FrameBufferGL::destroy()
  4123. {
  4124. if (0 != m_num)
  4125. {
  4126. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  4127. m_num = 0;
  4128. }
  4129. if (NULL != m_swapChain)
  4130. {
  4131. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  4132. m_swapChain = NULL;
  4133. }
  4134. memset(m_fbo, 0, sizeof(m_fbo) );
  4135. uint16_t denseIdx = m_denseIdx;
  4136. m_denseIdx = UINT16_MAX;
  4137. return denseIdx;
  4138. }
  4139. void FrameBufferGL::resolve()
  4140. {
  4141. if (0 != m_fbo[1])
  4142. {
  4143. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4144. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  4145. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  4146. GL_CHECK(glBlitFramebuffer(0
  4147. , 0
  4148. , m_width
  4149. , m_height
  4150. , 0
  4151. , 0
  4152. , m_width
  4153. , m_height
  4154. , GL_COLOR_BUFFER_BIT
  4155. , GL_LINEAR
  4156. ) );
  4157. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4158. GL_CHECK(glReadBuffer(GL_NONE) );
  4159. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4160. }
  4161. }
  4162. void FrameBufferGL::discard(uint16_t _flags)
  4163. {
  4164. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  4165. uint32_t idx = 0;
  4166. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  4167. {
  4168. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  4169. {
  4170. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  4171. {
  4172. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  4173. }
  4174. }
  4175. }
  4176. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  4177. if (BGFX_CLEAR_NONE != dsFlags)
  4178. {
  4179. if ( (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  4180. {
  4181. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  4182. }
  4183. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  4184. {
  4185. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  4186. }
  4187. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  4188. {
  4189. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  4190. }
  4191. }
  4192. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  4193. }
  4194. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  4195. {
  4196. if (1 < m_numWindows
  4197. && m_vaoSupport)
  4198. {
  4199. m_vaoSupport = false;
  4200. GL_CHECK(glBindVertexArray(0) );
  4201. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  4202. m_vao = 0;
  4203. m_vaoStateCache.invalidate();
  4204. }
  4205. m_glctx.makeCurrent(NULL);
  4206. const GLuint defaultVao = m_vao;
  4207. if (0 != defaultVao)
  4208. {
  4209. GL_CHECK(glBindVertexArray(defaultVao) );
  4210. }
  4211. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  4212. updateResolution(_render->m_resolution);
  4213. int64_t elapsed = -bx::getHPCounter();
  4214. int64_t captureElapsed = 0;
  4215. if (m_timerQuerySupport)
  4216. {
  4217. m_gpuTimer.begin();
  4218. }
  4219. if (0 < _render->m_iboffset)
  4220. {
  4221. TransientIndexBuffer* ib = _render->m_transientIb;
  4222. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data);
  4223. }
  4224. if (0 < _render->m_vboffset)
  4225. {
  4226. TransientVertexBuffer* vb = _render->m_transientVb;
  4227. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data);
  4228. }
  4229. _render->sort();
  4230. RenderDraw currentState;
  4231. currentState.clear();
  4232. currentState.m_flags = BGFX_STATE_NONE;
  4233. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  4234. _render->m_hmdInitialized = m_ovr.isInitialized();
  4235. const bool hmdEnabled = m_ovr.isEnabled() || m_ovr.isDebug();
  4236. ViewState viewState(_render, hmdEnabled);
  4237. uint16_t programIdx = invalidHandle;
  4238. SortKey key;
  4239. uint8_t view = 0xff;
  4240. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  4241. int32_t height = hmdEnabled
  4242. ? _render->m_hmd.height
  4243. : _render->m_resolution.m_height
  4244. ;
  4245. uint32_t blendFactor = 0;
  4246. uint8_t primIndex;
  4247. {
  4248. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  4249. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4250. }
  4251. PrimInfo prim = s_primInfo[primIndex];
  4252. uint32_t baseVertex = 0;
  4253. GLuint currentVao = 0;
  4254. bool wasCompute = false;
  4255. bool viewHasScissor = false;
  4256. Rect viewScissorRect;
  4257. viewScissorRect.clear();
  4258. uint16_t discardFlags = BGFX_CLEAR_NONE;
  4259. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  4260. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  4261. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  4262. ;
  4263. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  4264. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  4265. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  4266. uint32_t statsNumIndices = 0;
  4267. uint32_t statsKeyType[2] = {};
  4268. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  4269. {
  4270. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  4271. bool viewRestart = false;
  4272. uint8_t eye = 0;
  4273. uint8_t restartState = 0;
  4274. viewState.m_rect = _render->m_rect[0];
  4275. int32_t numItems = _render->m_num;
  4276. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  4277. {
  4278. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  4279. statsKeyType[isCompute]++;
  4280. const bool viewChanged = 0
  4281. || key.m_view != view
  4282. || item == numItems
  4283. ;
  4284. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  4285. ++item;
  4286. if (viewChanged)
  4287. {
  4288. if (1 == restartState)
  4289. {
  4290. restartState = 2;
  4291. item = restartItem;
  4292. restartItem = numItems;
  4293. view = 0xff;
  4294. continue;
  4295. }
  4296. view = key.m_view;
  4297. programIdx = invalidHandle;
  4298. if (_render->m_fb[view].idx != fbh.idx)
  4299. {
  4300. fbh = _render->m_fb[view];
  4301. height = hmdEnabled
  4302. ? _render->m_hmd.height
  4303. : _render->m_resolution.m_height
  4304. ;
  4305. height = setFrameBuffer(fbh, height, discardFlags);
  4306. }
  4307. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  4308. viewRestart &= hmdEnabled;
  4309. if (viewRestart)
  4310. {
  4311. if (0 == restartState)
  4312. {
  4313. restartState = 1;
  4314. restartItem = item - 1;
  4315. }
  4316. eye = (restartState - 1) & 1;
  4317. restartState &= 1;
  4318. }
  4319. else
  4320. {
  4321. eye = 0;
  4322. }
  4323. viewState.m_rect = _render->m_rect[view];
  4324. if (viewRestart)
  4325. {
  4326. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4327. {
  4328. char* viewName = s_viewName[view];
  4329. viewName[3] = ' ';
  4330. viewName[4] = eye ? 'R' : 'L';
  4331. GL_CHECK(glInsertEventMarker(0, viewName) );
  4332. }
  4333. if (m_ovr.isEnabled() )
  4334. {
  4335. m_ovr.getViewport(eye, &viewState.m_rect);
  4336. }
  4337. else
  4338. {
  4339. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  4340. viewState.m_rect.m_width /= 2;
  4341. }
  4342. }
  4343. else
  4344. {
  4345. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4346. {
  4347. char* viewName = s_viewName[view];
  4348. viewName[3] = ' ';
  4349. viewName[4] = ' ';
  4350. GL_CHECK(glInsertEventMarker(0, viewName) );
  4351. }
  4352. }
  4353. const Rect& scissorRect = _render->m_scissor[view];
  4354. viewHasScissor = !scissorRect.isZero();
  4355. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  4356. GL_CHECK(glViewport(viewState.m_rect.m_x
  4357. , height-viewState.m_rect.m_height-viewState.m_rect.m_y
  4358. , viewState.m_rect.m_width
  4359. , viewState.m_rect.m_height
  4360. ) );
  4361. Clear& clear = _render->m_clear[view];
  4362. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  4363. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  4364. {
  4365. clearQuad(_clearQuad, viewState.m_rect, clear, height, _render->m_clearColor);
  4366. }
  4367. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4368. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4369. GL_CHECK(glDepthFunc(GL_LESS) );
  4370. GL_CHECK(glEnable(GL_CULL_FACE) );
  4371. GL_CHECK(glDisable(GL_BLEND) );
  4372. }
  4373. if (isCompute)
  4374. {
  4375. if (!wasCompute)
  4376. {
  4377. wasCompute = true;
  4378. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4379. {
  4380. char* viewName = s_viewName[view];
  4381. viewName[3] = 'C';
  4382. GL_CHECK(glInsertEventMarker(0, viewName) );
  4383. }
  4384. }
  4385. if (computeSupported)
  4386. {
  4387. const RenderCompute& compute = renderItem.compute;
  4388. ProgramGL& program = m_program[key.m_program];
  4389. GL_CHECK(glUseProgram(program.m_id) );
  4390. GLbitfield barrier = 0;
  4391. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  4392. {
  4393. const Binding& bind = compute.m_bind[ii];
  4394. if (invalidHandle != bind.m_idx)
  4395. {
  4396. switch (bind.m_type)
  4397. {
  4398. case Binding::Image:
  4399. {
  4400. const TextureGL& texture = m_textures[bind.m_idx];
  4401. GL_CHECK(glBindImageTexture(ii
  4402. , texture.m_id
  4403. , bind.m_un.m_compute.m_mip
  4404. , GL_FALSE
  4405. , 0
  4406. , s_access[bind.m_un.m_compute.m_access]
  4407. , s_imageFormat[bind.m_un.m_compute.m_format])
  4408. );
  4409. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  4410. }
  4411. break;
  4412. case Binding::IndexBuffer:
  4413. {
  4414. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  4415. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  4416. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4417. }
  4418. break;
  4419. case Binding::VertexBuffer:
  4420. {
  4421. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  4422. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  4423. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4424. }
  4425. break;
  4426. }
  4427. }
  4428. }
  4429. if (0 != barrier)
  4430. {
  4431. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  4432. rendererUpdateUniforms(this, _render->m_constantBuffer, compute.m_constBegin, compute.m_constEnd);
  4433. if (constantsChanged
  4434. && NULL != program.m_constantBuffer)
  4435. {
  4436. commit(*program.m_constantBuffer);
  4437. }
  4438. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  4439. if (isValid(compute.m_indirectBuffer) )
  4440. {
  4441. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  4442. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  4443. {
  4444. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  4445. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  4446. }
  4447. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  4448. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4449. : compute.m_numIndirect
  4450. ;
  4451. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4452. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  4453. {
  4454. GL_CHECK(glDispatchComputeIndirect(args) );
  4455. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4456. }
  4457. }
  4458. else
  4459. {
  4460. if (isValid(currentState.m_indirectBuffer) )
  4461. {
  4462. currentState.m_indirectBuffer.idx = invalidHandle;
  4463. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  4464. }
  4465. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  4466. }
  4467. GL_CHECK(glMemoryBarrier(barrier) );
  4468. }
  4469. }
  4470. continue;
  4471. }
  4472. bool resetState = viewChanged || wasCompute;
  4473. if (wasCompute)
  4474. {
  4475. wasCompute = false;
  4476. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4477. {
  4478. char* viewName = s_viewName[view];
  4479. viewName[3] = ' ';
  4480. GL_CHECK(glInsertEventMarker(0, viewName) );
  4481. }
  4482. }
  4483. const RenderDraw& draw = renderItem.draw;
  4484. const uint64_t newFlags = draw.m_flags;
  4485. uint64_t changedFlags = currentState.m_flags ^ draw.m_flags;
  4486. currentState.m_flags = newFlags;
  4487. const uint64_t newStencil = draw.m_stencil;
  4488. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  4489. currentState.m_stencil = newStencil;
  4490. if (resetState)
  4491. {
  4492. currentState.clear();
  4493. currentState.m_scissor = !draw.m_scissor;
  4494. changedFlags = BGFX_STATE_MASK;
  4495. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  4496. currentState.m_flags = newFlags;
  4497. currentState.m_stencil = newStencil;
  4498. }
  4499. uint16_t scissor = draw.m_scissor;
  4500. if (currentState.m_scissor != scissor)
  4501. {
  4502. currentState.m_scissor = scissor;
  4503. if (UINT16_MAX == scissor)
  4504. {
  4505. if (viewHasScissor)
  4506. {
  4507. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4508. GL_CHECK(glScissor(viewScissorRect.m_x
  4509. , height-viewScissorRect.m_height-viewScissorRect.m_y
  4510. , viewScissorRect.m_width
  4511. , viewScissorRect.m_height
  4512. ) );
  4513. }
  4514. else
  4515. {
  4516. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  4517. }
  4518. }
  4519. else
  4520. {
  4521. Rect scissorRect;
  4522. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  4523. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4524. GL_CHECK(glScissor(scissorRect.m_x
  4525. , height-scissorRect.m_height-scissorRect.m_y
  4526. , scissorRect.m_width
  4527. , scissorRect.m_height
  4528. ) );
  4529. }
  4530. }
  4531. if (0 != changedStencil)
  4532. {
  4533. if (0 != newStencil)
  4534. {
  4535. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  4536. uint32_t bstencil = unpackStencil(1, newStencil);
  4537. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  4538. // uint32_t bchanged = unpackStencil(1, changedStencil);
  4539. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  4540. // {
  4541. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4542. // GL_CHECK(glStencilMask(wmask) );
  4543. // }
  4544. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  4545. {
  4546. uint32_t stencil = unpackStencil(ii, newStencil);
  4547. uint32_t changed = unpackStencil(ii, changedStencil);
  4548. GLenum face = s_stencilFace[frontAndBack+ii];
  4549. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  4550. {
  4551. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  4552. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4553. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  4554. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) );
  4555. }
  4556. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  4557. {
  4558. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  4559. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  4560. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  4561. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  4562. }
  4563. }
  4564. }
  4565. else
  4566. {
  4567. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4568. }
  4569. }
  4570. if ( (0
  4571. | BGFX_STATE_CULL_MASK
  4572. | BGFX_STATE_DEPTH_WRITE
  4573. | BGFX_STATE_DEPTH_TEST_MASK
  4574. | BGFX_STATE_RGB_WRITE
  4575. | BGFX_STATE_ALPHA_WRITE
  4576. | BGFX_STATE_BLEND_MASK
  4577. | BGFX_STATE_BLEND_EQUATION_MASK
  4578. | BGFX_STATE_ALPHA_REF_MASK
  4579. | BGFX_STATE_PT_MASK
  4580. | BGFX_STATE_POINT_SIZE_MASK
  4581. | BGFX_STATE_MSAA
  4582. ) & changedFlags)
  4583. {
  4584. if (BGFX_STATE_CULL_MASK & changedFlags)
  4585. {
  4586. if (BGFX_STATE_CULL_CW & newFlags)
  4587. {
  4588. GL_CHECK(glEnable(GL_CULL_FACE) );
  4589. GL_CHECK(glCullFace(GL_BACK) );
  4590. }
  4591. else if (BGFX_STATE_CULL_CCW & newFlags)
  4592. {
  4593. GL_CHECK(glEnable(GL_CULL_FACE) );
  4594. GL_CHECK(glCullFace(GL_FRONT) );
  4595. }
  4596. else
  4597. {
  4598. GL_CHECK(glDisable(GL_CULL_FACE) );
  4599. }
  4600. }
  4601. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  4602. {
  4603. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  4604. }
  4605. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  4606. {
  4607. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  4608. if (0 != func)
  4609. {
  4610. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4611. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  4612. }
  4613. else
  4614. {
  4615. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  4616. }
  4617. }
  4618. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  4619. {
  4620. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  4621. viewState.m_alphaRef = ref/255.0f;
  4622. }
  4623. #if BGFX_CONFIG_RENDERER_OPENGL
  4624. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  4625. {
  4626. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  4627. GL_CHECK(glPointSize(pointSize) );
  4628. }
  4629. if (BGFX_STATE_MSAA & changedFlags)
  4630. {
  4631. if (BGFX_STATE_MSAA & newFlags)
  4632. {
  4633. GL_CHECK(glEnable(GL_MULTISAMPLE) );
  4634. }
  4635. else
  4636. {
  4637. GL_CHECK(glDisable(GL_MULTISAMPLE) );
  4638. }
  4639. }
  4640. #endif // BGFX_CONFIG_RENDERER_OPENGL
  4641. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  4642. {
  4643. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  4644. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  4645. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  4646. }
  4647. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & changedFlags
  4648. || blendFactor != draw.m_rgba)
  4649. {
  4650. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & newFlags
  4651. || blendFactor != draw.m_rgba)
  4652. {
  4653. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  4654. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  4655. && blendIndependentSupported
  4656. ;
  4657. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  4658. const uint32_t srcRGB = (blend )&0xf;
  4659. const uint32_t dstRGB = (blend>> 4)&0xf;
  4660. const uint32_t srcA = (blend>> 8)&0xf;
  4661. const uint32_t dstA = (blend>>12)&0xf;
  4662. const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  4663. const uint32_t equRGB = (equ )&0x7;
  4664. const uint32_t equA = (equ>>3)&0x7;
  4665. const uint32_t numRt = getNumRt();
  4666. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4667. || 1 >= numRt
  4668. || !independent)
  4669. {
  4670. if (enabled)
  4671. {
  4672. GL_CHECK(glEnable(GL_BLEND) );
  4673. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  4674. , s_blendFactor[dstRGB].m_dst
  4675. , s_blendFactor[srcA].m_src
  4676. , s_blendFactor[dstA].m_dst
  4677. ) );
  4678. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  4679. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  4680. && blendFactor != draw.m_rgba)
  4681. {
  4682. const uint32_t rgba = draw.m_rgba;
  4683. GLclampf rr = ( (rgba>>24) )/255.0f;
  4684. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  4685. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  4686. GLclampf aa = ( (rgba )&0xff)/255.0f;
  4687. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  4688. }
  4689. }
  4690. else
  4691. {
  4692. GL_CHECK(glDisable(GL_BLEND) );
  4693. }
  4694. }
  4695. else
  4696. {
  4697. if (enabled)
  4698. {
  4699. GL_CHECK(glEnablei(GL_BLEND, 0) );
  4700. GL_CHECK(glBlendFuncSeparatei(0
  4701. , s_blendFactor[srcRGB].m_src
  4702. , s_blendFactor[dstRGB].m_dst
  4703. , s_blendFactor[srcA].m_src
  4704. , s_blendFactor[dstA].m_dst
  4705. ) );
  4706. GL_CHECK(glBlendEquationSeparatei(0
  4707. , s_blendEquation[equRGB]
  4708. , s_blendEquation[equA]
  4709. ) );
  4710. }
  4711. else
  4712. {
  4713. GL_CHECK(glDisablei(GL_BLEND, 0) );
  4714. }
  4715. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  4716. {
  4717. if (0 != (rgba&0x7ff) )
  4718. {
  4719. const uint32_t src = (rgba )&0xf;
  4720. const uint32_t dst = (rgba>>4)&0xf;
  4721. const uint32_t equation = (rgba>>8)&0x7;
  4722. GL_CHECK(glEnablei(GL_BLEND, ii) );
  4723. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  4724. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  4725. }
  4726. else
  4727. {
  4728. GL_CHECK(glDisablei(GL_BLEND, ii) );
  4729. }
  4730. }
  4731. }
  4732. }
  4733. else
  4734. {
  4735. GL_CHECK(glDisable(GL_BLEND) );
  4736. }
  4737. blendFactor = draw.m_rgba;
  4738. }
  4739. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  4740. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4741. prim = s_primInfo[primIndex];
  4742. }
  4743. bool programChanged = false;
  4744. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  4745. bool bindAttribs = false;
  4746. rendererUpdateUniforms(this, _render->m_constantBuffer, draw.m_constBegin, draw.m_constEnd);
  4747. if (key.m_program != programIdx)
  4748. {
  4749. programIdx = key.m_program;
  4750. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  4751. // Skip rendering if program index is valid, but program is invalid.
  4752. programIdx = 0 == id ? invalidHandle : programIdx;
  4753. GL_CHECK(glUseProgram(id) );
  4754. programChanged =
  4755. constantsChanged =
  4756. bindAttribs = true;
  4757. }
  4758. if (invalidHandle != programIdx)
  4759. {
  4760. ProgramGL& program = m_program[programIdx];
  4761. if (constantsChanged
  4762. && NULL != program.m_constantBuffer)
  4763. {
  4764. commit(*program.m_constantBuffer);
  4765. }
  4766. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  4767. {
  4768. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  4769. {
  4770. const Binding& sampler = draw.m_bind[stage];
  4771. Binding& current = currentState.m_bind[stage];
  4772. if (current.m_idx != sampler.m_idx
  4773. || current.m_un.m_draw.m_flags != sampler.m_un.m_draw.m_flags
  4774. || programChanged)
  4775. {
  4776. if (invalidHandle != sampler.m_idx)
  4777. {
  4778. TextureGL& texture = m_textures[sampler.m_idx];
  4779. texture.commit(stage, sampler.m_un.m_draw.m_flags);
  4780. }
  4781. }
  4782. current = sampler;
  4783. }
  4784. }
  4785. if (0 != defaultVao
  4786. && 0 == draw.m_startVertex
  4787. && 0 == draw.m_instanceDataOffset)
  4788. {
  4789. if (programChanged
  4790. || baseVertex != draw.m_startVertex
  4791. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4792. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  4793. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4794. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  4795. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx)
  4796. {
  4797. bx::HashMurmur2A murmur;
  4798. murmur.begin();
  4799. murmur.add(draw.m_vertexBuffer.idx);
  4800. if (isValid(draw.m_vertexBuffer) )
  4801. {
  4802. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4803. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4804. murmur.add(decl);
  4805. }
  4806. murmur.add(draw.m_indexBuffer.idx);
  4807. murmur.add(draw.m_instanceDataBuffer.idx);
  4808. murmur.add(draw.m_instanceDataOffset);
  4809. murmur.add(draw.m_instanceDataStride);
  4810. murmur.add(programIdx);
  4811. uint32_t hash = murmur.end();
  4812. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4813. currentState.m_indexBuffer = draw.m_indexBuffer;
  4814. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4815. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4816. baseVertex = draw.m_startVertex;
  4817. GLuint id = m_vaoStateCache.find(hash);
  4818. if (UINT32_MAX != id)
  4819. {
  4820. currentVao = id;
  4821. GL_CHECK(glBindVertexArray(id) );
  4822. }
  4823. else
  4824. {
  4825. id = m_vaoStateCache.add(hash);
  4826. currentVao = id;
  4827. GL_CHECK(glBindVertexArray(id) );
  4828. program.add(hash);
  4829. if (isValid(draw.m_vertexBuffer) )
  4830. {
  4831. VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4832. vb.add(hash);
  4833. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4834. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4835. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4836. if (isValid(draw.m_instanceDataBuffer) )
  4837. {
  4838. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  4839. instanceVb.add(hash);
  4840. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  4841. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4842. }
  4843. }
  4844. else
  4845. {
  4846. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4847. }
  4848. if (isValid(draw.m_indexBuffer) )
  4849. {
  4850. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4851. ib.add(hash);
  4852. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4853. }
  4854. else
  4855. {
  4856. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4857. }
  4858. }
  4859. }
  4860. }
  4861. else
  4862. {
  4863. if (0 != defaultVao
  4864. && 0 != currentVao)
  4865. {
  4866. GL_CHECK(glBindVertexArray(defaultVao) );
  4867. currentState.m_vertexBuffer.idx = invalidHandle;
  4868. currentState.m_indexBuffer.idx = invalidHandle;
  4869. bindAttribs = true;
  4870. currentVao = 0;
  4871. }
  4872. if (programChanged
  4873. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4874. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  4875. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4876. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  4877. {
  4878. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4879. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  4880. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4881. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4882. uint16_t handle = draw.m_vertexBuffer.idx;
  4883. if (invalidHandle != handle)
  4884. {
  4885. VertexBufferGL& vb = m_vertexBuffers[handle];
  4886. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4887. bindAttribs = true;
  4888. }
  4889. else
  4890. {
  4891. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4892. }
  4893. }
  4894. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  4895. {
  4896. currentState.m_indexBuffer = draw.m_indexBuffer;
  4897. uint16_t handle = draw.m_indexBuffer.idx;
  4898. if (invalidHandle != handle)
  4899. {
  4900. IndexBufferGL& ib = m_indexBuffers[handle];
  4901. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4902. }
  4903. else
  4904. {
  4905. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4906. }
  4907. }
  4908. if (isValid(currentState.m_vertexBuffer) )
  4909. {
  4910. if (baseVertex != draw.m_startVertex
  4911. || bindAttribs)
  4912. {
  4913. baseVertex = draw.m_startVertex;
  4914. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4915. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4916. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4917. if (isValid(draw.m_instanceDataBuffer) )
  4918. {
  4919. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  4920. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4921. }
  4922. }
  4923. }
  4924. }
  4925. if (isValid(currentState.m_vertexBuffer) )
  4926. {
  4927. uint32_t numVertices = draw.m_numVertices;
  4928. if (UINT32_MAX == numVertices)
  4929. {
  4930. const VertexBufferGL& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  4931. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4932. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  4933. numVertices = vb.m_size/vertexDecl.m_stride;
  4934. }
  4935. uint32_t numIndices = 0;
  4936. uint32_t numPrimsSubmitted = 0;
  4937. uint32_t numInstances = 0;
  4938. uint32_t numPrimsRendered = 0;
  4939. uint32_t numDrawIndirect = 0;
  4940. if (isValid(draw.m_indirectBuffer) )
  4941. {
  4942. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  4943. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  4944. {
  4945. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  4946. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  4947. }
  4948. if (isValid(draw.m_indexBuffer) )
  4949. {
  4950. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4951. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  4952. const GLenum indexFormat = hasIndex16
  4953. ? GL_UNSIGNED_SHORT
  4954. : GL_UNSIGNED_INT
  4955. ;
  4956. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  4957. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4958. : draw.m_numIndirect
  4959. ;
  4960. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4961. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  4962. , (void*)args
  4963. , numDrawIndirect
  4964. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4965. ) );
  4966. }
  4967. else
  4968. {
  4969. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  4970. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4971. : draw.m_numIndirect
  4972. ;
  4973. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4974. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  4975. , (void*)args
  4976. , numDrawIndirect
  4977. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4978. ) );
  4979. }
  4980. }
  4981. else
  4982. {
  4983. if (isValid(currentState.m_indirectBuffer) )
  4984. {
  4985. currentState.m_indirectBuffer.idx = invalidHandle;
  4986. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  4987. }
  4988. if (isValid(draw.m_indexBuffer) )
  4989. {
  4990. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4991. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  4992. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  4993. const GLenum indexFormat = hasIndex16
  4994. ? GL_UNSIGNED_SHORT
  4995. : GL_UNSIGNED_INT
  4996. ;
  4997. if (UINT32_MAX == draw.m_numIndices)
  4998. {
  4999. numIndices = ib.m_size/indexSize;
  5000. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  5001. numInstances = draw.m_numInstances;
  5002. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5003. GL_CHECK(glDrawElementsInstanced(prim.m_type
  5004. , numIndices
  5005. , indexFormat
  5006. , (void*)0
  5007. , draw.m_numInstances
  5008. ) );
  5009. }
  5010. else if (prim.m_min <= draw.m_numIndices)
  5011. {
  5012. numIndices = draw.m_numIndices;
  5013. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  5014. numInstances = draw.m_numInstances;
  5015. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5016. GL_CHECK(glDrawElementsInstanced(prim.m_type
  5017. , numIndices
  5018. , indexFormat
  5019. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  5020. , draw.m_numInstances
  5021. ) );
  5022. }
  5023. }
  5024. else
  5025. {
  5026. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  5027. numInstances = draw.m_numInstances;
  5028. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5029. GL_CHECK(glDrawArraysInstanced(prim.m_type
  5030. , 0
  5031. , numVertices
  5032. , draw.m_numInstances
  5033. ) );
  5034. }
  5035. }
  5036. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  5037. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  5038. statsNumInstances[primIndex] += numInstances;
  5039. statsNumIndices += numIndices;
  5040. }
  5041. }
  5042. }
  5043. blitMsaaFbo();
  5044. if (0 < _render->m_num)
  5045. {
  5046. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  5047. {
  5048. GL_CHECK(glFlush() );
  5049. }
  5050. captureElapsed = -bx::getHPCounter();
  5051. capture();
  5052. captureElapsed += bx::getHPCounter();
  5053. }
  5054. }
  5055. m_glctx.makeCurrent(NULL);
  5056. int64_t now = bx::getHPCounter();
  5057. elapsed += now;
  5058. static int64_t last = now;
  5059. int64_t frameTime = now - last;
  5060. last = now;
  5061. static int64_t min = frameTime;
  5062. static int64_t max = frameTime;
  5063. min = min > frameTime ? frameTime : min;
  5064. max = max < frameTime ? frameTime : max;
  5065. static uint32_t maxGpuLatency = 0;
  5066. static double maxGpuElapsed = 0.0f;
  5067. double elapsedGpuMs = 0.0;
  5068. uint64_t elapsedGl = 0;
  5069. if (m_timerQuerySupport)
  5070. {
  5071. m_gpuTimer.end();
  5072. while (m_gpuTimer.get() )
  5073. {
  5074. elapsedGl = m_gpuTimer.m_elapsed;
  5075. elapsedGpuMs = double(elapsedGl)/1e6;
  5076. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  5077. }
  5078. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  5079. }
  5080. const int64_t timerFreq = bx::getHPFrequency();
  5081. Stats& perfStats = _render->m_perfStats;
  5082. perfStats.cpuTime = frameTime;
  5083. perfStats.cpuTimerFreq = timerFreq;
  5084. perfStats.gpuTime = elapsedGl;
  5085. perfStats.gpuTimerFreq = 100000000;
  5086. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  5087. {
  5088. TextVideoMem& tvm = m_textVideoMem;
  5089. static int64_t next = now;
  5090. if (now >= next)
  5091. {
  5092. next = now + timerFreq;
  5093. double freq = double(timerFreq);
  5094. double toMs = 1000.0/freq;
  5095. tvm.clear();
  5096. uint16_t pos = 0;
  5097. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  5098. , getRendererName()
  5099. );
  5100. tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor);
  5101. tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer);
  5102. tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version);
  5103. tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion);
  5104. pos = 10;
  5105. tvm.printf(10, pos++, 0x8e, " Frame CPU: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  5106. , double(frameTime)*toMs
  5107. , double(min)*toMs
  5108. , double(max)*toMs
  5109. , freq/frameTime
  5110. );
  5111. char hmd[16];
  5112. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  5113. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  5114. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  5115. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  5116. , 0 != msaa ? '\xfe' : ' '
  5117. , 1<<msaa
  5118. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  5119. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  5120. );
  5121. double elapsedCpuMs = double(elapsed)*toMs;
  5122. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) "
  5123. , _render->m_num
  5124. , statsKeyType[0]
  5125. , statsKeyType[1]
  5126. , elapsedCpuMs
  5127. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  5128. , maxGpuElapsed
  5129. , maxGpuLatency
  5130. );
  5131. maxGpuLatency = 0;
  5132. maxGpuElapsed = 0.0;
  5133. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  5134. {
  5135. tvm.printf(10, pos++, 0x8e, " %9s: %7d (#inst: %5d), submitted: %7d "
  5136. , s_primName[ii]
  5137. , statsNumPrimsRendered[ii]
  5138. , statsNumInstances[ii]
  5139. , statsNumPrimsSubmitted[ii]
  5140. );
  5141. }
  5142. if (NULL != m_renderdocdll)
  5143. {
  5144. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  5145. }
  5146. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  5147. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d ", _render->m_constEnd);
  5148. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  5149. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  5150. pos++;
  5151. tvm.printf(10, pos++, 0x8e, " State cache: ");
  5152. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  5153. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  5154. , m_vaoStateCache.getCount()
  5155. , m_samplerStateCache.getCount()
  5156. );
  5157. #if BGFX_CONFIG_RENDERER_OPENGL
  5158. if (s_extension[Extension::ATI_meminfo].m_supported)
  5159. {
  5160. GLint vboFree[4];
  5161. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  5162. GLint texFree[4];
  5163. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  5164. GLint rbfFree[4];
  5165. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  5166. pos++;
  5167. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb ");
  5168. char tmp0[16];
  5169. char tmp1[16];
  5170. char tmp2[16];
  5171. char tmp3[16];
  5172. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  5173. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  5174. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  5175. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  5176. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5177. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  5178. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  5179. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  5180. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  5181. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5182. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  5183. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  5184. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  5185. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  5186. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5187. }
  5188. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  5189. {
  5190. GLint dedicated;
  5191. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  5192. GLint totalAvail;
  5193. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  5194. GLint currAvail;
  5195. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  5196. GLint evictedCount;
  5197. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  5198. GLint evictedMemory;
  5199. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  5200. pos++;
  5201. char tmp0[16];
  5202. char tmp1[16];
  5203. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  5204. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s ", tmp0);
  5205. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  5206. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  5207. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s ", tmp0, tmp1);
  5208. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  5209. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  5210. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s ", tmp0, tmp1);
  5211. }
  5212. #endif // BGFX_CONFIG_RENDERER_OPENGL
  5213. pos++;
  5214. double captureMs = double(captureElapsed)*toMs;
  5215. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms] ", captureMs);
  5216. uint8_t attr[2] = { 0x89, 0x8a };
  5217. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  5218. pos++;
  5219. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs);
  5220. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs);
  5221. min = frameTime;
  5222. max = frameTime;
  5223. }
  5224. blit(this, _textVideoMemBlitter, tvm);
  5225. }
  5226. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  5227. {
  5228. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  5229. }
  5230. GL_CHECK(glFrameTerminatorGREMEDY() );
  5231. }
  5232. } } // namespace bgfx
  5233. #else
  5234. namespace bgfx { namespace gl
  5235. {
  5236. RendererContextI* rendererCreate()
  5237. {
  5238. return NULL;
  5239. }
  5240. void rendererDestroy()
  5241. {
  5242. }
  5243. } /* namespace gl */ } // namespace bgfx
  5244. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)