renderer_gl.cpp 180 KB

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