renderer_gl.cpp 236 KB

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