renderer_gl.cpp 257 KB

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