renderer_gl.cpp 201 KB

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