renderer_gl.cpp 225 KB

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