renderer_gl.cpp 257 KB

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