renderer_gl.cpp 227 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-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. { GL_ZERO, 0, 0, 0 },
  28. };
  29. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_primInfo)-1);
  30. static const char* s_attribName[] =
  31. {
  32. "a_position",
  33. "a_normal",
  34. "a_tangent",
  35. "a_bitangent",
  36. "a_color0",
  37. "a_color1",
  38. "a_color2",
  39. "a_color3",
  40. "a_indices",
  41. "a_weight",
  42. "a_texcoord0",
  43. "a_texcoord1",
  44. "a_texcoord2",
  45. "a_texcoord3",
  46. "a_texcoord4",
  47. "a_texcoord5",
  48. "a_texcoord6",
  49. "a_texcoord7",
  50. };
  51. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  52. static const char* s_instanceDataName[] =
  53. {
  54. "i_data0",
  55. "i_data1",
  56. "i_data2",
  57. "i_data3",
  58. "i_data4",
  59. };
  60. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  61. static const GLenum s_access[] =
  62. {
  63. GL_READ_ONLY,
  64. GL_WRITE_ONLY,
  65. GL_READ_WRITE,
  66. };
  67. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  68. static const GLenum s_attribType[] =
  69. {
  70. GL_UNSIGNED_BYTE, // Uint8
  71. GL_UNSIGNED_INT_10_10_10_2, // Uint10
  72. GL_SHORT, // Int16
  73. GL_HALF_FLOAT, // Half
  74. GL_FLOAT, // Float
  75. };
  76. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  77. struct Blend
  78. {
  79. GLenum m_src;
  80. GLenum m_dst;
  81. bool m_factor;
  82. };
  83. static const Blend s_blendFactor[] =
  84. {
  85. { 0, 0, false }, // ignored
  86. { GL_ZERO, GL_ZERO, false }, // ZERO
  87. { GL_ONE, GL_ONE, false }, // ONE
  88. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  89. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  90. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  91. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  92. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  93. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  94. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  95. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  96. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  97. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  98. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  99. };
  100. static const GLenum s_blendEquation[] =
  101. {
  102. GL_FUNC_ADD,
  103. GL_FUNC_SUBTRACT,
  104. GL_FUNC_REVERSE_SUBTRACT,
  105. GL_MIN,
  106. GL_MAX,
  107. };
  108. static const GLenum s_cmpFunc[] =
  109. {
  110. 0, // ignored
  111. GL_LESS,
  112. GL_LEQUAL,
  113. GL_EQUAL,
  114. GL_GEQUAL,
  115. GL_GREATER,
  116. GL_NOTEQUAL,
  117. GL_NEVER,
  118. GL_ALWAYS,
  119. };
  120. static const GLenum s_stencilOp[] =
  121. {
  122. GL_ZERO,
  123. GL_KEEP,
  124. GL_REPLACE,
  125. GL_INCR_WRAP,
  126. GL_INCR,
  127. GL_DECR_WRAP,
  128. GL_DECR,
  129. GL_INVERT,
  130. };
  131. static const GLenum s_stencilFace[] =
  132. {
  133. GL_FRONT_AND_BACK,
  134. GL_FRONT,
  135. GL_BACK,
  136. };
  137. static GLenum s_textureAddress[] =
  138. {
  139. GL_REPEAT,
  140. GL_MIRRORED_REPEAT,
  141. GL_CLAMP_TO_EDGE,
  142. GL_CLAMP_TO_BORDER,
  143. };
  144. static const GLenum s_textureFilterMag[] =
  145. {
  146. GL_LINEAR,
  147. GL_NEAREST,
  148. GL_LINEAR,
  149. };
  150. static const GLenum s_textureFilterMin[][3] =
  151. {
  152. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  153. { GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_NEAREST },
  154. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  155. };
  156. struct TextureFormatInfo
  157. {
  158. GLenum m_internalFmt;
  159. GLenum m_internalFmtSrgb;
  160. GLenum m_fmt;
  161. GLenum m_type;
  162. bool m_supported;
  163. };
  164. static TextureFormatInfo s_textureFormat[] =
  165. {
  166. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  167. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  168. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  169. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  170. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  171. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  172. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  173. { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  174. { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  175. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  176. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  177. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  178. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  179. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  180. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  181. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  182. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  183. { GL_ATC_RGB_AMD, GL_ZERO, GL_ATC_RGB_AMD, GL_ZERO, false }, // ATC
  184. { GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_ZERO, GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_ZERO, false }, // ATCE
  185. { GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_ZERO, GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_ZERO, false }, // ATCI
  186. { GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_COMPRESSED_SRGB8_ASTC_4x4_KHR, GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_ZERO, false }, // ASTC4x4
  187. { GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_COMPRESSED_SRGB8_ASTC_5x5_KHR, GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_ZERO, false }, // ASTC5x5
  188. { GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_COMPRESSED_SRGB8_ASTC_6x6_KHR, GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_ZERO, false }, // ASTC6x6
  189. { GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_COMPRESSED_SRGB8_ASTC_8x5_KHR, GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_ZERO, false }, // ASTC8x5
  190. { GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_COMPRESSED_SRGB8_ASTC_8x6_KHR, GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_ZERO, false }, // ASTC8x6
  191. { GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_COMPRESSED_SRGB8_ASTC_10x5_KHR, GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_ZERO, false }, // ASTC10x5
  192. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown
  193. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1
  194. { GL_ALPHA, GL_ZERO, GL_ALPHA, GL_UNSIGNED_BYTE, false }, // A8
  195. { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8
  196. { GL_R8I, GL_ZERO, GL_RED, GL_BYTE, false }, // R8I
  197. { GL_R8UI, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8U
  198. { GL_R8_SNORM, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S
  199. { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16
  200. { GL_R16I, GL_ZERO, GL_RED, GL_SHORT, false }, // R16I
  201. { GL_R16UI, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16U
  202. { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F
  203. { GL_R16_SNORM, GL_ZERO, GL_RED, GL_SHORT, false }, // R16S
  204. { GL_R32I, GL_ZERO, GL_RED, GL_INT, false }, // R32I
  205. { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32U
  206. { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F
  207. { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8
  208. { GL_RG8I, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8I
  209. { GL_RG8UI, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8U
  210. { GL_RG8_SNORM, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8S
  211. { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  212. { GL_RG16I, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16I
  213. { GL_RG16UI, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16U
  214. { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F
  215. { GL_RG16_SNORM, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16S
  216. { GL_RG32I, GL_ZERO, GL_RG, GL_INT, false }, // RG32I
  217. { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32U
  218. { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F
  219. { GL_RGB8, GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8
  220. { GL_RGB8I, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8I
  221. { GL_RGB8UI, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8U
  222. { GL_RGB8_SNORM, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8S
  223. { GL_RGB9_E5, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, false }, // RGB9E5F
  224. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8
  225. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8
  226. { GL_RGBA8I, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8I
  227. { GL_RGBA8UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8U
  228. { GL_RGBA8_SNORM, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8S
  229. { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16
  230. { GL_RGBA16I, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16I
  231. { GL_RGBA16UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16U
  232. { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F
  233. { GL_RGBA16_SNORM, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16S
  234. { GL_RGBA32I, GL_ZERO, GL_RGBA, GL_INT, false }, // RGBA32I
  235. { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32U
  236. { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F
  237. { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5
  238. { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV, false }, // RGBA4
  239. { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, false }, // RGB5A1
  240. { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2
  241. { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // RG11B10F
  242. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth
  243. { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  244. { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  245. { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  246. { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  247. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  248. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  249. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  250. { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  251. };
  252. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  253. static bool s_textureFilter[TextureFormat::Count+1];
  254. static GLenum s_rboFormat[] =
  255. {
  256. GL_ZERO, // BC1
  257. GL_ZERO, // BC2
  258. GL_ZERO, // BC3
  259. GL_ZERO, // BC4
  260. GL_ZERO, // BC5
  261. GL_ZERO, // BC6H
  262. GL_ZERO, // BC7
  263. GL_ZERO, // ETC1
  264. GL_ZERO, // ETC2
  265. GL_ZERO, // ETC2A
  266. GL_ZERO, // ETC2A1
  267. GL_ZERO, // PTC12
  268. GL_ZERO, // PTC14
  269. GL_ZERO, // PTC12A
  270. GL_ZERO, // PTC14A
  271. GL_ZERO, // PTC22
  272. GL_ZERO, // PTC24
  273. GL_ZERO, // ATC
  274. GL_ZERO, // ATCE
  275. GL_ZERO, // ATCI
  276. GL_ZERO, // ASTC4x4
  277. GL_ZERO, // ASTC5x5
  278. GL_ZERO, // ASTC6x6
  279. GL_ZERO, // ASTC8x5
  280. GL_ZERO, // ASTC8x6
  281. GL_ZERO, // ASTC10x5
  282. GL_ZERO, // Unknown
  283. GL_ZERO, // R1
  284. GL_ALPHA, // A8
  285. GL_R8, // R8
  286. GL_R8I, // R8I
  287. GL_R8UI, // R8U
  288. GL_R8_SNORM, // R8S
  289. GL_R16, // R16
  290. GL_R16I, // R16I
  291. GL_R16UI, // R16U
  292. GL_R16F, // R16F
  293. GL_R16_SNORM, // R16S
  294. GL_R32I, // R32I
  295. GL_R32UI, // R32U
  296. GL_R32F, // R32F
  297. GL_RG8, // RG8
  298. GL_RG8I, // RG8I
  299. GL_RG8UI, // RG8U
  300. GL_RG8_SNORM, // RG8S
  301. GL_RG16, // RG16
  302. GL_RG16I, // RG16I
  303. GL_RG16UI, // RG16U
  304. GL_RG16F, // RG16F
  305. GL_RG16_SNORM, // RG16S
  306. GL_RG32I, // RG32I
  307. GL_RG32UI, // RG32U
  308. GL_RG32F, // RG32F
  309. GL_RGB8, // RGB8
  310. GL_RGB8I, // RGB8I
  311. GL_RGB8UI, // RGB8UI
  312. GL_RGB8_SNORM, // RGB8S
  313. GL_RGB9_E5, // RGB9E5F
  314. GL_RGBA8, // BGRA8
  315. GL_RGBA8, // RGBA8
  316. GL_RGBA8I, // RGBA8I
  317. GL_RGBA8UI, // RGBA8UI
  318. GL_RGBA8_SNORM, // RGBA8S
  319. GL_RGBA16, // RGBA16
  320. GL_RGBA16I, // RGBA16I
  321. GL_RGBA16UI, // RGBA16U
  322. GL_RGBA16F, // RGBA16F
  323. GL_RGBA16_SNORM, // RGBA16S
  324. GL_RGBA32I, // RGBA32I
  325. GL_RGBA32UI, // RGBA32U
  326. GL_RGBA32F, // RGBA32F
  327. GL_RGB565, // R5G6B5
  328. GL_RGBA4, // RGBA4
  329. GL_RGB5_A1, // RGB5A1
  330. GL_RGB10_A2, // RGB10A2
  331. GL_R11F_G11F_B10F, // RG11B10F
  332. GL_ZERO, // UnknownDepth
  333. GL_DEPTH_COMPONENT16, // D16
  334. GL_DEPTH_COMPONENT24, // D24
  335. GL_DEPTH24_STENCIL8, // D24S8
  336. GL_DEPTH_COMPONENT32, // D32
  337. GL_DEPTH_COMPONENT32F, // D16F
  338. GL_DEPTH_COMPONENT32F, // D24F
  339. GL_DEPTH_COMPONENT32F, // D32F
  340. GL_STENCIL_INDEX8, // D0S8
  341. };
  342. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  343. static GLenum s_imageFormat[] =
  344. {
  345. GL_ZERO, // BC1
  346. GL_ZERO, // BC2
  347. GL_ZERO, // BC3
  348. GL_ZERO, // BC4
  349. GL_ZERO, // BC5
  350. GL_ZERO, // BC6H
  351. GL_ZERO, // BC7
  352. GL_ZERO, // ETC1
  353. GL_ZERO, // ETC2
  354. GL_ZERO, // ETC2A
  355. GL_ZERO, // ETC2A1
  356. GL_ZERO, // PTC12
  357. GL_ZERO, // PTC14
  358. GL_ZERO, // PTC12A
  359. GL_ZERO, // PTC14A
  360. GL_ZERO, // PTC22
  361. GL_ZERO, // PTC24
  362. GL_ZERO, // ATC
  363. GL_ZERO, // ATCE
  364. GL_ZERO, // ATCI
  365. GL_ZERO, // ASTC4x4
  366. GL_ZERO, // ASTC5x5
  367. GL_ZERO, // ASTC6x6
  368. GL_ZERO, // ASTC8x5
  369. GL_ZERO, // ASTC8x6
  370. GL_ZERO, // ASTC10x5
  371. GL_ZERO, // Unknown
  372. GL_ZERO, // R1
  373. GL_ALPHA, // A8
  374. GL_R8, // R8
  375. GL_R8I, // R8I
  376. GL_R8UI, // R8UI
  377. GL_R8_SNORM, // R8S
  378. GL_R16, // R16
  379. GL_R16I, // R16I
  380. GL_R16UI, // R16U
  381. GL_R16F, // R16F
  382. GL_R16_SNORM, // R16S
  383. GL_R32I, // R32I
  384. GL_R32UI, // R32U
  385. GL_R32F, // R32F
  386. GL_RG8, // RG8
  387. GL_RG8I, // RG8I
  388. GL_RG8UI, // RG8U
  389. GL_RG8_SNORM, // RG8S
  390. GL_RG16, // RG16
  391. GL_RG16I, // RG16I
  392. GL_RG16UI, // RG16U
  393. GL_RG16F, // RG16F
  394. GL_RG16_SNORM, // RG16S
  395. GL_RG32I, // RG32I
  396. GL_RG32UI, // RG32U
  397. GL_RG32F, // RG32F
  398. GL_RGB8, // RGB8
  399. GL_RGB8I, // RGB8I
  400. GL_RGB8UI, // RGB8UI
  401. GL_RGB8_SNORM, // RGB8S
  402. GL_RGB9_E5, // RGB9E5F
  403. GL_RGBA8, // BGRA8
  404. GL_RGBA8, // RGBA8
  405. GL_RGBA8I, // RGBA8I
  406. GL_RGBA8UI, // RGBA8UI
  407. GL_RGBA8_SNORM, // RGBA8S
  408. GL_RGBA16, // RGBA16
  409. GL_RGBA16I, // RGBA16I
  410. GL_RGBA16UI, // RGBA16U
  411. GL_RGBA16F, // RGBA16F
  412. GL_RGBA16_SNORM, // RGBA16S
  413. GL_RGBA32I, // RGBA32I
  414. GL_RGBA32UI, // RGBA32U
  415. GL_RGBA32F, // RGBA32F
  416. GL_RGB565, // R5G6B5
  417. GL_RGBA4, // RGBA4
  418. GL_RGB5_A1, // RGB5A1
  419. GL_RGB10_A2, // RGB10A2
  420. GL_R11F_G11F_B10F, // RG11B10F
  421. GL_ZERO, // UnknownDepth
  422. GL_ZERO, // D16
  423. GL_ZERO, // D24
  424. GL_ZERO, // D24S8
  425. GL_ZERO, // D32
  426. GL_ZERO, // D16F
  427. GL_ZERO, // D24F
  428. GL_ZERO, // D32F
  429. GL_ZERO, // D0S8
  430. };
  431. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  432. struct Extension
  433. {
  434. enum Enum
  435. {
  436. AMD_conservative_depth,
  437. AMD_multi_draw_indirect,
  438. ANGLE_depth_texture,
  439. ANGLE_framebuffer_blit,
  440. ANGLE_framebuffer_multisample,
  441. ANGLE_instanced_arrays,
  442. ANGLE_texture_compression_dxt1,
  443. ANGLE_texture_compression_dxt3,
  444. ANGLE_texture_compression_dxt5,
  445. ANGLE_timer_query,
  446. ANGLE_translated_shader_source,
  447. APPLE_texture_format_BGRA8888,
  448. APPLE_texture_max_level,
  449. ARB_clip_control,
  450. ARB_compute_shader,
  451. ARB_conservative_depth,
  452. ARB_copy_image,
  453. ARB_debug_label,
  454. ARB_debug_output,
  455. ARB_depth_buffer_float,
  456. ARB_depth_clamp,
  457. ARB_draw_buffers_blend,
  458. ARB_draw_indirect,
  459. ARB_draw_instanced,
  460. ARB_ES3_compatibility,
  461. ARB_framebuffer_object,
  462. ARB_framebuffer_sRGB,
  463. ARB_get_program_binary,
  464. ARB_half_float_pixel,
  465. ARB_half_float_vertex,
  466. ARB_instanced_arrays,
  467. ARB_internalformat_query,
  468. ARB_internalformat_query2,
  469. ARB_invalidate_subdata,
  470. ARB_map_buffer_range,
  471. ARB_multi_draw_indirect,
  472. ARB_multisample,
  473. ARB_occlusion_query,
  474. ARB_occlusion_query2,
  475. ARB_program_interface_query,
  476. ARB_sampler_objects,
  477. ARB_seamless_cube_map,
  478. ARB_shader_bit_encoding,
  479. ARB_shader_image_load_store,
  480. ARB_shader_storage_buffer_object,
  481. ARB_shader_texture_lod,
  482. ARB_texture_compression_bptc,
  483. ARB_texture_compression_rgtc,
  484. ARB_texture_cube_map_array,
  485. ARB_texture_float,
  486. ARB_texture_multisample,
  487. ARB_texture_rg,
  488. ARB_texture_rgb10_a2ui,
  489. ARB_texture_stencil8,
  490. ARB_texture_storage,
  491. ARB_texture_swizzle,
  492. ARB_timer_query,
  493. ARB_uniform_buffer_object,
  494. ARB_vertex_array_object,
  495. ARB_vertex_type_2_10_10_10_rev,
  496. ATI_meminfo,
  497. CHROMIUM_color_buffer_float_rgb,
  498. CHROMIUM_color_buffer_float_rgba,
  499. CHROMIUM_depth_texture,
  500. CHROMIUM_framebuffer_multisample,
  501. CHROMIUM_texture_compression_dxt3,
  502. CHROMIUM_texture_compression_dxt5,
  503. EXT_bgra,
  504. EXT_blend_color,
  505. EXT_blend_minmax,
  506. EXT_blend_subtract,
  507. EXT_color_buffer_half_float,
  508. EXT_color_buffer_float,
  509. EXT_copy_image,
  510. EXT_compressed_ETC1_RGB8_sub_texture,
  511. EXT_debug_label,
  512. EXT_debug_marker,
  513. EXT_debug_tool,
  514. EXT_discard_framebuffer,
  515. EXT_disjoint_timer_query,
  516. EXT_draw_buffers,
  517. EXT_draw_instanced,
  518. EXT_instanced_arrays,
  519. EXT_frag_depth,
  520. EXT_framebuffer_blit,
  521. EXT_framebuffer_object,
  522. EXT_framebuffer_sRGB,
  523. EXT_gpu_shader4,
  524. EXT_multi_draw_indirect,
  525. EXT_occlusion_query_boolean,
  526. EXT_packed_float,
  527. EXT_read_format_bgra,
  528. EXT_shader_image_load_store,
  529. EXT_shader_texture_lod,
  530. EXT_shadow_samplers,
  531. EXT_sRGB_write_control,
  532. EXT_texture_array,
  533. EXT_texture_compression_dxt1,
  534. EXT_texture_compression_latc,
  535. EXT_texture_compression_rgtc,
  536. EXT_texture_compression_s3tc,
  537. EXT_texture_cube_map_array,
  538. EXT_texture_filter_anisotropic,
  539. EXT_texture_format_BGRA8888,
  540. EXT_texture_rg,
  541. EXT_texture_shared_exponent,
  542. EXT_texture_snorm,
  543. EXT_texture_sRGB,
  544. EXT_texture_storage,
  545. EXT_texture_swizzle,
  546. EXT_texture_type_2_10_10_10_REV,
  547. EXT_timer_query,
  548. EXT_unpack_subimage,
  549. GOOGLE_depth_texture,
  550. IMG_multisampled_render_to_texture,
  551. IMG_read_format,
  552. IMG_shader_binary,
  553. IMG_texture_compression_pvrtc,
  554. IMG_texture_compression_pvrtc2,
  555. IMG_texture_format_BGRA8888,
  556. INTEL_fragment_shader_ordering,
  557. KHR_debug,
  558. KHR_no_error,
  559. MOZ_WEBGL_compressed_texture_s3tc,
  560. MOZ_WEBGL_depth_texture,
  561. NV_conservative_raster,
  562. NV_copy_image,
  563. NV_draw_buffers,
  564. NV_occlusion_query,
  565. NV_texture_border_clamp,
  566. NVX_gpu_memory_info,
  567. OES_copy_image,
  568. OES_compressed_ETC1_RGB8_texture,
  569. OES_depth24,
  570. OES_depth32,
  571. OES_depth_texture,
  572. OES_element_index_uint,
  573. OES_fragment_precision_high,
  574. OES_get_program_binary,
  575. OES_required_internalformat,
  576. OES_packed_depth_stencil,
  577. OES_read_format,
  578. OES_rgb8_rgba8,
  579. OES_standard_derivatives,
  580. OES_texture_3D,
  581. OES_texture_float,
  582. OES_texture_float_linear,
  583. OES_texture_npot,
  584. OES_texture_half_float,
  585. OES_texture_half_float_linear,
  586. OES_texture_stencil8,
  587. OES_texture_storage_multisample_2d_array,
  588. OES_vertex_array_object,
  589. OES_vertex_half_float,
  590. OES_vertex_type_10_10_10_2,
  591. WEBGL_color_buffer_float,
  592. WEBGL_compressed_texture_etc1,
  593. WEBGL_compressed_texture_s3tc,
  594. WEBGL_compressed_texture_pvrtc,
  595. WEBGL_depth_texture,
  596. WEBGL_draw_buffers,
  597. WEBKIT_EXT_texture_filter_anisotropic,
  598. WEBKIT_WEBGL_compressed_texture_s3tc,
  599. WEBKIT_WEBGL_depth_texture,
  600. Count
  601. };
  602. const char* m_name;
  603. bool m_supported;
  604. bool m_initialize;
  605. };
  606. // Extension registry
  607. //
  608. // ANGLE:
  609. // https://github.com/google/angle/tree/master/extensions
  610. //
  611. // CHROMIUM:
  612. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  613. //
  614. // EGL:
  615. // https://www.khronos.org/registry/egl/extensions/
  616. //
  617. // GL:
  618. // https://www.opengl.org/registry/
  619. //
  620. // GLES:
  621. // https://www.khronos.org/registry/gles/extensions/
  622. //
  623. // WEBGL:
  624. // https://www.khronos.org/registry/webgl/extensions/
  625. //
  626. static Extension s_extension[] =
  627. {
  628. { "AMD_conservative_depth", false, true },
  629. { "AMD_multi_draw_indirect", false, true },
  630. { "ANGLE_depth_texture", false, true },
  631. { "ANGLE_framebuffer_blit", false, true },
  632. { "ANGLE_framebuffer_multisample", false, false },
  633. { "ANGLE_instanced_arrays", false, true },
  634. { "ANGLE_texture_compression_dxt1", false, true },
  635. { "ANGLE_texture_compression_dxt3", false, true },
  636. { "ANGLE_texture_compression_dxt5", false, true },
  637. { "ANGLE_timer_query", false, true },
  638. { "ANGLE_translated_shader_source", false, true },
  639. { "APPLE_texture_format_BGRA8888", false, true },
  640. { "APPLE_texture_max_level", false, true },
  641. { "ARB_clip_control", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  642. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  643. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  644. { "ARB_copy_image", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  645. { "ARB_debug_label", false, true },
  646. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  647. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  648. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  649. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  650. { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  651. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  652. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  653. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  654. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  655. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  656. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  657. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  658. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  659. { "ARB_internalformat_query", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  660. { "ARB_internalformat_query2", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  661. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  662. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  663. { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  664. { "ARB_multisample", false, true },
  665. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  666. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  667. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  668. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  669. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  670. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  671. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  672. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  673. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  674. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  675. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  676. { "ARB_texture_cube_map_array", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  677. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  678. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  679. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  680. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  681. { "ARB_texture_stencil8", false, true },
  682. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  683. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  684. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  685. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  686. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  687. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  688. { "ATI_meminfo", false, true },
  689. { "CHROMIUM_color_buffer_float_rgb", false, true },
  690. { "CHROMIUM_color_buffer_float_rgba", false, true },
  691. { "CHROMIUM_depth_texture", false, true },
  692. { "CHROMIUM_framebuffer_multisample", false, true },
  693. { "CHROMIUM_texture_compression_dxt3", false, true },
  694. { "CHROMIUM_texture_compression_dxt5", false, true },
  695. { "EXT_bgra", false, true },
  696. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  697. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  698. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  699. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  700. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  701. { "EXT_copy_image", false, true }, // GLES2 extension.
  702. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  703. { "EXT_debug_label", false, true },
  704. { "EXT_debug_marker", false, true },
  705. { "EXT_debug_tool", false, true }, // RenderDoc extension.
  706. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  707. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  708. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  709. { "EXT_draw_instanced", false, true }, // GLES2 extension.
  710. { "EXT_instanced_arrays", false, true }, // GLES2 extension.
  711. { "EXT_frag_depth", false, true }, // GLES2 extension.
  712. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  713. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  714. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  715. { "EXT_gpu_shader4", false, true },
  716. { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension.
  717. { "EXT_occlusion_query_boolean", false, true }, // GLES2 extension.
  718. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  719. { "EXT_read_format_bgra", false, true },
  720. { "EXT_shader_image_load_store", false, true },
  721. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  722. { "EXT_shadow_samplers", false, true },
  723. { "EXT_sRGB_write_control", false, true }, // GLES2 extension.
  724. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  725. { "EXT_texture_compression_dxt1", false, true },
  726. { "EXT_texture_compression_latc", false, true },
  727. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  728. { "EXT_texture_compression_s3tc", false, true },
  729. { "EXT_texture_cube_map_array", false, true }, // GLES3.1 extension.
  730. { "EXT_texture_filter_anisotropic", false, true },
  731. { "EXT_texture_format_BGRA8888", false, true },
  732. { "EXT_texture_rg", false, true }, // GLES2 extension.
  733. { "EXT_texture_shared_exponent", false, true },
  734. { "EXT_texture_snorm", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  735. { "EXT_texture_sRGB", false, true },
  736. { "EXT_texture_storage", false, true },
  737. { "EXT_texture_swizzle", false, true },
  738. { "EXT_texture_type_2_10_10_10_REV", false, true },
  739. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  740. { "EXT_unpack_subimage", false, true },
  741. { "GOOGLE_depth_texture", false, true },
  742. { "IMG_multisampled_render_to_texture", false, true },
  743. { "IMG_read_format", false, true },
  744. { "IMG_shader_binary", false, true },
  745. { "IMG_texture_compression_pvrtc", false, true },
  746. { "IMG_texture_compression_pvrtc2", false, true },
  747. { "IMG_texture_format_BGRA8888", false, true },
  748. { "INTEL_fragment_shader_ordering", false, true },
  749. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  750. { "KHR_no_error", false, true },
  751. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  752. { "MOZ_WEBGL_depth_texture", false, true },
  753. { "NV_conservative_raster", false, true },
  754. { "NV_copy_image", false, true },
  755. { "NV_draw_buffers", false, true }, // GLES2 extension.
  756. { "NV_occlusion_query", false, true },
  757. { "NV_texture_border_clamp", false, true }, // GLES2 extension.
  758. { "NVX_gpu_memory_info", false, true },
  759. { "OES_copy_image", false, true },
  760. { "OES_compressed_ETC1_RGB8_texture", false, true },
  761. { "OES_depth24", false, true },
  762. { "OES_depth32", false, true },
  763. { "OES_depth_texture", false, true },
  764. { "OES_element_index_uint", false, true },
  765. { "OES_fragment_precision_high", false, true },
  766. { "OES_get_program_binary", false, true },
  767. { "OES_required_internalformat", false, true },
  768. { "OES_packed_depth_stencil", false, true },
  769. { "OES_read_format", false, true },
  770. { "OES_rgb8_rgba8", false, true },
  771. { "OES_standard_derivatives", false, true },
  772. { "OES_texture_3D", false, true },
  773. { "OES_texture_float", false, true },
  774. { "OES_texture_float_linear", false, true },
  775. { "OES_texture_npot", false, true },
  776. { "OES_texture_half_float", false, true },
  777. { "OES_texture_half_float_linear", false, true },
  778. { "OES_texture_stencil8", false, true },
  779. { "OES_texture_storage_multisample_2d_array", false, true },
  780. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  781. { "OES_vertex_half_float", false, true },
  782. { "OES_vertex_type_10_10_10_2", false, true },
  783. { "WEBGL_color_buffer_float", false, true },
  784. { "WEBGL_compressed_texture_etc1", false, true },
  785. { "WEBGL_compressed_texture_s3tc", false, true },
  786. { "WEBGL_compressed_texture_pvrtc", false, true },
  787. { "WEBGL_depth_texture", false, true },
  788. { "WEBGL_draw_buffers", false, true },
  789. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  790. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  791. { "WEBKIT_WEBGL_depth_texture", false, true },
  792. };
  793. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  794. static const char* s_ARB_shader_texture_lod[] =
  795. {
  796. "texture2DLod",
  797. "texture2DArrayLod", // BK - interacts with ARB_texture_array.
  798. "texture2DProjLod",
  799. "texture2DGrad",
  800. "texture2DProjGrad",
  801. "texture3DLod",
  802. "texture3DProjLod",
  803. "texture3DGrad",
  804. "texture3DProjGrad",
  805. "textureCubeLod",
  806. "textureCubeGrad",
  807. "shadow2DLod",
  808. "shadow2DProjLod",
  809. NULL
  810. // "texture1DLod",
  811. // "texture1DProjLod",
  812. // "shadow1DLod",
  813. // "shadow1DProjLod",
  814. };
  815. static const char* s_EXT_shader_texture_lod[] =
  816. {
  817. "texture2DLod",
  818. "texture2DProjLod",
  819. "textureCubeLod",
  820. "texture2DGrad",
  821. "texture2DProjGrad",
  822. "textureCubeGrad",
  823. NULL
  824. };
  825. static const char* s_EXT_shadow_samplers[] =
  826. {
  827. "shadow2D",
  828. "shadow2DProj",
  829. NULL
  830. };
  831. static const char* s_OES_standard_derivatives[] =
  832. {
  833. "dFdx",
  834. "dFdy",
  835. "fwidth",
  836. NULL
  837. };
  838. static const char* s_uisamplers[] =
  839. {
  840. "isampler2D",
  841. "usampler2D",
  842. "isampler3D",
  843. "usampler3D",
  844. "isamplerCube",
  845. "usamplerCube",
  846. NULL
  847. };
  848. static const char* s_uint[] =
  849. {
  850. "uint",
  851. "uvec2",
  852. "uvec3",
  853. "uvec4",
  854. NULL
  855. };
  856. static const char* s_texelFetch[] =
  857. {
  858. "texture",
  859. "textureLod",
  860. "textureGrad",
  861. "textureProj",
  862. "textureProjLod",
  863. "texelFetch",
  864. "texelFetchOffset",
  865. NULL
  866. };
  867. static const char* s_texture3D[] =
  868. {
  869. "sampler3D",
  870. "sampler3DArray",
  871. NULL
  872. };
  873. static const char* s_textureArray[] =
  874. {
  875. "sampler2DArray",
  876. "sampler2DMSArray",
  877. "samplerCubeArray",
  878. "sampler2DArrayShadow",
  879. NULL
  880. };
  881. static const char* s_ARB_texture_multisample[] =
  882. {
  883. "sampler2DMS",
  884. "isampler2DMS",
  885. "usampler2DMS",
  886. NULL
  887. };
  888. static const char* s_EXT_gpu_shader4[] =
  889. {
  890. "gl_VertexID",
  891. "gl_InstanceID",
  892. "uint",
  893. NULL
  894. };
  895. static const char* s_ARB_gpu_shader5[] =
  896. {
  897. "bitfieldReverse",
  898. "floatBitsToInt",
  899. "floatBitsToUint",
  900. "intBitsToFloat",
  901. "uintBitsToFloat",
  902. NULL
  903. };
  904. static const char* s_ARB_shading_language_packing[] =
  905. {
  906. "packHalf2x16",
  907. "unpackHalf2x16",
  908. NULL
  909. };
  910. static const char* s_intepolationQualifier[] =
  911. {
  912. "flat",
  913. "smooth",
  914. "noperspective",
  915. "centroid",
  916. NULL
  917. };
  918. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  919. {
  920. }
  921. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  922. {
  923. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  924. }
  925. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  926. {
  927. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  928. }
  929. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  930. {
  931. }
  932. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  933. {
  934. }
  935. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  936. {
  937. }
  938. static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  939. {
  940. const uint8_t* args = (const uint8_t*)_indirect;
  941. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  942. {
  943. GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) );
  944. args += _stride;
  945. }
  946. }
  947. static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  948. {
  949. const uint8_t* args = (const uint8_t*)_indirect;
  950. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  951. {
  952. GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) );
  953. args += _stride;
  954. }
  955. }
  956. static void GL_APIENTRY stubPolygonMode(GLenum /*_face*/, GLenum /*_mode*/)
  957. {
  958. }
  959. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  960. static const char* getGLString(GLenum _name)
  961. {
  962. const char* str = (const char*)glGetString(_name);
  963. glGetError(); // ignore error if glGetString returns NULL.
  964. if (NULL != str)
  965. {
  966. return str;
  967. }
  968. return "<unknown>";
  969. }
  970. static uint32_t getGLStringHash(GLenum _name)
  971. {
  972. const char* str = (const char*)glGetString(_name);
  973. glGetError(); // ignore error if glGetString returns NULL.
  974. if (NULL != str)
  975. {
  976. return bx::hash<bx::HashMurmur2A>(str, (uint32_t)bx::strLen(str) );
  977. }
  978. return 0;
  979. }
  980. void dumpExtensions(const char* _extensions)
  981. {
  982. if (NULL != _extensions)
  983. {
  984. char name[1024];
  985. const char* pos = _extensions;
  986. const char* end = _extensions + bx::strLen(_extensions);
  987. while (pos < end)
  988. {
  989. uint32_t len;
  990. bx::StringView space = bx::strFind(pos, ' ');
  991. if (!space.isEmpty() )
  992. {
  993. len = bx::uint32_min(sizeof(name), (uint32_t)(space.getPtr() - pos) );
  994. }
  995. else
  996. {
  997. len = bx::uint32_min(sizeof(name), (uint32_t)bx::strLen(pos) );
  998. }
  999. bx::strCopy(name, BX_COUNTOF(name), pos, len);
  1000. name[len] = '\0';
  1001. BX_TRACE("\t%s", name);
  1002. pos += len+1;
  1003. }
  1004. }
  1005. }
  1006. const char* toString(GLenum _enum)
  1007. {
  1008. switch (_enum)
  1009. {
  1010. case GL_DEBUG_SOURCE_API: return "API";
  1011. case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys";
  1012. case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader";
  1013. case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty";
  1014. case GL_DEBUG_SOURCE_APPLICATION: return "Application";
  1015. case GL_DEBUG_SOURCE_OTHER: return "Other";
  1016. case GL_DEBUG_TYPE_ERROR: return "Error";
  1017. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior";
  1018. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior";
  1019. case GL_DEBUG_TYPE_PORTABILITY: return "Portability";
  1020. case GL_DEBUG_TYPE_PERFORMANCE: return "Performance";
  1021. case GL_DEBUG_TYPE_OTHER: return "Other";
  1022. case GL_DEBUG_SEVERITY_HIGH: return "High";
  1023. case GL_DEBUG_SEVERITY_MEDIUM: return "Medium";
  1024. case GL_DEBUG_SEVERITY_LOW: return "Low";
  1025. case GL_DEBUG_SEVERITY_NOTIFICATION: return "SPAM";
  1026. default:
  1027. break;
  1028. }
  1029. return "<unknown>";
  1030. }
  1031. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  1032. {
  1033. if (GL_DEBUG_SEVERITY_NOTIFICATION != _severity)
  1034. {
  1035. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  1036. , toString(_source)
  1037. , toString(_type)
  1038. , _id
  1039. , toString(_severity)
  1040. , _message
  1041. );
  1042. BX_UNUSED(_source, _type, _id, _severity, _message);
  1043. }
  1044. }
  1045. GLint glGet(GLenum _pname)
  1046. {
  1047. GLint result = 0;
  1048. glGetIntegerv(_pname, &result);
  1049. GLenum err = glGetError();
  1050. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  1051. return 0 == err ? result : 0;
  1052. }
  1053. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  1054. {
  1055. TextureFormatInfo& tfi = s_textureFormat[_format];
  1056. tfi.m_internalFmt = _internalFmt;
  1057. tfi.m_fmt = _fmt;
  1058. tfi.m_type = _type;
  1059. }
  1060. void flushGlError()
  1061. {
  1062. for (GLenum err = glGetError(); err != 0; err = glGetError() );
  1063. }
  1064. static void texSubImage(
  1065. GLenum _target
  1066. , GLint _level
  1067. , GLint _xoffset
  1068. , GLint _yoffset
  1069. , GLint _zoffset
  1070. , GLsizei _width
  1071. , GLsizei _height
  1072. , GLsizei _depth
  1073. , GLenum _format
  1074. , GLenum _type
  1075. , const GLvoid* _data
  1076. )
  1077. {
  1078. if (NULL == _data)
  1079. {
  1080. return;
  1081. }
  1082. if (_target == GL_TEXTURE_3D
  1083. || _target == GL_TEXTURE_2D_ARRAY
  1084. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  1085. {
  1086. glTexSubImage3D(
  1087. _target
  1088. , _level
  1089. , _xoffset
  1090. , _yoffset
  1091. , _zoffset
  1092. , _width
  1093. , _height
  1094. , _depth
  1095. , _format
  1096. , _type
  1097. , _data
  1098. );
  1099. }
  1100. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  1101. {
  1102. }
  1103. else
  1104. {
  1105. BX_UNUSED(_zoffset, _depth);
  1106. glTexSubImage2D(
  1107. _target
  1108. , _level
  1109. , _xoffset
  1110. , _yoffset
  1111. , _width
  1112. , _height
  1113. , _format
  1114. , _type
  1115. , _data
  1116. );
  1117. }
  1118. }
  1119. static void texImage(
  1120. GLenum _target
  1121. , uint32_t _msaaQuality
  1122. , GLint _level
  1123. , GLint _internalFormat
  1124. , GLsizei _width
  1125. , GLsizei _height
  1126. , GLsizei _depth
  1127. , GLint _border
  1128. , GLenum _format
  1129. , GLenum _type
  1130. , const GLvoid* _data
  1131. )
  1132. {
  1133. if (_target == GL_TEXTURE_3D)
  1134. {
  1135. glTexImage3D(
  1136. _target
  1137. , _level
  1138. , _internalFormat
  1139. , _width
  1140. , _height
  1141. , _depth
  1142. , _border
  1143. , _format
  1144. , _type
  1145. , _data
  1146. );
  1147. }
  1148. else if (_target == GL_TEXTURE_2D_ARRAY
  1149. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  1150. {
  1151. texSubImage(
  1152. _target
  1153. , _level
  1154. , 0
  1155. , 0
  1156. , _depth
  1157. , _width
  1158. , _height
  1159. , 1
  1160. , _format
  1161. , _type
  1162. , _data
  1163. );
  1164. }
  1165. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  1166. {
  1167. }
  1168. else if (_target == GL_TEXTURE_2D_MULTISAMPLE)
  1169. {
  1170. glTexImage2DMultisample(
  1171. _target
  1172. , _msaaQuality
  1173. , _internalFormat
  1174. , _width
  1175. , _height
  1176. , false
  1177. );
  1178. }
  1179. else
  1180. {
  1181. glTexImage2D(
  1182. _target
  1183. , _level
  1184. , _internalFormat
  1185. , _width
  1186. , _height
  1187. , _border
  1188. , _format
  1189. , _type
  1190. , _data
  1191. );
  1192. }
  1193. BX_UNUSED(_msaaQuality, _depth, _border, _data);
  1194. }
  1195. static void compressedTexSubImage(
  1196. GLenum _target
  1197. , GLint _level
  1198. , GLint _xoffset
  1199. , GLint _yoffset
  1200. , GLint _zoffset
  1201. , GLsizei _width
  1202. , GLsizei _height
  1203. , GLsizei _depth
  1204. , GLenum _format
  1205. , GLsizei _imageSize
  1206. , const GLvoid* _data
  1207. )
  1208. {
  1209. if (_target == GL_TEXTURE_3D
  1210. || _target == GL_TEXTURE_2D_ARRAY)
  1211. {
  1212. glCompressedTexSubImage3D(
  1213. _target
  1214. , _level
  1215. , _xoffset
  1216. , _yoffset
  1217. , _zoffset
  1218. , _width
  1219. , _height
  1220. , _depth
  1221. , _format
  1222. , _imageSize
  1223. , _data
  1224. );
  1225. }
  1226. else
  1227. {
  1228. BX_UNUSED(_zoffset, _depth);
  1229. glCompressedTexSubImage2D(
  1230. _target
  1231. , _level
  1232. , _xoffset
  1233. , _yoffset
  1234. , _width
  1235. , _height
  1236. , _format
  1237. , _imageSize
  1238. , _data
  1239. );
  1240. }
  1241. }
  1242. static void compressedTexImage(
  1243. GLenum _target
  1244. , GLint _level
  1245. , GLenum _internalformat
  1246. , GLsizei _width
  1247. , GLsizei _height
  1248. , GLsizei _depth
  1249. , GLint _border
  1250. , GLsizei _imageSize
  1251. , const GLvoid* _data
  1252. )
  1253. {
  1254. if (_target == GL_TEXTURE_3D)
  1255. {
  1256. glCompressedTexImage3D(
  1257. _target
  1258. , _level
  1259. , _internalformat
  1260. , _width
  1261. , _height
  1262. , _depth
  1263. , _border
  1264. , _imageSize
  1265. , _data
  1266. );
  1267. }
  1268. else if (_target == GL_TEXTURE_2D_ARRAY
  1269. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  1270. {
  1271. compressedTexSubImage(
  1272. _target
  1273. , _level
  1274. , 0
  1275. , 0
  1276. , _depth
  1277. , _width
  1278. , _height
  1279. , 1
  1280. , _internalformat
  1281. , _imageSize
  1282. , _data
  1283. );
  1284. }
  1285. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  1286. {
  1287. }
  1288. else
  1289. {
  1290. BX_UNUSED(_depth);
  1291. glCompressedTexImage2D(
  1292. _target
  1293. , _level
  1294. , _internalformat
  1295. , _width
  1296. , _height
  1297. , _border
  1298. , _imageSize
  1299. , _data
  1300. );
  1301. }
  1302. }
  1303. GLenum initTestTexture(TextureFormat::Enum _format, bool _srgb, bool _mipmaps, bool _array, GLsizei _dim)
  1304. {
  1305. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1306. GLenum internalFmt = _srgb
  1307. ? tfi.m_internalFmtSrgb
  1308. : tfi.m_internalFmt
  1309. ;
  1310. GLsizei bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(_format) );
  1311. GLsizei size = (_dim*_dim*bpp)/8;
  1312. void* data = NULL;
  1313. if (bimg::isDepth(bimg::TextureFormat::Enum(_format) ) )
  1314. {
  1315. _srgb = false;
  1316. _mipmaps = false;
  1317. _array = false;
  1318. }
  1319. else
  1320. {
  1321. data = bx::alignPtr(alloca(size+16), 0, 16);
  1322. }
  1323. flushGlError();
  1324. GLenum err = 0;
  1325. const GLenum target = _array
  1326. ? GL_TEXTURE_2D_ARRAY
  1327. : GL_TEXTURE_2D
  1328. ;
  1329. if (bimg::isCompressed(bimg::TextureFormat::Enum(_format) ) )
  1330. {
  1331. for (uint32_t ii = 0, dim = _dim; ii < (_mipmaps ? 5u : 1u) && 0 == err; ++ii, dim >>= 1)
  1332. {
  1333. dim = bx::uint32_max(1, dim);
  1334. uint32_t block = bx::uint32_max(4, dim);
  1335. size = (block*block*bpp)/8;
  1336. compressedTexImage(target, ii, internalFmt, dim, dim, 0, 0, size, data);
  1337. err |= glGetError();
  1338. }
  1339. }
  1340. else
  1341. {
  1342. for (uint32_t ii = 0, dim = _dim; ii < (_mipmaps ? 5u : 1u) && 0 == err; ++ii, dim >>= 1)
  1343. {
  1344. dim = bx::uint32_max(1, dim);
  1345. size = (dim*dim*bpp)/8;
  1346. texImage(target, 0, ii, internalFmt, dim, dim, 0, 0, tfi.m_fmt, tfi.m_type, data);
  1347. err |= glGetError();
  1348. }
  1349. }
  1350. return err;
  1351. }
  1352. static bool isTextureFormatValid(
  1353. TextureFormat::Enum _format
  1354. , bool _srgb = false
  1355. , bool _mipAutogen = false
  1356. , bool _array = false
  1357. , GLsizei _dim = 16
  1358. )
  1359. {
  1360. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1361. GLenum internalFmt = _srgb
  1362. ? tfi.m_internalFmtSrgb
  1363. : tfi.m_internalFmt
  1364. ;
  1365. if (GL_ZERO == internalFmt)
  1366. {
  1367. return false;
  1368. }
  1369. BX_TRACE("%d, %d, %d, %s", _array, _srgb, _mipAutogen, getName(_format) );
  1370. const GLenum target = _array
  1371. ? GL_TEXTURE_2D_ARRAY
  1372. : GL_TEXTURE_2D
  1373. ;
  1374. GLuint id;
  1375. GL_CHECK(glGenTextures(1, &id) );
  1376. GL_CHECK(glBindTexture(target, id) );
  1377. GLenum err = 0;
  1378. if (_array)
  1379. {
  1380. glTexStorage3D(target
  1381. , 1 + GLsizei(bx::log2(float(_dim) ) )
  1382. , internalFmt
  1383. , _dim
  1384. , _dim
  1385. , _dim
  1386. );
  1387. err = glGetError();
  1388. }
  1389. if (0 == err)
  1390. {
  1391. err = initTestTexture(_format, _srgb, _mipAutogen, _array, _dim);
  1392. BX_WARN(0 == err, "TextureFormat::%s %s%s%sis not supported (%x: %s)."
  1393. , getName(_format)
  1394. , _srgb ? "+sRGB " : ""
  1395. , _mipAutogen ? "+mipAutoGen " : ""
  1396. , _array ? "+array " : ""
  1397. , err
  1398. , glEnumName(err)
  1399. );
  1400. if (0 == err
  1401. && _mipAutogen)
  1402. {
  1403. glGenerateMipmap(target);
  1404. err = glGetError();
  1405. }
  1406. }
  1407. GL_CHECK(glDeleteTextures(1, &id) );
  1408. return 0 == err;
  1409. }
  1410. static bool isImageFormatValid(TextureFormat::Enum _format, GLsizei _dim = 16)
  1411. {
  1412. if (GL_ZERO == s_imageFormat[_format])
  1413. {
  1414. return false;
  1415. }
  1416. GLuint id;
  1417. GL_CHECK(glGenTextures(1, &id) );
  1418. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1419. flushGlError();
  1420. GLenum err = 0;
  1421. glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], _dim, _dim);
  1422. err |= glGetError();
  1423. if (0 == err)
  1424. {
  1425. glBindImageTexture(0
  1426. , id
  1427. , 0
  1428. , GL_FALSE
  1429. , 0
  1430. , GL_READ_WRITE
  1431. , s_imageFormat[_format]
  1432. );
  1433. err |= glGetError();
  1434. }
  1435. GL_CHECK(glDeleteTextures(1, &id) );
  1436. return 0 == err;
  1437. }
  1438. static bool isFramebufferFormatValid(
  1439. TextureFormat::Enum _format
  1440. , bool _srgb = false
  1441. , bool _writeOnly = false
  1442. , GLsizei _dim = 16
  1443. )
  1444. {
  1445. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1446. GLenum internalFmt = _srgb
  1447. ? tfi.m_internalFmtSrgb
  1448. : tfi.m_internalFmt
  1449. ;
  1450. if (GL_ZERO == internalFmt)
  1451. {
  1452. return false;
  1453. }
  1454. if (_writeOnly)
  1455. {
  1456. GLuint rbo;
  1457. glGenRenderbuffers(1, &rbo);
  1458. glBindRenderbuffer(GL_RENDERBUFFER, rbo);
  1459. glRenderbufferStorage(GL_RENDERBUFFER
  1460. , s_rboFormat[_format]
  1461. , _dim
  1462. , _dim
  1463. );
  1464. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  1465. glDeleteRenderbuffers(1, &rbo);
  1466. GLenum err = glGetError();
  1467. return 0 == err;
  1468. }
  1469. GLuint fbo;
  1470. GL_CHECK(glGenFramebuffers(1, &fbo) );
  1471. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
  1472. GLuint id;
  1473. GL_CHECK(glGenTextures(1, &id) );
  1474. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1475. GLenum err = initTestTexture(_format, _srgb, false, false, _dim);
  1476. GLenum attachment;
  1477. if (bimg::isDepth(bimg::TextureFormat::Enum(_format) ) )
  1478. {
  1479. const bimg::ImageBlockInfo& info = bimg::getBlockInfo(bimg::TextureFormat::Enum(_format) );
  1480. if (0 == info.depthBits)
  1481. {
  1482. attachment = GL_STENCIL_ATTACHMENT;
  1483. }
  1484. else if (0 == info.stencilBits)
  1485. {
  1486. attachment = GL_DEPTH_ATTACHMENT;
  1487. }
  1488. else
  1489. {
  1490. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  1491. }
  1492. }
  1493. else
  1494. {
  1495. attachment = GL_COLOR_ATTACHMENT0;
  1496. }
  1497. glFramebufferTexture2D(GL_FRAMEBUFFER
  1498. , attachment
  1499. , GL_TEXTURE_2D
  1500. , id
  1501. , 0
  1502. );
  1503. err = glGetError();
  1504. if (0 == err)
  1505. {
  1506. err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  1507. }
  1508. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1509. GL_CHECK(glDeleteFramebuffers(1, &fbo) );
  1510. GL_CHECK(glDeleteTextures(1, &id) );
  1511. return GL_FRAMEBUFFER_COMPLETE == err;
  1512. }
  1513. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  1514. {
  1515. const uint32_t mag = (_flags&BGFX_SAMPLER_MAG_MASK)>>BGFX_SAMPLER_MAG_SHIFT;
  1516. const uint32_t min = (_flags&BGFX_SAMPLER_MIN_MASK)>>BGFX_SAMPLER_MIN_SHIFT;
  1517. const uint32_t mip = (_flags&BGFX_SAMPLER_MIP_MASK)>>BGFX_SAMPLER_MIP_SHIFT;
  1518. _magFilter = s_textureFilterMag[mag];
  1519. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  1520. }
  1521. void updateExtension(const char* _name)
  1522. {
  1523. bool supported = false;
  1524. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1525. {
  1526. Extension& extension = s_extension[ii];
  1527. if (!extension.m_supported
  1528. && extension.m_initialize)
  1529. {
  1530. const char* ext = _name;
  1531. if (0 == bx::strCmp(ext, "GL_", 3) ) // skip GL_
  1532. {
  1533. ext += 3;
  1534. }
  1535. if (0 == bx::strCmp(ext, extension.m_name) )
  1536. {
  1537. extension.m_supported = true;
  1538. supported = true;
  1539. break;
  1540. }
  1541. }
  1542. }
  1543. BX_TRACE("GL_EXTENSION %s: %s", supported ? " (supported)" : "", _name);
  1544. BX_UNUSED(supported);
  1545. }
  1546. struct VendorId
  1547. {
  1548. const char* name;
  1549. uint16_t id;
  1550. };
  1551. static const VendorId s_vendorIds[] =
  1552. {
  1553. { "NVIDIA Corporation", BGFX_PCI_ID_NVIDIA },
  1554. { "Advanced Micro Devices, Inc.", BGFX_PCI_ID_AMD },
  1555. { "Intel", BGFX_PCI_ID_INTEL },
  1556. { "ATI Technologies Inc.", BGFX_PCI_ID_AMD },
  1557. };
  1558. struct Workaround
  1559. {
  1560. void reset()
  1561. {
  1562. m_detachShader = true;
  1563. }
  1564. bool m_detachShader;
  1565. };
  1566. struct RendererContextGL : public RendererContextI
  1567. {
  1568. RendererContextGL()
  1569. : m_numWindows(1)
  1570. , m_rtMsaa(false)
  1571. , m_fbDiscard(BGFX_CLEAR_NONE)
  1572. , m_capture(NULL)
  1573. , m_captureSize(0)
  1574. , m_maxAnisotropy(0.0f)
  1575. , m_maxAnisotropyDefault(0.0f)
  1576. , m_maxMsaa(0)
  1577. , m_vao(0)
  1578. , m_blitSupported(false)
  1579. , m_readBackSupported(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1580. , m_vaoSupport(false)
  1581. , m_samplerObjectSupport(false)
  1582. , m_shadowSamplersSupport(false)
  1583. , m_srgbWriteControlSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1584. , m_borderColorSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1585. , m_programBinarySupport(false)
  1586. , m_textureSwizzleSupport(false)
  1587. , m_depthTextureSupport(false)
  1588. , m_timerQuerySupport(false)
  1589. , m_occlusionQuerySupport(false)
  1590. , m_atocSupport(false)
  1591. , m_conservativeRasterSupport(false)
  1592. , m_flip(false)
  1593. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1594. , m_backBufferFbo(0)
  1595. , m_msaaBackBufferFbo(0)
  1596. {
  1597. bx::memSet(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  1598. }
  1599. ~RendererContextGL()
  1600. {
  1601. }
  1602. bool init(const Init& _init)
  1603. {
  1604. struct ErrorState
  1605. {
  1606. enum Enum
  1607. {
  1608. Default,
  1609. };
  1610. };
  1611. ErrorState::Enum errorState = ErrorState::Default;
  1612. if (_init.debug
  1613. || _init.profile)
  1614. {
  1615. m_renderdocdll = loadRenderDoc();
  1616. }
  1617. m_fbh.idx = kInvalidHandle;
  1618. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  1619. bx::memSet(&m_resolution, 0, sizeof(m_resolution) );
  1620. setRenderContextSize(_init.resolution.width, _init.resolution.height);
  1621. m_vendor = getGLString(GL_VENDOR);
  1622. m_renderer = getGLString(GL_RENDERER);
  1623. m_version = getGLString(GL_VERSION);
  1624. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  1625. for (uint32_t ii = 0; ii < BX_COUNTOF(s_vendorIds); ++ii)
  1626. {
  1627. const VendorId& vendorId = s_vendorIds[ii];
  1628. if (0 == bx::strCmp(vendorId.name, m_vendor, bx::strLen(vendorId.name) ) )
  1629. {
  1630. g_caps.vendorId = vendorId.id;
  1631. break;
  1632. }
  1633. }
  1634. m_workaround.reset();
  1635. GLint numCmpFormats = 0;
  1636. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1637. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1638. GLint* cmpFormat = NULL;
  1639. if (0 < numCmpFormats)
  1640. {
  1641. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  1642. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1643. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  1644. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1645. {
  1646. GLint internalFmt = cmpFormat[ii];
  1647. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  1648. for (uint32_t jj = 0; jj < fmt; ++jj)
  1649. {
  1650. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  1651. {
  1652. s_textureFormat[jj].m_supported = true;
  1653. fmt = jj;
  1654. }
  1655. }
  1656. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  1657. }
  1658. }
  1659. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1660. {
  1661. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1662. BX_TRACE("Defaults:");
  1663. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1664. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1665. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1666. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1667. #else
  1668. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1669. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1670. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1671. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1672. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1673. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1674. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1675. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1676. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1677. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1678. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1679. GL_GET(GL_MAX_COLOR_ATTACHMENTS, 1);
  1680. GL_GET(GL_MAX_DRAW_BUFFERS, 1);
  1681. #undef GL_GET
  1682. BX_TRACE(" Vendor: %s", m_vendor);
  1683. BX_TRACE(" Renderer: %s", m_renderer);
  1684. BX_TRACE(" Version: %s", m_version);
  1685. BX_TRACE("GLSL version: %s", m_glslVersion);
  1686. }
  1687. // Initial binary shader hash depends on driver version.
  1688. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1689. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1690. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1691. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1692. ;
  1693. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1694. && 0 == bx::strCmp(m_vendor, "Imagination Technologies")
  1695. && !bx::strFind(m_version, "(SDK 3.5@3510720)").isEmpty() )
  1696. {
  1697. // Skip initializing extensions that are broken in emulator.
  1698. s_extension[Extension::ARB_program_interface_query ].m_initialize =
  1699. s_extension[Extension::ARB_shader_storage_buffer_object].m_initialize = false;
  1700. }
  1701. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  1702. && 0 == bx::strCmp(m_vendor, "Imagination Technologies")
  1703. && !bx::strFind(m_version, "1.8@905891").isEmpty() )
  1704. {
  1705. m_workaround.m_detachShader = false;
  1706. }
  1707. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  1708. {
  1709. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1710. glGetError(); // ignore error if glGetString returns NULL.
  1711. if (NULL != extensions)
  1712. {
  1713. char name[1024];
  1714. const char* pos = extensions;
  1715. const char* end = extensions + bx::strLen(extensions);
  1716. uint32_t index = 0;
  1717. while (pos < end)
  1718. {
  1719. uint32_t len;
  1720. const bx::StringView space = bx::strFind(pos, ' ');
  1721. if (!space.isEmpty() )
  1722. {
  1723. len = bx::uint32_min(sizeof(name), (uint32_t)(space.getPtr() - pos) );
  1724. }
  1725. else
  1726. {
  1727. len = bx::uint32_min(sizeof(name), (uint32_t)bx::strLen(pos) );
  1728. }
  1729. bx::strCopy(name, BX_COUNTOF(name), pos, len);
  1730. name[len] = '\0';
  1731. updateExtension(name);
  1732. pos += len+1;
  1733. ++index;
  1734. }
  1735. }
  1736. else if (NULL != glGetStringi)
  1737. {
  1738. GLint numExtensions = 0;
  1739. glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
  1740. glGetError(); // ignore error if glGetIntegerv returns NULL.
  1741. for (GLint index = 0; index < numExtensions; ++index)
  1742. {
  1743. const char* name = (const char*)glGetStringi(GL_EXTENSIONS, index);
  1744. updateExtension(name);
  1745. }
  1746. }
  1747. BX_TRACE("Supported extensions:");
  1748. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1749. {
  1750. if (s_extension[ii].m_supported)
  1751. {
  1752. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1753. }
  1754. }
  1755. }
  1756. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1757. && !s_extension[Extension::ARB_framebuffer_object].m_supported)
  1758. {
  1759. BX_TRACE("Init error: ARB_framebuffer_object not supported.");
  1760. goto error;
  1761. }
  1762. {
  1763. // Allow all texture filters.
  1764. bx::memSet(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1765. bool bc123Supported = 0
  1766. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1767. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1768. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1769. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1770. ;
  1771. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1772. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1773. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1774. ;
  1775. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1776. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1777. {
  1778. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1779. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1780. {
  1781. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1782. {
  1783. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1784. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1785. break;
  1786. }
  1787. }
  1788. }
  1789. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1790. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1791. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1792. ;
  1793. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1794. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1795. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1796. ;
  1797. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1798. {
  1799. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1800. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1801. }
  1802. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1803. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1804. {
  1805. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1806. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1807. }
  1808. bool etc1Supported = 0
  1809. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1810. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1811. ;
  1812. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1813. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1814. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1815. ;
  1816. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1817. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1818. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1819. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1820. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1821. {
  1822. // When ETC2 is supported override ETC1 texture format settings.
  1823. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1824. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1825. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1826. }
  1827. bool ptc1Supported = 0
  1828. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1829. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1830. ;
  1831. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1832. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1833. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1834. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1835. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1836. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1837. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1838. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1839. {
  1840. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1841. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1842. {
  1843. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1844. setTextureFormat(TextureFormat::RGBA32F, GL_RGBA, GL_RGBA, GL_FLOAT);
  1845. // internalFormat and format must match:
  1846. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml
  1847. setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1848. setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5_REV);
  1849. setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV);
  1850. setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV);
  1851. if (s_extension[Extension::OES_texture_half_float].m_supported
  1852. || s_extension[Extension::OES_texture_float ].m_supported)
  1853. {
  1854. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1855. // When half/float is available via extensions texture will be marked as
  1856. // incomplete if it uses anything other than nearest filter.
  1857. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1858. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1859. s_textureFilter[TextureFormat::R16F] = linear16F;
  1860. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1861. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1862. s_textureFilter[TextureFormat::R32F] = linear32F;
  1863. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1864. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1865. }
  1866. if (BX_ENABLED(BX_PLATFORM_IOS) || BX_ENABLED(BX_PLATFORM_EMSCRIPTEN))
  1867. {
  1868. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1869. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1870. }
  1871. }
  1872. }
  1873. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1874. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1875. {
  1876. setTextureFormat(TextureFormat::R8I, GL_R8I, GL_RED_INTEGER, GL_BYTE);
  1877. setTextureFormat(TextureFormat::R8U, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE);
  1878. setTextureFormat(TextureFormat::R16I, GL_R16I, GL_RED_INTEGER, GL_SHORT);
  1879. setTextureFormat(TextureFormat::R16U, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1880. // setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1881. // setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1882. setTextureFormat(TextureFormat::R32U, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1883. setTextureFormat(TextureFormat::RG32U, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1884. setTextureFormat(TextureFormat::RGBA32U, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1885. }
  1886. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1887. || s_extension[Extension::EXT_bgra ].m_supported
  1888. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1889. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1890. {
  1891. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1892. {
  1893. m_readPixelsFmt = GL_BGRA;
  1894. }
  1895. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1896. // APPLE_texture_format_BGRA8888 wants
  1897. // format to be BGRA but internal format to stay RGBA, but
  1898. // EXT_texture_format_BGRA8888 wants both format and internal
  1899. // format to be BGRA.
  1900. //
  1901. // Reference(s):
  1902. // - https://web.archive.org/web/20181126035829/https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1903. // - https://web.archive.org/web/20181126035841/https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_bgra.txt
  1904. // - https://web.archive.org/web/20181126035851/https://www.khronos.org/registry/OpenGL/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1905. //
  1906. if (!s_extension[Extension::EXT_bgra ].m_supported
  1907. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1908. {
  1909. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1910. }
  1911. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1912. {
  1913. // Revert back to RGBA if texture can't be created.
  1914. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE);
  1915. }
  1916. }
  1917. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) )
  1918. {
  1919. setTextureFormat(TextureFormat::RGBA4, GL_ZERO, GL_ZERO, GL_ZERO);
  1920. setTextureFormat(TextureFormat::RGB5A1, GL_ZERO, GL_ZERO, GL_ZERO);
  1921. if (!isTextureFormatValid(TextureFormat::R8) )
  1922. {
  1923. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1924. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1925. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1926. }
  1927. }
  1928. for (uint32_t ii = BX_ENABLED(BX_PLATFORM_IOS) ? TextureFormat::Unknown : 0 // skip test on iOS!
  1929. ; ii < TextureFormat::Count
  1930. ; ++ii
  1931. )
  1932. {
  1933. if (TextureFormat::Unknown != ii
  1934. && TextureFormat::UnknownDepth != ii)
  1935. {
  1936. s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) );
  1937. }
  1938. }
  1939. if (BX_ENABLED(0) )
  1940. {
  1941. // Disable all compressed texture formats. For testing only.
  1942. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  1943. {
  1944. s_textureFormat[ii].m_supported = false;
  1945. }
  1946. }
  1947. const bool computeSupport = false
  1948. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1949. || s_extension[Extension::ARB_compute_shader].m_supported
  1950. ;
  1951. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1952. {
  1953. uint16_t supported = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  1954. supported |= s_textureFormat[ii].m_supported
  1955. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  1956. | BGFX_CAPS_FORMAT_TEXTURE_3D
  1957. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  1958. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1959. ;
  1960. supported |= isTextureFormatValid(TextureFormat::Enum(ii), true)
  1961. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  1962. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  1963. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  1964. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1965. ;
  1966. supported |= isTextureFormatValid(TextureFormat::Enum(ii), false, true)
  1967. ? BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN
  1968. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1969. ;
  1970. supported |= computeSupport
  1971. && isImageFormatValid(TextureFormat::Enum(ii) )
  1972. ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE
  1973. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1974. ;
  1975. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii) )
  1976. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1977. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1978. ;
  1979. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii), false, true)
  1980. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1981. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1982. ;
  1983. if (NULL != glGetInternalformativ)
  1984. {
  1985. GLint maxSamples;
  1986. glGetInternalformativ(GL_RENDERBUFFER
  1987. , s_textureFormat[ii].m_internalFmt
  1988. , GL_SAMPLES
  1989. , 1
  1990. , &maxSamples
  1991. );
  1992. GLenum err = glGetError();
  1993. supported |= 0 == err && maxSamples > 0
  1994. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  1995. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1996. ;
  1997. glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE
  1998. , s_textureFormat[ii].m_internalFmt
  1999. , GL_SAMPLES
  2000. , 1
  2001. , &maxSamples
  2002. );
  2003. err = glGetError();
  2004. supported |= 0 == err && maxSamples > 0
  2005. ? BGFX_CAPS_FORMAT_TEXTURE_MSAA
  2006. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  2007. ;
  2008. }
  2009. g_caps.formats[ii] = supported;
  2010. }
  2011. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2012. || s_extension[Extension::OES_texture_3D].m_supported
  2013. ? BGFX_CAPS_TEXTURE_3D
  2014. : 0
  2015. ;
  2016. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2017. || s_extension[Extension::EXT_shadow_samplers].m_supported
  2018. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  2019. : 0
  2020. ;
  2021. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2022. || s_extension[Extension::OES_vertex_half_float].m_supported
  2023. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  2024. : 0
  2025. ;
  2026. g_caps.supported |= false
  2027. || s_extension[Extension::ARB_vertex_type_2_10_10_10_rev].m_supported
  2028. || s_extension[Extension::OES_vertex_type_10_10_10_2].m_supported
  2029. ? BGFX_CAPS_VERTEX_ATTRIB_UINT10
  2030. : 0
  2031. ;
  2032. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2033. || s_extension[Extension::EXT_frag_depth].m_supported
  2034. ? BGFX_CAPS_FRAGMENT_DEPTH
  2035. : 0
  2036. ;
  2037. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  2038. ? BGFX_CAPS_BLEND_INDEPENDENT
  2039. : 0
  2040. ;
  2041. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  2042. ? BGFX_CAPS_FRAGMENT_ORDERING
  2043. : 0
  2044. ;
  2045. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2046. || s_extension[Extension::OES_element_index_uint].m_supported
  2047. ? BGFX_CAPS_INDEX32
  2048. : 0
  2049. ;
  2050. const bool drawIndirectSupported = false
  2051. || s_extension[Extension::AMD_multi_draw_indirect].m_supported
  2052. || s_extension[Extension::ARB_draw_indirect ].m_supported
  2053. || s_extension[Extension::ARB_multi_draw_indirect].m_supported
  2054. || s_extension[Extension::EXT_multi_draw_indirect].m_supported
  2055. ;
  2056. if (drawIndirectSupported)
  2057. {
  2058. if (NULL == glMultiDrawArraysIndirect
  2059. || NULL == glMultiDrawElementsIndirect)
  2060. {
  2061. glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect;
  2062. glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect;
  2063. }
  2064. }
  2065. g_caps.supported |= drawIndirectSupported
  2066. ? BGFX_CAPS_DRAW_INDIRECT
  2067. : 0
  2068. ;
  2069. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  2070. || NULL == glPolygonMode)
  2071. {
  2072. glPolygonMode = stubPolygonMode;
  2073. }
  2074. if (s_extension[Extension::ARB_copy_image].m_supported
  2075. || s_extension[Extension::EXT_copy_image].m_supported
  2076. || s_extension[Extension:: NV_copy_image].m_supported
  2077. || s_extension[Extension::OES_copy_image].m_supported)
  2078. {
  2079. m_blitSupported = NULL != glCopyImageSubData;
  2080. g_caps.supported |= m_blitSupported
  2081. ? BGFX_CAPS_TEXTURE_BLIT
  2082. : 0
  2083. ;
  2084. }
  2085. g_caps.supported |= m_readBackSupported
  2086. ? BGFX_CAPS_TEXTURE_READ_BACK
  2087. : 0
  2088. ;
  2089. g_caps.supported |= false
  2090. || s_extension[Extension::EXT_texture_array].m_supported
  2091. || s_extension[Extension::EXT_gpu_shader4].m_supported
  2092. || (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) && !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) )
  2093. ? BGFX_CAPS_TEXTURE_2D_ARRAY
  2094. : 0
  2095. ;
  2096. g_caps.supported |= false
  2097. || s_extension[Extension::EXT_gpu_shader4].m_supported
  2098. || (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) && !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) )
  2099. ? BGFX_CAPS_VERTEX_ID
  2100. : 0
  2101. ;
  2102. g_caps.supported |= false
  2103. || s_extension[Extension::ARB_texture_cube_map_array].m_supported
  2104. || s_extension[Extension::EXT_texture_cube_map_array].m_supported
  2105. ? BGFX_CAPS_TEXTURE_CUBE_ARRAY
  2106. : 0
  2107. ;
  2108. g_caps.limits.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) );
  2109. g_caps.limits.maxTextureLayers = uint16_t(bx::max(glGet(GL_MAX_ARRAY_TEXTURE_LAYERS), 1) );
  2110. g_caps.limits.maxComputeBindings = computeSupport ? BGFX_MAX_COMPUTE_BINDINGS : 0;
  2111. g_caps.limits.maxVertexStreams = BGFX_CONFIG_MAX_VERTEX_STREAMS;
  2112. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2113. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2114. || s_extension[Extension::EXT_draw_buffers ].m_supported
  2115. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  2116. {
  2117. g_caps.limits.maxFBAttachments = uint8_t(bx::uint32_clamp(
  2118. glGet(GL_MAX_DRAW_BUFFERS)
  2119. , 1
  2120. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS)
  2121. );
  2122. }
  2123. // if (s_extension[Extension::ARB_clip_control].m_supported)
  2124. // {
  2125. // GL_CHECK(glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE) );
  2126. // g_caps.originBottomLeft = true;
  2127. // }
  2128. // else
  2129. {
  2130. g_caps.homogeneousDepth = true;
  2131. g_caps.originBottomLeft = true;
  2132. }
  2133. m_vaoSupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  2134. && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2135. || s_extension[Extension::ARB_vertex_array_object].m_supported
  2136. || s_extension[Extension::OES_vertex_array_object].m_supported
  2137. );
  2138. if (m_vaoSupport)
  2139. {
  2140. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  2141. }
  2142. m_samplerObjectSupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  2143. && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2144. || s_extension[Extension::ARB_sampler_objects].m_supported
  2145. );
  2146. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2147. || s_extension[Extension::EXT_shadow_samplers].m_supported
  2148. ;
  2149. m_programBinarySupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  2150. && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2151. || s_extension[Extension::ARB_get_program_binary].m_supported
  2152. || s_extension[Extension::OES_get_program_binary].m_supported
  2153. || s_extension[Extension::IMG_shader_binary ].m_supported
  2154. );
  2155. m_textureSwizzleSupport = false
  2156. || s_extension[Extension::ARB_texture_swizzle].m_supported
  2157. || s_extension[Extension::EXT_texture_swizzle].m_supported
  2158. ;
  2159. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2160. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  2161. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  2162. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  2163. || s_extension[Extension::OES_depth_texture ].m_supported
  2164. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  2165. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  2166. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  2167. ;
  2168. m_timerQuerySupport = false
  2169. || s_extension[Extension::ANGLE_timer_query ].m_supported
  2170. || s_extension[Extension::ARB_timer_query ].m_supported
  2171. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  2172. || s_extension[Extension::EXT_timer_query ].m_supported
  2173. ;
  2174. m_timerQuerySupport &= true
  2175. && NULL != glQueryCounter
  2176. && NULL != glGetQueryObjectiv
  2177. && NULL != glGetQueryObjectui64v
  2178. ;
  2179. m_occlusionQuerySupport = false
  2180. || s_extension[Extension::ARB_occlusion_query ].m_supported
  2181. || s_extension[Extension::ARB_occlusion_query2 ].m_supported
  2182. || s_extension[Extension::EXT_occlusion_query_boolean].m_supported
  2183. || s_extension[Extension::NV_occlusion_query ].m_supported
  2184. ;
  2185. m_occlusionQuerySupport &= true
  2186. && NULL != glGenQueries
  2187. && NULL != glDeleteQueries
  2188. && NULL != glBeginQuery
  2189. && NULL != glEndQuery
  2190. ;
  2191. m_atocSupport = s_extension[Extension::ARB_multisample].m_supported;
  2192. m_conservativeRasterSupport = s_extension[Extension::NV_conservative_raster].m_supported;
  2193. g_caps.supported |= 0
  2194. | (m_atocSupport ? BGFX_CAPS_ALPHA_TO_COVERAGE : 0)
  2195. | (m_conservativeRasterSupport ? BGFX_CAPS_CONSERVATIVE_RASTER : 0)
  2196. | (m_occlusionQuerySupport ? BGFX_CAPS_OCCLUSION_QUERY : 0)
  2197. | (m_depthTextureSupport ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL : 0)
  2198. | (computeSupport ? BGFX_CAPS_COMPUTE : 0)
  2199. ;
  2200. g_caps.supported |= m_glctx.getCaps();
  2201. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  2202. {
  2203. m_srgbWriteControlSupport = s_extension[Extension::EXT_sRGB_write_control].m_supported;
  2204. m_borderColorSupport = s_extension[Extension::NV_texture_border_clamp].m_supported;
  2205. s_textureAddress[BGFX_SAMPLER_U_BORDER>>BGFX_SAMPLER_U_SHIFT] = s_extension[Extension::NV_texture_border_clamp].m_supported
  2206. ? GL_CLAMP_TO_BORDER
  2207. : GL_CLAMP_TO_EDGE
  2208. ;
  2209. }
  2210. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  2211. {
  2212. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  2213. }
  2214. if (s_extension[Extension::ARB_texture_multisample].m_supported
  2215. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  2216. {
  2217. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  2218. }
  2219. if (s_extension[Extension::OES_read_format].m_supported
  2220. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  2221. {
  2222. m_readPixelsFmt = GL_BGRA;
  2223. }
  2224. else
  2225. {
  2226. m_readPixelsFmt = GL_RGBA;
  2227. }
  2228. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2229. {
  2230. g_caps.supported |= BGFX_CAPS_INSTANCING;
  2231. }
  2232. else
  2233. {
  2234. if (s_extension[Extension::ANGLE_instanced_arrays].m_supported
  2235. || s_extension[Extension::ARB_instanced_arrays].m_supported
  2236. || s_extension[Extension::EXT_instanced_arrays].m_supported)
  2237. {
  2238. if (NULL != glVertexAttribDivisor
  2239. && NULL != glDrawArraysInstanced
  2240. && NULL != glDrawElementsInstanced)
  2241. {
  2242. g_caps.supported |= BGFX_CAPS_INSTANCING;
  2243. }
  2244. }
  2245. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  2246. {
  2247. glVertexAttribDivisor = stubVertexAttribDivisor;
  2248. glDrawArraysInstanced = stubDrawArraysInstanced;
  2249. glDrawElementsInstanced = stubDrawElementsInstanced;
  2250. }
  2251. }
  2252. if (s_extension[Extension::ARB_debug_output].m_supported
  2253. || s_extension[Extension::KHR_debug].m_supported)
  2254. {
  2255. if (NULL != glDebugMessageControl
  2256. && NULL != glDebugMessageInsert
  2257. && NULL != glDebugMessageCallback
  2258. && NULL != glGetDebugMessageLog)
  2259. {
  2260. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  2261. GL_CHECK(glDebugMessageControl(GL_DONT_CARE
  2262. , GL_DONT_CARE
  2263. , GL_DEBUG_SEVERITY_MEDIUM
  2264. , 0
  2265. , NULL
  2266. , GL_TRUE
  2267. ) );
  2268. }
  2269. }
  2270. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  2271. {
  2272. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  2273. }
  2274. if (NULL == glInsertEventMarker
  2275. || !s_extension[Extension::EXT_debug_marker].m_supported)
  2276. {
  2277. glInsertEventMarker = stubInsertEventMarker;
  2278. }
  2279. setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported);
  2280. if (NULL == glObjectLabel)
  2281. {
  2282. glObjectLabel = stubObjectLabel;
  2283. }
  2284. if (NULL == glInvalidateFramebuffer)
  2285. {
  2286. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  2287. }
  2288. if (m_timerQuerySupport)
  2289. {
  2290. m_gpuTimer.create();
  2291. }
  2292. if (m_occlusionQuerySupport)
  2293. {
  2294. m_occlusionQuery.create();
  2295. }
  2296. // Init reserved part of view name.
  2297. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  2298. {
  2299. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  2300. }
  2301. m_needPresent = false;
  2302. }
  2303. return true;
  2304. error:
  2305. switch (errorState)
  2306. {
  2307. case ErrorState::Default:
  2308. break;
  2309. }
  2310. m_glctx.destroy();
  2311. unloadRenderDoc(m_renderdocdll);
  2312. return false;
  2313. }
  2314. void shutdown()
  2315. {
  2316. if (m_vaoSupport)
  2317. {
  2318. GL_CHECK(glBindVertexArray(0) );
  2319. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  2320. m_vao = 0;
  2321. }
  2322. captureFinish();
  2323. invalidateCache();
  2324. if (m_timerQuerySupport)
  2325. {
  2326. m_gpuTimer.destroy();
  2327. }
  2328. if (m_occlusionQuerySupport)
  2329. {
  2330. m_occlusionQuery.destroy();
  2331. }
  2332. destroyMsaaFbo();
  2333. m_glctx.destroy();
  2334. m_flip = false;
  2335. unloadRenderDoc(m_renderdocdll);
  2336. }
  2337. RendererType::Enum getRendererType() const override
  2338. {
  2339. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  2340. {
  2341. return RendererType::OpenGL;
  2342. }
  2343. return RendererType::OpenGLES;
  2344. }
  2345. const char* getRendererName() const override
  2346. {
  2347. return BGFX_RENDERER_OPENGL_NAME;
  2348. }
  2349. bool isDeviceRemoved() override
  2350. {
  2351. return false;
  2352. }
  2353. void flip() override
  2354. {
  2355. if (m_flip)
  2356. {
  2357. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  2358. {
  2359. FrameBufferGL& frameBuffer = m_frameBuffers[m_windows[ii].idx];
  2360. if (frameBuffer.m_needPresent)
  2361. {
  2362. m_glctx.swap(frameBuffer.m_swapChain);
  2363. frameBuffer.m_needPresent = false;
  2364. }
  2365. }
  2366. if (m_needPresent)
  2367. {
  2368. // Ensure the back buffer is bound as the source of the flip
  2369. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo));
  2370. m_glctx.swap();
  2371. m_needPresent = false;
  2372. }
  2373. }
  2374. }
  2375. void createIndexBuffer(IndexBufferHandle _handle, const Memory* _mem, uint16_t _flags) override
  2376. {
  2377. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  2378. }
  2379. void destroyIndexBuffer(IndexBufferHandle _handle) override
  2380. {
  2381. m_indexBuffers[_handle.idx].destroy();
  2382. }
  2383. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) override
  2384. {
  2385. VertexDecl& decl = m_vertexDecls[_handle.idx];
  2386. bx::memCopy(&decl, &_decl, sizeof(VertexDecl) );
  2387. dump(decl);
  2388. }
  2389. void destroyVertexDecl(VertexDeclHandle /*_handle*/) override
  2390. {
  2391. }
  2392. void createVertexBuffer(VertexBufferHandle _handle, const Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) override
  2393. {
  2394. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  2395. }
  2396. void destroyVertexBuffer(VertexBufferHandle _handle) override
  2397. {
  2398. m_vertexBuffers[_handle.idx].destroy();
  2399. }
  2400. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  2401. {
  2402. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  2403. }
  2404. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  2405. {
  2406. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2407. }
  2408. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override
  2409. {
  2410. m_indexBuffers[_handle.idx].destroy();
  2411. }
  2412. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  2413. {
  2414. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  2415. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  2416. }
  2417. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  2418. {
  2419. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2420. }
  2421. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override
  2422. {
  2423. m_vertexBuffers[_handle.idx].destroy();
  2424. }
  2425. void createShader(ShaderHandle _handle, const Memory* _mem) override
  2426. {
  2427. m_shaders[_handle.idx].create(_mem);
  2428. }
  2429. void destroyShader(ShaderHandle _handle) override
  2430. {
  2431. m_shaders[_handle.idx].destroy();
  2432. }
  2433. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override
  2434. {
  2435. ShaderGL dummyFragmentShader;
  2436. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  2437. }
  2438. void destroyProgram(ProgramHandle _handle) override
  2439. {
  2440. m_program[_handle.idx].destroy();
  2441. }
  2442. void* createTexture(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip) override
  2443. {
  2444. m_textures[_handle.idx].create(_mem, _flags, _skip);
  2445. return NULL;
  2446. }
  2447. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) override
  2448. {
  2449. }
  2450. 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) override
  2451. {
  2452. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  2453. }
  2454. void updateTextureEnd() override
  2455. {
  2456. }
  2457. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override
  2458. {
  2459. if (m_readBackSupported)
  2460. {
  2461. const TextureGL& texture = m_textures[_handle.idx];
  2462. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(texture.m_textureFormat) );
  2463. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  2464. if (compressed)
  2465. {
  2466. GL_CHECK(glGetCompressedTexImage(texture.m_target
  2467. , _mip
  2468. , _data
  2469. ) );
  2470. }
  2471. else
  2472. {
  2473. GL_CHECK(glGetTexImage(texture.m_target
  2474. , _mip
  2475. , texture.m_fmt
  2476. , texture.m_type
  2477. , _data
  2478. ) );
  2479. }
  2480. GL_CHECK(glBindTexture(texture.m_target, 0) );
  2481. }
  2482. else
  2483. {
  2484. const TextureGL& texture = m_textures[_handle.idx];
  2485. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(texture.m_textureFormat) );
  2486. if(!compressed)
  2487. {
  2488. Attachment attachment[1];
  2489. attachment[0].handle = _handle;
  2490. attachment[0].mip = 0;
  2491. attachment[0].layer = 0;
  2492. FrameBufferGL frameBuffer;
  2493. frameBuffer.create(1, attachment);
  2494. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  2495. GL_CHECK(glFramebufferTexture2D(
  2496. GL_FRAMEBUFFER
  2497. , GL_COLOR_ATTACHMENT0
  2498. , GL_TEXTURE_2D
  2499. , texture.m_id
  2500. , attachment[0].mip
  2501. ) );
  2502. if (!BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  2503. && !BX_ENABLED(BX_PLATFORM_IOS))
  2504. {
  2505. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  2506. }
  2507. if (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER) )
  2508. {
  2509. GL_CHECK(glReadPixels(
  2510. 0
  2511. , 0
  2512. , texture.m_width
  2513. , texture.m_height
  2514. , m_readPixelsFmt
  2515. , GL_UNSIGNED_BYTE
  2516. , _data
  2517. ) );
  2518. }
  2519. frameBuffer.destroy();
  2520. }
  2521. }
  2522. }
  2523. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, uint16_t _numLayers) override
  2524. {
  2525. TextureGL& texture = m_textures[_handle.idx];
  2526. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  2527. const Memory* mem = alloc(size);
  2528. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2529. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2530. bx::write(&writer, magic);
  2531. TextureCreate tc;
  2532. tc.m_width = _width;
  2533. tc.m_height = _height;
  2534. tc.m_depth = 0;
  2535. tc.m_numLayers = _numLayers;
  2536. tc.m_numMips = _numMips;
  2537. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  2538. tc.m_cubeMap = false;
  2539. tc.m_mem = NULL;
  2540. bx::write(&writer, tc);
  2541. texture.destroy();
  2542. texture.create(mem, texture.m_flags, 0);
  2543. release(mem);
  2544. }
  2545. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override
  2546. {
  2547. m_textures[_handle.idx].overrideInternal(_ptr);
  2548. }
  2549. uintptr_t getInternal(TextureHandle _handle) override
  2550. {
  2551. return uintptr_t(m_textures[_handle.idx].m_id);
  2552. }
  2553. void destroyTexture(TextureHandle _handle) override
  2554. {
  2555. m_textures[_handle.idx].destroy();
  2556. }
  2557. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override
  2558. {
  2559. m_frameBuffers[_handle.idx].create(_num, _attachment);
  2560. }
  2561. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) override
  2562. {
  2563. uint16_t denseIdx = m_numWindows++;
  2564. m_windows[denseIdx] = _handle;
  2565. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _format, _depthFormat);
  2566. }
  2567. void destroyFrameBuffer(FrameBufferHandle _handle) override
  2568. {
  2569. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  2570. if (UINT16_MAX != denseIdx)
  2571. {
  2572. --m_numWindows;
  2573. if (m_numWindows > 1)
  2574. {
  2575. FrameBufferHandle handle = m_windows[m_numWindows];
  2576. m_windows[m_numWindows] = {kInvalidHandle};
  2577. if (m_numWindows != denseIdx)
  2578. {
  2579. m_windows[denseIdx] = handle;
  2580. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  2581. }
  2582. }
  2583. }
  2584. }
  2585. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override
  2586. {
  2587. if (NULL != m_uniforms[_handle.idx])
  2588. {
  2589. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2590. }
  2591. uint32_t size = g_uniformTypeSize[_type]*_num;
  2592. void* data = BX_ALLOC(g_allocator, size);
  2593. bx::memSet(data, 0, size);
  2594. m_uniforms[_handle.idx] = data;
  2595. m_uniformReg.add(_handle, _name);
  2596. }
  2597. void destroyUniform(UniformHandle _handle) override
  2598. {
  2599. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2600. m_uniforms[_handle.idx] = NULL;
  2601. m_uniformReg.remove(_handle);
  2602. }
  2603. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override
  2604. {
  2605. SwapChainGL* swapChain = NULL;
  2606. uint32_t width = m_resolution.width;
  2607. uint32_t height = m_resolution.height;
  2608. if (isValid(_handle) )
  2609. {
  2610. const FrameBufferGL& frameBuffer = m_frameBuffers[_handle.idx];
  2611. swapChain = frameBuffer.m_swapChain;
  2612. width = frameBuffer.m_width;
  2613. height = frameBuffer.m_height;
  2614. }
  2615. m_glctx.makeCurrent(swapChain);
  2616. uint32_t length = width*height*4;
  2617. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2618. GL_CHECK(glReadPixels(0
  2619. , 0
  2620. , width
  2621. , height
  2622. , m_readPixelsFmt
  2623. , GL_UNSIGNED_BYTE
  2624. , data
  2625. ) );
  2626. if (GL_RGBA == m_readPixelsFmt)
  2627. {
  2628. bimg::imageSwizzleBgra8(data, width*4, width, height, data, width*4);
  2629. }
  2630. g_callback->screenShot(_filePath
  2631. , width
  2632. , height
  2633. , width*4
  2634. , data
  2635. , length
  2636. , true
  2637. );
  2638. BX_FREE(g_allocator, data);
  2639. }
  2640. void updateViewName(ViewId _id, const char* _name) override
  2641. {
  2642. bx::strCopy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  2643. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  2644. , _name
  2645. );
  2646. }
  2647. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override
  2648. {
  2649. bx::memCopy(m_uniforms[_loc], _data, _size);
  2650. }
  2651. void setMarker(const char* _marker, uint32_t _size) override
  2652. {
  2653. GL_CHECK(glInsertEventMarker(_size, _marker) );
  2654. }
  2655. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override
  2656. {
  2657. m_occlusionQuery.invalidate(_handle);
  2658. }
  2659. virtual void setName(Handle _handle, const char* _name) override
  2660. {
  2661. switch (_handle.type)
  2662. {
  2663. case Handle::Shader:
  2664. GL_CHECK(glObjectLabel(GL_SHADER, m_shaders[_handle.idx].m_id, -1, _name) );
  2665. break;
  2666. case Handle::Texture:
  2667. GL_CHECK(glObjectLabel(GL_TEXTURE, m_textures[_handle.idx].m_id, -1, _name) );
  2668. break;
  2669. default:
  2670. BX_CHECK(false, "Invalid handle type?! %d", _handle.type);
  2671. break;
  2672. }
  2673. }
  2674. void submitBlit(BlitState& _bs, uint16_t _view);
  2675. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override;
  2676. void blitSetup(TextVideoMemBlitter& _blitter) override
  2677. {
  2678. if (0 != m_vao)
  2679. {
  2680. GL_CHECK(glBindVertexArray(m_vao) );
  2681. }
  2682. uint32_t width = m_resolution.width;
  2683. uint32_t height = m_resolution.height;
  2684. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2685. GL_CHECK(glViewport(0, 0, width, height) );
  2686. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2687. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2688. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2689. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2690. GL_CHECK(glDisable(GL_CULL_FACE) );
  2691. GL_CHECK(glDisable(GL_BLEND) );
  2692. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2693. ProgramGL& program = m_program[_blitter.m_program.idx];
  2694. GL_CHECK(glUseProgram(program.m_id) );
  2695. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  2696. float proj[16];
  2697. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, true);
  2698. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  2699. , 1
  2700. , GL_FALSE
  2701. , proj
  2702. ) );
  2703. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  2704. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  2705. if (!BX_ENABLED(BX_PLATFORM_OSX) )
  2706. {
  2707. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2708. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2709. {
  2710. if (m_samplerObjectSupport)
  2711. {
  2712. GL_CHECK(glBindSampler(0, 0) );
  2713. }
  2714. }
  2715. }
  2716. }
  2717. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override
  2718. {
  2719. const uint32_t numVertices = _numIndices*4/6;
  2720. if (0 < numVertices)
  2721. {
  2722. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  2723. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  2724. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  2725. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2726. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  2727. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2728. ProgramGL& program = m_program[_blitter.m_program.idx];
  2729. program.bindAttributesBegin();
  2730. program.bindAttributes(_blitter.m_decl, 0);
  2731. program.bindAttributesEnd();
  2732. GL_CHECK(glDrawElements(GL_TRIANGLES
  2733. , _numIndices
  2734. , GL_UNSIGNED_SHORT
  2735. , (void*)0
  2736. ) );
  2737. }
  2738. }
  2739. void updateResolution(const Resolution& _resolution)
  2740. {
  2741. m_maxAnisotropy = !!(_resolution.reset & BGFX_RESET_MAXANISOTROPY)
  2742. ? m_maxAnisotropyDefault
  2743. : 0.0f
  2744. ;
  2745. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  2746. {
  2747. if (!!(_resolution.reset & BGFX_RESET_DEPTH_CLAMP) )
  2748. {
  2749. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  2750. }
  2751. else
  2752. {
  2753. GL_CHECK(glDisable(GL_DEPTH_CLAMP) );
  2754. }
  2755. }
  2756. const uint32_t maskFlags = ~(0
  2757. | BGFX_RESET_MAXANISOTROPY
  2758. | BGFX_RESET_DEPTH_CLAMP
  2759. | BGFX_RESET_SUSPEND
  2760. );
  2761. if (m_resolution.width != _resolution.width
  2762. || m_resolution.height != _resolution.height
  2763. || (m_resolution.reset&maskFlags) != (_resolution.reset&maskFlags) )
  2764. {
  2765. uint32_t flags = _resolution.reset & (~BGFX_RESET_INTERNAL_FORCE);
  2766. m_resolution = _resolution;
  2767. m_resolution.reset = flags;
  2768. m_textVideoMem.resize(false, _resolution.width, _resolution.height);
  2769. m_textVideoMem.clear();
  2770. setRenderContextSize(m_resolution.width
  2771. , m_resolution.height
  2772. , flags
  2773. );
  2774. updateCapture();
  2775. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  2776. {
  2777. m_frameBuffers[ii].postReset();
  2778. }
  2779. m_currentFbo = 0;
  2780. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) );
  2781. }
  2782. }
  2783. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2784. {
  2785. GL_CHECK(glUniform4fv(_regIndex
  2786. , _numRegs
  2787. , (const GLfloat*)_val
  2788. ) );
  2789. }
  2790. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2791. {
  2792. GL_CHECK(glUniformMatrix4fv(_regIndex
  2793. , _numRegs
  2794. , GL_FALSE
  2795. , (const GLfloat*)_val
  2796. ) );
  2797. }
  2798. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  2799. {
  2800. if (isValid(m_fbh)
  2801. && m_fbh.idx != _fbh.idx)
  2802. {
  2803. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2804. frameBuffer.resolve();
  2805. if (BGFX_CLEAR_NONE != m_fbDiscard)
  2806. {
  2807. frameBuffer.discard(m_fbDiscard);
  2808. m_fbDiscard = BGFX_CLEAR_NONE;
  2809. }
  2810. }
  2811. m_glctx.makeCurrent(NULL);
  2812. if (!isValid(_fbh) )
  2813. {
  2814. m_needPresent |= true;
  2815. m_currentFbo = m_msaaBackBufferFbo;
  2816. if (m_srgbWriteControlSupport)
  2817. {
  2818. if (0 != (m_resolution.reset & BGFX_RESET_SRGB_BACKBUFFER) )
  2819. {
  2820. GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB) );
  2821. }
  2822. else
  2823. {
  2824. GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB) );
  2825. }
  2826. }
  2827. }
  2828. else
  2829. {
  2830. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  2831. _height = frameBuffer.m_height;
  2832. if (UINT16_MAX != frameBuffer.m_denseIdx)
  2833. {
  2834. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  2835. frameBuffer.m_needPresent = true;
  2836. m_currentFbo = 0;
  2837. }
  2838. else
  2839. {
  2840. m_glctx.makeCurrent(NULL);
  2841. m_currentFbo = frameBuffer.m_fbo[0];
  2842. }
  2843. }
  2844. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) );
  2845. m_fbh = _fbh;
  2846. m_fbDiscard = _discard;
  2847. m_rtMsaa = _msaa;
  2848. return _height;
  2849. }
  2850. uint32_t getNumRt() const
  2851. {
  2852. if (isValid(m_fbh) )
  2853. {
  2854. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2855. return frameBuffer.m_num;
  2856. }
  2857. return 1;
  2858. }
  2859. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  2860. {
  2861. if (0 == m_msaaBackBufferFbo // iOS
  2862. && 1 < _msaa)
  2863. {
  2864. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2865. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2866. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2867. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2868. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  2869. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2870. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  2871. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2872. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2873. ? GL_DEPTH_STENCIL_ATTACHMENT
  2874. : GL_DEPTH_ATTACHMENT
  2875. ;
  2876. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2877. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2878. , "glCheckFramebufferStatus failed 0x%08x"
  2879. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2880. );
  2881. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2882. }
  2883. }
  2884. void destroyMsaaFbo()
  2885. {
  2886. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2887. && 0 != m_msaaBackBufferFbo)
  2888. {
  2889. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2890. m_msaaBackBufferFbo = 0;
  2891. if (0 != m_msaaBackBufferRbos[0])
  2892. {
  2893. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2894. m_msaaBackBufferRbos[0] = 0;
  2895. m_msaaBackBufferRbos[1] = 0;
  2896. }
  2897. }
  2898. }
  2899. void blitMsaaFbo()
  2900. {
  2901. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2902. && 0 != m_msaaBackBufferFbo)
  2903. {
  2904. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2905. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2906. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2907. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2908. uint32_t width = m_resolution.width;
  2909. uint32_t height = m_resolution.height;
  2910. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2911. ? GL_NEAREST
  2912. : GL_LINEAR
  2913. ;
  2914. GL_CHECK(glBlitFramebuffer(0
  2915. , 0
  2916. , width
  2917. , height
  2918. , 0
  2919. , 0
  2920. , width
  2921. , height
  2922. , GL_COLOR_BUFFER_BIT
  2923. , filter
  2924. ) );
  2925. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2926. }
  2927. }
  2928. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2929. {
  2930. if (_width != 0
  2931. || _height != 0)
  2932. {
  2933. if (!m_glctx.isValid() )
  2934. {
  2935. m_glctx.create(_width, _height);
  2936. #if BX_PLATFORM_IOS
  2937. // iOS: need to figure out how to deal with FBO created by context.
  2938. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2939. #endif // BX_PLATFORM_IOS
  2940. }
  2941. else
  2942. {
  2943. destroyMsaaFbo();
  2944. m_glctx.resize(_width, _height, _flags);
  2945. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2946. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2947. createMsaaFbo(_width, _height, msaa);
  2948. }
  2949. }
  2950. m_flip = true;
  2951. }
  2952. void invalidateCache()
  2953. {
  2954. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2955. && m_samplerObjectSupport)
  2956. {
  2957. m_samplerStateCache.invalidate();
  2958. }
  2959. }
  2960. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags, const float _rgba[4])
  2961. {
  2962. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2963. && m_samplerObjectSupport)
  2964. {
  2965. if (0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags) )
  2966. {
  2967. const uint32_t index = (_flags & BGFX_SAMPLER_BORDER_COLOR_MASK) >> BGFX_SAMPLER_BORDER_COLOR_SHIFT;
  2968. _flags &= ~BGFX_SAMPLER_RESERVED_MASK;
  2969. _flags &= BGFX_SAMPLER_BITS_MASK;
  2970. _flags |= _numMips<<BGFX_SAMPLER_RESERVED_SHIFT;
  2971. GLuint sampler;
  2972. bool hasBorderColor = false;
  2973. bx::HashMurmur2A murmur;
  2974. uint32_t hash;
  2975. murmur.begin();
  2976. murmur.add(_flags);
  2977. if (!needBorderColor(_flags) )
  2978. {
  2979. murmur.add(-1);
  2980. hash = murmur.end();
  2981. sampler = m_samplerStateCache.find(hash);
  2982. }
  2983. else
  2984. {
  2985. murmur.add(index);
  2986. hash = murmur.end();
  2987. if (NULL != _rgba)
  2988. {
  2989. hasBorderColor = true;
  2990. sampler = UINT32_MAX;
  2991. }
  2992. else
  2993. {
  2994. sampler = m_samplerStateCache.find(hash);
  2995. }
  2996. }
  2997. if (UINT32_MAX == sampler)
  2998. {
  2999. sampler = m_samplerStateCache.add(hash);
  3000. GL_CHECK(glSamplerParameteri(sampler
  3001. , GL_TEXTURE_WRAP_S
  3002. , s_textureAddress[(_flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT]
  3003. ) );
  3004. GL_CHECK(glSamplerParameteri(sampler
  3005. , GL_TEXTURE_WRAP_T
  3006. , s_textureAddress[(_flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT]
  3007. ) );
  3008. GL_CHECK(glSamplerParameteri(sampler
  3009. , GL_TEXTURE_WRAP_R
  3010. , s_textureAddress[(_flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT]
  3011. ) );
  3012. GLenum minFilter;
  3013. GLenum magFilter;
  3014. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  3015. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  3016. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  3017. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  3018. {
  3019. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_LOD_BIAS, float(BGFX_CONFIG_MIP_LOD_BIAS) ) );
  3020. }
  3021. if (m_borderColorSupport
  3022. && hasBorderColor)
  3023. {
  3024. GL_CHECK(glSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR, _rgba) );
  3025. }
  3026. if (0 != (_flags & (BGFX_SAMPLER_MIN_ANISOTROPIC|BGFX_SAMPLER_MAG_ANISOTROPIC) )
  3027. && 0.0f < m_maxAnisotropy)
  3028. {
  3029. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  3030. }
  3031. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3032. || m_shadowSamplersSupport)
  3033. {
  3034. const uint32_t cmpFunc = (_flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT;
  3035. if (0 == cmpFunc)
  3036. {
  3037. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  3038. }
  3039. else
  3040. {
  3041. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  3042. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  3043. }
  3044. }
  3045. }
  3046. GL_CHECK(glBindSampler(_stage, sampler) );
  3047. }
  3048. else
  3049. {
  3050. GL_CHECK(glBindSampler(_stage, 0) );
  3051. }
  3052. }
  3053. }
  3054. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  3055. {
  3056. m_occlusionQuery.resolve(_render);
  3057. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  3058. }
  3059. void updateCapture()
  3060. {
  3061. if (m_resolution.reset&BGFX_RESET_CAPTURE)
  3062. {
  3063. m_captureSize = m_resolution.width*m_resolution.height*4;
  3064. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  3065. g_callback->captureBegin(m_resolution.width, m_resolution.height, m_resolution.width*4, TextureFormat::BGRA8, true);
  3066. }
  3067. else
  3068. {
  3069. captureFinish();
  3070. }
  3071. }
  3072. void capture()
  3073. {
  3074. if (NULL != m_capture)
  3075. {
  3076. GL_CHECK(glReadPixels(0
  3077. , 0
  3078. , m_resolution.width
  3079. , m_resolution.height
  3080. , m_readPixelsFmt
  3081. , GL_UNSIGNED_BYTE
  3082. , m_capture
  3083. ) );
  3084. if (GL_RGBA == m_readPixelsFmt)
  3085. {
  3086. bimg::imageSwizzleBgra8(
  3087. m_capture
  3088. , m_resolution.width*4
  3089. , m_resolution.width
  3090. , m_resolution.height
  3091. , m_capture
  3092. , m_resolution.width*4
  3093. );
  3094. }
  3095. g_callback->captureFrame(m_capture, m_captureSize);
  3096. }
  3097. }
  3098. void captureFinish()
  3099. {
  3100. if (NULL != m_capture)
  3101. {
  3102. g_callback->captureEnd();
  3103. BX_FREE(g_allocator, m_capture);
  3104. m_capture = NULL;
  3105. m_captureSize = 0;
  3106. }
  3107. }
  3108. bool programFetchFromCache(GLuint programId, uint64_t _id)
  3109. {
  3110. _id ^= m_hash;
  3111. bool cached = false;
  3112. if (m_programBinarySupport)
  3113. {
  3114. uint32_t length = g_callback->cacheReadSize(_id);
  3115. cached = length > 0;
  3116. if (cached)
  3117. {
  3118. void* data = BX_ALLOC(g_allocator, length);
  3119. if (g_callback->cacheRead(_id, data, length) )
  3120. {
  3121. bx::MemoryReader reader(data, length);
  3122. GLenum format;
  3123. bx::read(&reader, format);
  3124. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  3125. }
  3126. BX_FREE(g_allocator, data);
  3127. }
  3128. #if BGFX_CONFIG_RENDERER_OPENGL
  3129. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  3130. #endif // BGFX_CONFIG_RENDERER_OPENGL
  3131. }
  3132. return cached;
  3133. }
  3134. void programCache(GLuint programId, uint64_t _id)
  3135. {
  3136. _id ^= m_hash;
  3137. if (m_programBinarySupport)
  3138. {
  3139. GLint programLength;
  3140. GLenum format;
  3141. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  3142. if (0 < programLength)
  3143. {
  3144. uint32_t length = programLength + 4;
  3145. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  3146. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  3147. *(uint32_t*)data = format;
  3148. g_callback->cacheWrite(_id, data, length);
  3149. BX_FREE(g_allocator, data);
  3150. }
  3151. }
  3152. }
  3153. void commit(UniformBuffer& _uniformBuffer)
  3154. {
  3155. _uniformBuffer.reset();
  3156. for (;;)
  3157. {
  3158. uint32_t opcode = _uniformBuffer.read();
  3159. if (UniformType::End == opcode)
  3160. {
  3161. break;
  3162. }
  3163. UniformType::Enum type;
  3164. uint16_t ignore;
  3165. uint16_t num;
  3166. uint16_t copy;
  3167. UniformBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  3168. const char* data;
  3169. if (copy)
  3170. {
  3171. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  3172. }
  3173. else
  3174. {
  3175. UniformHandle handle;
  3176. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  3177. data = (const char*)m_uniforms[handle.idx];
  3178. }
  3179. uint32_t loc = _uniformBuffer.read();
  3180. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  3181. case UniformType::_uniform: \
  3182. { \
  3183. _type* value = (_type*)data; \
  3184. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  3185. } \
  3186. break;
  3187. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  3188. case UniformType::_uniform: \
  3189. { \
  3190. _type* value = (_type*)data; \
  3191. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  3192. } \
  3193. break;
  3194. switch (type)
  3195. {
  3196. CASE_IMPLEMENT_UNIFORM(Sampler, 1iv, I, int);
  3197. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  3198. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  3199. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  3200. case UniformType::End:
  3201. break;
  3202. default:
  3203. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  3204. break;
  3205. }
  3206. #undef CASE_IMPLEMENT_UNIFORM
  3207. #undef CASE_IMPLEMENT_UNIFORM_T
  3208. }
  3209. }
  3210. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  3211. {
  3212. uint32_t numMrt = 1;
  3213. FrameBufferHandle fbh = m_fbh;
  3214. if (isValid(fbh) )
  3215. {
  3216. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  3217. numMrt = bx::uint32_max(1, fb.m_num);
  3218. }
  3219. if (1 == numMrt)
  3220. {
  3221. GLuint flags = 0;
  3222. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  3223. {
  3224. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  3225. {
  3226. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  3227. const float* rgba = _palette[index];
  3228. const float rr = rgba[0];
  3229. const float gg = rgba[1];
  3230. const float bb = rgba[2];
  3231. const float aa = rgba[3];
  3232. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  3233. }
  3234. else
  3235. {
  3236. float rr = _clear.m_index[0]*1.0f/255.0f;
  3237. float gg = _clear.m_index[1]*1.0f/255.0f;
  3238. float bb = _clear.m_index[2]*1.0f/255.0f;
  3239. float aa = _clear.m_index[3]*1.0f/255.0f;
  3240. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  3241. }
  3242. flags |= GL_COLOR_BUFFER_BIT;
  3243. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  3244. }
  3245. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  3246. {
  3247. flags |= GL_DEPTH_BUFFER_BIT;
  3248. GL_CHECK(glClearDepth(_clear.m_depth) );
  3249. GL_CHECK(glDepthMask(GL_TRUE) );
  3250. }
  3251. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  3252. {
  3253. flags |= GL_STENCIL_BUFFER_BIT;
  3254. GL_CHECK(glClearStencil(_clear.m_stencil) );
  3255. }
  3256. if (0 != flags)
  3257. {
  3258. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  3259. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  3260. GL_CHECK(glClear(flags) );
  3261. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  3262. }
  3263. }
  3264. else
  3265. {
  3266. const GLuint defaultVao = m_vao;
  3267. if (0 != defaultVao)
  3268. {
  3269. GL_CHECK(glBindVertexArray(defaultVao) );
  3270. }
  3271. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  3272. GL_CHECK(glDisable(GL_CULL_FACE) );
  3273. GL_CHECK(glDisable(GL_BLEND) );
  3274. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  3275. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  3276. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  3277. {
  3278. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  3279. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  3280. GL_CHECK(glDepthMask(GL_TRUE) );
  3281. }
  3282. else
  3283. {
  3284. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  3285. }
  3286. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  3287. {
  3288. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  3289. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  3290. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  3291. }
  3292. else
  3293. {
  3294. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  3295. }
  3296. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  3297. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  3298. {
  3299. struct Vertex
  3300. {
  3301. float m_x;
  3302. float m_y;
  3303. float m_z;
  3304. };
  3305. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  3306. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  3307. const float depth = _clear.m_depth * 2.0f - 1.0f;
  3308. vertex->m_x = -1.0f;
  3309. vertex->m_y = -1.0f;
  3310. vertex->m_z = depth;
  3311. vertex++;
  3312. vertex->m_x = 1.0f;
  3313. vertex->m_y = -1.0f;
  3314. vertex->m_z = depth;
  3315. vertex++;
  3316. vertex->m_x = -1.0f;
  3317. vertex->m_y = 1.0f;
  3318. vertex->m_z = depth;
  3319. vertex++;
  3320. vertex->m_x = 1.0f;
  3321. vertex->m_y = 1.0f;
  3322. vertex->m_z = depth;
  3323. }
  3324. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  3325. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  3326. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  3327. GL_CHECK(glUseProgram(program.m_id) );
  3328. program.bindAttributesBegin();
  3329. program.bindAttributes(vertexDecl, 0);
  3330. program.bindAttributesEnd();
  3331. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  3332. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  3333. {
  3334. for (uint32_t ii = 0; ii < numMrt; ++ii)
  3335. {
  3336. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  3337. bx::memCopy(mrtClear[ii], _palette[index], 16);
  3338. }
  3339. }
  3340. else
  3341. {
  3342. float rgba[4] =
  3343. {
  3344. _clear.m_index[0] * 1.0f / 255.0f,
  3345. _clear.m_index[1] * 1.0f / 255.0f,
  3346. _clear.m_index[2] * 1.0f / 255.0f,
  3347. _clear.m_index[3] * 1.0f / 255.0f,
  3348. };
  3349. for (uint32_t ii = 0; ii < numMrt; ++ii)
  3350. {
  3351. bx::memCopy(mrtClear[ii], rgba, 16);
  3352. }
  3353. }
  3354. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  3355. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  3356. , 0
  3357. , 4
  3358. ) );
  3359. }
  3360. }
  3361. void* m_renderdocdll;
  3362. uint16_t m_numWindows;
  3363. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  3364. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  3365. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  3366. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  3367. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  3368. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  3369. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  3370. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  3371. UniformRegistry m_uniformReg;
  3372. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  3373. TimerQueryGL m_gpuTimer;
  3374. OcclusionQueryGL m_occlusionQuery;
  3375. SamplerStateCache m_samplerStateCache;
  3376. TextVideoMem m_textVideoMem;
  3377. bool m_rtMsaa;
  3378. FrameBufferHandle m_fbh;
  3379. uint16_t m_fbDiscard;
  3380. Resolution m_resolution;
  3381. void* m_capture;
  3382. uint32_t m_captureSize;
  3383. float m_maxAnisotropy;
  3384. float m_maxAnisotropyDefault;
  3385. int32_t m_maxMsaa;
  3386. GLuint m_vao;
  3387. bool m_blitSupported;
  3388. bool m_readBackSupported;
  3389. bool m_vaoSupport;
  3390. bool m_samplerObjectSupport;
  3391. bool m_shadowSamplersSupport;
  3392. bool m_srgbWriteControlSupport;
  3393. bool m_borderColorSupport;
  3394. bool m_programBinarySupport;
  3395. bool m_textureSwizzleSupport;
  3396. bool m_depthTextureSupport;
  3397. bool m_timerQuerySupport;
  3398. bool m_occlusionQuerySupport;
  3399. bool m_atocSupport;
  3400. bool m_conservativeRasterSupport;
  3401. bool m_flip;
  3402. uint64_t m_hash;
  3403. GLenum m_readPixelsFmt;
  3404. GLuint m_backBufferFbo;
  3405. GLuint m_msaaBackBufferFbo;
  3406. GLuint m_msaaBackBufferRbos[2];
  3407. GlContext m_glctx;
  3408. bool m_needPresent;
  3409. const char* m_vendor;
  3410. const char* m_renderer;
  3411. const char* m_version;
  3412. const char* m_glslVersion;
  3413. Workaround m_workaround;
  3414. GLuint m_currentFbo;
  3415. };
  3416. RendererContextGL* s_renderGL;
  3417. RendererContextI* rendererCreate(const Init& _init)
  3418. {
  3419. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  3420. if (!s_renderGL->init(_init) )
  3421. {
  3422. BX_DELETE(g_allocator, s_renderGL);
  3423. s_renderGL = NULL;
  3424. }
  3425. return s_renderGL;
  3426. }
  3427. void rendererDestroy()
  3428. {
  3429. s_renderGL->shutdown();
  3430. BX_DELETE(g_allocator, s_renderGL);
  3431. s_renderGL = NULL;
  3432. }
  3433. static void frameBufferValidate()
  3434. {
  3435. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3436. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  3437. , "glCheckFramebufferStatus failed 0x%08x: %s"
  3438. , complete
  3439. , glEnumName(complete)
  3440. );
  3441. BX_UNUSED(complete);
  3442. }
  3443. const char* glslTypeName(GLuint _type)
  3444. {
  3445. #define GLSL_TYPE(_ty) case _ty: return #_ty
  3446. switch (_type)
  3447. {
  3448. GLSL_TYPE(GL_BOOL);
  3449. GLSL_TYPE(GL_INT);
  3450. GLSL_TYPE(GL_INT_VEC2);
  3451. GLSL_TYPE(GL_INT_VEC3);
  3452. GLSL_TYPE(GL_INT_VEC4);
  3453. GLSL_TYPE(GL_UNSIGNED_INT);
  3454. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  3455. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  3456. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  3457. GLSL_TYPE(GL_FLOAT);
  3458. GLSL_TYPE(GL_FLOAT_VEC2);
  3459. GLSL_TYPE(GL_FLOAT_VEC3);
  3460. GLSL_TYPE(GL_FLOAT_VEC4);
  3461. GLSL_TYPE(GL_FLOAT_MAT2);
  3462. GLSL_TYPE(GL_FLOAT_MAT3);
  3463. GLSL_TYPE(GL_FLOAT_MAT4);
  3464. GLSL_TYPE(GL_SAMPLER_2D);
  3465. GLSL_TYPE(GL_SAMPLER_2D_ARRAY);
  3466. GLSL_TYPE(GL_SAMPLER_2D_MULTISAMPLE);
  3467. GLSL_TYPE(GL_INT_SAMPLER_2D);
  3468. GLSL_TYPE(GL_INT_SAMPLER_2D_ARRAY);
  3469. GLSL_TYPE(GL_INT_SAMPLER_2D_MULTISAMPLE);
  3470. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  3471. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY);
  3472. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE);
  3473. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  3474. GLSL_TYPE(GL_SAMPLER_2D_ARRAY_SHADOW);
  3475. GLSL_TYPE(GL_SAMPLER_3D);
  3476. GLSL_TYPE(GL_INT_SAMPLER_3D);
  3477. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  3478. GLSL_TYPE(GL_SAMPLER_CUBE);
  3479. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  3480. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  3481. GLSL_TYPE(GL_IMAGE_1D);
  3482. GLSL_TYPE(GL_INT_IMAGE_1D);
  3483. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  3484. GLSL_TYPE(GL_IMAGE_2D);
  3485. GLSL_TYPE(GL_IMAGE_2D_ARRAY);
  3486. GLSL_TYPE(GL_INT_IMAGE_2D);
  3487. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  3488. GLSL_TYPE(GL_IMAGE_3D);
  3489. GLSL_TYPE(GL_INT_IMAGE_3D);
  3490. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  3491. GLSL_TYPE(GL_IMAGE_CUBE);
  3492. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  3493. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  3494. }
  3495. #undef GLSL_TYPE
  3496. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  3497. return "UNKNOWN GLSL TYPE!";
  3498. }
  3499. const char* glEnumName(GLenum _enum)
  3500. {
  3501. #define GLENUM(_ty) case _ty: return #_ty
  3502. switch (_enum)
  3503. {
  3504. GLENUM(GL_TEXTURE);
  3505. GLENUM(GL_RENDERBUFFER);
  3506. GLENUM(GL_INVALID_ENUM);
  3507. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  3508. GLENUM(GL_INVALID_VALUE);
  3509. GLENUM(GL_INVALID_OPERATION);
  3510. GLENUM(GL_OUT_OF_MEMORY);
  3511. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  3512. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  3513. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  3514. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  3515. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  3516. }
  3517. #undef GLENUM
  3518. BX_WARN(false, "Unknown enum? %x", _enum);
  3519. return "<GLenum?>";
  3520. }
  3521. UniformType::Enum convertGlType(GLenum _type)
  3522. {
  3523. switch (_type)
  3524. {
  3525. case GL_INT:
  3526. case GL_UNSIGNED_INT:
  3527. return UniformType::Sampler;
  3528. case GL_FLOAT:
  3529. case GL_FLOAT_VEC2:
  3530. case GL_FLOAT_VEC3:
  3531. case GL_FLOAT_VEC4:
  3532. return UniformType::Vec4;
  3533. case GL_FLOAT_MAT2:
  3534. break;
  3535. case GL_FLOAT_MAT3:
  3536. return UniformType::Mat3;
  3537. case GL_FLOAT_MAT4:
  3538. return UniformType::Mat4;
  3539. case GL_SAMPLER_2D:
  3540. case GL_SAMPLER_2D_ARRAY:
  3541. case GL_SAMPLER_2D_MULTISAMPLE:
  3542. case GL_INT_SAMPLER_2D:
  3543. case GL_INT_SAMPLER_2D_ARRAY:
  3544. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3545. case GL_UNSIGNED_INT_SAMPLER_2D:
  3546. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3547. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3548. case GL_SAMPLER_2D_SHADOW:
  3549. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3550. case GL_SAMPLER_3D:
  3551. case GL_INT_SAMPLER_3D:
  3552. case GL_UNSIGNED_INT_SAMPLER_3D:
  3553. case GL_SAMPLER_CUBE:
  3554. case GL_INT_SAMPLER_CUBE:
  3555. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3556. case GL_IMAGE_1D:
  3557. case GL_INT_IMAGE_1D:
  3558. case GL_UNSIGNED_INT_IMAGE_1D:
  3559. case GL_IMAGE_2D:
  3560. case GL_IMAGE_2D_ARRAY:
  3561. case GL_INT_IMAGE_2D:
  3562. case GL_UNSIGNED_INT_IMAGE_2D:
  3563. case GL_IMAGE_3D:
  3564. case GL_INT_IMAGE_3D:
  3565. case GL_UNSIGNED_INT_IMAGE_3D:
  3566. case GL_IMAGE_CUBE:
  3567. case GL_INT_IMAGE_CUBE:
  3568. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3569. return UniformType::Sampler;
  3570. };
  3571. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  3572. return UniformType::End;
  3573. }
  3574. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  3575. {
  3576. m_id = glCreateProgram();
  3577. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  3578. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  3579. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  3580. if (!cached)
  3581. {
  3582. GLint linked = 0;
  3583. if (0 != _vsh.m_id)
  3584. {
  3585. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  3586. if (0 != _fsh.m_id)
  3587. {
  3588. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  3589. }
  3590. GL_CHECK(glLinkProgram(m_id) );
  3591. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  3592. if (0 == linked)
  3593. {
  3594. char log[1024];
  3595. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  3596. BX_TRACE("%d: %s", linked, log);
  3597. }
  3598. }
  3599. if (0 == linked)
  3600. {
  3601. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  3602. GL_CHECK(glDeleteProgram(m_id) );
  3603. m_usedCount = 0;
  3604. m_id = 0;
  3605. return;
  3606. }
  3607. s_renderGL->programCache(m_id, id);
  3608. }
  3609. init();
  3610. if (!cached
  3611. && s_renderGL->m_workaround.m_detachShader)
  3612. {
  3613. // Must be after init, otherwise init might fail to lookup shader
  3614. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  3615. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  3616. if (0 != _fsh.m_id)
  3617. {
  3618. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  3619. }
  3620. }
  3621. }
  3622. void ProgramGL::destroy()
  3623. {
  3624. if (NULL != m_constantBuffer)
  3625. {
  3626. UniformBuffer::destroy(m_constantBuffer);
  3627. m_constantBuffer = NULL;
  3628. }
  3629. m_numPredefined = 0;
  3630. if (0 != m_id)
  3631. {
  3632. GL_CHECK(glUseProgram(0) );
  3633. GL_CHECK(glDeleteProgram(m_id) );
  3634. m_id = 0;
  3635. }
  3636. }
  3637. void ProgramGL::init()
  3638. {
  3639. GLint activeAttribs = 0;
  3640. GLint activeUniforms = 0;
  3641. GLint activeBuffers = 0;
  3642. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  3643. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  3644. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  3645. GLint max0, max1;
  3646. bool piqSupported = true
  3647. && s_extension[Extension::ARB_program_interface_query ].m_supported
  3648. && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported
  3649. ;
  3650. if (piqSupported)
  3651. {
  3652. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  3653. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  3654. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  3655. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_MAX_NAME_LENGTH, &max0 ) );
  3656. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_MAX_NAME_LENGTH, &max1 ) );
  3657. }
  3658. else
  3659. {
  3660. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  3661. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  3662. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  3663. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  3664. }
  3665. uint32_t maxLength = bx::uint32_max(max0, max1);
  3666. char* name = (char*)alloca(maxLength + 1);
  3667. BX_TRACE("Program %d", m_id);
  3668. BX_TRACE("Attributes (%d):", activeAttribs);
  3669. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  3670. {
  3671. GLint size;
  3672. GLenum type = 0;
  3673. if (piqSupported)
  3674. {
  3675. GL_CHECK(glGetProgramResourceName(m_id, GL_PROGRAM_INPUT, ii, maxLength + 1, &size, name) );
  3676. GLenum typeProp[] = { GL_TYPE };
  3677. GL_CHECK(glGetProgramResourceiv(m_id
  3678. , GL_PROGRAM_INPUT
  3679. , ii
  3680. , BX_COUNTOF(typeProp)
  3681. , typeProp
  3682. , 1
  3683. , NULL
  3684. , (GLint *)&type)
  3685. );
  3686. }
  3687. else
  3688. {
  3689. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  3690. }
  3691. BX_TRACE("\t%s %s is at location %d"
  3692. , glslTypeName(type)
  3693. , name
  3694. , glGetAttribLocation(m_id, name)
  3695. );
  3696. }
  3697. m_numPredefined = 0;
  3698. m_numSamplers = 0;
  3699. BX_TRACE("Uniforms (%d):", activeUniforms);
  3700. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  3701. {
  3702. struct VariableInfo
  3703. {
  3704. GLenum type;
  3705. GLint loc;
  3706. GLint num;
  3707. };
  3708. VariableInfo vi;
  3709. GLenum props[] = { GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  3710. GLenum gltype;
  3711. GLint num;
  3712. GLint loc;
  3713. if (piqSupported)
  3714. {
  3715. GL_CHECK(glGetProgramResourceiv(m_id
  3716. , GL_UNIFORM
  3717. , ii
  3718. , BX_COUNTOF(props)
  3719. , props
  3720. , BX_COUNTOF(props)
  3721. , NULL
  3722. , (GLint*)&vi
  3723. ) );
  3724. GL_CHECK(glGetProgramResourceName(m_id
  3725. , GL_UNIFORM
  3726. , ii
  3727. , maxLength + 1
  3728. , NULL
  3729. , name
  3730. ) );
  3731. gltype = vi.type;
  3732. loc = vi.loc;
  3733. num = vi.num;
  3734. }
  3735. else
  3736. {
  3737. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  3738. loc = glGetUniformLocation(m_id, name);
  3739. }
  3740. num = bx::uint32_max(num, 1);
  3741. int32_t offset = 0;
  3742. const bx::StringView array = bx::strFind(name, '[');
  3743. if (!array.isEmpty() )
  3744. {
  3745. name[array.getPtr() - name] = '\0';
  3746. BX_TRACE("--- %s", name);
  3747. const bx::StringView end = bx::strFind(array.getPtr()+1, ']');
  3748. bx::fromString(&offset, bx::StringView(array.getPtr()+1, end.getPtr() ) );
  3749. }
  3750. switch (gltype)
  3751. {
  3752. case GL_SAMPLER_2D:
  3753. case GL_SAMPLER_2D_ARRAY:
  3754. case GL_SAMPLER_2D_MULTISAMPLE:
  3755. case GL_INT_SAMPLER_2D:
  3756. case GL_INT_SAMPLER_2D_ARRAY:
  3757. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3758. case GL_UNSIGNED_INT_SAMPLER_2D:
  3759. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3760. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3761. case GL_SAMPLER_2D_SHADOW:
  3762. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3763. case GL_SAMPLER_3D:
  3764. case GL_INT_SAMPLER_3D:
  3765. case GL_UNSIGNED_INT_SAMPLER_3D:
  3766. case GL_SAMPLER_CUBE:
  3767. case GL_INT_SAMPLER_CUBE:
  3768. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3769. case GL_IMAGE_1D:
  3770. case GL_INT_IMAGE_1D:
  3771. case GL_UNSIGNED_INT_IMAGE_1D:
  3772. case GL_IMAGE_2D:
  3773. case GL_INT_IMAGE_2D:
  3774. case GL_UNSIGNED_INT_IMAGE_2D:
  3775. case GL_IMAGE_3D:
  3776. case GL_INT_IMAGE_3D:
  3777. case GL_UNSIGNED_INT_IMAGE_3D:
  3778. case GL_IMAGE_CUBE:
  3779. case GL_INT_IMAGE_CUBE:
  3780. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3781. if (m_numSamplers < BX_COUNTOF(m_sampler) )
  3782. {
  3783. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  3784. m_sampler[m_numSamplers] = loc;
  3785. m_numSamplers++;
  3786. }
  3787. else
  3788. {
  3789. BX_TRACE("Too many samplers (max: %d)! Sampler at location %d."
  3790. , BX_COUNTOF(m_sampler)
  3791. , loc
  3792. );
  3793. }
  3794. break;
  3795. default:
  3796. break;
  3797. }
  3798. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  3799. if (PredefinedUniform::Count != predefined)
  3800. {
  3801. m_predefined[m_numPredefined].m_loc = loc;
  3802. m_predefined[m_numPredefined].m_count = uint16_t(num);
  3803. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  3804. m_numPredefined++;
  3805. }
  3806. else
  3807. {
  3808. const UniformRegInfo* info = s_renderGL->m_uniformReg.find(name);
  3809. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  3810. if (NULL != info)
  3811. {
  3812. if (NULL == m_constantBuffer)
  3813. {
  3814. m_constantBuffer = UniformBuffer::create(1024);
  3815. }
  3816. UniformType::Enum type = convertGlType(gltype);
  3817. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  3818. m_constantBuffer->write(loc);
  3819. BX_TRACE("store %s %d", name, info->m_handle);
  3820. }
  3821. }
  3822. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  3823. , glslTypeName(gltype)
  3824. , name
  3825. , PredefinedUniform::Count != predefined ? "*" : ""
  3826. , loc
  3827. , num
  3828. , offset
  3829. );
  3830. BX_UNUSED(offset);
  3831. }
  3832. if (NULL != m_constantBuffer)
  3833. {
  3834. m_constantBuffer->finish();
  3835. }
  3836. if (piqSupported)
  3837. {
  3838. struct VariableInfo
  3839. {
  3840. GLenum type;
  3841. };
  3842. VariableInfo vi;
  3843. GLenum props[] = { GL_TYPE };
  3844. BX_TRACE("Buffers (%d):", activeBuffers);
  3845. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  3846. {
  3847. GL_CHECK(glGetProgramResourceiv(m_id
  3848. , GL_BUFFER_VARIABLE
  3849. , ii
  3850. , BX_COUNTOF(props)
  3851. , props
  3852. , BX_COUNTOF(props)
  3853. , NULL
  3854. , (GLint*)&vi
  3855. ) );
  3856. GL_CHECK(glGetProgramResourceName(m_id
  3857. , GL_BUFFER_VARIABLE
  3858. , ii
  3859. , maxLength + 1
  3860. , NULL
  3861. , name
  3862. ) );
  3863. BX_TRACE("\t%s %s at %d"
  3864. , glslTypeName(vi.type)
  3865. , name
  3866. , 0 //vi.loc
  3867. );
  3868. }
  3869. }
  3870. bx::memSet(m_attributes, 0xff, sizeof(m_attributes) );
  3871. uint32_t used = 0;
  3872. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  3873. {
  3874. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  3875. if (-1 != loc)
  3876. {
  3877. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  3878. m_attributes[ii] = loc;
  3879. m_used[used++] = ii;
  3880. }
  3881. }
  3882. BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d.", used, Attrib::Count);
  3883. m_usedCount = (uint8_t)used;
  3884. used = 0;
  3885. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  3886. {
  3887. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  3888. if (GLuint(-1) != loc )
  3889. {
  3890. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  3891. m_instanceData[used++] = loc;
  3892. }
  3893. }
  3894. BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d."
  3895. , used
  3896. , BX_COUNTOF(m_instanceData)
  3897. );
  3898. m_instanceData[used] = 0xffff;
  3899. }
  3900. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex)
  3901. {
  3902. for (uint32_t ii = 0, iiEnd = m_usedCount; ii < iiEnd; ++ii)
  3903. {
  3904. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3905. GLint loc = m_attributes[attr];
  3906. uint8_t num;
  3907. AttribType::Enum type;
  3908. bool normalized;
  3909. bool asInt;
  3910. _vertexDecl.decode(attr, num, type, normalized, asInt);
  3911. if (-1 != loc)
  3912. {
  3913. if (UINT16_MAX != _vertexDecl.m_attributes[attr])
  3914. {
  3915. GL_CHECK(glEnableVertexAttribArray(loc) );
  3916. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  3917. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  3918. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 30) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  3919. && (AttribType::Uint8 == type || AttribType::Int16 == type)
  3920. && !normalized)
  3921. {
  3922. GL_CHECK(glVertexAttribIPointer(loc
  3923. , num
  3924. , s_attribType[type]
  3925. , _vertexDecl.m_stride
  3926. , (void*)(uintptr_t)baseVertex)
  3927. );
  3928. }
  3929. else
  3930. {
  3931. GL_CHECK(glVertexAttribPointer(loc
  3932. , num
  3933. , s_attribType[type]
  3934. , normalized
  3935. , _vertexDecl.m_stride
  3936. , (void*)(uintptr_t)baseVertex)
  3937. );
  3938. }
  3939. m_unboundUsedAttrib[ii] = Attrib::Count;
  3940. }
  3941. }
  3942. }
  3943. }
  3944. void ProgramGL::unbindAttributes()
  3945. {
  3946. for(uint32_t ii = 0, iiEnd = m_usedCount; ii < iiEnd; ++ii)
  3947. {
  3948. if(Attrib::Count == m_unboundUsedAttrib[ii])
  3949. {
  3950. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3951. GLint loc = m_attributes[attr];
  3952. GL_CHECK(glDisableVertexAttribArray(loc));
  3953. }
  3954. }
  3955. }
  3956. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  3957. {
  3958. uint32_t baseVertex = _baseVertex;
  3959. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3960. {
  3961. GLint loc = m_instanceData[ii];
  3962. GL_CHECK(glEnableVertexAttribArray(loc) );
  3963. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  3964. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  3965. baseVertex += 16;
  3966. }
  3967. }
  3968. void ProgramGL::unbindInstanceData() const
  3969. {
  3970. for(uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3971. {
  3972. GLint loc = m_instanceData[ii];
  3973. GL_CHECK(glDisableVertexAttribArray(loc));
  3974. }
  3975. }
  3976. void IndexBufferGL::destroy()
  3977. {
  3978. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  3979. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3980. }
  3981. void VertexBufferGL::destroy()
  3982. {
  3983. GL_CHECK(glBindBuffer(m_target, 0) );
  3984. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3985. }
  3986. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips, uint64_t _flags)
  3987. {
  3988. m_target = _target;
  3989. m_numMips = _numMips;
  3990. m_flags = _flags;
  3991. m_width = _width;
  3992. m_height = _height;
  3993. m_depth = _depth;
  3994. m_currentSamplerHash = UINT32_MAX;
  3995. const bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  3996. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  3997. const bool srgb = 0 != (m_flags&BGFX_TEXTURE_SRGB);
  3998. const bool textureArray = false
  3999. || _target == GL_TEXTURE_2D_ARRAY
  4000. || _target == GL_TEXTURE_CUBE_MAP_ARRAY
  4001. ;
  4002. if (!writeOnly)
  4003. {
  4004. GL_CHECK(glGenTextures(1, &m_id) );
  4005. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  4006. GL_CHECK(glBindTexture(_target, m_id) );
  4007. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  4008. const TextureFormatInfo& tfi = s_textureFormat[m_textureFormat];
  4009. m_fmt = tfi.m_fmt;
  4010. m_type = tfi.m_type;
  4011. const bool swizzle = true
  4012. && TextureFormat::BGRA8 == m_requestedFormat
  4013. && !s_textureFormat[m_requestedFormat].m_supported
  4014. && !s_renderGL->m_textureSwizzleSupport
  4015. ;
  4016. const bool convert = false
  4017. || m_textureFormat != m_requestedFormat
  4018. || swizzle
  4019. ;
  4020. if (convert)
  4021. {
  4022. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  4023. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  4024. m_fmt = tfiRgba8.m_fmt;
  4025. m_type = tfiRgba8.m_type;
  4026. }
  4027. const GLenum internalFmt = srgb
  4028. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  4029. : s_textureFormat[m_textureFormat].m_internalFmt
  4030. ;
  4031. if (textureArray)
  4032. {
  4033. GL_CHECK(glTexStorage3D(_target
  4034. , _numMips
  4035. , internalFmt
  4036. , m_width
  4037. , m_height
  4038. , _depth
  4039. ) );
  4040. }
  4041. else if (computeWrite)
  4042. {
  4043. if (_target == GL_TEXTURE_3D)
  4044. {
  4045. GL_CHECK(glTexStorage3D(_target
  4046. , _numMips
  4047. , internalFmt
  4048. , m_width
  4049. , m_height
  4050. , _depth
  4051. ) );
  4052. }
  4053. else
  4054. {
  4055. GL_CHECK(glTexStorage2D(_target
  4056. , _numMips
  4057. , internalFmt
  4058. , m_width
  4059. , m_height
  4060. ) );
  4061. }
  4062. }
  4063. setSamplerState(uint32_t(_flags), NULL);
  4064. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4065. && TextureFormat::BGRA8 == m_requestedFormat
  4066. && !s_textureFormat[m_requestedFormat].m_supported
  4067. && s_renderGL->m_textureSwizzleSupport)
  4068. {
  4069. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  4070. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  4071. }
  4072. }
  4073. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4074. if (renderTarget)
  4075. {
  4076. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4077. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4078. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4079. const bool msaaSample = 0 != (m_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4080. if (!msaaSample
  4081. && (0 != msaaQuality || writeOnly) )
  4082. {
  4083. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  4084. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  4085. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  4086. if (0 == msaaQuality)
  4087. {
  4088. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  4089. , s_rboFormat[m_textureFormat]
  4090. , _width
  4091. , _height
  4092. ) );
  4093. }
  4094. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4095. {
  4096. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  4097. , msaaQuality
  4098. , s_rboFormat[m_textureFormat]
  4099. , _width
  4100. , _height
  4101. ) );
  4102. }
  4103. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  4104. if (writeOnly)
  4105. {
  4106. // This is render buffer, there is no sampling, no need
  4107. // to create texture.
  4108. return false;
  4109. }
  4110. }
  4111. }
  4112. return true;
  4113. }
  4114. void TextureGL::create(const Memory* _mem, uint64_t _flags, uint8_t _skip)
  4115. {
  4116. bimg::ImageContainer imageContainer;
  4117. if (bimg::imageParse(imageContainer, _mem->data, _mem->size) )
  4118. {
  4119. uint8_t numMips = imageContainer.m_numMips;
  4120. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  4121. numMips -= startLod;
  4122. const uint16_t numLayers = imageContainer.m_numLayers;
  4123. uint32_t textureWidth;
  4124. uint32_t textureHeight;
  4125. uint32_t textureDepth;
  4126. {
  4127. const bimg::ImageBlockInfo& ibi = bimg::getBlockInfo(bimg::TextureFormat::Enum(imageContainer.m_format) );
  4128. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  4129. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  4130. textureDepth = 1 < imageContainer.m_depth
  4131. ? imageContainer.m_depth
  4132. : imageContainer.m_numLayers
  4133. ;
  4134. }
  4135. m_requestedFormat = uint8_t(imageContainer.m_format);
  4136. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  4137. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  4138. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  4139. const bool msaaSample = 0 != (_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4140. uint32_t msaaQuality = ( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4141. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4142. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4143. GLenum target = msaaSample ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
  4144. if (imageContainer.m_cubeMap)
  4145. {
  4146. target = GL_TEXTURE_CUBE_MAP;
  4147. }
  4148. else if (imageContainer.m_depth > 1)
  4149. {
  4150. target = GL_TEXTURE_3D;
  4151. }
  4152. const bool textureArray = 1 < numLayers;
  4153. if (textureArray)
  4154. {
  4155. switch (target)
  4156. {
  4157. case GL_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP_ARRAY; break;
  4158. case GL_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; break;
  4159. default: target = GL_TEXTURE_2D_ARRAY; break;
  4160. }
  4161. }
  4162. if (!init(target
  4163. , textureWidth
  4164. , textureHeight
  4165. , textureDepth
  4166. , numMips
  4167. , _flags
  4168. ) )
  4169. {
  4170. return;
  4171. }
  4172. target = isCubeMap()
  4173. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4174. : m_target
  4175. ;
  4176. const GLenum internalFmt = srgb
  4177. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  4178. : s_textureFormat[m_textureFormat].m_internalFmt
  4179. ;
  4180. const bool swizzle = true
  4181. && TextureFormat::BGRA8 == m_requestedFormat
  4182. && !s_textureFormat[m_requestedFormat].m_supported
  4183. && !s_renderGL->m_textureSwizzleSupport
  4184. ;
  4185. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(m_requestedFormat) );
  4186. const bool convert = false
  4187. || m_textureFormat != m_requestedFormat
  4188. || swizzle
  4189. ;
  4190. BX_TRACE("Texture%-4s %3d: %s %s(requested: %s), layers %d, %dx%dx%d%s."
  4191. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  4192. , this - s_renderGL->m_textures
  4193. , getName( (TextureFormat::Enum)m_textureFormat)
  4194. , srgb ? "+sRGB " : ""
  4195. , getName( (TextureFormat::Enum)m_requestedFormat)
  4196. , numLayers
  4197. , textureWidth
  4198. , textureHeight
  4199. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  4200. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  4201. );
  4202. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  4203. , swizzle ? "swizzle" : ""
  4204. , swizzle&&convert ? " and " : ""
  4205. , convert ? "convert" : ""
  4206. , getName( (TextureFormat::Enum)m_requestedFormat)
  4207. , getName( (TextureFormat::Enum)m_textureFormat)
  4208. );
  4209. uint8_t* temp = NULL;
  4210. if (convert)
  4211. {
  4212. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  4213. }
  4214. const uint16_t numSides = numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  4215. for (uint16_t side = 0; side < numSides; ++side)
  4216. {
  4217. uint32_t width = textureWidth;
  4218. uint32_t height = textureHeight;
  4219. uint32_t depth = imageContainer.m_depth;
  4220. GLenum imageTarget = imageContainer.m_cubeMap && !textureArray
  4221. ? target+side
  4222. : target
  4223. ;
  4224. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  4225. {
  4226. width = bx::uint32_max(1, width);
  4227. height = bx::uint32_max(1, height);
  4228. depth = 1 < imageContainer.m_depth
  4229. ? bx::uint32_max(1, depth)
  4230. : side
  4231. ;
  4232. bimg::ImageMip mip;
  4233. if (bimg::imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  4234. {
  4235. if (compressed
  4236. && !convert)
  4237. {
  4238. GL_CHECK(compressedTexImage(imageTarget
  4239. , lod
  4240. , internalFmt
  4241. , width
  4242. , height
  4243. , depth
  4244. , 0
  4245. , mip.m_size
  4246. , mip.m_data
  4247. ) );
  4248. }
  4249. else
  4250. {
  4251. const uint8_t* data = mip.m_data;
  4252. if (convert)
  4253. {
  4254. imageDecodeToRgba8(
  4255. g_allocator
  4256. , temp
  4257. , mip.m_data
  4258. , mip.m_width
  4259. , mip.m_height
  4260. , mip.m_width*4
  4261. , mip.m_format
  4262. );
  4263. data = temp;
  4264. }
  4265. GL_CHECK(texImage(imageTarget
  4266. , msaaQuality
  4267. , lod
  4268. , internalFmt
  4269. , width
  4270. , height
  4271. , depth
  4272. , 0
  4273. , m_fmt
  4274. , m_type
  4275. , data
  4276. ) );
  4277. }
  4278. }
  4279. else if (!computeWrite)
  4280. {
  4281. if (compressed)
  4282. {
  4283. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  4284. * bx::uint32_max(1, (height + 3)>>2)
  4285. * 4*4* bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) )/8
  4286. ;
  4287. GL_CHECK(compressedTexImage(imageTarget
  4288. , lod
  4289. , internalFmt
  4290. , width
  4291. , height
  4292. , depth
  4293. , 0
  4294. , size
  4295. , NULL
  4296. ) );
  4297. }
  4298. else
  4299. {
  4300. GL_CHECK(texImage(imageTarget
  4301. , msaaQuality
  4302. , lod
  4303. , internalFmt
  4304. , width
  4305. , height
  4306. , depth
  4307. , 0
  4308. , m_fmt
  4309. , m_type
  4310. , NULL
  4311. ) );
  4312. }
  4313. }
  4314. width >>= 1;
  4315. height >>= 1;
  4316. depth >>= 1;
  4317. }
  4318. }
  4319. if (NULL != temp)
  4320. {
  4321. BX_FREE(g_allocator, temp);
  4322. }
  4323. }
  4324. GL_CHECK(glBindTexture(m_target, 0) );
  4325. }
  4326. void TextureGL::destroy()
  4327. {
  4328. if (0 == (m_flags & BGFX_SAMPLER_INTERNAL_SHARED)
  4329. && 0 != m_id)
  4330. {
  4331. GL_CHECK(glBindTexture(m_target, 0) );
  4332. GL_CHECK(glDeleteTextures(1, &m_id) );
  4333. m_id = 0;
  4334. }
  4335. if (0 != m_rbo)
  4336. {
  4337. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  4338. m_rbo = 0;
  4339. }
  4340. }
  4341. void TextureGL::overrideInternal(uintptr_t _ptr)
  4342. {
  4343. destroy();
  4344. m_flags |= BGFX_SAMPLER_INTERNAL_SHARED;
  4345. m_id = (GLuint)_ptr;
  4346. }
  4347. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  4348. {
  4349. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  4350. const uint32_t rectpitch = _rect.m_width*bpp/8;
  4351. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  4352. GL_CHECK(glBindTexture(m_target, m_id) );
  4353. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  4354. GLenum target = isCubeMap()
  4355. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4356. : m_target
  4357. ;
  4358. const bool swizzle = true
  4359. && TextureFormat::BGRA8 == m_requestedFormat
  4360. && !s_textureFormat[m_requestedFormat].m_supported
  4361. && !s_renderGL->m_textureSwizzleSupport
  4362. ;
  4363. const bool unpackRowLength = !!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported;
  4364. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(m_requestedFormat) );
  4365. const bool convert = false
  4366. || (compressed && m_textureFormat != m_requestedFormat)
  4367. || swizzle
  4368. ;
  4369. const uint32_t width = _rect.m_width;
  4370. const uint32_t height = _rect.m_height;
  4371. uint8_t* temp = NULL;
  4372. if (convert
  4373. || !unpackRowLength)
  4374. {
  4375. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  4376. }
  4377. else if (unpackRowLength)
  4378. {
  4379. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  4380. }
  4381. if (compressed)
  4382. {
  4383. const uint8_t* data = _mem->data;
  4384. if (!unpackRowLength)
  4385. {
  4386. bimg::imageCopy(temp, width, height, 1, bpp, srcpitch, data);
  4387. data = temp;
  4388. }
  4389. GL_CHECK(compressedTexSubImage(target+_side
  4390. , _mip
  4391. , _rect.m_x
  4392. , _rect.m_y
  4393. , _z
  4394. , _rect.m_width
  4395. , _rect.m_height
  4396. , _depth
  4397. , m_fmt
  4398. , _mem->size
  4399. , data
  4400. ) );
  4401. }
  4402. else
  4403. {
  4404. const uint8_t* data = _mem->data;
  4405. if (convert)
  4406. {
  4407. bimg::imageDecodeToRgba8(g_allocator, temp, data, width, height, srcpitch, bimg::TextureFormat::Enum(m_requestedFormat) );
  4408. data = temp;
  4409. srcpitch = rectpitch;
  4410. }
  4411. if (BX_IGNORE_C4127(true
  4412. && !unpackRowLength
  4413. && !convert) )
  4414. {
  4415. bimg::imageCopy(temp, width, height, 1, bpp, srcpitch, data);
  4416. data = temp;
  4417. }
  4418. GL_CHECK(texSubImage(target+_side
  4419. , _mip
  4420. , _rect.m_x
  4421. , _rect.m_y
  4422. , _z
  4423. , _rect.m_width
  4424. , _rect.m_height
  4425. , _depth
  4426. , m_fmt
  4427. , m_type
  4428. , data
  4429. ) );
  4430. }
  4431. if (!convert
  4432. && unpackRowLength)
  4433. {
  4434. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  4435. }
  4436. if (NULL != temp)
  4437. {
  4438. BX_FREE(g_allocator, temp);
  4439. }
  4440. }
  4441. void TextureGL::setSamplerState(uint32_t _flags, const float _rgba[4])
  4442. {
  4443. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  4444. && !s_textureFilter[m_textureFormat])
  4445. {
  4446. // Force point sampling when texture format doesn't support linear sampling.
  4447. _flags &= ~(0
  4448. | BGFX_SAMPLER_MIN_MASK
  4449. | BGFX_SAMPLER_MAG_MASK
  4450. | BGFX_SAMPLER_MIP_MASK
  4451. );
  4452. _flags |= 0
  4453. | BGFX_SAMPLER_MIN_POINT
  4454. | BGFX_SAMPLER_MAG_POINT
  4455. | BGFX_SAMPLER_MIP_POINT
  4456. ;
  4457. }
  4458. const uint32_t flags = (0 != (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags) ? m_flags : _flags) & BGFX_SAMPLER_BITS_MASK;
  4459. bool hasBorderColor = false;
  4460. bx::HashMurmur2A murmur;
  4461. murmur.begin();
  4462. murmur.add(flags);
  4463. if (NULL != _rgba)
  4464. {
  4465. if (BGFX_SAMPLER_U_BORDER == (flags & BGFX_SAMPLER_U_BORDER)
  4466. || BGFX_SAMPLER_V_BORDER == (flags & BGFX_SAMPLER_V_BORDER)
  4467. || BGFX_SAMPLER_W_BORDER == (flags & BGFX_SAMPLER_W_BORDER) )
  4468. {
  4469. murmur.add(_rgba, 16);
  4470. hasBorderColor = true;
  4471. }
  4472. }
  4473. uint32_t hash = murmur.end();
  4474. if (hash != m_currentSamplerHash)
  4475. {
  4476. const GLenum target = m_target == GL_TEXTURE_2D_MULTISAMPLE ? GL_TEXTURE_2D : m_target;
  4477. const GLenum targetMsaa = m_target;
  4478. const uint8_t numMips = m_numMips;
  4479. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT]) );
  4480. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT]) );
  4481. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4482. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  4483. {
  4484. GL_CHECK(glTexParameteri(targetMsaa, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  4485. }
  4486. if (target == GL_TEXTURE_3D)
  4487. {
  4488. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT]) );
  4489. }
  4490. GLenum magFilter;
  4491. GLenum minFilter;
  4492. getFilters(flags, 1 < numMips, magFilter, minFilter);
  4493. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  4494. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  4495. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4496. {
  4497. GL_CHECK(glTexParameterf(target, GL_TEXTURE_LOD_BIAS, float(BGFX_CONFIG_MIP_LOD_BIAS) ) );
  4498. }
  4499. if (s_renderGL->m_borderColorSupport
  4500. && hasBorderColor)
  4501. {
  4502. GL_CHECK(glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, _rgba) );
  4503. }
  4504. if (0 != (flags & (BGFX_SAMPLER_MIN_ANISOTROPIC|BGFX_SAMPLER_MAG_ANISOTROPIC) )
  4505. && 0.0f < s_renderGL->m_maxAnisotropy)
  4506. {
  4507. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  4508. }
  4509. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4510. || s_renderGL->m_shadowSamplersSupport)
  4511. {
  4512. const uint32_t cmpFunc = (flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT;
  4513. if (0 == cmpFunc)
  4514. {
  4515. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  4516. }
  4517. else
  4518. {
  4519. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  4520. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  4521. }
  4522. }
  4523. m_currentSamplerHash = hash;
  4524. }
  4525. }
  4526. void TextureGL::commit(uint32_t _stage, uint32_t _flags, const float _palette[][4])
  4527. {
  4528. const uint32_t flags = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags)
  4529. ? _flags
  4530. : uint32_t(m_flags)
  4531. ;
  4532. const uint32_t index = (flags & BGFX_SAMPLER_BORDER_COLOR_MASK) >> BGFX_SAMPLER_BORDER_COLOR_SHIFT;
  4533. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  4534. GL_CHECK(glBindTexture(m_target, m_id) );
  4535. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4536. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4537. {
  4538. // GLES2 doesn't have support for sampler object.
  4539. setSamplerState(flags, _palette[index]);
  4540. }
  4541. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4542. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  4543. {
  4544. // In case that GL 2.1 sampler object is supported via extension.
  4545. if (s_renderGL->m_samplerObjectSupport)
  4546. {
  4547. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4548. }
  4549. else
  4550. {
  4551. setSamplerState(flags, _palette[index]);
  4552. }
  4553. }
  4554. else
  4555. {
  4556. // Everything else has sampler object.
  4557. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4558. }
  4559. }
  4560. void TextureGL::resolve(uint8_t _resolve) const
  4561. {
  4562. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4563. if (renderTarget
  4564. && 1 < m_numMips
  4565. && 0 != (_resolve & BGFX_RESOLVE_AUTO_GEN_MIPS) )
  4566. {
  4567. GL_CHECK(glBindTexture(m_target, m_id) );
  4568. GL_CHECK(glGenerateMipmap(m_target) );
  4569. GL_CHECK(glBindTexture(m_target, 0) );
  4570. }
  4571. }
  4572. void strins(char* _str, const char* _insert)
  4573. {
  4574. size_t len = bx::strLen(_insert);
  4575. bx::memMove(&_str[len], _str, bx::strLen(_str)+1);
  4576. bx::memCopy(_str, _insert, len);
  4577. }
  4578. void ShaderGL::create(const Memory* _mem)
  4579. {
  4580. bx::MemoryReader reader(_mem->data, _mem->size);
  4581. m_hash = bx::hash<bx::HashMurmur2A>(_mem->data, _mem->size);
  4582. uint32_t magic;
  4583. bx::read(&reader, magic);
  4584. if (isShaderType(magic, 'C') )
  4585. {
  4586. m_type = GL_COMPUTE_SHADER;
  4587. }
  4588. else if (isShaderType(magic, 'F') )
  4589. {
  4590. m_type = GL_FRAGMENT_SHADER;
  4591. }
  4592. else if (isShaderType(magic, 'V') )
  4593. {
  4594. m_type = GL_VERTEX_SHADER;
  4595. }
  4596. uint32_t hashIn;
  4597. bx::read(&reader, hashIn);
  4598. uint32_t hashOut;
  4599. if (isShaderVerLess(magic, 6) )
  4600. {
  4601. hashOut = hashIn;
  4602. }
  4603. else
  4604. {
  4605. bx::read(&reader, hashOut);
  4606. }
  4607. uint16_t count;
  4608. bx::read(&reader, count);
  4609. BX_TRACE("%s Shader consts %d"
  4610. , getShaderTypeName(magic)
  4611. , count
  4612. );
  4613. for (uint32_t ii = 0; ii < count; ++ii)
  4614. {
  4615. uint8_t nameSize = 0;
  4616. bx::read(&reader, nameSize);
  4617. char name[256];
  4618. bx::read(&reader, &name, nameSize);
  4619. name[nameSize] = '\0';
  4620. uint8_t type;
  4621. bx::read(&reader, type);
  4622. uint8_t num;
  4623. bx::read(&reader, num);
  4624. uint16_t regIndex;
  4625. bx::read(&reader, regIndex);
  4626. uint16_t regCount;
  4627. bx::read(&reader, regCount);
  4628. }
  4629. uint32_t shaderSize;
  4630. bx::read(&reader, shaderSize);
  4631. m_id = glCreateShader(m_type);
  4632. BX_WARN(0 != m_id, "Failed to create shader.");
  4633. bx::StringView code( (const char*)reader.getDataPtr(), shaderSize);
  4634. if (0 != m_id)
  4635. {
  4636. if (GL_COMPUTE_SHADER != m_type
  4637. && 0 != bx::strCmp(code, "#version 430", 12) )
  4638. {
  4639. int32_t tempLen = code.getLength() + (4<<10);
  4640. char* temp = (char*)alloca(tempLen);
  4641. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  4642. bx::Error err;
  4643. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4644. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4645. {
  4646. bx::write(&writer
  4647. , "#define centroid\n"
  4648. "#define flat\n"
  4649. "#define noperspective\n"
  4650. "#define smooth\n"
  4651. );
  4652. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  4653. && !bx::findIdentifierMatch(code, s_OES_standard_derivatives).isEmpty()
  4654. ;
  4655. const bool usesFragData = !bx::findIdentifierMatch(code, "gl_FragData").isEmpty();
  4656. const bool usesFragDepth = !bx::findIdentifierMatch(code, "gl_FragDepth").isEmpty();
  4657. const bool usesShadowSamplers = !bx::findIdentifierMatch(code, s_EXT_shadow_samplers).isEmpty();
  4658. const bool usesTextureLod = !bx::findIdentifierMatch(code, s_EXT_shader_texture_lod).isEmpty();
  4659. const bool usesFragmentOrdering = !bx::findIdentifierMatch(code, "beginFragmentShaderOrdering").isEmpty();
  4660. const bool usesTexture3D = true
  4661. && s_extension[Extension::OES_texture_3D].m_supported
  4662. && !bx::findIdentifierMatch(code, s_texture3D).isEmpty()
  4663. ;
  4664. if (usesDerivatives)
  4665. {
  4666. bx::write(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  4667. }
  4668. if (usesFragData)
  4669. {
  4670. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  4671. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  4672. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  4673. );
  4674. bx::write(&writer, "#extension GL_EXT_draw_buffers : enable\n");
  4675. }
  4676. bool insertFragDepth = false;
  4677. if (usesFragDepth)
  4678. {
  4679. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  4680. if (s_extension[Extension::EXT_frag_depth].m_supported)
  4681. {
  4682. bx::write(&writer
  4683. , "#extension GL_EXT_frag_depth : enable\n"
  4684. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  4685. );
  4686. char str[128];
  4687. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  4688. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  4689. );
  4690. bx::write(&writer, str);
  4691. }
  4692. else
  4693. {
  4694. insertFragDepth = true;
  4695. }
  4696. }
  4697. if (usesShadowSamplers)
  4698. {
  4699. if (s_renderGL->m_shadowSamplersSupport)
  4700. {
  4701. bx::write(&writer
  4702. , "#extension GL_EXT_shadow_samplers : enable\n"
  4703. "#define shadow2D shadow2DEXT\n"
  4704. "#define shadow2DProj shadow2DProjEXT\n"
  4705. );
  4706. }
  4707. else
  4708. {
  4709. bx::write(&writer
  4710. , "#define sampler2DShadow sampler2D\n"
  4711. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  4712. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  4713. );
  4714. }
  4715. }
  4716. if (usesTexture3D)
  4717. {
  4718. bx::write(&writer, "#extension GL_OES_texture_3D : enable\n");
  4719. }
  4720. if (usesTextureLod)
  4721. {
  4722. BX_WARN(s_extension[Extension::ARB_shader_texture_lod].m_supported
  4723. || s_extension[Extension::EXT_shader_texture_lod].m_supported
  4724. , "(ARB|EXT)_shader_texture_lod is used but not supported by GLES2 driver."
  4725. );
  4726. if (s_extension[Extension::ARB_shader_texture_lod].m_supported)
  4727. {
  4728. bx::write(&writer
  4729. , "#extension GL_ARB_shader_texture_lod : enable\n"
  4730. "#define texture2DLod texture2DLodARB\n"
  4731. "#define texture2DProjLod texture2DProjLodARB\n"
  4732. "#define textureCubeLod textureCubeLodARB\n"
  4733. "#define texture2DGrad texture2DGradARB\n"
  4734. "#define texture2DProjGrad texture2DProjGradARB\n"
  4735. "#define textureCubeGrad textureCubeGradARB\n"
  4736. );
  4737. }
  4738. else
  4739. {
  4740. if(s_extension[Extension::EXT_shader_texture_lod].m_supported)
  4741. {
  4742. bx::write(&writer
  4743. , "#extension GL_EXT_shader_texture_lod : enable\n"
  4744. "#define texture2DLod texture2DLodEXT\n"
  4745. "#define texture2DProjLod texture2DProjLodEXT\n"
  4746. "#define textureCubeLod textureCubeLodEXT\n"
  4747. );
  4748. }
  4749. else
  4750. {
  4751. bx::write(&writer
  4752. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  4753. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  4754. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  4755. );
  4756. }
  4757. }
  4758. }
  4759. if (usesFragmentOrdering)
  4760. {
  4761. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4762. {
  4763. bx::write(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4764. }
  4765. else
  4766. {
  4767. bx::write(&writer, "#define beginFragmentShaderOrdering()\n");
  4768. }
  4769. }
  4770. bx::write(&writer, &err, "precision %s float;\n"
  4771. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  4772. );
  4773. bx::write(&writer, code);
  4774. bx::write(&writer, '\0');
  4775. if (insertFragDepth)
  4776. {
  4777. bx::StringView shader(temp);
  4778. bx::StringView entry = bx::strFind(shader, "void main ()");
  4779. if (!entry.isEmpty() )
  4780. {
  4781. entry.set(entry.getTerm(), shader.getTerm() );
  4782. bx::StringView brace = bx::strFind(entry, "{");
  4783. if (!brace.isEmpty() )
  4784. {
  4785. bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}');
  4786. if (!block.isEmpty() )
  4787. {
  4788. strins(const_cast<char*>(brace.getPtr()+1), "\n float bgfx_FragDepth = 0.0;\n");
  4789. }
  4790. }
  4791. }
  4792. }
  4793. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  4794. for (bx::StringView fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth")
  4795. ; !fragDepth.isEmpty()
  4796. ; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth")
  4797. )
  4798. {
  4799. char* insert = const_cast<char*>(fragDepth.getPtr() );
  4800. strins(insert, "bg");
  4801. bx::memCopy(insert + 2, "fx", 2);
  4802. }
  4803. }
  4804. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4805. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  4806. {
  4807. const bool usesTextureLod = true
  4808. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  4809. && !bx::findIdentifierMatch(code, s_ARB_shader_texture_lod).isEmpty()
  4810. ;
  4811. const bool usesGpuShader4 = !bx::findIdentifierMatch(code, s_EXT_gpu_shader4).isEmpty();
  4812. const bool usesGpuShader5 = !bx::findIdentifierMatch(code, s_ARB_gpu_shader5).isEmpty();
  4813. const bool usesIUsamplers = !bx::findIdentifierMatch(code, s_uisamplers).isEmpty();
  4814. const bool usesUint = !bx::findIdentifierMatch(code, s_uint).isEmpty();
  4815. const bool usesTexelFetch = !bx::findIdentifierMatch(code, s_texelFetch).isEmpty();
  4816. const bool usesTextureArray = !bx::findIdentifierMatch(code, s_textureArray).isEmpty();
  4817. const bool usesTexture3D = !bx::findIdentifierMatch(code, s_texture3D).isEmpty();
  4818. const bool usesTextureMS = !bx::findIdentifierMatch(code, s_ARB_texture_multisample).isEmpty();
  4819. const bool usesPacking = !bx::findIdentifierMatch(code, s_ARB_shading_language_packing).isEmpty();
  4820. const bool usesInterpQ = !bx::findIdentifierMatch(code, s_intepolationQualifier).isEmpty();
  4821. uint32_t version = BX_ENABLED(BX_PLATFORM_OSX) ? 120
  4822. : usesTextureArray
  4823. || usesTexture3D
  4824. || usesIUsamplers
  4825. || usesUint
  4826. || usesTexelFetch
  4827. || usesGpuShader5
  4828. || usesInterpQ ? 130
  4829. : usesTextureLod ? 120
  4830. : 120
  4831. ;
  4832. if (0 != version)
  4833. {
  4834. bx::write(&writer, &err, "#version %d\n", version);
  4835. }
  4836. if (usesTextureLod)
  4837. {
  4838. if (m_type == GL_FRAGMENT_SHADER)
  4839. {
  4840. bx::write(&writer
  4841. , "#extension GL_ARB_shader_texture_lod : enable\n"
  4842. "#define texture2DGrad texture2DGradARB\n"
  4843. "#define texture2DProjGrad texture2DProjGradARB\n"
  4844. "#define textureCubeGrad textureCubeGradARB\n"
  4845. );
  4846. }
  4847. }
  4848. if (usesGpuShader4)
  4849. {
  4850. bx::write(&writer, "#extension GL_EXT_gpu_shader4 : enable\n");
  4851. }
  4852. if (usesGpuShader5)
  4853. {
  4854. bx::write(&writer, "#extension GL_ARB_gpu_shader5 : enable\n");
  4855. }
  4856. if (usesPacking)
  4857. {
  4858. bx::write(&writer, "#extension GL_ARB_shading_language_packing : enable\n");
  4859. }
  4860. if (usesTextureMS)
  4861. {
  4862. bx::write(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  4863. }
  4864. if (usesTextureArray)
  4865. {
  4866. bx::write(&writer, "#extension GL_EXT_texture_array : enable\n");
  4867. if (BX_ENABLED(BX_PLATFORM_OSX) )
  4868. {
  4869. bx::write(&writer, "#define texture2DArrayLodEXT texture2DArray\n");
  4870. }
  4871. else
  4872. {
  4873. bx::write(&writer, "#define texture2DArrayLodEXT texture2DArrayLod\n");
  4874. }
  4875. }
  4876. if (usesTexture3D)
  4877. {
  4878. bx::write(&writer, "#define texture3DEXT texture3D\n");
  4879. if (BX_ENABLED(BX_PLATFORM_OSX) )
  4880. {
  4881. bx::write(&writer, "#define texture3DLodEXT texture3D\n");
  4882. }
  4883. else
  4884. {
  4885. bx::write(&writer, "#define texture3DLodEXT texture3DLod\n");
  4886. }
  4887. }
  4888. if (130 <= version)
  4889. {
  4890. if (m_type == GL_FRAGMENT_SHADER)
  4891. {
  4892. bx::write(&writer, "#define varying in\n");
  4893. }
  4894. else
  4895. {
  4896. bx::write(&writer, "#define attribute in\n");
  4897. bx::write(&writer, "#define varying out\n");
  4898. }
  4899. uint32_t fragData = 0;
  4900. if (!bx::findIdentifierMatch(code, "gl_FragData").isEmpty() )
  4901. {
  4902. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4903. {
  4904. char tmpFragData[16];
  4905. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4906. fragData = bx::uint32_max(fragData, bx::strFind(code, tmpFragData).isEmpty() ? 0 : ii+1);
  4907. }
  4908. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4909. }
  4910. if (0 != fragData)
  4911. {
  4912. bx::write(&writer, &err, "out vec4 bgfx_FragData[%d];\n", fragData);
  4913. bx::write(&writer, "#define gl_FragData bgfx_FragData\n");
  4914. }
  4915. else
  4916. {
  4917. bx::write(&writer, "out vec4 bgfx_FragColor;\n");
  4918. bx::write(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4919. }
  4920. }
  4921. else
  4922. {
  4923. if (m_type == GL_FRAGMENT_SHADER)
  4924. {
  4925. bx::write(&writer, "#define in varying\n");
  4926. }
  4927. else
  4928. {
  4929. bx::write(&writer
  4930. , "#define in attribute\n"
  4931. "#define out varying\n"
  4932. );
  4933. }
  4934. }
  4935. bx::write(&writer,
  4936. "#define lowp\n"
  4937. "#define mediump\n"
  4938. "#define highp\n"
  4939. );
  4940. if (!usesInterpQ)
  4941. {
  4942. bx::write(&writer,
  4943. "#define centroid\n"
  4944. "#define flat\n"
  4945. "#define noperspective\n"
  4946. "#define smooth\n"
  4947. );
  4948. }
  4949. bx::write(&writer, code);
  4950. bx::write(&writer, '\0');
  4951. }
  4952. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  4953. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4954. {
  4955. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4956. {
  4957. bx::write(&writer, &err
  4958. , "#version 300 es\n"
  4959. "precision %s float;\n"
  4960. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  4961. );
  4962. }
  4963. else
  4964. {
  4965. bx::write(&writer, "#version 140\n");
  4966. }
  4967. bx::write(&writer
  4968. , "#define texture2DLod textureLod\n"
  4969. "#define texture3DLod textureLod\n"
  4970. "#define textureCubeLod textureLod\n"
  4971. "#define texture2DGrad textureGrad\n"
  4972. "#define texture3DGrad textureGrad\n"
  4973. "#define textureCubeGrad textureGrad\n"
  4974. );
  4975. if (m_type == GL_FRAGMENT_SHADER)
  4976. {
  4977. bx::write(&writer
  4978. , "#define varying in\n"
  4979. "#define texture2D texture\n"
  4980. "#define texture2DProj textureProj\n"
  4981. );
  4982. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4983. {
  4984. bx::write(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4985. bx::write(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  4986. }
  4987. else
  4988. {
  4989. bx::write(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4990. bx::write(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  4991. }
  4992. bx::write(&writer, "#define texture3D texture\n");
  4993. bx::write(&writer, "#define textureCube texture\n");
  4994. uint32_t fragData = 0;
  4995. if (!bx::findIdentifierMatch(code, "gl_FragData").isEmpty() )
  4996. {
  4997. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4998. {
  4999. char tmpFragData[16];
  5000. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  5001. fragData = bx::max(fragData, bx::strFind(code, tmpFragData).isEmpty() ? 0 : ii+1);
  5002. }
  5003. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  5004. }
  5005. if (!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering").isEmpty() )
  5006. {
  5007. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  5008. {
  5009. bx::write(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  5010. }
  5011. else
  5012. {
  5013. bx::write(&writer, "#define beginFragmentShaderOrdering()\n");
  5014. }
  5015. }
  5016. if (!bx::findIdentifierMatch(code, s_ARB_texture_multisample).isEmpty() )
  5017. {
  5018. bx::write(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  5019. }
  5020. if (0 != fragData)
  5021. {
  5022. bx::write(&writer, &err, "out vec4 bgfx_FragData[%d];\n", fragData);
  5023. bx::write(&writer, "#define gl_FragData bgfx_FragData\n");
  5024. }
  5025. else
  5026. {
  5027. bx::write(&writer
  5028. , "out vec4 bgfx_FragColor;\n"
  5029. "#define gl_FragColor bgfx_FragColor\n"
  5030. );
  5031. }
  5032. }
  5033. else
  5034. {
  5035. bx::write(&writer
  5036. , "#define attribute in\n"
  5037. "#define varying out\n"
  5038. );
  5039. }
  5040. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  5041. {
  5042. bx::write(&writer
  5043. , "#define lowp\n"
  5044. "#define mediump\n"
  5045. "#define highp\n"
  5046. );
  5047. }
  5048. bx::write(&writer, code.getPtr(), code.getLength() );
  5049. bx::write(&writer, '\0');
  5050. }
  5051. code.set(temp);
  5052. }
  5053. else if (GL_COMPUTE_SHADER == m_type)
  5054. {
  5055. int32_t codeLen = (int32_t)bx::strLen(code);
  5056. int32_t tempLen = codeLen + (4<<10);
  5057. char* temp = (char*)alloca(tempLen);
  5058. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  5059. bx::write(&writer
  5060. , "#version 430\n"
  5061. "#define texture2DLod textureLod\n"
  5062. "#define texture2DLodOffset textureLodOffset\n"
  5063. "#define texture2DArrayLod textureLod\n"
  5064. "#define texture2DArrayLodOffset textureLodOffset\n"
  5065. "#define texture3DLod textureLod\n"
  5066. "#define textureCubeLod textureLod\n"
  5067. "#define texture2DGrad textureGrad\n"
  5068. "#define texture3DGrad textureGrad\n"
  5069. "#define textureCubeGrad textureGrad\n"
  5070. );
  5071. bx::write(&writer, code.getPtr()+bx::strLen("#version 430"), codeLen);
  5072. bx::write(&writer, '\0');
  5073. code = temp;
  5074. }
  5075. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  5076. GL_CHECK(glCompileShader(m_id) );
  5077. GLint compiled = 0;
  5078. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  5079. if (0 == compiled)
  5080. {
  5081. LineReader lineReader(code);
  5082. bx::Error err;
  5083. for (int32_t line = 1; err.isOk(); ++line)
  5084. {
  5085. char str[4096];
  5086. int32_t len = bx::read(&lineReader, str, BX_COUNTOF(str)-1, &err);
  5087. if (err.isOk() )
  5088. {
  5089. str[len] = '\0';
  5090. bx::StringView eol = bx::strFindEol(str);
  5091. if (eol.getPtr() != str)
  5092. {
  5093. *const_cast<char*>(eol.getPtr() ) = '\0';
  5094. }
  5095. BX_TRACE("%3d %s", line, str);
  5096. }
  5097. }
  5098. GLsizei len;
  5099. char log[1024];
  5100. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  5101. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  5102. GL_CHECK(glDeleteShader(m_id) );
  5103. m_id = 0;
  5104. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  5105. }
  5106. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  5107. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  5108. && NULL != glGetTranslatedShaderSourceANGLE)
  5109. {
  5110. GLsizei len;
  5111. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  5112. char* source = (char*)alloca(len);
  5113. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  5114. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  5115. }
  5116. }
  5117. }
  5118. void ShaderGL::destroy()
  5119. {
  5120. if (0 != m_id)
  5121. {
  5122. GL_CHECK(glDeleteShader(m_id) );
  5123. m_id = 0;
  5124. }
  5125. }
  5126. void FrameBufferGL::create(uint8_t _num, const Attachment* _attachment)
  5127. {
  5128. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  5129. m_denseIdx = UINT16_MAX;
  5130. m_numTh = _num;
  5131. bx::memCopy(m_attachment, _attachment, _num*sizeof(Attachment) );
  5132. m_needPresent = false;
  5133. postReset();
  5134. }
  5135. void FrameBufferGL::postReset()
  5136. {
  5137. if (0 != m_fbo[0])
  5138. {
  5139. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  5140. bool needResolve = false;
  5141. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  5142. uint32_t colorIdx = 0;
  5143. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5144. {
  5145. const Attachment& at = m_attachment[ii];
  5146. if (isValid(at.handle) )
  5147. {
  5148. const TextureGL& texture = s_renderGL->m_textures[at.handle.idx];
  5149. if (0 == colorIdx)
  5150. {
  5151. m_width = bx::uint32_max(texture.m_width >> at.mip, 1);
  5152. m_height = bx::uint32_max(texture.m_height >> at.mip, 1);
  5153. }
  5154. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5155. bimg::TextureFormat::Enum format = bimg::TextureFormat::Enum(texture.m_textureFormat);
  5156. if (bimg::isDepth(format) )
  5157. {
  5158. const bimg::ImageBlockInfo& info = bimg::getBlockInfo(format);
  5159. if (0 < info.stencilBits)
  5160. {
  5161. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  5162. }
  5163. else if (0 == info.depthBits)
  5164. {
  5165. attachment = GL_STENCIL_ATTACHMENT;
  5166. }
  5167. else
  5168. {
  5169. attachment = GL_DEPTH_ATTACHMENT;
  5170. }
  5171. }
  5172. else
  5173. {
  5174. buffers[colorIdx] = attachment;
  5175. ++colorIdx;
  5176. }
  5177. if (0 != texture.m_rbo)
  5178. {
  5179. #if !(BGFX_CONFIG_RENDERER_OPENGL >= 30 || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  5180. if (GL_DEPTH_STENCIL_ATTACHMENT == attachment)
  5181. {
  5182. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  5183. , GL_DEPTH_ATTACHMENT
  5184. , GL_RENDERBUFFER
  5185. , texture.m_rbo
  5186. ) );
  5187. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  5188. , GL_STENCIL_ATTACHMENT
  5189. , GL_RENDERBUFFER
  5190. , texture.m_rbo
  5191. ) );
  5192. }
  5193. else
  5194. #endif
  5195. {
  5196. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  5197. , attachment
  5198. , GL_RENDERBUFFER
  5199. , texture.m_rbo
  5200. ) );
  5201. }
  5202. }
  5203. else if (Access::Write == at.access)
  5204. {
  5205. if (1 < texture.m_depth
  5206. && !texture.isCubeMap())
  5207. {
  5208. GL_CHECK(glFramebufferTextureLayer(GL_FRAMEBUFFER
  5209. , attachment
  5210. , texture.m_id
  5211. , at.mip
  5212. , at.layer
  5213. ) );
  5214. }
  5215. else
  5216. {
  5217. GLenum target = texture.isCubeMap()
  5218. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + at.layer
  5219. : texture.m_target
  5220. ;
  5221. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5222. , attachment
  5223. , target
  5224. , texture.m_id
  5225. , at.mip
  5226. ) );
  5227. }
  5228. }
  5229. else
  5230. {
  5231. BX_CHECK(false, "");
  5232. }
  5233. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  5234. }
  5235. }
  5236. m_num = uint8_t(colorIdx);
  5237. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  5238. {
  5239. if (0 == colorIdx)
  5240. {
  5241. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5242. {
  5243. // When only depth is attached disable draw buffer to avoid
  5244. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  5245. GL_CHECK(glDrawBuffer(GL_NONE) );
  5246. }
  5247. }
  5248. else
  5249. {
  5250. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  5251. }
  5252. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  5253. GL_CHECK(glReadBuffer(GL_NONE) );
  5254. }
  5255. frameBufferValidate();
  5256. if (needResolve)
  5257. {
  5258. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  5259. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  5260. colorIdx = 0;
  5261. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5262. {
  5263. const Attachment& at = m_attachment[ii];
  5264. if (isValid(at.handle) )
  5265. {
  5266. const TextureGL& texture = s_renderGL->m_textures[at.handle.idx];
  5267. if (0 != texture.m_id)
  5268. {
  5269. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5270. if (!bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) )
  5271. {
  5272. ++colorIdx;
  5273. GLenum target = texture.isCubeMap()
  5274. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + at.layer
  5275. : texture.m_target
  5276. ;
  5277. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5278. , attachment
  5279. , target
  5280. , texture.m_id
  5281. , at.mip
  5282. ) );
  5283. }
  5284. }
  5285. }
  5286. }
  5287. frameBufferValidate();
  5288. }
  5289. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5290. }
  5291. }
  5292. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  5293. {
  5294. BX_UNUSED(_format, _depthFormat);
  5295. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  5296. m_width = _width;
  5297. m_height = _height;
  5298. m_numTh = 0;
  5299. m_denseIdx = _denseIdx;
  5300. m_needPresent = false;
  5301. }
  5302. uint16_t FrameBufferGL::destroy()
  5303. {
  5304. if (0 != m_num)
  5305. {
  5306. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  5307. m_num = 0;
  5308. }
  5309. if (NULL != m_swapChain)
  5310. {
  5311. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  5312. m_swapChain = NULL;
  5313. }
  5314. bx::memSet(m_fbo, 0, sizeof(m_fbo) );
  5315. uint16_t denseIdx = m_denseIdx;
  5316. m_denseIdx = UINT16_MAX;
  5317. m_needPresent = false;
  5318. m_numTh = 0;
  5319. return denseIdx;
  5320. }
  5321. void FrameBufferGL::resolve()
  5322. {
  5323. if (0 != m_fbo[1])
  5324. {
  5325. uint32_t colorIdx = 0;
  5326. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5327. {
  5328. const Attachment& at = m_attachment[ii];
  5329. if (isValid(at.handle) )
  5330. {
  5331. const TextureGL& texture = s_renderGL->m_textures[at.handle.idx];
  5332. bimg::TextureFormat::Enum format = bimg::TextureFormat::Enum(texture.m_textureFormat);
  5333. if (!bimg::isDepth(format) )
  5334. {
  5335. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5336. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  5337. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0 + colorIdx) );
  5338. GL_CHECK(glDrawBuffer(GL_COLOR_ATTACHMENT0 + colorIdx) );
  5339. colorIdx++;
  5340. GL_CHECK(glBlitFramebuffer(0
  5341. , 0
  5342. , m_width
  5343. , m_height
  5344. , 0
  5345. , 0
  5346. , m_width
  5347. , m_height
  5348. , GL_COLOR_BUFFER_BIT
  5349. , GL_LINEAR
  5350. ) );
  5351. }
  5352. }
  5353. }
  5354. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5355. GL_CHECK(glReadBuffer(GL_NONE) );
  5356. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5357. }
  5358. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5359. {
  5360. const Attachment& at = m_attachment[ii];
  5361. if (isValid(at.handle) )
  5362. {
  5363. const TextureGL& texture = s_renderGL->m_textures[at.handle.idx];
  5364. texture.resolve(at.resolve);
  5365. }
  5366. }
  5367. }
  5368. void FrameBufferGL::discard(uint16_t _flags)
  5369. {
  5370. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  5371. uint32_t idx = 0;
  5372. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  5373. {
  5374. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  5375. {
  5376. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  5377. {
  5378. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  5379. }
  5380. }
  5381. }
  5382. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  5383. if (BGFX_CLEAR_NONE != dsFlags)
  5384. {
  5385. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  5386. && (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  5387. {
  5388. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  5389. }
  5390. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  5391. {
  5392. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  5393. }
  5394. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  5395. {
  5396. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  5397. }
  5398. }
  5399. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  5400. }
  5401. void OcclusionQueryGL::create()
  5402. {
  5403. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5404. {
  5405. Query& query = m_query[ii];
  5406. GL_CHECK(glGenQueries(1, &query.m_id) );
  5407. }
  5408. }
  5409. void OcclusionQueryGL::destroy()
  5410. {
  5411. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5412. {
  5413. Query& query = m_query[ii];
  5414. GL_CHECK(glDeleteQueries(1, &query.m_id) );
  5415. }
  5416. }
  5417. void OcclusionQueryGL::begin(Frame* _render, OcclusionQueryHandle _handle)
  5418. {
  5419. while (0 == m_control.reserve(1) )
  5420. {
  5421. resolve(_render, true);
  5422. }
  5423. Query& query = m_query[m_control.m_current];
  5424. GL_CHECK(glBeginQuery(GL_SAMPLES_PASSED, query.m_id) );
  5425. query.m_handle = _handle;
  5426. }
  5427. void OcclusionQueryGL::end()
  5428. {
  5429. GL_CHECK(glEndQuery(GL_SAMPLES_PASSED) );
  5430. m_control.commit(1);
  5431. }
  5432. void OcclusionQueryGL::resolve(Frame* _render, bool _wait)
  5433. {
  5434. while (0 != m_control.available() )
  5435. {
  5436. Query& query = m_query[m_control.m_read];
  5437. if (isValid(query.m_handle) )
  5438. {
  5439. int32_t result;
  5440. if (!_wait)
  5441. {
  5442. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT_AVAILABLE, &result) );
  5443. if (!result)
  5444. {
  5445. break;
  5446. }
  5447. }
  5448. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT, &result) );
  5449. _render->m_occlusion[query.m_handle.idx] = int32_t(result);
  5450. }
  5451. m_control.consume(1);
  5452. }
  5453. }
  5454. void OcclusionQueryGL::invalidate(OcclusionQueryHandle _handle)
  5455. {
  5456. const uint32_t size = m_control.m_size;
  5457. for (uint32_t ii = 0, num = m_control.available(); ii < num; ++ii)
  5458. {
  5459. Query& query = m_query[(m_control.m_read + ii) % size];
  5460. if (query.m_handle.idx == _handle.idx)
  5461. {
  5462. query.m_handle.idx = bgfx::kInvalidHandle;
  5463. }
  5464. }
  5465. }
  5466. void RendererContextGL::submitBlit(BlitState& _bs, uint16_t _view)
  5467. {
  5468. if (m_blitSupported)
  5469. {
  5470. while (_bs.hasItem(_view) )
  5471. {
  5472. const BlitItem& bi = _bs.advance();
  5473. const TextureGL& src = m_textures[bi.m_src.idx];
  5474. const TextureGL& dst = m_textures[bi.m_dst.idx];
  5475. uint32_t srcWidth = bx::uint32_min(src.m_width, bi.m_srcX + bi.m_width) - bi.m_srcX;
  5476. uint32_t srcHeight = bx::uint32_min(src.m_height, bi.m_srcY + bi.m_height) - bi.m_srcY;
  5477. uint32_t srcDepth = bx::uint32_min(src.m_depth, bi.m_srcZ + bi.m_depth) - bi.m_srcZ;
  5478. uint32_t dstWidth = bx::uint32_min(dst.m_width, bi.m_dstX + bi.m_width) - bi.m_dstX;
  5479. uint32_t dstHeight = bx::uint32_min(dst.m_height, bi.m_dstY + bi.m_height) - bi.m_dstY;
  5480. uint32_t dstDepth = bx::uint32_min(dst.m_depth, bi.m_dstZ + bi.m_depth) - bi.m_dstZ;
  5481. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  5482. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  5483. uint32_t depth = bx::uint32_min(srcDepth, dstDepth);
  5484. GL_CHECK(glCopyImageSubData(src.m_id
  5485. , src.m_target
  5486. , bi.m_srcMip
  5487. , bi.m_srcX
  5488. , bi.m_srcY
  5489. , bi.m_srcZ
  5490. , dst.m_id
  5491. , dst.m_target
  5492. , bi.m_dstMip
  5493. , bi.m_dstX
  5494. , bi.m_dstY
  5495. , bi.m_dstZ
  5496. , width
  5497. , height
  5498. , bx::uint32_imax(depth, 1)
  5499. ) );
  5500. }
  5501. }
  5502. }
  5503. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  5504. {
  5505. if (_render->m_capture)
  5506. {
  5507. renderDocTriggerCapture();
  5508. }
  5509. if (1 < m_numWindows
  5510. && m_vaoSupport)
  5511. {
  5512. m_vaoSupport = false;
  5513. GL_CHECK(glBindVertexArray(0) );
  5514. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  5515. m_vao = 0;
  5516. }
  5517. m_glctx.makeCurrent(NULL);
  5518. const GLuint defaultVao = m_vao;
  5519. if (0 != defaultVao)
  5520. {
  5521. GL_CHECK(glBindVertexArray(defaultVao) );
  5522. }
  5523. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  5524. GL_CHECK(glFrontFace(GL_CW) );
  5525. updateResolution(_render->m_resolution);
  5526. int64_t timeBegin = bx::getHPCounter();
  5527. int64_t captureElapsed = 0;
  5528. uint32_t frameQueryIdx = UINT32_MAX;
  5529. if (m_timerQuerySupport
  5530. && !BX_ENABLED(BX_PLATFORM_OSX) )
  5531. {
  5532. frameQueryIdx = m_gpuTimer.begin(BGFX_CONFIG_MAX_VIEWS);
  5533. }
  5534. if (0 < _render->m_iboffset)
  5535. {
  5536. TransientIndexBuffer* ib = _render->m_transientIb;
  5537. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  5538. }
  5539. if (0 < _render->m_vboffset)
  5540. {
  5541. TransientVertexBuffer* vb = _render->m_transientVb;
  5542. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  5543. }
  5544. _render->sort();
  5545. RenderDraw currentState;
  5546. currentState.clear();
  5547. currentState.m_stateFlags = BGFX_STATE_NONE;
  5548. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  5549. RenderBind currentBind;
  5550. currentBind.clear();
  5551. static ViewState viewState;
  5552. viewState.reset(_render);
  5553. ProgramHandle currentProgram = BGFX_INVALID_HANDLE;
  5554. ProgramHandle boundProgram = BGFX_INVALID_HANDLE;
  5555. SortKey key;
  5556. uint16_t view = UINT16_MAX;
  5557. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  5558. BlitState bs(_render);
  5559. int32_t resolutionHeight = _render->m_resolution.height;
  5560. uint32_t blendFactor = 0;
  5561. uint8_t primIndex;
  5562. {
  5563. const uint64_t pt = 0;
  5564. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  5565. }
  5566. PrimInfo prim = s_primInfo[primIndex];
  5567. GL_CHECK(glPolygonMode(GL_FRONT_AND_BACK
  5568. , _render->m_debug&BGFX_DEBUG_WIREFRAME
  5569. ? GL_LINE
  5570. : GL_FILL
  5571. ) );
  5572. bool wasCompute = false;
  5573. bool viewHasScissor = false;
  5574. Rect viewScissorRect;
  5575. viewScissorRect.clear();
  5576. uint16_t discardFlags = BGFX_CLEAR_NONE;
  5577. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  5578. const bool computeSupported = false
  5579. || (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  5580. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  5581. ;
  5582. const uint32_t maxComputeBindings = g_caps.limits.maxComputeBindings;
  5583. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  5584. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  5585. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  5586. uint32_t statsNumIndices = 0;
  5587. uint32_t statsKeyType[2] = {};
  5588. Profiler<TimerQueryGL> profiler(
  5589. _render
  5590. , m_gpuTimer
  5591. , s_viewName
  5592. , m_timerQuerySupport && !BX_ENABLED(BX_PLATFORM_OSX)
  5593. );
  5594. if (m_occlusionQuerySupport)
  5595. {
  5596. m_occlusionQuery.resolve(_render);
  5597. }
  5598. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  5599. {
  5600. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  5601. viewState.m_rect = _render->m_view[0].m_rect;
  5602. int32_t numItems = _render->m_numRenderItems;
  5603. for (int32_t item = 0; item < numItems;)
  5604. {
  5605. const uint64_t encodedKey = _render->m_sortKeys[item];
  5606. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  5607. statsKeyType[isCompute]++;
  5608. const bool viewChanged = 0
  5609. || key.m_view != view
  5610. || item == numItems
  5611. ;
  5612. const uint32_t itemIdx = _render->m_sortValues[item];
  5613. const RenderItem& renderItem = _render->m_renderItem[itemIdx];
  5614. const RenderBind& renderBind = _render->m_renderItemBind[itemIdx];
  5615. ++item;
  5616. if (viewChanged)
  5617. {
  5618. view = key.m_view;
  5619. currentProgram = BGFX_INVALID_HANDLE;
  5620. if (_render->m_view[view].m_fbh.idx != fbh.idx)
  5621. {
  5622. fbh = _render->m_view[view].m_fbh;
  5623. resolutionHeight = _render->m_resolution.height;
  5624. resolutionHeight = setFrameBuffer(fbh, resolutionHeight, discardFlags);
  5625. }
  5626. if (item > 1)
  5627. {
  5628. profiler.end();
  5629. }
  5630. profiler.begin(view);
  5631. viewState.m_rect = _render->m_view[view].m_rect;
  5632. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5633. {
  5634. char* viewName = s_viewName[view];
  5635. viewName[3] = ' ';
  5636. viewName[4] = ' ';
  5637. GL_CHECK(glInsertEventMarker(0, viewName) );
  5638. }
  5639. const Rect& scissorRect = _render->m_view[view].m_scissor;
  5640. viewHasScissor = !scissorRect.isZero();
  5641. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  5642. GL_CHECK(glViewport(viewState.m_rect.m_x
  5643. , resolutionHeight-viewState.m_rect.m_height-viewState.m_rect.m_y
  5644. , viewState.m_rect.m_width
  5645. , viewState.m_rect.m_height
  5646. ) );
  5647. Clear& clear = _render->m_view[view].m_clear;
  5648. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  5649. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  5650. {
  5651. clearQuad(_clearQuad, viewState.m_rect, clear, resolutionHeight, _render->m_colorPalette);
  5652. }
  5653. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5654. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5655. GL_CHECK(glDepthFunc(GL_LESS) );
  5656. GL_CHECK(glEnable(GL_CULL_FACE) );
  5657. GL_CHECK(glDisable(GL_BLEND) );
  5658. submitBlit(bs, view);
  5659. }
  5660. if (isCompute)
  5661. {
  5662. if (!wasCompute)
  5663. {
  5664. wasCompute = true;
  5665. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5666. {
  5667. char* viewName = s_viewName[view];
  5668. viewName[3] = 'C';
  5669. GL_CHECK(glInsertEventMarker(0, viewName) );
  5670. }
  5671. }
  5672. if (computeSupported)
  5673. {
  5674. const RenderCompute& compute = renderItem.compute;
  5675. ProgramGL& program = m_program[key.m_program.idx];
  5676. GL_CHECK(glUseProgram(program.m_id) );
  5677. GLbitfield barrier = 0;
  5678. for (uint32_t ii = 0; ii < maxComputeBindings; ++ii)
  5679. {
  5680. const Binding& bind = renderBind.m_bind[ii];
  5681. if (kInvalidHandle != bind.m_idx)
  5682. {
  5683. switch (bind.m_type)
  5684. {
  5685. case Binding::Texture:
  5686. {
  5687. TextureGL& texture = m_textures[bind.m_idx];
  5688. texture.commit(ii, bind.m_samplerFlags, _render->m_colorPalette);
  5689. }
  5690. break;
  5691. case Binding::Image:
  5692. {
  5693. const TextureGL& texture = m_textures[bind.m_idx];
  5694. GL_CHECK(glBindImageTexture(ii
  5695. , texture.m_id
  5696. , bind.m_mip
  5697. , texture.isCubeMap() || texture.m_target == GL_TEXTURE_2D_ARRAY ? GL_TRUE : GL_FALSE
  5698. , 0
  5699. , s_access[bind.m_access]
  5700. , s_imageFormat[bind.m_format])
  5701. );
  5702. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  5703. }
  5704. break;
  5705. case Binding::IndexBuffer:
  5706. {
  5707. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  5708. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5709. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5710. }
  5711. break;
  5712. case Binding::VertexBuffer:
  5713. {
  5714. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  5715. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5716. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5717. }
  5718. break;
  5719. }
  5720. }
  5721. }
  5722. if (0 != barrier)
  5723. {
  5724. bool constantsChanged = compute.m_uniformBegin < compute.m_uniformEnd;
  5725. rendererUpdateUniforms(this, _render->m_uniformBuffer[compute.m_uniformIdx], compute.m_uniformBegin, compute.m_uniformEnd);
  5726. if (constantsChanged
  5727. && NULL != program.m_constantBuffer)
  5728. {
  5729. commit(*program.m_constantBuffer);
  5730. }
  5731. viewState.setPredefined<1>(this, view, program, _render, compute);
  5732. if (isValid(compute.m_indirectBuffer) )
  5733. {
  5734. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  5735. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  5736. {
  5737. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  5738. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  5739. }
  5740. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  5741. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5742. : compute.m_numIndirect
  5743. ;
  5744. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5745. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  5746. {
  5747. GL_CHECK(glDispatchComputeIndirect( (GLintptr)args) );
  5748. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5749. }
  5750. }
  5751. else
  5752. {
  5753. if (isValid(currentState.m_indirectBuffer) )
  5754. {
  5755. currentState.m_indirectBuffer.idx = kInvalidHandle;
  5756. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  5757. }
  5758. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  5759. }
  5760. GL_CHECK(glMemoryBarrier(barrier) );
  5761. }
  5762. }
  5763. continue;
  5764. }
  5765. bool resetState = viewChanged || wasCompute;
  5766. if (wasCompute)
  5767. {
  5768. wasCompute = false;
  5769. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5770. {
  5771. char* viewName = s_viewName[view];
  5772. viewName[3] = ' ';
  5773. GL_CHECK(glInsertEventMarker(0, viewName) );
  5774. }
  5775. }
  5776. const RenderDraw& draw = renderItem.draw;
  5777. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  5778. {
  5779. const bool occluded = true
  5780. && isValid(draw.m_occlusionQuery)
  5781. && !hasOcclusionQuery
  5782. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) )
  5783. ;
  5784. if (occluded
  5785. || _render->m_frameCache.isZeroArea(viewScissorRect, draw.m_scissor) )
  5786. {
  5787. if (resetState)
  5788. {
  5789. currentState.clear();
  5790. currentState.m_scissor = !draw.m_scissor;
  5791. currentBind.clear();
  5792. }
  5793. continue;
  5794. }
  5795. }
  5796. const uint64_t newFlags = draw.m_stateFlags;
  5797. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  5798. currentState.m_stateFlags = newFlags;
  5799. const uint64_t newStencil = draw.m_stencil;
  5800. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  5801. currentState.m_stencil = newStencil;
  5802. if (resetState)
  5803. {
  5804. currentState.clear();
  5805. currentState.m_scissor = !draw.m_scissor;
  5806. changedFlags = BGFX_STATE_MASK;
  5807. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  5808. currentState.m_stateFlags = newFlags;
  5809. currentState.m_stencil = newStencil;
  5810. currentBind.clear();
  5811. }
  5812. uint16_t scissor = draw.m_scissor;
  5813. if (currentState.m_scissor != scissor)
  5814. {
  5815. currentState.m_scissor = scissor;
  5816. if (UINT16_MAX == scissor)
  5817. {
  5818. if (viewHasScissor)
  5819. {
  5820. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5821. GL_CHECK(glScissor(viewScissorRect.m_x
  5822. , resolutionHeight-viewScissorRect.m_height-viewScissorRect.m_y
  5823. , viewScissorRect.m_width
  5824. , viewScissorRect.m_height
  5825. ) );
  5826. }
  5827. else
  5828. {
  5829. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  5830. }
  5831. }
  5832. else
  5833. {
  5834. Rect scissorRect;
  5835. scissorRect.setIntersect(viewScissorRect, _render->m_frameCache.m_rectCache.m_cache[scissor]);
  5836. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5837. GL_CHECK(glScissor(scissorRect.m_x
  5838. , resolutionHeight-scissorRect.m_height-scissorRect.m_y
  5839. , scissorRect.m_width
  5840. , scissorRect.m_height
  5841. ) );
  5842. }
  5843. }
  5844. if (0 != changedStencil)
  5845. {
  5846. if (0 != newStencil)
  5847. {
  5848. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  5849. uint32_t bstencil = unpackStencil(1, newStencil);
  5850. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  5851. // uint32_t bchanged = unpackStencil(1, changedStencil);
  5852. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  5853. // {
  5854. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5855. // GL_CHECK(glStencilMask(wmask) );
  5856. // }
  5857. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  5858. {
  5859. uint32_t stencil = unpackStencil(ii, newStencil);
  5860. uint32_t changed = unpackStencil(ii, changedStencil);
  5861. GLenum face = s_stencilFace[frontAndBack+ii];
  5862. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  5863. {
  5864. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  5865. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5866. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  5867. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) );
  5868. }
  5869. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  5870. {
  5871. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  5872. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  5873. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  5874. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  5875. }
  5876. }
  5877. }
  5878. else
  5879. {
  5880. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5881. }
  5882. }
  5883. if ( (0
  5884. | BGFX_STATE_CULL_MASK
  5885. | BGFX_STATE_WRITE_Z
  5886. | BGFX_STATE_DEPTH_TEST_MASK
  5887. | BGFX_STATE_WRITE_RGB
  5888. | BGFX_STATE_WRITE_A
  5889. | BGFX_STATE_BLEND_MASK
  5890. | BGFX_STATE_BLEND_EQUATION_MASK
  5891. | BGFX_STATE_ALPHA_REF_MASK
  5892. | BGFX_STATE_PT_MASK
  5893. | BGFX_STATE_POINT_SIZE_MASK
  5894. | BGFX_STATE_MSAA
  5895. | BGFX_STATE_LINEAA
  5896. | BGFX_STATE_CONSERVATIVE_RASTER
  5897. ) & changedFlags)
  5898. {
  5899. if (BGFX_STATE_CULL_MASK & changedFlags)
  5900. {
  5901. if (BGFX_STATE_CULL_CCW & newFlags)
  5902. {
  5903. GL_CHECK(glEnable(GL_CULL_FACE) );
  5904. GL_CHECK(glCullFace(GL_BACK) );
  5905. }
  5906. else if (BGFX_STATE_CULL_CW & newFlags)
  5907. {
  5908. GL_CHECK(glEnable(GL_CULL_FACE) );
  5909. GL_CHECK(glCullFace(GL_FRONT) );
  5910. }
  5911. else
  5912. {
  5913. GL_CHECK(glDisable(GL_CULL_FACE) );
  5914. }
  5915. }
  5916. if (BGFX_STATE_WRITE_Z & changedFlags)
  5917. {
  5918. GL_CHECK(glDepthMask(!!(BGFX_STATE_WRITE_Z & newFlags) ) );
  5919. }
  5920. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  5921. {
  5922. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  5923. if (0 != func)
  5924. {
  5925. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5926. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  5927. }
  5928. else
  5929. {
  5930. if (BGFX_STATE_WRITE_Z & newFlags)
  5931. {
  5932. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5933. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  5934. }
  5935. else
  5936. {
  5937. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  5938. }
  5939. }
  5940. }
  5941. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  5942. {
  5943. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  5944. viewState.m_alphaRef = ref/255.0f;
  5945. }
  5946. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5947. {
  5948. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  5949. {
  5950. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  5951. GL_CHECK(glPointSize(pointSize) );
  5952. }
  5953. if (BGFX_STATE_MSAA & changedFlags)
  5954. {
  5955. GL_CHECK(BGFX_STATE_MSAA & newFlags
  5956. ? glEnable(GL_MULTISAMPLE)
  5957. : glDisable(GL_MULTISAMPLE)
  5958. );
  5959. }
  5960. if (BGFX_STATE_LINEAA & changedFlags)
  5961. {
  5962. GL_CHECK(BGFX_STATE_LINEAA & newFlags
  5963. ? glEnable(GL_LINE_SMOOTH)
  5964. : glDisable(GL_LINE_SMOOTH)
  5965. );
  5966. }
  5967. if (m_conservativeRasterSupport
  5968. && BGFX_STATE_CONSERVATIVE_RASTER & changedFlags)
  5969. {
  5970. GL_CHECK(BGFX_STATE_CONSERVATIVE_RASTER & newFlags
  5971. ? glEnable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5972. : glDisable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5973. );
  5974. }
  5975. }
  5976. if ( (BGFX_STATE_WRITE_A|BGFX_STATE_WRITE_RGB) & changedFlags)
  5977. {
  5978. const GLboolean rr = !!(newFlags&BGFX_STATE_WRITE_R);
  5979. const GLboolean gg = !!(newFlags&BGFX_STATE_WRITE_G);
  5980. const GLboolean bb = !!(newFlags&BGFX_STATE_WRITE_B);
  5981. const GLboolean aa = !!(newFlags&BGFX_STATE_WRITE_A);
  5982. GL_CHECK(glColorMask(rr, gg, bb, aa) );
  5983. }
  5984. if ( ( (0
  5985. | BGFX_STATE_BLEND_MASK
  5986. | BGFX_STATE_BLEND_EQUATION_MASK
  5987. | BGFX_STATE_BLEND_INDEPENDENT
  5988. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  5989. ) & changedFlags)
  5990. || blendFactor != draw.m_rgba)
  5991. {
  5992. if (m_atocSupport)
  5993. {
  5994. if (BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & newFlags)
  5995. {
  5996. GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5997. }
  5998. else
  5999. {
  6000. GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  6001. }
  6002. }
  6003. if ( ( (0
  6004. | BGFX_STATE_BLEND_MASK
  6005. | BGFX_STATE_BLEND_EQUATION_MASK
  6006. | BGFX_STATE_BLEND_INDEPENDENT) & newFlags)
  6007. || blendFactor != draw.m_rgba)
  6008. {
  6009. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  6010. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  6011. && blendIndependentSupported
  6012. ;
  6013. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  6014. const uint32_t srcRGB = (blend )&0xf;
  6015. const uint32_t dstRGB = (blend>> 4)&0xf;
  6016. const uint32_t srcA = (blend>> 8)&0xf;
  6017. const uint32_t dstA = (blend>>12)&0xf;
  6018. const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  6019. const uint32_t equRGB = (equ )&0x7;
  6020. const uint32_t equA = (equ>>3)&0x7;
  6021. const uint32_t numRt = getNumRt();
  6022. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  6023. || 1 >= numRt
  6024. || !independent)
  6025. {
  6026. if (enabled)
  6027. {
  6028. GL_CHECK(glEnable(GL_BLEND) );
  6029. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  6030. , s_blendFactor[dstRGB].m_dst
  6031. , s_blendFactor[srcA].m_src
  6032. , s_blendFactor[dstA].m_dst
  6033. ) );
  6034. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  6035. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  6036. && blendFactor != draw.m_rgba)
  6037. {
  6038. const uint32_t rgba = draw.m_rgba;
  6039. GLclampf rr = ( (rgba>>24) )/255.0f;
  6040. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  6041. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  6042. GLclampf aa = ( (rgba )&0xff)/255.0f;
  6043. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  6044. }
  6045. }
  6046. else
  6047. {
  6048. GL_CHECK(glDisable(GL_BLEND) );
  6049. }
  6050. }
  6051. else
  6052. {
  6053. if (enabled)
  6054. {
  6055. GL_CHECK(glEnablei(GL_BLEND, 0) );
  6056. GL_CHECK(glBlendFuncSeparatei(0
  6057. , s_blendFactor[srcRGB].m_src
  6058. , s_blendFactor[dstRGB].m_dst
  6059. , s_blendFactor[srcA].m_src
  6060. , s_blendFactor[dstA].m_dst
  6061. ) );
  6062. GL_CHECK(glBlendEquationSeparatei(0
  6063. , s_blendEquation[equRGB]
  6064. , s_blendEquation[equA]
  6065. ) );
  6066. }
  6067. else
  6068. {
  6069. GL_CHECK(glDisablei(GL_BLEND, 0) );
  6070. }
  6071. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  6072. {
  6073. if (0 != (rgba&0x7ff) )
  6074. {
  6075. const uint32_t src = (rgba )&0xf;
  6076. const uint32_t dst = (rgba>>4)&0xf;
  6077. const uint32_t equation = (rgba>>8)&0x7;
  6078. GL_CHECK(glEnablei(GL_BLEND, ii) );
  6079. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  6080. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  6081. }
  6082. else
  6083. {
  6084. GL_CHECK(glDisablei(GL_BLEND, ii) );
  6085. }
  6086. }
  6087. }
  6088. }
  6089. else
  6090. {
  6091. GL_CHECK(glDisable(GL_BLEND) );
  6092. }
  6093. blendFactor = draw.m_rgba;
  6094. }
  6095. const uint64_t pt = newFlags&BGFX_STATE_PT_MASK;
  6096. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  6097. prim = s_primInfo[primIndex];
  6098. }
  6099. bool programChanged = false;
  6100. bool constantsChanged = draw.m_uniformBegin < draw.m_uniformEnd;
  6101. bool bindAttribs = false;
  6102. rendererUpdateUniforms(this, _render->m_uniformBuffer[draw.m_uniformIdx], draw.m_uniformBegin, draw.m_uniformEnd);
  6103. if (key.m_program.idx != currentProgram.idx)
  6104. {
  6105. currentProgram = key.m_program;
  6106. GLuint id = isValid(currentProgram) ? m_program[currentProgram.idx].m_id : 0;
  6107. // Skip rendering if program index is valid, but program is invalid.
  6108. currentProgram = 0 == id ? ProgramHandle{kInvalidHandle} : currentProgram;
  6109. GL_CHECK(glUseProgram(id) );
  6110. programChanged =
  6111. constantsChanged =
  6112. bindAttribs = true;
  6113. }
  6114. if (isValid(currentProgram) )
  6115. {
  6116. ProgramGL& program = m_program[currentProgram.idx];
  6117. if (constantsChanged
  6118. && NULL != program.m_constantBuffer)
  6119. {
  6120. commit(*program.m_constantBuffer);
  6121. }
  6122. viewState.setPredefined<1>(this, view, program, _render, draw);
  6123. {
  6124. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  6125. {
  6126. const Binding& bind = renderBind.m_bind[stage];
  6127. Binding& current = currentBind.m_bind[stage];
  6128. if (current.m_idx != bind.m_idx
  6129. || current.m_type != bind.m_type
  6130. || current.m_samplerFlags != bind.m_samplerFlags
  6131. || programChanged)
  6132. {
  6133. if (kInvalidHandle != bind.m_idx)
  6134. {
  6135. switch (bind.m_type)
  6136. {
  6137. case Binding::Texture:
  6138. {
  6139. TextureGL& texture = m_textures[bind.m_idx];
  6140. texture.commit(stage, bind.m_samplerFlags, _render->m_colorPalette);
  6141. }
  6142. break;
  6143. case Binding::IndexBuffer:
  6144. {
  6145. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  6146. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, stage, buffer.m_id) );
  6147. }
  6148. break;
  6149. case Binding::VertexBuffer:
  6150. {
  6151. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  6152. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, stage, buffer.m_id) );
  6153. }
  6154. break;
  6155. }
  6156. }
  6157. }
  6158. current = bind;
  6159. }
  6160. }
  6161. {
  6162. bool diffStreamHandles = false;
  6163. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6164. ; 0 != streamMask
  6165. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6166. )
  6167. {
  6168. streamMask >>= ntz;
  6169. idx += ntz;
  6170. if (currentState.m_stream[idx].m_handle.idx != draw.m_stream[idx].m_handle.idx)
  6171. {
  6172. diffStreamHandles = true;
  6173. break;
  6174. }
  6175. }
  6176. if (programChanged
  6177. || currentState.m_streamMask != draw.m_streamMask
  6178. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  6179. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  6180. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  6181. || diffStreamHandles)
  6182. {
  6183. currentState.m_streamMask = draw.m_streamMask;
  6184. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  6185. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  6186. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  6187. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6188. ; 0 != streamMask
  6189. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6190. )
  6191. {
  6192. streamMask >>= ntz;
  6193. idx += ntz;
  6194. currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle;
  6195. }
  6196. bindAttribs = true;
  6197. }
  6198. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  6199. {
  6200. currentState.m_indexBuffer = draw.m_indexBuffer;
  6201. uint16_t handle = draw.m_indexBuffer.idx;
  6202. if (kInvalidHandle != handle)
  6203. {
  6204. IndexBufferGL& ib = m_indexBuffers[handle];
  6205. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  6206. }
  6207. else
  6208. {
  6209. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  6210. }
  6211. }
  6212. if (0 != currentState.m_streamMask)
  6213. {
  6214. bool diffStartVertex = false;
  6215. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6216. ; 0 != streamMask
  6217. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6218. )
  6219. {
  6220. streamMask >>= ntz;
  6221. idx += ntz;
  6222. if (currentState.m_stream[idx].m_startVertex != draw.m_stream[idx].m_startVertex)
  6223. {
  6224. diffStartVertex = true;
  6225. break;
  6226. }
  6227. }
  6228. if (bindAttribs || diffStartVertex)
  6229. {
  6230. if (isValid(boundProgram) )
  6231. {
  6232. m_program[boundProgram.idx].unbindAttributes();
  6233. boundProgram = BGFX_INVALID_HANDLE;
  6234. }
  6235. boundProgram = currentProgram;
  6236. program.bindAttributesBegin();
  6237. if (UINT8_MAX != draw.m_streamMask)
  6238. {
  6239. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6240. ; 0 != streamMask
  6241. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6242. )
  6243. {
  6244. streamMask >>= ntz;
  6245. idx += ntz;
  6246. currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex;
  6247. const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx];
  6248. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[idx].m_decl.idx : vb.m_decl.idx;
  6249. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  6250. program.bindAttributes(m_vertexDecls[decl], draw.m_stream[idx].m_startVertex);
  6251. }
  6252. }
  6253. program.bindAttributesEnd();
  6254. if (isValid(draw.m_instanceDataBuffer) )
  6255. {
  6256. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  6257. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  6258. }
  6259. }
  6260. }
  6261. }
  6262. if (0 != currentState.m_streamMask)
  6263. {
  6264. uint32_t numVertices = draw.m_numVertices;
  6265. if (UINT32_MAX == numVertices)
  6266. {
  6267. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6268. ; 0 != streamMask
  6269. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6270. )
  6271. {
  6272. streamMask >>= ntz;
  6273. idx += ntz;
  6274. const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx];
  6275. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[idx].m_decl.idx : vb.m_decl.idx;
  6276. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  6277. numVertices = bx::uint32_min(numVertices, vb.m_size/vertexDecl.m_stride);
  6278. }
  6279. }
  6280. uint32_t numIndices = 0;
  6281. uint32_t numPrimsSubmitted = 0;
  6282. uint32_t numInstances = 0;
  6283. uint32_t numPrimsRendered = 0;
  6284. uint32_t numDrawIndirect = 0;
  6285. if (hasOcclusionQuery)
  6286. {
  6287. m_occlusionQuery.begin(_render, draw.m_occlusionQuery);
  6288. }
  6289. if (isValid(draw.m_indirectBuffer) )
  6290. {
  6291. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  6292. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  6293. {
  6294. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  6295. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  6296. }
  6297. if (isValid(draw.m_indexBuffer) )
  6298. {
  6299. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6300. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6301. const GLenum indexFormat = hasIndex16
  6302. ? GL_UNSIGNED_SHORT
  6303. : GL_UNSIGNED_INT
  6304. ;
  6305. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6306. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6307. : draw.m_numIndirect
  6308. ;
  6309. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6310. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  6311. , (void*)args
  6312. , numDrawIndirect
  6313. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6314. ) );
  6315. }
  6316. else
  6317. {
  6318. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6319. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6320. : draw.m_numIndirect
  6321. ;
  6322. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6323. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  6324. , (void*)args
  6325. , numDrawIndirect
  6326. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6327. ) );
  6328. }
  6329. }
  6330. else
  6331. {
  6332. if (isValid(currentState.m_indirectBuffer) )
  6333. {
  6334. currentState.m_indirectBuffer.idx = kInvalidHandle;
  6335. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  6336. }
  6337. if (isValid(draw.m_indexBuffer) )
  6338. {
  6339. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6340. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6341. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  6342. const GLenum indexFormat = hasIndex16
  6343. ? GL_UNSIGNED_SHORT
  6344. : GL_UNSIGNED_INT
  6345. ;
  6346. if (UINT32_MAX == draw.m_numIndices)
  6347. {
  6348. numIndices = ib.m_size/indexSize;
  6349. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6350. numInstances = draw.m_numInstances;
  6351. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6352. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6353. , numIndices
  6354. , indexFormat
  6355. , (void*)0
  6356. , draw.m_numInstances
  6357. ) );
  6358. }
  6359. else if (prim.m_min <= draw.m_numIndices)
  6360. {
  6361. numIndices = draw.m_numIndices;
  6362. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6363. numInstances = draw.m_numInstances;
  6364. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6365. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6366. , numIndices
  6367. , indexFormat
  6368. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  6369. , draw.m_numInstances
  6370. ) );
  6371. }
  6372. }
  6373. else
  6374. {
  6375. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  6376. numInstances = draw.m_numInstances;
  6377. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6378. GL_CHECK(glDrawArraysInstanced(prim.m_type
  6379. , 0
  6380. , numVertices
  6381. , draw.m_numInstances
  6382. ) );
  6383. }
  6384. }
  6385. if (hasOcclusionQuery)
  6386. {
  6387. m_occlusionQuery.end();
  6388. }
  6389. if(isValid(draw.m_instanceDataBuffer))
  6390. {
  6391. program.unbindInstanceData();
  6392. }
  6393. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  6394. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  6395. statsNumInstances[primIndex] += numInstances;
  6396. statsNumIndices += numIndices;
  6397. }
  6398. }
  6399. }
  6400. if (isValid(boundProgram) )
  6401. {
  6402. m_program[boundProgram.idx].unbindAttributes();
  6403. boundProgram = BGFX_INVALID_HANDLE;
  6404. }
  6405. submitBlit(bs, BGFX_CONFIG_MAX_VIEWS);
  6406. blitMsaaFbo();
  6407. if (m_vaoSupport)
  6408. {
  6409. GL_CHECK(glBindVertexArray(m_vao) );
  6410. }
  6411. if (0 < _render->m_numRenderItems)
  6412. {
  6413. if (0 != (m_resolution.reset & BGFX_RESET_FLUSH_AFTER_RENDER) )
  6414. {
  6415. GL_CHECK(glFlush() );
  6416. }
  6417. captureElapsed = -bx::getHPCounter();
  6418. capture();
  6419. captureElapsed += bx::getHPCounter();
  6420. profiler.end();
  6421. }
  6422. }
  6423. m_glctx.makeCurrent(NULL);
  6424. int64_t timeEnd = bx::getHPCounter();
  6425. int64_t frameTime = timeEnd - timeBegin;
  6426. static int64_t min = frameTime;
  6427. static int64_t max = frameTime;
  6428. min = min > frameTime ? frameTime : min;
  6429. max = max < frameTime ? frameTime : max;
  6430. static uint32_t maxGpuLatency = 0;
  6431. static double maxGpuElapsed = 0.0f;
  6432. double elapsedGpuMs = 0.0;
  6433. if (UINT32_MAX != frameQueryIdx)
  6434. {
  6435. m_gpuTimer.end(frameQueryIdx);
  6436. const TimerQueryGL::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS];
  6437. double toGpuMs = 1000.0 / 1e9;
  6438. elapsedGpuMs = (result.m_end - result.m_begin) * toGpuMs;
  6439. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  6440. maxGpuLatency = bx::uint32_imax(maxGpuLatency, result.m_pending-1);
  6441. }
  6442. const int64_t timerFreq = bx::getHPFrequency();
  6443. Stats& perfStats = _render->m_perfStats;
  6444. perfStats.cpuTimeBegin = timeBegin;
  6445. perfStats.cpuTimeEnd = timeEnd;
  6446. perfStats.cpuTimerFreq = timerFreq;
  6447. const TimerQueryGL::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS];
  6448. perfStats.gpuTimeBegin = result.m_begin;
  6449. perfStats.gpuTimeEnd = result.m_end;
  6450. perfStats.gpuTimerFreq = 1000000000;
  6451. perfStats.numDraw = statsKeyType[0];
  6452. perfStats.numCompute = statsKeyType[1];
  6453. perfStats.numBlit = _render->m_numBlitItems;
  6454. perfStats.maxGpuLatency = maxGpuLatency;
  6455. bx::memCopy(perfStats.numPrims, statsNumPrimsRendered, sizeof(perfStats.numPrims) );
  6456. perfStats.gpuMemoryMax = -INT64_MAX;
  6457. perfStats.gpuMemoryUsed = -INT64_MAX;
  6458. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  6459. {
  6460. m_needPresent = true;
  6461. TextVideoMem& tvm = m_textVideoMem;
  6462. static int64_t next = timeEnd;
  6463. if (timeEnd >= next)
  6464. {
  6465. next = timeEnd + timerFreq;
  6466. double freq = double(timerFreq);
  6467. double toMs = 1000.0/freq;
  6468. tvm.clear();
  6469. uint16_t pos = 0;
  6470. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x8c : 0x8f
  6471. , " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  6472. , getRendererName()
  6473. );
  6474. tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor);
  6475. tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer);
  6476. tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version);
  6477. tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion);
  6478. char processMemoryUsed[16];
  6479. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  6480. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  6481. pos = 10;
  6482. tvm.printf(10, pos++, 0x8b, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  6483. , double(frameTime)*toMs
  6484. , double(min)*toMs
  6485. , double(max)*toMs
  6486. , freq/frameTime
  6487. );
  6488. const uint32_t msaa = (m_resolution.reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  6489. tvm.printf(10, pos++, 0x8b, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  6490. , !!(m_resolution.reset&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  6491. , 0 != msaa ? '\xfe' : ' '
  6492. , 1<<msaa
  6493. , !!(m_resolution.reset&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  6494. );
  6495. double elapsedCpuMs = double(frameTime)*toMs;
  6496. tvm.printf(10, pos++, 0x8b, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) "
  6497. , _render->m_numRenderItems
  6498. , statsKeyType[0]
  6499. , statsKeyType[1]
  6500. , elapsedCpuMs
  6501. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  6502. , maxGpuElapsed
  6503. , maxGpuLatency
  6504. );
  6505. maxGpuLatency = 0;
  6506. maxGpuElapsed = 0.0;
  6507. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  6508. {
  6509. tvm.printf(10, pos++, 0x8b, " %10s: %7d (#inst: %5d), submitted: %7d "
  6510. , getName(Topology::Enum(ii) )
  6511. , statsNumPrimsRendered[ii]
  6512. , statsNumInstances[ii]
  6513. , statsNumPrimsSubmitted[ii]
  6514. );
  6515. }
  6516. if (NULL != m_renderdocdll)
  6517. {
  6518. tvm.printf(tvm.m_width-27, 0, 0x4f, " [F11 - RenderDoc capture] ");
  6519. }
  6520. tvm.printf(10, pos++, 0x8b, " Indices: %7d ", statsNumIndices);
  6521. // tvm.printf(10, pos++, 0x8b, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  6522. tvm.printf(10, pos++, 0x8b, " DVB size: %7d ", _render->m_vboffset);
  6523. tvm.printf(10, pos++, 0x8b, " DIB size: %7d ", _render->m_iboffset);
  6524. pos++;
  6525. tvm.printf(10, pos++, 0x8b, " State cache: ");
  6526. tvm.printf(10, pos++, 0x8b, " Sampler ");
  6527. tvm.printf(10, pos++, 0x8b, " %6d "
  6528. , m_samplerStateCache.getCount()
  6529. );
  6530. #if BGFX_CONFIG_RENDERER_OPENGL
  6531. if (s_extension[Extension::ATI_meminfo].m_supported)
  6532. {
  6533. GLint vboFree[4];
  6534. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  6535. GLint texFree[4];
  6536. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  6537. GLint rbfFree[4];
  6538. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  6539. pos++;
  6540. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb ");
  6541. char tmp0[16];
  6542. char tmp1[16];
  6543. char tmp2[16];
  6544. char tmp3[16];
  6545. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  6546. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  6547. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  6548. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  6549. tvm.printf(10, pos++, 0x8b, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6550. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  6551. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  6552. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  6553. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  6554. tvm.printf(10, pos++, 0x8b, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6555. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  6556. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  6557. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  6558. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  6559. tvm.printf(10, pos++, 0x8b, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6560. }
  6561. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  6562. {
  6563. GLint dedicated;
  6564. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  6565. GLint totalAvail;
  6566. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  6567. GLint currAvail;
  6568. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  6569. GLint evictedCount;
  6570. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  6571. GLint evictedMemory;
  6572. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  6573. pos++;
  6574. char tmp0[16];
  6575. char tmp1[16];
  6576. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  6577. tvm.printf(10, pos++, 0x8b, " Dedicated: %10s ", tmp0);
  6578. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  6579. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  6580. tvm.printf(10, pos++, 0x8b, " Available: %10s / %10s ", tmp0, tmp1);
  6581. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  6582. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  6583. tvm.printf(10, pos++, 0x8b, " Eviction: %10s / %10s ", tmp0, tmp1);
  6584. }
  6585. #endif // BGFX_CONFIG_RENDERER_OPENGL
  6586. pos++;
  6587. double captureMs = double(captureElapsed)*toMs;
  6588. tvm.printf(10, pos++, 0x8b, " Capture: %7.4f [ms] ", captureMs);
  6589. uint8_t attr[2] = { 0x8c, 0x8a };
  6590. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  6591. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs);
  6592. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs);
  6593. min = frameTime;
  6594. max = frameTime;
  6595. }
  6596. blit(this, _textVideoMemBlitter, tvm);
  6597. }
  6598. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  6599. {
  6600. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  6601. }
  6602. }
  6603. } } // namespace bgfx
  6604. #else
  6605. namespace bgfx { namespace gl
  6606. {
  6607. RendererContextI* rendererCreate(const Init& _init)
  6608. {
  6609. BX_UNUSED(_init);
  6610. return NULL;
  6611. }
  6612. void rendererDestroy()
  6613. {
  6614. }
  6615. } /* namespace gl */ } // namespace bgfx
  6616. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)