renderer_gl.cpp 215 KB

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