renderer_gl.cpp 228 KB

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