renderer_gl.cpp 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. namespace bgfx { namespace gl
  11. {
  12. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  13. struct PrimInfo
  14. {
  15. GLenum m_type;
  16. uint32_t m_min;
  17. uint32_t m_div;
  18. uint32_t m_sub;
  19. };
  20. static const PrimInfo s_primInfo[] =
  21. {
  22. { GL_TRIANGLES, 3, 3, 0 },
  23. { GL_TRIANGLE_STRIP, 3, 1, 2 },
  24. { GL_LINES, 2, 2, 0 },
  25. { GL_LINE_STRIP, 2, 1, 1 },
  26. { GL_POINTS, 1, 1, 0 },
  27. };
  28. static const char* s_primName[] =
  29. {
  30. "TriList",
  31. "TriStrip",
  32. "Line",
  33. "LineStrip",
  34. "Point",
  35. };
  36. static const char* s_attribName[] =
  37. {
  38. "a_position",
  39. "a_normal",
  40. "a_tangent",
  41. "a_bitangent",
  42. "a_color0",
  43. "a_color1",
  44. "a_indices",
  45. "a_weight",
  46. "a_texcoord0",
  47. "a_texcoord1",
  48. "a_texcoord2",
  49. "a_texcoord3",
  50. "a_texcoord4",
  51. "a_texcoord5",
  52. "a_texcoord6",
  53. "a_texcoord7",
  54. };
  55. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  56. static const char* s_instanceDataName[] =
  57. {
  58. "i_data0",
  59. "i_data1",
  60. "i_data2",
  61. "i_data3",
  62. "i_data4",
  63. };
  64. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  65. static const GLenum s_access[] =
  66. {
  67. GL_READ_ONLY,
  68. GL_WRITE_ONLY,
  69. GL_READ_WRITE,
  70. };
  71. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  72. static const GLenum s_attribType[] =
  73. {
  74. GL_UNSIGNED_BYTE,
  75. GL_SHORT,
  76. GL_HALF_FLOAT,
  77. GL_FLOAT,
  78. };
  79. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  80. struct Blend
  81. {
  82. GLenum m_src;
  83. GLenum m_dst;
  84. bool m_factor;
  85. };
  86. static const Blend s_blendFactor[] =
  87. {
  88. { 0, 0, false }, // ignored
  89. { GL_ZERO, GL_ZERO, false }, // ZERO
  90. { GL_ONE, GL_ONE, false }, // ONE
  91. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  92. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  93. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  94. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  95. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  96. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  97. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  98. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  99. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  100. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  101. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  102. };
  103. static const GLenum s_blendEquation[] =
  104. {
  105. GL_FUNC_ADD,
  106. GL_FUNC_SUBTRACT,
  107. GL_FUNC_REVERSE_SUBTRACT,
  108. GL_MIN,
  109. GL_MAX,
  110. };
  111. static const GLenum s_cmpFunc[] =
  112. {
  113. 0, // ignored
  114. GL_LESS,
  115. GL_LEQUAL,
  116. GL_EQUAL,
  117. GL_GEQUAL,
  118. GL_GREATER,
  119. GL_NOTEQUAL,
  120. GL_NEVER,
  121. GL_ALWAYS,
  122. };
  123. static const GLenum s_stencilOp[] =
  124. {
  125. GL_ZERO,
  126. GL_KEEP,
  127. GL_REPLACE,
  128. GL_INCR_WRAP,
  129. GL_INCR,
  130. GL_DECR_WRAP,
  131. GL_DECR,
  132. GL_INVERT,
  133. };
  134. static const GLenum s_stencilFace[] =
  135. {
  136. GL_FRONT_AND_BACK,
  137. GL_FRONT,
  138. GL_BACK,
  139. };
  140. static const GLenum s_textureAddress[] =
  141. {
  142. GL_REPEAT,
  143. GL_MIRRORED_REPEAT,
  144. GL_CLAMP_TO_EDGE,
  145. };
  146. static const GLenum s_textureFilterMag[] =
  147. {
  148. GL_LINEAR,
  149. GL_NEAREST,
  150. GL_LINEAR,
  151. };
  152. static const GLenum s_textureFilterMin[][3] =
  153. {
  154. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  155. { GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_NEAREST },
  156. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  157. };
  158. struct TextureFormatInfo
  159. {
  160. GLenum m_internalFmt;
  161. GLenum m_fmt;
  162. GLenum m_type;
  163. bool m_supported;
  164. };
  165. static TextureFormatInfo s_textureFormat[] =
  166. {
  167. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  168. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  169. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  170. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  171. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  172. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  173. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  174. { GL_ETC1_RGB8_OES, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  175. { GL_COMPRESSED_RGB8_ETC2, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  176. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  177. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  178. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  179. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  180. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  181. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  182. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  183. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  184. { GL_ZERO, GL_ZERO, GL_ZERO, true }, // Unknown
  185. { GL_ZERO, GL_ZERO, GL_ZERO, true }, // R1
  186. { GL_R8, GL_RED, GL_UNSIGNED_BYTE, true }, // R8
  187. { GL_R16, GL_RED, GL_UNSIGNED_SHORT, true }, // R16
  188. { GL_R16F, GL_RED, GL_HALF_FLOAT, true }, // R16F
  189. { GL_R32UI, GL_RED, GL_UNSIGNED_INT, true }, // R32
  190. { GL_R32F, GL_RED, GL_FLOAT, true }, // R32F
  191. { GL_RG8, GL_RG, GL_UNSIGNED_BYTE, true }, // RG8
  192. { GL_RG16, GL_RG, GL_UNSIGNED_SHORT, true }, // RG16
  193. { GL_RG16F, GL_RG, GL_FLOAT, true }, // RG16F
  194. { GL_RG32UI, GL_RG, GL_UNSIGNED_INT, true }, // RG32
  195. { GL_RG32F, GL_RG, GL_FLOAT, true }, // RG32F
  196. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, true }, // BGRA8
  197. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, true }, // RGBA8
  198. { GL_RGBA16, GL_RGBA, GL_UNSIGNED_BYTE, true }, // RGBA16
  199. { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, true }, // RGBA16F
  200. { GL_RGBA32UI, GL_RGBA, GL_UNSIGNED_INT, true }, // RGBA32
  201. { GL_RGBA32F, GL_RGBA, GL_FLOAT, true }, // RGBA32F
  202. { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, true }, // R5G6B5
  203. { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, true }, // RGBA4
  204. { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, true }, // RGB5A1
  205. { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, true }, // RGB10A2
  206. { GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, true }, // R11G11B10F
  207. { GL_ZERO, GL_ZERO, GL_ZERO, true }, // UnknownDepth
  208. { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  209. { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  210. { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  211. { GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  212. { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  213. { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  214. { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  215. { GL_STENCIL_INDEX8, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  216. };
  217. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  218. static bool s_textureFilter[TextureFormat::Count+1];
  219. static GLenum s_rboFormat[] =
  220. {
  221. GL_ZERO, // BC1
  222. GL_ZERO, // BC2
  223. GL_ZERO, // BC3
  224. GL_ZERO, // BC4
  225. GL_ZERO, // BC5
  226. GL_ZERO, // BC6H
  227. GL_ZERO, // BC7
  228. GL_ZERO, // ETC1
  229. GL_ZERO, // ETC2
  230. GL_ZERO, // ETC2A
  231. GL_ZERO, // ETC2A1
  232. GL_ZERO, // PTC12
  233. GL_ZERO, // PTC14
  234. GL_ZERO, // PTC12A
  235. GL_ZERO, // PTC14A
  236. GL_ZERO, // PTC22
  237. GL_ZERO, // PTC24
  238. GL_ZERO, // Unknown
  239. GL_ZERO, // R1
  240. GL_R8, // R8
  241. GL_R16, // R16
  242. GL_R16F, // R16F
  243. GL_R32UI, // R32
  244. GL_R32F, // R32F
  245. GL_RG8, // RG8
  246. GL_RG16, // RG16
  247. GL_RG16F, // RG16F
  248. GL_RG32UI, // RG32
  249. GL_RG32F, // RG32F
  250. GL_RGBA8, // BGRA8
  251. GL_RGBA8, // RGBA8
  252. GL_RGBA16, // RGBA16
  253. GL_RGBA16F, // RGBA16F
  254. GL_RGBA32UI, // RGBA32
  255. GL_RGBA32F, // RGBA32F
  256. GL_RGB565, // R5G6B5
  257. GL_RGBA4, // RGBA4
  258. GL_RGB5_A1, // RGB5A1
  259. GL_RGB10_A2, // RGB10A2
  260. GL_R11F_G11F_B10F, // R11G11B10F
  261. GL_ZERO, // UnknownDepth
  262. GL_DEPTH_COMPONENT16, // D16
  263. GL_DEPTH_COMPONENT24, // D24
  264. GL_DEPTH24_STENCIL8, // D24S8
  265. GL_DEPTH_COMPONENT32, // D32
  266. GL_DEPTH_COMPONENT32F, // D16F
  267. GL_DEPTH_COMPONENT32F, // D24F
  268. GL_DEPTH_COMPONENT32F, // D32F
  269. GL_STENCIL_INDEX8, // D0S8
  270. };
  271. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  272. static GLenum s_imageFormat[] =
  273. {
  274. GL_ZERO, // BC1
  275. GL_ZERO, // BC2
  276. GL_ZERO, // BC3
  277. GL_ZERO, // BC4
  278. GL_ZERO, // BC5
  279. GL_ZERO, // BC6H
  280. GL_ZERO, // BC7
  281. GL_ZERO, // ETC1
  282. GL_ZERO, // ETC2
  283. GL_ZERO, // ETC2A
  284. GL_ZERO, // ETC2A1
  285. GL_ZERO, // PTC12
  286. GL_ZERO, // PTC14
  287. GL_ZERO, // PTC12A
  288. GL_ZERO, // PTC14A
  289. GL_ZERO, // PTC22
  290. GL_ZERO, // PTC24
  291. GL_ZERO, // Unknown
  292. GL_ZERO, // R1
  293. GL_R8, // R8
  294. GL_R16, // R16
  295. GL_R16F, // R16F
  296. GL_R32UI, // R32
  297. GL_R32F, // R32F
  298. GL_RG8, // RG8
  299. GL_RG16, // RG16
  300. GL_RG16F, // RG16F
  301. GL_RG32UI, // RG32
  302. GL_RG32F, // RG32F
  303. GL_RGBA8, // BGRA8
  304. GL_RGBA8, // RGBA8
  305. GL_RGBA16, // RGBA16
  306. GL_RGBA16F, // RGBA16F
  307. GL_RGBA32UI, // RGBA32
  308. GL_RGBA32F, // RGBA32F
  309. GL_RGB565, // R5G6B5
  310. GL_RGBA4, // RGBA4
  311. GL_RGB5_A1, // RGB5A1
  312. GL_RGB10_A2, // RGB10A2
  313. GL_R11F_G11F_B10F, // R11G11B10F
  314. GL_ZERO, // UnknownDepth
  315. GL_ZERO, // D16
  316. GL_ZERO, // D24
  317. GL_ZERO, // D24S8
  318. GL_ZERO, // D32
  319. GL_ZERO, // D16F
  320. GL_ZERO, // D24F
  321. GL_ZERO, // D32F
  322. GL_ZERO, // D0S8
  323. };
  324. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  325. struct Extension
  326. {
  327. enum Enum
  328. {
  329. AMD_conservative_depth,
  330. ANGLE_depth_texture,
  331. ANGLE_framebuffer_blit,
  332. ANGLE_framebuffer_multisample,
  333. ANGLE_instanced_arrays,
  334. ANGLE_texture_compression_dxt1,
  335. ANGLE_texture_compression_dxt3,
  336. ANGLE_texture_compression_dxt5,
  337. ANGLE_timer_query,
  338. ANGLE_translated_shader_source,
  339. APPLE_texture_format_BGRA8888,
  340. APPLE_texture_max_level,
  341. ARB_compute_shader,
  342. ARB_conservative_depth,
  343. ARB_debug_label,
  344. ARB_debug_output,
  345. ARB_depth_buffer_float,
  346. ARB_depth_clamp,
  347. ARB_draw_buffers_blend,
  348. ARB_draw_instanced,
  349. ARB_ES3_compatibility,
  350. ARB_framebuffer_object,
  351. ARB_framebuffer_sRGB,
  352. ARB_get_program_binary,
  353. ARB_half_float_pixel,
  354. ARB_half_float_vertex,
  355. ARB_instanced_arrays,
  356. ARB_invalidate_subdata,
  357. ARB_map_buffer_range,
  358. ARB_multisample,
  359. ARB_occlusion_query,
  360. ARB_occlusion_query2,
  361. ARB_program_interface_query,
  362. ARB_sampler_objects,
  363. ARB_seamless_cube_map,
  364. ARB_shader_bit_encoding,
  365. ARB_shader_image_load_store,
  366. ARB_shader_storage_buffer_object,
  367. ARB_shader_texture_lod,
  368. ARB_texture_compression_bptc,
  369. ARB_texture_compression_rgtc,
  370. ARB_texture_float,
  371. ARB_texture_multisample,
  372. ARB_texture_rg,
  373. ARB_texture_rgb10_a2ui,
  374. ARB_texture_stencil8,
  375. ARB_texture_storage,
  376. ARB_texture_swizzle,
  377. ARB_timer_query,
  378. ARB_uniform_buffer_object,
  379. ARB_vertex_array_object,
  380. ARB_vertex_type_2_10_10_10_rev,
  381. ATI_meminfo,
  382. CHROMIUM_color_buffer_float_rgb,
  383. CHROMIUM_color_buffer_float_rgba,
  384. CHROMIUM_depth_texture,
  385. CHROMIUM_framebuffer_multisample,
  386. CHROMIUM_texture_compression_dxt3,
  387. CHROMIUM_texture_compression_dxt5,
  388. EXT_bgra,
  389. EXT_blend_color,
  390. EXT_blend_minmax,
  391. EXT_blend_subtract,
  392. EXT_color_buffer_half_float,
  393. EXT_color_buffer_float,
  394. EXT_compressed_ETC1_RGB8_sub_texture,
  395. EXT_debug_label,
  396. EXT_debug_marker,
  397. EXT_discard_framebuffer,
  398. EXT_disjoint_timer_query,
  399. EXT_draw_buffers,
  400. EXT_frag_depth,
  401. EXT_framebuffer_blit,
  402. EXT_framebuffer_object,
  403. EXT_framebuffer_sRGB,
  404. EXT_occlusion_query_boolean,
  405. EXT_packed_float,
  406. EXT_read_format_bgra,
  407. EXT_shader_image_load_store,
  408. EXT_shader_texture_lod,
  409. EXT_shadow_samplers,
  410. EXT_texture_array,
  411. EXT_texture_compression_dxt1,
  412. EXT_texture_compression_latc,
  413. EXT_texture_compression_rgtc,
  414. EXT_texture_compression_s3tc,
  415. EXT_texture_filter_anisotropic,
  416. EXT_texture_format_BGRA8888,
  417. EXT_texture_rg,
  418. EXT_texture_sRGB,
  419. EXT_texture_storage,
  420. EXT_texture_swizzle,
  421. EXT_texture_type_2_10_10_10_REV,
  422. EXT_timer_query,
  423. EXT_unpack_subimage,
  424. GOOGLE_depth_texture,
  425. GREMEDY_string_marker,
  426. GREMEDY_frame_terminator,
  427. IMG_multisampled_render_to_texture,
  428. IMG_read_format,
  429. IMG_shader_binary,
  430. IMG_texture_compression_pvrtc,
  431. IMG_texture_compression_pvrtc2,
  432. IMG_texture_format_BGRA8888,
  433. INTEL_fragment_shader_ordering,
  434. KHR_debug,
  435. MOZ_WEBGL_compressed_texture_s3tc,
  436. MOZ_WEBGL_depth_texture,
  437. NV_draw_buffers,
  438. NVX_gpu_memory_info,
  439. OES_compressed_ETC1_RGB8_texture,
  440. OES_depth24,
  441. OES_depth32,
  442. OES_depth_texture,
  443. OES_fragment_precision_high,
  444. OES_get_program_binary,
  445. OES_required_internalformat,
  446. OES_packed_depth_stencil,
  447. OES_read_format,
  448. OES_rgb8_rgba8,
  449. OES_standard_derivatives,
  450. OES_texture_3D,
  451. OES_texture_float,
  452. OES_texture_float_linear,
  453. OES_texture_npot,
  454. OES_texture_half_float,
  455. OES_texture_half_float_linear,
  456. OES_texture_stencil8,
  457. OES_vertex_array_object,
  458. OES_vertex_half_float,
  459. OES_vertex_type_10_10_10_2,
  460. WEBGL_color_buffer_float,
  461. WEBGL_compressed_texture_etc1,
  462. WEBGL_compressed_texture_s3tc,
  463. WEBGL_compressed_texture_pvrtc,
  464. WEBGL_depth_texture,
  465. WEBGL_draw_buffers,
  466. WEBKIT_EXT_texture_filter_anisotropic,
  467. WEBKIT_WEBGL_compressed_texture_s3tc,
  468. WEBKIT_WEBGL_depth_texture,
  469. Count
  470. };
  471. const char* m_name;
  472. bool m_supported;
  473. bool m_initialize;
  474. };
  475. // Extension registry
  476. //
  477. // ANGLE:
  478. // https://github.com/google/angle/tree/master/extensions
  479. //
  480. // CHROMIUM:
  481. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  482. //
  483. // EGL:
  484. // https://www.khronos.org/registry/egl/extensions/
  485. //
  486. // GL:
  487. // https://www.opengl.org/registry/
  488. //
  489. // GLES:
  490. // https://www.khronos.org/registry/gles/extensions/
  491. //
  492. // WEBGL:
  493. // https://www.khronos.org/registry/webgl/extensions/
  494. //
  495. static Extension s_extension[] =
  496. {
  497. { "AMD_conservative_depth", false, true },
  498. { "ANGLE_depth_texture", false, true },
  499. { "ANGLE_framebuffer_blit", false, true },
  500. { "ANGLE_framebuffer_multisample", false, false },
  501. { "ANGLE_instanced_arrays", false, true },
  502. { "ANGLE_texture_compression_dxt1", false, true },
  503. { "ANGLE_texture_compression_dxt3", false, true },
  504. { "ANGLE_texture_compression_dxt5", false, true },
  505. { "ANGLE_timer_query", false, true },
  506. { "ANGLE_translated_shader_source", false, true },
  507. { "APPLE_texture_format_BGRA8888", false, true },
  508. { "APPLE_texture_max_level", false, true },
  509. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  510. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  511. { "ARB_debug_label", false, true },
  512. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  513. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  514. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  515. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  516. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  517. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  518. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  519. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  520. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  521. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  522. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  523. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  524. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  525. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  526. { "ARB_multisample", false, true },
  527. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  528. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  529. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  530. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  531. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  532. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  533. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  534. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  535. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  536. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  537. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  538. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  539. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  540. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  541. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  542. { "ARB_texture_stencil8", false, true },
  543. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  544. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  545. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  546. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  547. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  548. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  549. { "ATI_meminfo", false, true },
  550. { "CHROMIUM_color_buffer_float_rgb", false, true },
  551. { "CHROMIUM_color_buffer_float_rgba", false, true },
  552. { "CHROMIUM_depth_texture", false, true },
  553. { "CHROMIUM_framebuffer_multisample", false, true },
  554. { "CHROMIUM_texture_compression_dxt3", false, true },
  555. { "CHROMIUM_texture_compression_dxt5", false, true },
  556. { "EXT_bgra", false, true },
  557. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  558. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  559. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  560. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  561. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  562. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  563. { "EXT_debug_label", false, true },
  564. { "EXT_debug_marker", false, true },
  565. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  566. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  567. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  568. { "EXT_frag_depth", false, true }, // GLES2 extension.
  569. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  570. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  571. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  572. { "EXT_occlusion_query_boolean", false, true },
  573. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  574. { "EXT_read_format_bgra", false, true },
  575. { "EXT_shader_image_load_store", false, true },
  576. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  577. { "EXT_shadow_samplers", false, true },
  578. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  579. { "EXT_texture_compression_dxt1", false, true },
  580. { "EXT_texture_compression_latc", false, true },
  581. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  582. { "EXT_texture_compression_s3tc", false, true },
  583. { "EXT_texture_filter_anisotropic", false, true },
  584. { "EXT_texture_format_BGRA8888", false, true },
  585. { "EXT_texture_rg", false, true }, // GLES2 extension.
  586. { "EXT_texture_sRGB", false, true },
  587. { "EXT_texture_storage", false, true },
  588. { "EXT_texture_swizzle", false, true },
  589. { "EXT_texture_type_2_10_10_10_REV", false, true },
  590. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  591. { "EXT_unpack_subimage", false, true },
  592. { "GOOGLE_depth_texture", false, true },
  593. { "GREMEDY_string_marker", false, true },
  594. { "GREMEDY_frame_terminator", false, true },
  595. { "IMG_multisampled_render_to_texture", false, true },
  596. { "IMG_read_format", false, true },
  597. { "IMG_shader_binary", false, true },
  598. { "IMG_texture_compression_pvrtc", false, true },
  599. { "IMG_texture_compression_pvrtc2", false, true },
  600. { "IMG_texture_format_BGRA8888", false, true },
  601. { "INTEL_fragment_shader_ordering", false, true },
  602. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  603. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  604. { "MOZ_WEBGL_depth_texture", false, true },
  605. { "NV_draw_buffers", false, true }, // GLES2 extension.
  606. { "NVX_gpu_memory_info", false, true },
  607. { "OES_compressed_ETC1_RGB8_texture", false, true },
  608. { "OES_depth24", false, true },
  609. { "OES_depth32", false, true },
  610. { "OES_depth_texture", false, true },
  611. { "OES_fragment_precision_high", false, true },
  612. { "OES_get_program_binary", false, true },
  613. { "OES_required_internalformat", false, true },
  614. { "OES_packed_depth_stencil", false, true },
  615. { "OES_read_format", false, true },
  616. { "OES_rgb8_rgba8", false, true },
  617. { "OES_standard_derivatives", false, true },
  618. { "OES_texture_3D", false, true },
  619. { "OES_texture_float", false, true },
  620. { "OES_texture_float_linear", false, true },
  621. { "OES_texture_npot", false, true },
  622. { "OES_texture_half_float", false, true },
  623. { "OES_texture_half_float_linear", false, true },
  624. { "OES_texture_stencil8", false, true },
  625. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  626. { "OES_vertex_half_float", false, true },
  627. { "OES_vertex_type_10_10_10_2", false, true },
  628. { "WEBGL_color_buffer_float", false, true },
  629. { "WEBGL_compressed_texture_etc1", false, true },
  630. { "WEBGL_compressed_texture_s3tc", false, true },
  631. { "WEBGL_compressed_texture_pvrtc", false, true },
  632. { "WEBGL_depth_texture", false, true },
  633. { "WEBGL_draw_buffers", false, true },
  634. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  635. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  636. { "WEBKIT_WEBGL_depth_texture", false, true },
  637. };
  638. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  639. static const char* s_ARB_shader_texture_lod[] =
  640. {
  641. "texture2DLod",
  642. "texture2DProjLod",
  643. "texture3DLod",
  644. "texture3DProjLod",
  645. "textureCubeLod",
  646. "shadow2DLod",
  647. "shadow2DProjLod",
  648. NULL
  649. // "texture1DLod",
  650. // "texture1DProjLod",
  651. // "shadow1DLod",
  652. // "shadow1DProjLod",
  653. };
  654. static const char* s_EXT_shader_texture_lod[] =
  655. {
  656. "texture2DLod",
  657. "texture2DProjLod",
  658. "textureCubeLod",
  659. NULL
  660. // "texture2DGrad",
  661. // "texture2DProjGrad",
  662. // "textureCubeGrad",
  663. };
  664. static const char* s_EXT_shadow_samplers[] =
  665. {
  666. "shadow2D",
  667. "shadow2DProj",
  668. NULL
  669. };
  670. static const char* s_OES_standard_derivatives[] =
  671. {
  672. "dFdx",
  673. "dFdy",
  674. "fwidth",
  675. NULL
  676. };
  677. static const char* s_OES_texture_3D[] =
  678. {
  679. "texture3D",
  680. "texture3DProj",
  681. "texture3DLod",
  682. "texture3DProjLod",
  683. NULL
  684. };
  685. static const char* s_uisamplers[] =
  686. {
  687. "isampler2D",
  688. "usampler2D",
  689. "isampler3D",
  690. "usampler3D",
  691. "isamplerCube",
  692. "usamplerCube",
  693. NULL
  694. };
  695. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  696. {
  697. }
  698. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  699. {
  700. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  701. }
  702. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  703. {
  704. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  705. }
  706. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  707. {
  708. }
  709. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  710. {
  711. }
  712. static void GL_APIENTRY stubInsertEventMarkerGREMEDY(GLsizei _length, const char* _marker)
  713. {
  714. // If <marker> is a null-terminated string then <length> should not
  715. // include the terminator.
  716. //
  717. // If <length> is 0 then <marker> is assumed to be null-terminated.
  718. uint32_t size = (0 == _length ? (uint32_t)strlen(_marker) : _length) + 1;
  719. size *= sizeof(wchar_t);
  720. wchar_t* name = (wchar_t*)alloca(size);
  721. mbstowcs(name, _marker, size-2);
  722. GL_CHECK(glStringMarkerGREMEDY(_length, _marker) );
  723. }
  724. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  725. {
  726. }
  727. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  728. {
  729. }
  730. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  731. static const char* getGLString(GLenum _name)
  732. {
  733. const char* str = (const char*)glGetString(_name);
  734. glGetError(); // ignore error if glGetString returns NULL.
  735. if (NULL != str)
  736. {
  737. return str;
  738. }
  739. return "<unknown>";
  740. }
  741. static uint32_t getGLStringHash(GLenum _name)
  742. {
  743. const char* str = (const char*)glGetString(_name);
  744. glGetError(); // ignore error if glGetString returns NULL.
  745. if (NULL != str)
  746. {
  747. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  748. }
  749. return 0;
  750. }
  751. void dumpExtensions(const char* _extensions)
  752. {
  753. if (NULL != _extensions)
  754. {
  755. char name[1024];
  756. const char* pos = _extensions;
  757. const char* end = _extensions + strlen(_extensions);
  758. while (pos < end)
  759. {
  760. uint32_t len;
  761. const char* space = strchr(pos, ' ');
  762. if (NULL != space)
  763. {
  764. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  765. }
  766. else
  767. {
  768. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  769. }
  770. strncpy(name, pos, len);
  771. name[len] = '\0';
  772. BX_TRACE("\t%s", name);
  773. pos += len+1;
  774. }
  775. }
  776. }
  777. const char* toString(GLenum _enum)
  778. {
  779. #if defined(GL_DEBUG_SOURCE_API_ARB)
  780. switch (_enum)
  781. {
  782. case GL_DEBUG_SOURCE_API_ARB: return "API";
  783. case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: return "WinSys";
  784. case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: return "Shader";
  785. case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: return "3rdparty";
  786. case GL_DEBUG_SOURCE_APPLICATION_ARB: return "Application";
  787. case GL_DEBUG_SOURCE_OTHER_ARB: return "Other";
  788. case GL_DEBUG_TYPE_ERROR_ARB: return "Error";
  789. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: return "Deprecated behavior";
  790. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: return "Undefined behavior";
  791. case GL_DEBUG_TYPE_PORTABILITY_ARB: return "Portability";
  792. case GL_DEBUG_TYPE_PERFORMANCE_ARB: return "Performance";
  793. case GL_DEBUG_TYPE_OTHER_ARB: return "Other";
  794. case GL_DEBUG_SEVERITY_HIGH_ARB: return "High";
  795. case GL_DEBUG_SEVERITY_MEDIUM_ARB: return "Medium";
  796. case GL_DEBUG_SEVERITY_LOW_ARB: return "Low";
  797. default:
  798. break;
  799. }
  800. #else
  801. BX_UNUSED(_enum);
  802. #endif // defined(GL_DEBUG_SOURCE_API_ARB)
  803. return "<unknown>";
  804. }
  805. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  806. {
  807. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  808. , toString(_source)
  809. , toString(_type)
  810. , _id
  811. , toString(_severity)
  812. , _message
  813. );
  814. BX_UNUSED(_source, _type, _id, _severity, _message);
  815. }
  816. GLint glGet(GLenum _pname)
  817. {
  818. GLint result = 0;
  819. glGetIntegerv(_pname, &result);
  820. GLenum err = glGetError();
  821. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  822. return 0 == err ? result : 0;
  823. }
  824. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  825. {
  826. TextureFormatInfo& tfi = s_textureFormat[_format];
  827. tfi.m_internalFmt = _internalFmt;
  828. tfi.m_fmt = _fmt;
  829. tfi.m_type = _type;
  830. }
  831. bool isTextureFormatValid(TextureFormat::Enum _format)
  832. {
  833. const TextureFormatInfo& tfi = s_textureFormat[_format];
  834. if (GL_ZERO == tfi.m_internalFmt)
  835. {
  836. return false;
  837. }
  838. GLuint id;
  839. GL_CHECK(glGenTextures(1, &id) );
  840. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  841. GLsizei size = (16*16*getBitsPerPixel(_format) )/8;
  842. void* data = alloca(size);
  843. if (isCompressed(_format) )
  844. {
  845. glCompressedTexImage2D(GL_TEXTURE_2D, 0, tfi.m_internalFmt, 16, 16, 0, size, data);
  846. }
  847. else
  848. {
  849. glTexImage2D(GL_TEXTURE_2D, 0, tfi.m_internalFmt, 16, 16, 0, tfi.m_fmt, tfi.m_type, data);
  850. }
  851. GLenum err = glGetError();
  852. BX_WARN(0 == err, "TextureFormat::%s is not supported (%x: %s).", getName(_format), err, glEnumName(err) );
  853. GL_CHECK(glDeleteTextures(1, &id) );
  854. return 0 == err;
  855. }
  856. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  857. {
  858. const uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  859. const uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  860. const uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  861. _magFilter = s_textureFilterMag[mag];
  862. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  863. }
  864. struct RendererContextGL : public RendererContextI
  865. {
  866. RendererContextGL()
  867. : m_numWindows(1)
  868. , m_rtMsaa(false)
  869. , m_fbDiscard(BGFX_CLEAR_NONE)
  870. , m_capture(NULL)
  871. , m_captureSize(0)
  872. , m_maxAnisotropy(0.0f)
  873. , m_maxAnisotropyDefault(0.0f)
  874. , m_maxMsaa(0)
  875. , m_vao(0)
  876. , m_vaoSupport(false)
  877. , m_samplerObjectSupport(false)
  878. , m_shadowSamplersSupport(false)
  879. , m_programBinarySupport(false)
  880. , m_textureSwizzleSupport(false)
  881. , m_depthTextureSupport(false)
  882. , m_timerQuerySupport(false)
  883. , m_flip(false)
  884. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  885. , m_backBufferFbo(0)
  886. , m_msaaBackBufferFbo(0)
  887. , m_ovrFbo(0)
  888. {
  889. memset(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  890. }
  891. ~RendererContextGL()
  892. {
  893. }
  894. void init()
  895. {
  896. m_renderdocdll = loadRenderDoc();
  897. m_fbh.idx = invalidHandle;
  898. memset(m_uniforms, 0, sizeof(m_uniforms) );
  899. memset(&m_resolution, 0, sizeof(m_resolution) );
  900. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  901. // Must be after context is initialized?!
  902. m_ovr.init();
  903. m_vendor = getGLString(GL_VENDOR);
  904. m_renderer = getGLString(GL_RENDERER);
  905. m_version = getGLString(GL_VERSION);
  906. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  907. GLint numCmpFormats = 0;
  908. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  909. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  910. GLint* cmpFormat = NULL;
  911. if (0 < numCmpFormats)
  912. {
  913. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  914. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  915. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  916. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  917. {
  918. GLint internalFmt = cmpFormat[ii];
  919. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  920. for (uint32_t jj = 0; jj < fmt; ++jj)
  921. {
  922. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  923. {
  924. s_textureFormat[jj].m_supported = true;
  925. fmt = jj;
  926. }
  927. }
  928. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  929. }
  930. }
  931. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  932. {
  933. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  934. BX_TRACE("Defaults:");
  935. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  936. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  937. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  938. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  939. #else
  940. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  941. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  942. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  943. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  944. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  945. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  946. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  947. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  948. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  949. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  950. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  951. #undef GL_GET
  952. BX_TRACE(" Vendor: %s", m_vendor);
  953. BX_TRACE(" Renderer: %s", m_renderer);
  954. BX_TRACE(" Version: %s", m_version);
  955. BX_TRACE("GLSL version: %s", m_glslVersion);
  956. }
  957. // Initial binary shader hash depends on driver version.
  958. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  959. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  960. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  961. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  962. ;
  963. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  964. {
  965. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  966. glGetError(); // ignore error if glGetString returns NULL.
  967. if (NULL != extensions)
  968. {
  969. char name[1024];
  970. const char* pos = extensions;
  971. const char* end = extensions + strlen(extensions);
  972. uint32_t index = 0;
  973. while (pos < end)
  974. {
  975. uint32_t len;
  976. const char* space = strchr(pos, ' ');
  977. if (NULL != space)
  978. {
  979. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  980. }
  981. else
  982. {
  983. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  984. }
  985. strncpy(name, pos, len);
  986. name[len] = '\0';
  987. bool supported = false;
  988. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  989. {
  990. Extension& extension = s_extension[ii];
  991. if (!extension.m_supported
  992. && extension.m_initialize)
  993. {
  994. const char* ext = name;
  995. if (0 == strncmp(ext, "GL_", 3) ) // skip GL_
  996. {
  997. ext += 3;
  998. }
  999. if (0 == strcmp(ext, extension.m_name) )
  1000. {
  1001. extension.m_supported = true;
  1002. supported = true;
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. BX_TRACE("GL_EXTENSION %3d%s: %s", index, supported ? " (supported)" : "", name);
  1008. BX_UNUSED(supported);
  1009. pos += len+1;
  1010. ++index;
  1011. }
  1012. BX_TRACE("Supported extensions:");
  1013. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1014. {
  1015. if (s_extension[ii].m_supported)
  1016. {
  1017. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. // Allow all texture filters.
  1023. memset(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1024. bool bc123Supported = 0
  1025. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1026. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1027. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1028. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1029. ;
  1030. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1031. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1032. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1033. ;
  1034. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1035. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1036. {
  1037. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1038. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1039. {
  1040. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1041. {
  1042. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1043. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1044. break;
  1045. }
  1046. }
  1047. }
  1048. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1049. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1050. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1051. ;
  1052. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1053. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1054. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1055. ;
  1056. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1057. {
  1058. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1059. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1060. }
  1061. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1062. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1063. {
  1064. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1065. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1066. }
  1067. bool etc1Supported = 0
  1068. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1069. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1070. ;
  1071. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1072. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1073. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1074. ;
  1075. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1076. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1077. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1078. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1079. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1080. {
  1081. // When ETC2 is supported override ETC1 texture format settings.
  1082. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1083. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1084. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1085. }
  1086. bool ptc1Supported = 0
  1087. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1088. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1089. ;
  1090. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1091. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1092. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1093. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1094. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1095. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1096. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1097. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1098. {
  1099. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1100. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1101. {
  1102. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1103. if (s_extension[Extension::OES_texture_half_float].m_supported
  1104. || s_extension[Extension::OES_texture_float ].m_supported)
  1105. {
  1106. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1107. // When half/float is available via extensions texture will be marked as
  1108. // incomplete if it uses anything other than nearest filter.
  1109. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1110. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1111. s_textureFilter[TextureFormat::R16F] = linear16F;
  1112. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1113. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1114. s_textureFilter[TextureFormat::R32F] = linear32F;
  1115. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1116. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1117. }
  1118. if (BX_ENABLED(BX_PLATFORM_IOS) )
  1119. {
  1120. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1121. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1122. }
  1123. }
  1124. }
  1125. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1126. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1127. {
  1128. setTextureFormat(TextureFormat::R16, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1129. setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1130. setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1131. setTextureFormat(TextureFormat::R32, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1132. setTextureFormat(TextureFormat::RG32, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1133. setTextureFormat(TextureFormat::RGBA32, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1134. }
  1135. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1136. || s_extension[Extension::EXT_bgra ].m_supported
  1137. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1138. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1139. {
  1140. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1141. {
  1142. m_readPixelsFmt = GL_BGRA;
  1143. }
  1144. s_textureFormat[TextureFormat::BGRA8].m_fmt = GL_BGRA;
  1145. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1146. // APPLE_texture_format_BGRA8888 wants
  1147. // format to be BGRA but internal format to stay RGBA, but
  1148. // EXT_texture_format_BGRA8888 wants both format and internal
  1149. // format to be BGRA.
  1150. //
  1151. // Reference:
  1152. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1153. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  1154. // https://www.khronos.org/registry/gles/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1155. if (!s_extension[Extension::EXT_bgra ].m_supported
  1156. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1157. {
  1158. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1159. }
  1160. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1161. {
  1162. // Revert back to RGBA if texture can't be created.
  1163. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1164. }
  1165. }
  1166. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  1167. || !isTextureFormatValid(TextureFormat::R8) )
  1168. {
  1169. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1170. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1171. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1172. }
  1173. if (!BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) )
  1174. {
  1175. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1176. {
  1177. if (TextureFormat::Unknown != ii
  1178. && TextureFormat::UnknownDepth != ii)
  1179. {
  1180. s_textureFormat[ii].m_supported = isTextureFormatValid( (TextureFormat::Enum)ii);
  1181. }
  1182. }
  1183. }
  1184. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1185. {
  1186. g_caps.formats[ii] = s_textureFormat[ii].m_supported ? 1 : 0;
  1187. }
  1188. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::OES_texture_3D].m_supported
  1189. ? BGFX_CAPS_TEXTURE_3D
  1190. : 0
  1191. ;
  1192. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_shadow_samplers].m_supported
  1193. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  1194. : 0
  1195. ;
  1196. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::OES_vertex_half_float].m_supported
  1197. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  1198. : 0
  1199. ;
  1200. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_frag_depth].m_supported
  1201. ? BGFX_CAPS_FRAGMENT_DEPTH
  1202. : 0
  1203. ;
  1204. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  1205. ? BGFX_CAPS_BLEND_INDEPENDENT
  1206. : 0
  1207. ;
  1208. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  1209. ? BGFX_CAPS_FRAGMENT_ORDERING
  1210. : 0
  1211. ;
  1212. g_caps.maxTextureSize = glGet(GL_MAX_TEXTURE_SIZE);
  1213. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1214. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1215. || s_extension[Extension::EXT_draw_buffers ].m_supported
  1216. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  1217. {
  1218. g_caps.maxFBAttachments = bx::uint32_min(glGet(GL_MAX_COLOR_ATTACHMENTS), BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS);
  1219. }
  1220. m_vaoSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1221. || s_extension[Extension::ARB_vertex_array_object].m_supported
  1222. || s_extension[Extension::OES_vertex_array_object].m_supported
  1223. ;
  1224. if (BX_ENABLED(BX_PLATFORM_NACL) )
  1225. {
  1226. m_vaoSupport &= true
  1227. && NULL != glGenVertexArrays
  1228. && NULL != glDeleteVertexArrays
  1229. && NULL != glBindVertexArray
  1230. ;
  1231. }
  1232. if (m_vaoSupport)
  1233. {
  1234. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  1235. }
  1236. m_samplerObjectSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1237. || s_extension[Extension::ARB_sampler_objects].m_supported
  1238. ;
  1239. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1240. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1241. ;
  1242. m_programBinarySupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1243. || s_extension[Extension::ARB_get_program_binary].m_supported
  1244. || s_extension[Extension::OES_get_program_binary].m_supported
  1245. || s_extension[Extension::IMG_shader_binary ].m_supported
  1246. ;
  1247. m_textureSwizzleSupport = false
  1248. || s_extension[Extension::ARB_texture_swizzle].m_supported
  1249. || s_extension[Extension::EXT_texture_swizzle].m_supported
  1250. ;
  1251. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1252. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  1253. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  1254. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  1255. || s_extension[Extension::OES_depth_texture ].m_supported
  1256. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  1257. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  1258. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  1259. ;
  1260. m_timerQuerySupport = 0
  1261. || s_extension[Extension::ANGLE_timer_query ].m_supported
  1262. || s_extension[Extension::ARB_timer_query ].m_supported
  1263. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  1264. || s_extension[Extension::EXT_timer_query ].m_supported
  1265. ;
  1266. m_timerQuerySupport &= NULL != glGetQueryObjectui64v;
  1267. g_caps.supported |= m_depthTextureSupport
  1268. ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  1269. : 0
  1270. ;
  1271. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1272. || s_extension[Extension::ARB_compute_shader].m_supported
  1273. ? BGFX_CAPS_COMPUTE
  1274. : 0
  1275. ;
  1276. g_caps.supported |= GlContext::isSwapChainSupported()
  1277. ? BGFX_CAPS_SWAP_CHAIN
  1278. : 0
  1279. ;
  1280. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  1281. {
  1282. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  1283. }
  1284. if (s_extension[Extension::ARB_texture_multisample].m_supported
  1285. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  1286. {
  1287. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  1288. }
  1289. if (s_extension[Extension::OES_read_format].m_supported
  1290. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  1291. {
  1292. m_readPixelsFmt = GL_BGRA;
  1293. }
  1294. else
  1295. {
  1296. m_readPixelsFmt = GL_RGBA;
  1297. }
  1298. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1299. {
  1300. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1301. }
  1302. else
  1303. {
  1304. if (!BX_ENABLED(BX_PLATFORM_IOS) )
  1305. {
  1306. if (s_extension[Extension::ARB_instanced_arrays].m_supported
  1307. || s_extension[Extension::ANGLE_instanced_arrays].m_supported)
  1308. {
  1309. if (NULL != glVertexAttribDivisor
  1310. && NULL != glDrawArraysInstanced
  1311. && NULL != glDrawElementsInstanced)
  1312. {
  1313. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1314. }
  1315. }
  1316. }
  1317. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  1318. {
  1319. glVertexAttribDivisor = stubVertexAttribDivisor;
  1320. glDrawArraysInstanced = stubDrawArraysInstanced;
  1321. glDrawElementsInstanced = stubDrawElementsInstanced;
  1322. }
  1323. }
  1324. #if BGFX_CONFIG_RENDERER_OPENGL
  1325. if (s_extension[Extension::ARB_debug_output].m_supported
  1326. || s_extension[Extension::KHR_debug].m_supported)
  1327. {
  1328. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  1329. GL_CHECK(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_TRUE) );
  1330. }
  1331. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  1332. {
  1333. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  1334. }
  1335. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  1336. {
  1337. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  1338. }
  1339. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1340. if (NULL == glFrameTerminatorGREMEDY
  1341. || !s_extension[Extension::GREMEDY_frame_terminator].m_supported)
  1342. {
  1343. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  1344. }
  1345. if (NULL == glInsertEventMarker
  1346. || !s_extension[Extension::EXT_debug_marker].m_supported)
  1347. {
  1348. glInsertEventMarker = (NULL != glStringMarkerGREMEDY && s_extension[Extension::GREMEDY_string_marker].m_supported)
  1349. ? stubInsertEventMarkerGREMEDY
  1350. : stubInsertEventMarker
  1351. ;
  1352. }
  1353. if (NULL == glObjectLabel)
  1354. {
  1355. glObjectLabel = stubObjectLabel;
  1356. }
  1357. if (NULL == glInvalidateFramebuffer)
  1358. {
  1359. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  1360. }
  1361. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1362. && m_timerQuerySupport)
  1363. {
  1364. m_queries.create();
  1365. }
  1366. // Init reserved part of view name.
  1367. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1368. {
  1369. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  1370. }
  1371. ovrPostReset();
  1372. }
  1373. void shutdown()
  1374. {
  1375. ovrPreReset();
  1376. m_ovr.shutdown();
  1377. if (m_vaoSupport)
  1378. {
  1379. GL_CHECK(glBindVertexArray(0) );
  1380. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  1381. m_vao = 0;
  1382. }
  1383. captureFinish();
  1384. invalidateCache();
  1385. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1386. && m_timerQuerySupport)
  1387. {
  1388. m_queries.destroy();
  1389. }
  1390. destroyMsaaFbo();
  1391. m_glctx.destroy();
  1392. m_flip = false;
  1393. unloadRenderDoc(m_renderdocdll);
  1394. }
  1395. RendererType::Enum getRendererType() const BX_OVERRIDE
  1396. {
  1397. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1398. {
  1399. return RendererType::OpenGL;
  1400. }
  1401. return RendererType::OpenGLES;
  1402. }
  1403. const char* getRendererName() const BX_OVERRIDE
  1404. {
  1405. return BGFX_RENDERER_OPENGL_NAME;
  1406. }
  1407. void flip()
  1408. {
  1409. if (m_flip)
  1410. {
  1411. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  1412. {
  1413. m_glctx.swap(m_frameBuffers[m_windows[ii].idx].m_swapChain);
  1414. }
  1415. if (!m_ovr.swap() )
  1416. {
  1417. m_glctx.swap();
  1418. }
  1419. }
  1420. }
  1421. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint8_t /*_flags*/) BX_OVERRIDE
  1422. {
  1423. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  1424. }
  1425. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1426. {
  1427. m_indexBuffers[_handle.idx].destroy();
  1428. }
  1429. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  1430. {
  1431. VertexDecl& decl = m_vertexDecls[_handle.idx];
  1432. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  1433. dump(decl);
  1434. }
  1435. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  1436. {
  1437. }
  1438. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint8_t /*_flags*/) BX_OVERRIDE
  1439. {
  1440. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  1441. }
  1442. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1443. {
  1444. m_vertexBuffers[_handle.idx].destroy();
  1445. }
  1446. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint8_t /*_flags*/) BX_OVERRIDE
  1447. {
  1448. m_indexBuffers[_handle.idx].create(_size, NULL);
  1449. }
  1450. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1451. {
  1452. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1453. }
  1454. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1455. {
  1456. m_indexBuffers[_handle.idx].destroy();
  1457. }
  1458. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint8_t /*_flags*/) BX_OVERRIDE
  1459. {
  1460. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1461. m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  1462. }
  1463. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1464. {
  1465. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1466. }
  1467. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1468. {
  1469. m_vertexBuffers[_handle.idx].destroy();
  1470. }
  1471. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  1472. {
  1473. m_shaders[_handle.idx].create(_mem);
  1474. }
  1475. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  1476. {
  1477. m_shaders[_handle.idx].destroy();
  1478. }
  1479. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  1480. {
  1481. ShaderGL dummyFragmentShader;
  1482. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  1483. }
  1484. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  1485. {
  1486. m_program[_handle.idx].destroy();
  1487. }
  1488. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  1489. {
  1490. m_textures[_handle.idx].create(_mem, _flags, _skip);
  1491. }
  1492. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  1493. {
  1494. }
  1495. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  1496. {
  1497. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1498. }
  1499. void updateTextureEnd() BX_OVERRIDE
  1500. {
  1501. }
  1502. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  1503. {
  1504. m_textures[_handle.idx].destroy();
  1505. }
  1506. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const TextureHandle* _textureHandles) BX_OVERRIDE
  1507. {
  1508. m_frameBuffers[_handle.idx].create(_num, _textureHandles);
  1509. }
  1510. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  1511. {
  1512. uint16_t denseIdx = m_numWindows++;
  1513. m_windows[denseIdx] = _handle;
  1514. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  1515. }
  1516. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  1517. {
  1518. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  1519. if (UINT16_MAX != denseIdx)
  1520. {
  1521. --m_numWindows;
  1522. if (m_numWindows > 1)
  1523. {
  1524. FrameBufferHandle handle = m_windows[m_numWindows];
  1525. m_windows[denseIdx] = handle;
  1526. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  1527. }
  1528. }
  1529. }
  1530. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  1531. {
  1532. if (NULL != m_uniforms[_handle.idx])
  1533. {
  1534. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1535. }
  1536. uint32_t size = g_uniformTypeSize[_type]*_num;
  1537. void* data = BX_ALLOC(g_allocator, size);
  1538. memset(data, 0, size);
  1539. m_uniforms[_handle.idx] = data;
  1540. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  1541. }
  1542. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  1543. {
  1544. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1545. m_uniforms[_handle.idx] = NULL;
  1546. }
  1547. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  1548. {
  1549. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  1550. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  1551. uint32_t width = m_resolution.m_width;
  1552. uint32_t height = m_resolution.m_height;
  1553. GL_CHECK(glReadPixels(0
  1554. , 0
  1555. , width
  1556. , height
  1557. , m_readPixelsFmt
  1558. , GL_UNSIGNED_BYTE
  1559. , data
  1560. ) );
  1561. if (GL_RGBA == m_readPixelsFmt)
  1562. {
  1563. imageSwizzleBgra8(width, height, width*4, data, data);
  1564. }
  1565. g_callback->screenShot(_filePath
  1566. , width
  1567. , height
  1568. , width*4
  1569. , data
  1570. , length
  1571. , true
  1572. );
  1573. BX_FREE(g_allocator, data);
  1574. }
  1575. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  1576. {
  1577. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  1578. {
  1579. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  1580. , _name
  1581. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  1582. );
  1583. }
  1584. }
  1585. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  1586. {
  1587. memcpy(m_uniforms[_loc], _data, _size);
  1588. }
  1589. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  1590. {
  1591. GL_CHECK(glInsertEventMarker(_size, _marker) );
  1592. }
  1593. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  1594. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  1595. {
  1596. if (0 != m_vao)
  1597. {
  1598. GL_CHECK(glBindVertexArray(m_vao) );
  1599. }
  1600. uint32_t width = m_resolution.m_width;
  1601. uint32_t height = m_resolution.m_height;
  1602. if (m_ovr.isEnabled() )
  1603. {
  1604. m_ovr.getSize(width, height);
  1605. }
  1606. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  1607. GL_CHECK(glViewport(0, 0, width, height) );
  1608. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1609. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1610. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1611. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1612. GL_CHECK(glDisable(GL_CULL_FACE) );
  1613. GL_CHECK(glDisable(GL_BLEND) );
  1614. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1615. ProgramGL& program = m_program[_blitter.m_program.idx];
  1616. GL_CHECK(glUseProgram(program.m_id) );
  1617. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  1618. float proj[16];
  1619. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1620. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  1621. , 1
  1622. , GL_FALSE
  1623. , proj
  1624. ) );
  1625. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1626. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  1627. }
  1628. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  1629. {
  1630. const uint32_t numVertices = _numIndices*4/6;
  1631. if (0 < numVertices)
  1632. {
  1633. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  1634. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  1635. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1636. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1637. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  1638. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1639. ProgramGL& program = m_program[_blitter.m_program.idx];
  1640. program.bindAttributes(_blitter.m_decl, 0);
  1641. GL_CHECK(glDrawElements(GL_TRIANGLES
  1642. , _numIndices
  1643. , GL_UNSIGNED_SHORT
  1644. , (void*)0
  1645. ) );
  1646. }
  1647. }
  1648. void updateResolution(const Resolution& _resolution)
  1649. {
  1650. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  1651. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  1652. ? m_maxAnisotropyDefault
  1653. : 0.0f
  1654. ;
  1655. uint32_t flags = _resolution.m_flags & ~(BGFX_RESET_HMD_RECENTER | BGFX_RESET_MAXANISOTROPY);
  1656. if (m_resolution.m_width != _resolution.m_width
  1657. || m_resolution.m_height != _resolution.m_height
  1658. || m_resolution.m_flags != flags)
  1659. {
  1660. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  1661. m_textVideoMem.clear();
  1662. m_resolution = _resolution;
  1663. m_resolution.m_flags = flags;
  1664. uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  1665. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  1666. bool vsync = !!(m_resolution.m_flags&BGFX_RESET_VSYNC);
  1667. setRenderContextSize(_resolution.m_width, _resolution.m_height, msaa, vsync);
  1668. updateCapture();
  1669. ovrPreReset();
  1670. ovrPostReset();
  1671. }
  1672. if (recenter)
  1673. {
  1674. m_ovr.recenter();
  1675. }
  1676. }
  1677. void setShaderUniform4f(uint8_t /*_flags*/, uint16_t _regIndex, const void* _val, uint16_t _numRegs)
  1678. {
  1679. GL_CHECK(glUniform4fv(_regIndex
  1680. , _numRegs
  1681. , (const GLfloat*)_val
  1682. ) );
  1683. }
  1684. void setShaderUniform4x4f(uint8_t /*_flags*/, uint16_t _regIndex, const void* _val, uint16_t _numRegs)
  1685. {
  1686. GL_CHECK(glUniformMatrix4fv(_regIndex
  1687. , _numRegs
  1688. , GL_FALSE
  1689. , (const GLfloat*)_val
  1690. ) );
  1691. }
  1692. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint8_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  1693. {
  1694. if (isValid(m_fbh)
  1695. && m_fbh.idx != _fbh.idx
  1696. && (BGFX_CLEAR_NONE != m_fbDiscard || m_rtMsaa) )
  1697. {
  1698. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  1699. if (m_rtMsaa)
  1700. {
  1701. frameBuffer.resolve();
  1702. }
  1703. if (BGFX_CLEAR_NONE != m_fbDiscard)
  1704. {
  1705. frameBuffer.discard(m_fbDiscard);
  1706. }
  1707. m_fbDiscard = BGFX_CLEAR_NONE;
  1708. }
  1709. m_glctx.makeCurrent(NULL);
  1710. if (!isValid(_fbh) )
  1711. {
  1712. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1713. }
  1714. else
  1715. {
  1716. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  1717. _height = frameBuffer.m_height;
  1718. if (UINT16_MAX != frameBuffer.m_denseIdx)
  1719. {
  1720. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  1721. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1722. }
  1723. else
  1724. {
  1725. m_glctx.makeCurrent(NULL);
  1726. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  1727. }
  1728. }
  1729. m_fbh = _fbh;
  1730. m_fbDiscard = _discard;
  1731. m_rtMsaa = _msaa;
  1732. return _height;
  1733. }
  1734. uint32_t getNumRt() const
  1735. {
  1736. if (isValid(m_fbh) )
  1737. {
  1738. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  1739. return frameBuffer.m_num;
  1740. }
  1741. return 1;
  1742. }
  1743. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  1744. {
  1745. if (0 == m_msaaBackBufferFbo // iOS
  1746. && 1 < _msaa)
  1747. {
  1748. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  1749. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1750. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  1751. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  1752. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  1753. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  1754. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  1755. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  1756. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1757. ? GL_DEPTH_STENCIL_ATTACHMENT
  1758. : GL_DEPTH_ATTACHMENT
  1759. ;
  1760. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  1761. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1762. , "glCheckFramebufferStatus failed 0x%08x"
  1763. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1764. );
  1765. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1766. }
  1767. }
  1768. void destroyMsaaFbo()
  1769. {
  1770. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  1771. && 0 != m_msaaBackBufferFbo)
  1772. {
  1773. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  1774. m_msaaBackBufferFbo = 0;
  1775. if (0 != m_msaaBackBufferRbos[0])
  1776. {
  1777. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  1778. m_msaaBackBufferRbos[0] = 0;
  1779. m_msaaBackBufferRbos[1] = 0;
  1780. }
  1781. }
  1782. }
  1783. void blitMsaaFbo()
  1784. {
  1785. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  1786. && 0 != m_msaaBackBufferFbo)
  1787. {
  1788. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1789. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  1790. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1791. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  1792. uint32_t width = m_resolution.m_width;
  1793. uint32_t height = m_resolution.m_height;
  1794. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  1795. ? GL_NEAREST
  1796. : GL_LINEAR
  1797. ;
  1798. GL_CHECK(glBlitFramebuffer(0
  1799. , 0
  1800. , width
  1801. , height
  1802. , 0
  1803. , 0
  1804. , width
  1805. , height
  1806. , GL_COLOR_BUFFER_BIT
  1807. , filter
  1808. ) );
  1809. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  1810. }
  1811. }
  1812. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _msaa = 0, bool _vsync = false)
  1813. {
  1814. if (_width != 0
  1815. || _height != 0)
  1816. {
  1817. if (!m_glctx.isValid() )
  1818. {
  1819. m_glctx.create(_width, _height);
  1820. #if BX_PLATFORM_IOS
  1821. // iOS: need to figure out how to deal with FBO created by context.
  1822. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  1823. #endif // BX_PLATFORM_IOS
  1824. }
  1825. else
  1826. {
  1827. destroyMsaaFbo();
  1828. m_glctx.resize(_width, _height, _vsync);
  1829. createMsaaFbo(_width, _height, _msaa);
  1830. }
  1831. }
  1832. m_flip = true;
  1833. }
  1834. void invalidateCache()
  1835. {
  1836. if (m_vaoSupport)
  1837. {
  1838. m_vaoStateCache.invalidate();
  1839. }
  1840. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1841. && m_samplerObjectSupport)
  1842. {
  1843. m_samplerStateCache.invalidate();
  1844. }
  1845. }
  1846. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags)
  1847. {
  1848. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1849. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1850. {
  1851. if (0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) )
  1852. {
  1853. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  1854. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  1855. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  1856. GLuint sampler = m_samplerStateCache.find(_flags);
  1857. if (UINT32_MAX == sampler)
  1858. {
  1859. sampler = m_samplerStateCache.add(_flags);
  1860. GL_CHECK(glSamplerParameteri(sampler
  1861. , GL_TEXTURE_WRAP_S
  1862. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  1863. ) );
  1864. GL_CHECK(glSamplerParameteri(sampler
  1865. , GL_TEXTURE_WRAP_T
  1866. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  1867. ) );
  1868. GL_CHECK(glSamplerParameteri(sampler
  1869. , GL_TEXTURE_WRAP_R
  1870. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  1871. ) );
  1872. GLenum minFilter;
  1873. GLenum magFilter;
  1874. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  1875. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  1876. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  1877. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  1878. && 0.0f < m_maxAnisotropy)
  1879. {
  1880. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  1881. }
  1882. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1883. || m_shadowSamplersSupport)
  1884. {
  1885. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  1886. if (0 == cmpFunc)
  1887. {
  1888. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  1889. }
  1890. else
  1891. {
  1892. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  1893. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  1894. }
  1895. }
  1896. }
  1897. GL_CHECK(glBindSampler(_stage, sampler) );
  1898. }
  1899. else
  1900. {
  1901. GL_CHECK(glBindSampler(_stage, 0) );
  1902. }
  1903. }
  1904. }
  1905. void ovrPostReset()
  1906. {
  1907. #if BGFX_CONFIG_USE_OVR
  1908. if (m_resolution.m_flags & (BGFX_RESET_HMD|BGFX_RESET_HMD_DEBUG) )
  1909. {
  1910. ovrGLConfig config;
  1911. config.OGL.Header.API = ovrRenderAPI_OpenGL;
  1912. # if OVR_VERSION > OVR_VERSION_043
  1913. config.OGL.Header.BackBufferSize.w = m_resolution.m_width;
  1914. config.OGL.Header.BackBufferSize.h = m_resolution.m_height;
  1915. # else
  1916. config.OGL.Header.RTSize.w = m_resolution.m_width;
  1917. config.OGL.Header.RTSize.h = m_resolution.m_height;
  1918. # endif // OVR_VERSION > OVR_VERSION_043
  1919. config.OGL.Header.Multisample = 0;
  1920. config.OGL.Window = g_bgfxHwnd;
  1921. config.OGL.DC = GetDC(g_bgfxHwnd);
  1922. if (m_ovr.postReset(g_bgfxHwnd, &config.Config, !!(m_resolution.m_flags & BGFX_RESET_HMD_DEBUG) ) )
  1923. {
  1924. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  1925. const Memory* mem = alloc(size);
  1926. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  1927. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  1928. bx::write(&writer, magic);
  1929. TextureCreate tc;
  1930. tc.m_flags = BGFX_TEXTURE_RT;
  1931. tc.m_width = m_ovr.m_rtSize.w;
  1932. tc.m_height = m_ovr.m_rtSize.h;
  1933. tc.m_sides = 0;
  1934. tc.m_depth = 0;
  1935. tc.m_numMips = 1;
  1936. tc.m_format = uint8_t(bgfx::TextureFormat::BGRA8);
  1937. tc.m_cubeMap = false;
  1938. tc.m_mem = NULL;
  1939. bx::write(&writer, tc);
  1940. m_ovrRT.create(mem, tc.m_flags, 0);
  1941. release(mem);
  1942. m_ovrFbo = m_msaaBackBufferFbo;
  1943. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  1944. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1945. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1946. , GL_COLOR_ATTACHMENT0
  1947. , GL_TEXTURE_2D
  1948. , m_ovrRT.m_id
  1949. , 0
  1950. ) );
  1951. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_ovrFbo) );
  1952. ovrGLTexture texture;
  1953. texture.OGL.Header.API = ovrRenderAPI_OpenGL;
  1954. texture.OGL.Header.TextureSize = m_ovr.m_rtSize;
  1955. texture.OGL.TexId = m_ovrRT.m_id;
  1956. m_ovr.postReset(texture.Texture);
  1957. }
  1958. }
  1959. #endif // BGFX_CONFIG_USE_OVR
  1960. }
  1961. void ovrPreReset()
  1962. {
  1963. #if BGFX_CONFIG_USE_OVR
  1964. m_ovr.preReset();
  1965. if (m_ovr.isEnabled() )
  1966. {
  1967. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1968. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  1969. m_msaaBackBufferFbo = m_ovrFbo;
  1970. m_ovrFbo = 0;
  1971. m_ovrRT.destroy();
  1972. }
  1973. #endif // BGFX_CONFIG_USE_OVR
  1974. }
  1975. void updateCapture()
  1976. {
  1977. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  1978. {
  1979. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  1980. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  1981. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  1982. }
  1983. else
  1984. {
  1985. captureFinish();
  1986. }
  1987. }
  1988. void capture()
  1989. {
  1990. if (NULL != m_capture)
  1991. {
  1992. GL_CHECK(glReadPixels(0
  1993. , 0
  1994. , m_resolution.m_width
  1995. , m_resolution.m_height
  1996. , m_readPixelsFmt
  1997. , GL_UNSIGNED_BYTE
  1998. , m_capture
  1999. ) );
  2000. g_callback->captureFrame(m_capture, m_captureSize);
  2001. }
  2002. }
  2003. void captureFinish()
  2004. {
  2005. if (NULL != m_capture)
  2006. {
  2007. g_callback->captureEnd();
  2008. BX_FREE(g_allocator, m_capture);
  2009. m_capture = NULL;
  2010. m_captureSize = 0;
  2011. }
  2012. }
  2013. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2014. {
  2015. _id ^= m_hash;
  2016. bool cached = false;
  2017. if (m_programBinarySupport)
  2018. {
  2019. uint32_t length = g_callback->cacheReadSize(_id);
  2020. cached = length > 0;
  2021. if (cached)
  2022. {
  2023. void* data = BX_ALLOC(g_allocator, length);
  2024. if (g_callback->cacheRead(_id, data, length) )
  2025. {
  2026. bx::MemoryReader reader(data, length);
  2027. GLenum format;
  2028. bx::read(&reader, format);
  2029. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2030. }
  2031. BX_FREE(g_allocator, data);
  2032. }
  2033. #if BGFX_CONFIG_RENDERER_OPENGL
  2034. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2035. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2036. }
  2037. return cached;
  2038. }
  2039. void programCache(GLuint programId, uint64_t _id)
  2040. {
  2041. _id ^= m_hash;
  2042. if (m_programBinarySupport)
  2043. {
  2044. GLint programLength;
  2045. GLenum format;
  2046. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2047. if (0 < programLength)
  2048. {
  2049. uint32_t length = programLength + 4;
  2050. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2051. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2052. *(uint32_t*)data = format;
  2053. g_callback->cacheWrite(_id, data, length);
  2054. BX_FREE(g_allocator, data);
  2055. }
  2056. }
  2057. }
  2058. void commit(ConstantBuffer& _constantBuffer)
  2059. {
  2060. _constantBuffer.reset();
  2061. for (;;)
  2062. {
  2063. uint32_t opcode = _constantBuffer.read();
  2064. if (UniformType::End == opcode)
  2065. {
  2066. break;
  2067. }
  2068. UniformType::Enum type;
  2069. uint16_t ignore;
  2070. uint16_t num;
  2071. uint16_t copy;
  2072. ConstantBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2073. const char* data;
  2074. if (copy)
  2075. {
  2076. data = _constantBuffer.read(g_uniformTypeSize[type]*num);
  2077. }
  2078. else
  2079. {
  2080. UniformHandle handle;
  2081. memcpy(&handle, _constantBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2082. data = (const char*)m_uniforms[handle.idx];
  2083. }
  2084. uint32_t loc = _constantBuffer.read();
  2085. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2086. case UniformType::_uniform: \
  2087. { \
  2088. _type* value = (_type*)data; \
  2089. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2090. } \
  2091. break;
  2092. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2093. case UniformType::_uniform: \
  2094. { \
  2095. _type* value = (_type*)data; \
  2096. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2097. } \
  2098. break;
  2099. switch (type)
  2100. {
  2101. // case ConstantType::Uniform1iv:
  2102. // {
  2103. // int* value = (int*)data;
  2104. // BX_TRACE("Uniform1iv sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2105. // GL_CHECK(glUniform1iv(loc, num, value) );
  2106. // }
  2107. // break;
  2108. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  2109. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  2110. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  2111. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  2112. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  2113. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  2114. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  2115. CASE_IMPLEMENT_UNIFORM_T(Uniform3x3fv, Matrix3fv, F, float);
  2116. CASE_IMPLEMENT_UNIFORM_T(Uniform4x4fv, Matrix4fv, F, float);
  2117. case UniformType::End:
  2118. break;
  2119. default:
  2120. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _constantBuffer.getPos(), opcode, type, loc, num, copy);
  2121. break;
  2122. }
  2123. #undef CASE_IMPLEMENT_UNIFORM
  2124. #undef CASE_IMPLEMENT_UNIFORM_T
  2125. }
  2126. }
  2127. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2128. {
  2129. uint32_t numMrt = 1;
  2130. FrameBufferHandle fbh = m_fbh;
  2131. if (isValid(fbh) )
  2132. {
  2133. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2134. numMrt = bx::uint32_max(1, fb.m_num);
  2135. }
  2136. if (1 == numMrt)
  2137. {
  2138. GLuint flags = 0;
  2139. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2140. {
  2141. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2142. {
  2143. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[0]);
  2144. const float* rgba = _palette[index];
  2145. const float rr = rgba[0];
  2146. const float gg = rgba[1];
  2147. const float bb = rgba[2];
  2148. const float aa = rgba[3];
  2149. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2150. }
  2151. else
  2152. {
  2153. float rr = _clear.m_index[0]*1.0f/255.0f;
  2154. float gg = _clear.m_index[1]*1.0f/255.0f;
  2155. float bb = _clear.m_index[2]*1.0f/255.0f;
  2156. float aa = _clear.m_index[3]*1.0f/255.0f;
  2157. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2158. }
  2159. flags |= GL_COLOR_BUFFER_BIT;
  2160. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2161. }
  2162. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2163. {
  2164. flags |= GL_DEPTH_BUFFER_BIT;
  2165. GL_CHECK(glClearDepth(_clear.m_depth) );
  2166. GL_CHECK(glDepthMask(GL_TRUE) );
  2167. }
  2168. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2169. {
  2170. flags |= GL_STENCIL_BUFFER_BIT;
  2171. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2172. }
  2173. if (0 != flags)
  2174. {
  2175. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2176. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2177. GL_CHECK(glClear(flags) );
  2178. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2179. }
  2180. }
  2181. else
  2182. {
  2183. const GLuint defaultVao = m_vao;
  2184. if (0 != defaultVao)
  2185. {
  2186. GL_CHECK(glBindVertexArray(defaultVao) );
  2187. }
  2188. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2189. GL_CHECK(glDisable(GL_CULL_FACE) );
  2190. GL_CHECK(glDisable(GL_BLEND) );
  2191. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2192. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2193. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2194. {
  2195. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2196. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2197. GL_CHECK(glDepthMask(GL_TRUE) );
  2198. }
  2199. else
  2200. {
  2201. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2202. }
  2203. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2204. {
  2205. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2206. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2207. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2208. }
  2209. else
  2210. {
  2211. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2212. }
  2213. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2214. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2215. {
  2216. struct Vertex
  2217. {
  2218. float m_x;
  2219. float m_y;
  2220. float m_z;
  2221. };
  2222. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2223. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2224. const float depth = _clear.m_depth;
  2225. vertex->m_x = -1.0f;
  2226. vertex->m_y = -1.0f;
  2227. vertex->m_z = depth;
  2228. vertex++;
  2229. vertex->m_x = 1.0f;
  2230. vertex->m_y = -1.0f;
  2231. vertex->m_z = depth;
  2232. vertex++;
  2233. vertex->m_x = -1.0f;
  2234. vertex->m_y = 1.0f;
  2235. vertex->m_z = depth;
  2236. vertex++;
  2237. vertex->m_x = 1.0f;
  2238. vertex->m_y = 1.0f;
  2239. vertex->m_z = depth;
  2240. }
  2241. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2242. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2243. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2244. GL_CHECK(glUseProgram(program.m_id) );
  2245. program.bindAttributes(vertexDecl, 0);
  2246. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2247. {
  2248. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2249. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2250. {
  2251. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[ii]);
  2252. memcpy(mrtClear[ii], _palette[index], 16);
  2253. }
  2254. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  2255. }
  2256. else
  2257. {
  2258. float rgba[4] =
  2259. {
  2260. _clear.m_index[0]*1.0f/255.0f,
  2261. _clear.m_index[1]*1.0f/255.0f,
  2262. _clear.m_index[2]*1.0f/255.0f,
  2263. _clear.m_index[3]*1.0f/255.0f,
  2264. };
  2265. GL_CHECK(glUniform4fv(0, 1, rgba) );
  2266. }
  2267. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  2268. , 0
  2269. , 4
  2270. ) );
  2271. }
  2272. }
  2273. void* m_renderdocdll;
  2274. uint16_t m_numWindows;
  2275. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2276. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  2277. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  2278. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  2279. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  2280. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  2281. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  2282. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2283. UniformRegistry m_uniformReg;
  2284. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  2285. QueriesGL m_queries;
  2286. VaoStateCache m_vaoStateCache;
  2287. SamplerStateCache m_samplerStateCache;
  2288. TextVideoMem m_textVideoMem;
  2289. bool m_rtMsaa;
  2290. FrameBufferHandle m_fbh;
  2291. uint32_t m_fbDiscard;
  2292. Resolution m_resolution;
  2293. void* m_capture;
  2294. uint32_t m_captureSize;
  2295. float m_maxAnisotropy;
  2296. float m_maxAnisotropyDefault;
  2297. int32_t m_maxMsaa;
  2298. GLuint m_vao;
  2299. bool m_vaoSupport;
  2300. bool m_samplerObjectSupport;
  2301. bool m_shadowSamplersSupport;
  2302. bool m_programBinarySupport;
  2303. bool m_textureSwizzleSupport;
  2304. bool m_depthTextureSupport;
  2305. bool m_timerQuerySupport;
  2306. bool m_flip;
  2307. uint64_t m_hash;
  2308. GLenum m_readPixelsFmt;
  2309. GLuint m_backBufferFbo;
  2310. GLuint m_msaaBackBufferFbo;
  2311. GLuint m_msaaBackBufferRbos[2];
  2312. GlContext m_glctx;
  2313. const char* m_vendor;
  2314. const char* m_renderer;
  2315. const char* m_version;
  2316. const char* m_glslVersion;
  2317. OVR m_ovr;
  2318. TextureGL m_ovrRT;
  2319. GLint m_ovrFbo;
  2320. };
  2321. RendererContextGL* s_renderGL;
  2322. RendererContextI* rendererCreate()
  2323. {
  2324. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  2325. s_renderGL->init();
  2326. return s_renderGL;
  2327. }
  2328. void rendererDestroy()
  2329. {
  2330. s_renderGL->shutdown();
  2331. BX_DELETE(g_allocator, s_renderGL);
  2332. s_renderGL = NULL;
  2333. }
  2334. const char* glslTypeName(GLuint _type)
  2335. {
  2336. #define GLSL_TYPE(_ty) case _ty: return #_ty
  2337. switch (_type)
  2338. {
  2339. GLSL_TYPE(GL_INT);
  2340. GLSL_TYPE(GL_INT_VEC2);
  2341. GLSL_TYPE(GL_INT_VEC3);
  2342. GLSL_TYPE(GL_INT_VEC4);
  2343. GLSL_TYPE(GL_UNSIGNED_INT);
  2344. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  2345. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  2346. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  2347. GLSL_TYPE(GL_FLOAT);
  2348. GLSL_TYPE(GL_FLOAT_VEC2);
  2349. GLSL_TYPE(GL_FLOAT_VEC3);
  2350. GLSL_TYPE(GL_FLOAT_VEC4);
  2351. GLSL_TYPE(GL_FLOAT_MAT2);
  2352. GLSL_TYPE(GL_FLOAT_MAT3);
  2353. GLSL_TYPE(GL_FLOAT_MAT4);
  2354. GLSL_TYPE(GL_SAMPLER_2D);
  2355. GLSL_TYPE(GL_INT_SAMPLER_2D);
  2356. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  2357. GLSL_TYPE(GL_SAMPLER_3D);
  2358. GLSL_TYPE(GL_INT_SAMPLER_3D);
  2359. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  2360. GLSL_TYPE(GL_SAMPLER_CUBE);
  2361. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  2362. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  2363. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  2364. GLSL_TYPE(GL_IMAGE_1D);
  2365. GLSL_TYPE(GL_INT_IMAGE_1D);
  2366. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  2367. GLSL_TYPE(GL_IMAGE_2D);
  2368. GLSL_TYPE(GL_INT_IMAGE_2D);
  2369. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  2370. GLSL_TYPE(GL_IMAGE_3D);
  2371. GLSL_TYPE(GL_INT_IMAGE_3D);
  2372. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  2373. GLSL_TYPE(GL_IMAGE_CUBE);
  2374. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  2375. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  2376. }
  2377. #undef GLSL_TYPE
  2378. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  2379. return "UNKNOWN GLSL TYPE!";
  2380. }
  2381. const char* glEnumName(GLenum _enum)
  2382. {
  2383. #define GLENUM(_ty) case _ty: return #_ty
  2384. switch (_enum)
  2385. {
  2386. GLENUM(GL_TEXTURE);
  2387. GLENUM(GL_RENDERBUFFER);
  2388. GLENUM(GL_INVALID_ENUM);
  2389. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  2390. GLENUM(GL_INVALID_VALUE);
  2391. GLENUM(GL_INVALID_OPERATION);
  2392. GLENUM(GL_OUT_OF_MEMORY);
  2393. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  2394. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  2395. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  2396. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  2397. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  2398. }
  2399. #undef GLENUM
  2400. BX_WARN(false, "Unknown enum? %x", _enum);
  2401. return "<GLenum?>";
  2402. }
  2403. UniformType::Enum convertGlType(GLenum _type)
  2404. {
  2405. switch (_type)
  2406. {
  2407. case GL_INT:
  2408. case GL_UNSIGNED_INT:
  2409. return UniformType::Uniform1iv;
  2410. case GL_FLOAT:
  2411. return UniformType::Uniform1fv;
  2412. case GL_FLOAT_VEC2:
  2413. return UniformType::Uniform2fv;
  2414. case GL_FLOAT_VEC3:
  2415. return UniformType::Uniform3fv;
  2416. case GL_FLOAT_VEC4:
  2417. return UniformType::Uniform4fv;
  2418. case GL_FLOAT_MAT2:
  2419. break;
  2420. case GL_FLOAT_MAT3:
  2421. return UniformType::Uniform3x3fv;
  2422. case GL_FLOAT_MAT4:
  2423. return UniformType::Uniform4x4fv;
  2424. case GL_SAMPLER_2D:
  2425. case GL_INT_SAMPLER_2D:
  2426. case GL_UNSIGNED_INT_SAMPLER_2D:
  2427. case GL_SAMPLER_3D:
  2428. case GL_INT_SAMPLER_3D:
  2429. case GL_UNSIGNED_INT_SAMPLER_3D:
  2430. case GL_SAMPLER_CUBE:
  2431. case GL_INT_SAMPLER_CUBE:
  2432. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2433. case GL_SAMPLER_2D_SHADOW:
  2434. case GL_IMAGE_1D:
  2435. case GL_INT_IMAGE_1D:
  2436. case GL_UNSIGNED_INT_IMAGE_1D:
  2437. case GL_IMAGE_2D:
  2438. case GL_INT_IMAGE_2D:
  2439. case GL_UNSIGNED_INT_IMAGE_2D:
  2440. case GL_IMAGE_3D:
  2441. case GL_INT_IMAGE_3D:
  2442. case GL_UNSIGNED_INT_IMAGE_3D:
  2443. case GL_IMAGE_CUBE:
  2444. case GL_INT_IMAGE_CUBE:
  2445. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2446. return UniformType::Uniform1iv;
  2447. };
  2448. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  2449. return UniformType::End;
  2450. }
  2451. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  2452. {
  2453. m_id = glCreateProgram();
  2454. BX_TRACE("program create: %d: %d, %d", m_id, _vsh.m_id, _fsh.m_id);
  2455. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  2456. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  2457. if (!cached)
  2458. {
  2459. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  2460. if (0 != _fsh.m_id)
  2461. {
  2462. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  2463. }
  2464. GL_CHECK(glLinkProgram(m_id) );
  2465. GLint linked = 0;
  2466. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  2467. if (0 == linked)
  2468. {
  2469. char log[1024];
  2470. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  2471. BX_TRACE("%d: %s", linked, log);
  2472. GL_CHECK(glDeleteProgram(m_id) );
  2473. return;
  2474. }
  2475. s_renderGL->programCache(m_id, id);
  2476. }
  2477. init();
  2478. if (!cached)
  2479. {
  2480. // Must be after init, otherwise init might fail to lookup shader
  2481. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  2482. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  2483. if (0 != _fsh.m_id)
  2484. {
  2485. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  2486. }
  2487. }
  2488. }
  2489. void ProgramGL::destroy()
  2490. {
  2491. if (NULL != m_constantBuffer)
  2492. {
  2493. ConstantBuffer::destroy(m_constantBuffer);
  2494. m_constantBuffer = NULL;
  2495. }
  2496. m_numPredefined = 0;
  2497. if (0 != m_id)
  2498. {
  2499. GL_CHECK(glUseProgram(0) );
  2500. GL_CHECK(glDeleteProgram(m_id) );
  2501. m_id = 0;
  2502. }
  2503. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  2504. }
  2505. void ProgramGL::init()
  2506. {
  2507. GLint activeAttribs = 0;
  2508. GLint activeUniforms = 0;
  2509. GLint activeBuffers = 0;
  2510. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  2511. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  2512. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  2513. if (s_extension[Extension::ARB_program_interface_query].m_supported
  2514. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  2515. {
  2516. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  2517. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  2518. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  2519. }
  2520. else
  2521. {
  2522. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  2523. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  2524. }
  2525. GLint max0, max1;
  2526. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  2527. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  2528. uint32_t maxLength = bx::uint32_max(max0, max1);
  2529. char* name = (char*)alloca(maxLength + 1);
  2530. BX_TRACE("Program %d", m_id);
  2531. BX_TRACE("Attributes (%d):", activeAttribs);
  2532. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  2533. {
  2534. GLint size;
  2535. GLenum type;
  2536. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  2537. BX_TRACE("\t%s %s is at location %d"
  2538. , glslTypeName(type)
  2539. , name
  2540. , glGetAttribLocation(m_id, name)
  2541. );
  2542. }
  2543. m_numPredefined = 0;
  2544. m_numSamplers = 0;
  2545. const bool piqSupported = s_extension[Extension::ARB_program_interface_query].m_supported;
  2546. BX_TRACE("Uniforms (%d):", activeUniforms);
  2547. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  2548. {
  2549. struct VariableInfo
  2550. {
  2551. GLenum type;
  2552. GLint loc;
  2553. GLint num;
  2554. };
  2555. VariableInfo vi;
  2556. GLenum props[] ={ GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  2557. GLenum gltype;
  2558. GLint num;
  2559. GLint loc;
  2560. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  2561. || piqSupported)
  2562. {
  2563. GL_CHECK(glGetProgramResourceiv(m_id
  2564. , GL_UNIFORM
  2565. , ii
  2566. , BX_COUNTOF(props)
  2567. , props
  2568. , BX_COUNTOF(props)
  2569. , NULL
  2570. , (GLint*)&vi
  2571. ) );
  2572. GL_CHECK(glGetProgramResourceName(m_id
  2573. , GL_UNIFORM
  2574. , ii
  2575. , maxLength + 1
  2576. , NULL
  2577. , name
  2578. ) );
  2579. gltype = vi.type;
  2580. loc = vi.loc;
  2581. num = vi.num;
  2582. }
  2583. else
  2584. {
  2585. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  2586. loc = glGetUniformLocation(m_id, name);
  2587. }
  2588. num = bx::uint32_max(num, 1);
  2589. int offset = 0;
  2590. char* array = strchr(name, '[');
  2591. if (NULL != array)
  2592. {
  2593. BX_TRACE("--- %s", name);
  2594. *array = '\0';
  2595. array++;
  2596. char* end = strchr(array, ']');
  2597. *end = '\0';
  2598. offset = atoi(array);
  2599. }
  2600. switch (gltype)
  2601. {
  2602. case GL_SAMPLER_2D:
  2603. case GL_INT_SAMPLER_2D:
  2604. case GL_UNSIGNED_INT_SAMPLER_2D:
  2605. case GL_SAMPLER_3D:
  2606. case GL_INT_SAMPLER_3D:
  2607. case GL_UNSIGNED_INT_SAMPLER_3D:
  2608. case GL_SAMPLER_CUBE:
  2609. case GL_INT_SAMPLER_CUBE:
  2610. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2611. case GL_SAMPLER_2D_SHADOW:
  2612. case GL_IMAGE_1D:
  2613. case GL_INT_IMAGE_1D:
  2614. case GL_UNSIGNED_INT_IMAGE_1D:
  2615. case GL_IMAGE_2D:
  2616. case GL_INT_IMAGE_2D:
  2617. case GL_UNSIGNED_INT_IMAGE_2D:
  2618. case GL_IMAGE_3D:
  2619. case GL_INT_IMAGE_3D:
  2620. case GL_UNSIGNED_INT_IMAGE_3D:
  2621. case GL_IMAGE_CUBE:
  2622. case GL_INT_IMAGE_CUBE:
  2623. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2624. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  2625. m_sampler[m_numSamplers] = loc;
  2626. m_numSamplers++;
  2627. break;
  2628. default:
  2629. break;
  2630. }
  2631. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2632. if (PredefinedUniform::Count != predefined)
  2633. {
  2634. m_predefined[m_numPredefined].m_loc = loc;
  2635. m_predefined[m_numPredefined].m_type = predefined;
  2636. m_predefined[m_numPredefined].m_count = num;
  2637. m_numPredefined++;
  2638. }
  2639. else
  2640. {
  2641. const UniformInfo* info = s_renderGL->m_uniformReg.find(name);
  2642. if (NULL != info)
  2643. {
  2644. if (NULL == m_constantBuffer)
  2645. {
  2646. m_constantBuffer = ConstantBuffer::create(1024);
  2647. }
  2648. UniformType::Enum type = convertGlType(gltype);
  2649. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, num);
  2650. m_constantBuffer->write(loc);
  2651. BX_TRACE("store %s %d", name, info->m_handle);
  2652. }
  2653. }
  2654. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  2655. , glslTypeName(gltype)
  2656. , name
  2657. , PredefinedUniform::Count != predefined ? "*" : ""
  2658. , loc
  2659. , num
  2660. , offset
  2661. );
  2662. BX_UNUSED(offset);
  2663. }
  2664. if (NULL != m_constantBuffer)
  2665. {
  2666. m_constantBuffer->finish();
  2667. }
  2668. if (s_extension[Extension::ARB_program_interface_query].m_supported
  2669. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  2670. {
  2671. struct VariableInfo
  2672. {
  2673. GLenum type;
  2674. };
  2675. VariableInfo vi;
  2676. GLenum props[] = { GL_TYPE };
  2677. BX_TRACE("Buffers (%d):", activeBuffers);
  2678. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  2679. {
  2680. GL_CHECK(glGetProgramResourceiv(m_id
  2681. , GL_BUFFER_VARIABLE
  2682. , ii
  2683. , BX_COUNTOF(props)
  2684. , props
  2685. , BX_COUNTOF(props)
  2686. , NULL
  2687. , (GLint*)&vi
  2688. ) );
  2689. GL_CHECK(glGetProgramResourceName(m_id
  2690. , GL_BUFFER_VARIABLE
  2691. , ii
  2692. , maxLength + 1
  2693. , NULL
  2694. , name
  2695. ) );
  2696. BX_TRACE("\t%s %s at %d"
  2697. , glslTypeName(vi.type)
  2698. , name
  2699. , 0 //vi.loc
  2700. );
  2701. }
  2702. }
  2703. memset(m_attributes, 0xff, sizeof(m_attributes) );
  2704. uint32_t used = 0;
  2705. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  2706. {
  2707. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  2708. if (-1 != loc)
  2709. {
  2710. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  2711. m_attributes[ii] = loc;
  2712. m_used[used++] = ii;
  2713. }
  2714. }
  2715. m_used[used] = Attrib::Count;
  2716. used = 0;
  2717. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  2718. {
  2719. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  2720. if (GLuint(-1) != loc )
  2721. {
  2722. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  2723. m_instanceData[used++] = loc;
  2724. }
  2725. }
  2726. m_instanceData[used] = 0xffff;
  2727. }
  2728. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  2729. {
  2730. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  2731. {
  2732. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  2733. GLint loc = m_attributes[attr];
  2734. uint8_t num;
  2735. AttribType::Enum type;
  2736. bool normalized;
  2737. bool asInt;
  2738. _vertexDecl.decode(attr, num, type, normalized, asInt);
  2739. if (-1 != loc)
  2740. {
  2741. if (0xff != _vertexDecl.m_attributes[attr])
  2742. {
  2743. GL_CHECK(glEnableVertexAttribArray(loc) );
  2744. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  2745. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  2746. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  2747. }
  2748. else
  2749. {
  2750. GL_CHECK(glDisableVertexAttribArray(loc) );
  2751. }
  2752. }
  2753. }
  2754. }
  2755. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  2756. {
  2757. uint32_t baseVertex = _baseVertex;
  2758. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  2759. {
  2760. GLint loc = m_instanceData[ii];
  2761. GL_CHECK(glEnableVertexAttribArray(loc) );
  2762. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  2763. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  2764. baseVertex += 16;
  2765. }
  2766. }
  2767. void IndexBufferGL::destroy()
  2768. {
  2769. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2770. GL_CHECK(glDeleteBuffers(1, &m_id) );
  2771. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  2772. }
  2773. void VertexBufferGL::destroy()
  2774. {
  2775. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  2776. GL_CHECK(glDeleteBuffers(1, &m_id) );
  2777. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  2778. }
  2779. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _data)
  2780. {
  2781. if (_target == GL_TEXTURE_3D)
  2782. {
  2783. GL_CHECK(glTexImage3D(_target, _level, _internalFormat, _width, _height, _depth, _border, _format, _type, _data) );
  2784. }
  2785. else
  2786. {
  2787. BX_UNUSED(_depth);
  2788. GL_CHECK(glTexImage2D(_target, _level, _internalFormat, _width, _height, _border, _format, _type, _data) );
  2789. }
  2790. }
  2791. static void texSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLenum _type, const GLvoid* _data)
  2792. {
  2793. if (_target == GL_TEXTURE_3D)
  2794. {
  2795. GL_CHECK(glTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _type, _data) );
  2796. }
  2797. else
  2798. {
  2799. BX_UNUSED(_zoffset, _depth);
  2800. GL_CHECK(glTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _type, _data) );
  2801. }
  2802. }
  2803. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  2804. {
  2805. if (_target == GL_TEXTURE_3D)
  2806. {
  2807. GL_CHECK(glCompressedTexImage3D(_target, _level, _internalformat, _width, _height, _depth, _border, _imageSize, _data) );
  2808. }
  2809. else
  2810. {
  2811. BX_UNUSED(_depth);
  2812. GL_CHECK(glCompressedTexImage2D(_target, _level, _internalformat, _width, _height, _border, _imageSize, _data) );
  2813. }
  2814. }
  2815. static void compressedTexSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLsizei _imageSize, const GLvoid* _data)
  2816. {
  2817. if (_target == GL_TEXTURE_3D)
  2818. {
  2819. GL_CHECK(glCompressedTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _imageSize, _data) );
  2820. }
  2821. else
  2822. {
  2823. BX_UNUSED(_zoffset, _depth);
  2824. GL_CHECK(glCompressedTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _imageSize, _data) );
  2825. }
  2826. }
  2827. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint8_t _format, uint8_t _numMips, uint32_t _flags)
  2828. {
  2829. m_target = _target;
  2830. m_numMips = _numMips;
  2831. m_flags = _flags;
  2832. m_currentFlags = UINT32_MAX;
  2833. m_width = _width;
  2834. m_height = _height;
  2835. m_requestedFormat = _format;
  2836. m_textureFormat = _format;
  2837. const bool bufferOnly = 0 != (m_flags&BGFX_TEXTURE_RT_BUFFER_ONLY);
  2838. if (!bufferOnly)
  2839. {
  2840. GL_CHECK(glGenTextures(1, &m_id) );
  2841. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  2842. GL_CHECK(glBindTexture(_target, m_id) );
  2843. const TextureFormatInfo& tfi = s_textureFormat[_format];
  2844. m_fmt = tfi.m_fmt;
  2845. m_type = tfi.m_type;
  2846. const bool compressed = isCompressed(TextureFormat::Enum(_format) );
  2847. const bool decompress = !tfi.m_supported && compressed;
  2848. if (decompress)
  2849. {
  2850. m_textureFormat = (uint8_t)TextureFormat::BGRA8;
  2851. const TextureFormatInfo& tfiBgra8 = s_textureFormat[TextureFormat::BGRA8];
  2852. m_fmt = tfiBgra8.m_fmt;
  2853. m_type = tfiBgra8.m_type;
  2854. }
  2855. setSamplerState(_flags);
  2856. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2857. && TextureFormat::BGRA8 == m_textureFormat
  2858. && GL_RGBA == m_fmt
  2859. && s_renderGL->m_textureSwizzleSupport)
  2860. {
  2861. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  2862. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  2863. }
  2864. }
  2865. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  2866. if (renderTarget)
  2867. {
  2868. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  2869. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  2870. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  2871. if (0 != msaaQuality
  2872. || bufferOnly)
  2873. {
  2874. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  2875. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  2876. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  2877. if (0 == msaaQuality)
  2878. {
  2879. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  2880. , s_rboFormat[m_textureFormat]
  2881. , _width
  2882. , _height
  2883. ) );
  2884. }
  2885. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2886. {
  2887. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  2888. , msaaQuality
  2889. , s_rboFormat[m_textureFormat]
  2890. , _width
  2891. , _height
  2892. ) );
  2893. }
  2894. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  2895. if (bufferOnly)
  2896. {
  2897. // This is render buffer, there is no sampling, no need
  2898. // to create texture.
  2899. return false;
  2900. }
  2901. }
  2902. }
  2903. return true;
  2904. }
  2905. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  2906. {
  2907. ImageContainer imageContainer;
  2908. if (imageParse(imageContainer, _mem->data, _mem->size) )
  2909. {
  2910. uint8_t numMips = imageContainer.m_numMips;
  2911. const uint32_t startLod = bx::uint32_min(_skip, numMips-1);
  2912. numMips -= uint8_t(startLod);
  2913. const ImageBlockInfo& blockInfo = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  2914. const uint32_t textureWidth = bx::uint32_max(blockInfo.blockWidth, imageContainer.m_width >>startLod);
  2915. const uint32_t textureHeight = bx::uint32_max(blockInfo.blockHeight, imageContainer.m_height>>startLod);
  2916. GLenum target = GL_TEXTURE_2D;
  2917. if (imageContainer.m_cubeMap)
  2918. {
  2919. target = GL_TEXTURE_CUBE_MAP;
  2920. }
  2921. else if (imageContainer.m_depth > 1)
  2922. {
  2923. target = GL_TEXTURE_3D;
  2924. }
  2925. if (!init(target
  2926. , textureWidth
  2927. , textureHeight
  2928. , imageContainer.m_format
  2929. , numMips
  2930. , _flags
  2931. ) )
  2932. {
  2933. return;
  2934. }
  2935. target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  2936. const GLenum internalFmt = s_textureFormat[m_textureFormat].m_internalFmt;
  2937. const bool swizzle = true
  2938. && TextureFormat::BGRA8 == m_textureFormat
  2939. && GL_RGBA == m_fmt
  2940. && !s_renderGL->m_textureSwizzleSupport
  2941. ;
  2942. const bool convert = m_textureFormat != m_requestedFormat;
  2943. const bool compressed = isCompressed(TextureFormat::Enum(m_textureFormat) );
  2944. uint32_t blockWidth = 1;
  2945. uint32_t blockHeight = 1;
  2946. if (convert && compressed)
  2947. {
  2948. blockWidth = blockInfo.blockWidth;
  2949. blockHeight = blockInfo.blockHeight;
  2950. }
  2951. BX_TRACE("Texture%-4s %3d: %s (requested: %s), %dx%dx%d%s."
  2952. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  2953. , this - s_renderGL->m_textures
  2954. , getName( (TextureFormat::Enum)m_textureFormat)
  2955. , getName( (TextureFormat::Enum)m_requestedFormat)
  2956. , textureWidth
  2957. , textureHeight
  2958. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  2959. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  2960. );
  2961. BX_WARN(!swizzle && !convert, "Texture %s%s%s from %s to %s."
  2962. , swizzle ? "swizzle" : ""
  2963. , swizzle&&convert ? " and " : ""
  2964. , convert ? "convert" : ""
  2965. , getName( (TextureFormat::Enum)m_requestedFormat)
  2966. , getName( (TextureFormat::Enum)m_textureFormat)
  2967. );
  2968. uint8_t* temp = NULL;
  2969. if (convert || swizzle)
  2970. {
  2971. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  2972. }
  2973. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  2974. {
  2975. uint32_t width = textureWidth;
  2976. uint32_t height = textureHeight;
  2977. uint32_t depth = imageContainer.m_depth;
  2978. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  2979. {
  2980. width = bx::uint32_max(blockWidth, width);
  2981. height = bx::uint32_max(blockHeight, height);
  2982. depth = bx::uint32_max(1, depth);
  2983. ImageMip mip;
  2984. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  2985. {
  2986. if (compressed)
  2987. {
  2988. compressedTexImage(target+side
  2989. , lod
  2990. , internalFmt
  2991. , width
  2992. , height
  2993. , depth
  2994. , 0
  2995. , mip.m_size
  2996. , mip.m_data
  2997. );
  2998. }
  2999. else
  3000. {
  3001. const uint8_t* data = mip.m_data;
  3002. if (convert)
  3003. {
  3004. imageDecodeToBgra8(temp, mip.m_data, mip.m_width, mip.m_height, mip.m_width*4, mip.m_format);
  3005. data = temp;
  3006. }
  3007. if (swizzle)
  3008. {
  3009. imageSwizzleBgra8(width, height, mip.m_width*4, data, temp);
  3010. data = temp;
  3011. }
  3012. texImage(target+side
  3013. , lod
  3014. , internalFmt
  3015. , width
  3016. , height
  3017. , depth
  3018. , 0
  3019. , m_fmt
  3020. , m_type
  3021. , data
  3022. );
  3023. }
  3024. }
  3025. else
  3026. {
  3027. if (compressed)
  3028. {
  3029. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  3030. * bx::uint32_max(1, (height + 3)>>2)
  3031. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  3032. ;
  3033. compressedTexImage(target+side
  3034. , lod
  3035. , internalFmt
  3036. , width
  3037. , height
  3038. , depth
  3039. , 0
  3040. , size
  3041. , NULL
  3042. );
  3043. }
  3044. else
  3045. {
  3046. texImage(target+side
  3047. , lod
  3048. , internalFmt
  3049. , width
  3050. , height
  3051. , depth
  3052. , 0
  3053. , m_fmt
  3054. , m_type
  3055. , NULL
  3056. );
  3057. }
  3058. }
  3059. width >>= 1;
  3060. height >>= 1;
  3061. depth >>= 1;
  3062. }
  3063. }
  3064. if (NULL != temp)
  3065. {
  3066. BX_FREE(g_allocator, temp);
  3067. }
  3068. }
  3069. GL_CHECK(glBindTexture(m_target, 0) );
  3070. }
  3071. void TextureGL::destroy()
  3072. {
  3073. if (0 != m_id)
  3074. {
  3075. GL_CHECK(glBindTexture(m_target, 0) );
  3076. GL_CHECK(glDeleteTextures(1, &m_id) );
  3077. m_id = 0;
  3078. }
  3079. if (0 != m_rbo)
  3080. {
  3081. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  3082. m_rbo = 0;
  3083. }
  3084. }
  3085. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  3086. {
  3087. BX_UNUSED(_z, _depth);
  3088. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  3089. const uint32_t rectpitch = _rect.m_width*bpp/8;
  3090. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  3091. GL_CHECK(glBindTexture(m_target, m_id) );
  3092. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  3093. GLenum target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3094. const bool swizzle = true
  3095. && TextureFormat::BGRA8 == m_textureFormat
  3096. && GL_RGBA == m_fmt
  3097. && !s_renderGL->m_textureSwizzleSupport
  3098. ;
  3099. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  3100. const bool convert = m_textureFormat != m_requestedFormat;
  3101. const bool compressed = isCompressed(TextureFormat::Enum(m_textureFormat) );
  3102. const uint32_t width = _rect.m_width;
  3103. const uint32_t height = _rect.m_height;
  3104. uint8_t* temp = NULL;
  3105. if (convert
  3106. || swizzle
  3107. || !unpackRowLength)
  3108. {
  3109. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  3110. }
  3111. else if (unpackRowLength)
  3112. {
  3113. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  3114. }
  3115. if (compressed)
  3116. {
  3117. const uint8_t* data = _mem->data;
  3118. if (!unpackRowLength)
  3119. {
  3120. imageCopy(width, height, bpp, srcpitch, data, temp);
  3121. data = temp;
  3122. }
  3123. GL_CHECK(compressedTexSubImage(target+_side
  3124. , _mip
  3125. , _rect.m_x
  3126. , _rect.m_y
  3127. , _z
  3128. , _rect.m_width
  3129. , _rect.m_height
  3130. , _depth
  3131. , m_fmt
  3132. , _mem->size
  3133. , data
  3134. ) );
  3135. }
  3136. else
  3137. {
  3138. const uint8_t* data = _mem->data;
  3139. if (convert)
  3140. {
  3141. imageDecodeToBgra8(temp, data, width, height, srcpitch, m_requestedFormat);
  3142. data = temp;
  3143. srcpitch = rectpitch;
  3144. }
  3145. if (swizzle)
  3146. {
  3147. imageSwizzleBgra8(width, height, srcpitch, data, temp);
  3148. data = temp;
  3149. }
  3150. else if (!unpackRowLength && !convert)
  3151. {
  3152. imageCopy(width, height, bpp, srcpitch, data, temp);
  3153. data = temp;
  3154. }
  3155. GL_CHECK(texSubImage(target+_side
  3156. , _mip
  3157. , _rect.m_x
  3158. , _rect.m_y
  3159. , _z
  3160. , _rect.m_width
  3161. , _rect.m_height
  3162. , _depth
  3163. , m_fmt
  3164. , m_type
  3165. , data
  3166. ) );
  3167. }
  3168. if (NULL != temp)
  3169. {
  3170. BX_FREE(g_allocator, temp);
  3171. }
  3172. }
  3173. void TextureGL::setSamplerState(uint32_t _flags)
  3174. {
  3175. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  3176. && !s_textureFilter[m_textureFormat])
  3177. {
  3178. // Force point sampling when texture format doesn't support linear sampling.
  3179. _flags &= 0
  3180. | BGFX_TEXTURE_MIN_MASK
  3181. | BGFX_TEXTURE_MAG_MASK
  3182. | BGFX_TEXTURE_MIP_MASK
  3183. ;
  3184. _flags |= 0
  3185. | BGFX_TEXTURE_MIN_POINT
  3186. | BGFX_TEXTURE_MAG_POINT
  3187. | BGFX_TEXTURE_MIP_POINT
  3188. ;
  3189. }
  3190. const uint32_t flags = (0 != (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  3191. if (flags != m_currentFlags)
  3192. {
  3193. const GLenum target = m_target;
  3194. const uint8_t numMips = m_numMips;
  3195. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  3196. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  3197. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3198. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  3199. {
  3200. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  3201. }
  3202. if (target == GL_TEXTURE_3D)
  3203. {
  3204. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  3205. }
  3206. GLenum magFilter;
  3207. GLenum minFilter;
  3208. getFilters(flags, 1 < numMips, magFilter, minFilter);
  3209. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  3210. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  3211. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  3212. && 0.0f < s_renderGL->m_maxAnisotropy)
  3213. {
  3214. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  3215. }
  3216. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3217. || s_renderGL->m_shadowSamplersSupport)
  3218. {
  3219. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  3220. if (0 == cmpFunc)
  3221. {
  3222. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  3223. }
  3224. else
  3225. {
  3226. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  3227. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  3228. }
  3229. }
  3230. m_currentFlags = flags;
  3231. }
  3232. }
  3233. void TextureGL::commit(uint32_t _stage, uint32_t _flags)
  3234. {
  3235. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  3236. GL_CHECK(glBindTexture(m_target, m_id) );
  3237. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3238. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3239. {
  3240. // GLES2 doesn't have support for sampler object.
  3241. setSamplerState(_flags);
  3242. }
  3243. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3244. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  3245. {
  3246. // In case that GL 2.1 sampler object is supported via extension.
  3247. if (s_renderGL->m_samplerObjectSupport)
  3248. {
  3249. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3250. }
  3251. else
  3252. {
  3253. setSamplerState(_flags);
  3254. }
  3255. }
  3256. else
  3257. {
  3258. // Everything else has sampler object.
  3259. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3260. }
  3261. }
  3262. void writeString(bx::WriterI* _writer, const char* _str)
  3263. {
  3264. bx::write(_writer, _str, (int32_t)strlen(_str) );
  3265. }
  3266. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  3267. {
  3268. char temp[512];
  3269. va_list argList;
  3270. va_start(argList, _format);
  3271. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  3272. va_end(argList);
  3273. bx::write(_writer, temp, len);
  3274. }
  3275. void strins(char* _str, const char* _insert)
  3276. {
  3277. size_t len = strlen(_insert);
  3278. memmove(&_str[len], _str, strlen(_str)+1);
  3279. memcpy(_str, _insert, len);
  3280. }
  3281. void ShaderGL::create(Memory* _mem)
  3282. {
  3283. bx::MemoryReader reader(_mem->data, _mem->size);
  3284. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  3285. uint32_t magic;
  3286. bx::read(&reader, magic);
  3287. switch (magic)
  3288. {
  3289. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  3290. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  3291. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  3292. default:
  3293. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  3294. break;
  3295. }
  3296. uint32_t iohash;
  3297. bx::read(&reader, iohash);
  3298. uint16_t count;
  3299. bx::read(&reader, count);
  3300. BX_TRACE("%s Shader consts %d"
  3301. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  3302. , count
  3303. );
  3304. for (uint32_t ii = 0; ii < count; ++ii)
  3305. {
  3306. uint8_t nameSize;
  3307. bx::read(&reader, nameSize);
  3308. char name[256];
  3309. bx::read(&reader, &name, nameSize);
  3310. name[nameSize] = '\0';
  3311. uint8_t type;
  3312. bx::read(&reader, type);
  3313. uint8_t num;
  3314. bx::read(&reader, num);
  3315. uint16_t regIndex;
  3316. bx::read(&reader, regIndex);
  3317. uint16_t regCount;
  3318. bx::read(&reader, regCount);
  3319. }
  3320. uint32_t shaderSize;
  3321. bx::read(&reader, shaderSize);
  3322. m_id = glCreateShader(m_type);
  3323. BX_WARN(0 != m_id, "Failed to create %s shader."
  3324. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  3325. );
  3326. const char* code = (const char*)reader.getDataPtr();
  3327. if (0 != m_id)
  3328. {
  3329. if (GL_COMPUTE_SHADER != m_type)
  3330. {
  3331. int32_t codeLen = (int32_t)strlen(code);
  3332. int32_t tempLen = codeLen + (4<<10);
  3333. char* temp = (char*)alloca(tempLen);
  3334. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  3335. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3336. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3337. {
  3338. writeString(&writer
  3339. , "#define flat\n"
  3340. "#define smooth\n"
  3341. "#define noperspective\n"
  3342. );
  3343. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  3344. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  3345. ;
  3346. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  3347. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  3348. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  3349. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  3350. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  3351. ;
  3352. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  3353. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  3354. if (usesDerivatives)
  3355. {
  3356. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  3357. }
  3358. if (usesFragData)
  3359. {
  3360. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  3361. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  3362. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  3363. );
  3364. writeString(&writer
  3365. , "#extension GL_EXT_draw_buffers : enable\n"
  3366. );
  3367. }
  3368. bool insertFragDepth = false;
  3369. if (usesFragDepth)
  3370. {
  3371. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  3372. if (s_extension[Extension::EXT_frag_depth].m_supported)
  3373. {
  3374. writeString(&writer
  3375. , "#extension GL_EXT_frag_depth : enable\n"
  3376. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  3377. );
  3378. char str[128];
  3379. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  3380. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  3381. );
  3382. writeString(&writer, str);
  3383. }
  3384. else
  3385. {
  3386. insertFragDepth = true;
  3387. }
  3388. }
  3389. if (usesShadowSamplers)
  3390. {
  3391. if (s_renderGL->m_shadowSamplersSupport)
  3392. {
  3393. writeString(&writer
  3394. , "#extension GL_EXT_shadow_samplers : enable\n"
  3395. "#define shadow2D shadow2DEXT\n"
  3396. "#define shadow2DProj shadow2DProjEXT\n"
  3397. );
  3398. }
  3399. else
  3400. {
  3401. writeString(&writer
  3402. , "#define sampler2DShadow sampler2D\n"
  3403. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  3404. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  3405. );
  3406. }
  3407. }
  3408. if (usesTexture3D)
  3409. {
  3410. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  3411. }
  3412. if (usesTextureLod)
  3413. {
  3414. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  3415. if (s_extension[Extension::EXT_shader_texture_lod].m_supported)
  3416. {
  3417. writeString(&writer
  3418. , "#extension GL_EXT_shader_texture_lod : enable\n"
  3419. "#define texture2DLod texture2DLodEXT\n"
  3420. "#define texture2DProjLod texture2DProjLodEXT\n"
  3421. "#define textureCubeLod textureCubeLodEXT\n"
  3422. );
  3423. }
  3424. else
  3425. {
  3426. writeString(&writer
  3427. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  3428. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  3429. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  3430. );
  3431. }
  3432. }
  3433. if (usesFragmentOrdering)
  3434. {
  3435. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3436. {
  3437. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3438. }
  3439. else
  3440. {
  3441. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3442. }
  3443. }
  3444. writeStringf(&writer, "precision %s float;\n"
  3445. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  3446. );
  3447. bx::write(&writer, code, codeLen);
  3448. bx::write(&writer, '\0');
  3449. if (insertFragDepth)
  3450. {
  3451. char* entry = strstr(temp, "void main ()");
  3452. if (NULL != entry)
  3453. {
  3454. char* brace = strstr(entry, "{");
  3455. if (NULL != brace)
  3456. {
  3457. const char* end = bx::strmb(brace, '{', '}');
  3458. if (NULL != end)
  3459. {
  3460. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  3461. }
  3462. }
  3463. }
  3464. }
  3465. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  3466. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  3467. {
  3468. char* insert = const_cast<char*>(fragDepth);
  3469. strins(insert, "bg");
  3470. memcpy(insert + 2, "fx", 2);
  3471. }
  3472. }
  3473. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3474. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  3475. {
  3476. bool usesTextureLod = true
  3477. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  3478. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  3479. ;
  3480. bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  3481. uint32_t version = usesIUsamplers ? 130 : (usesTextureLod ? 120 : 0);
  3482. if (0 != version)
  3483. {
  3484. writeStringf(&writer, "#version %d\n", version);
  3485. }
  3486. if (usesTextureLod)
  3487. {
  3488. if (m_type == GL_FRAGMENT_SHADER)
  3489. {
  3490. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  3491. }
  3492. }
  3493. writeString(&writer
  3494. , "#define lowp\n"
  3495. "#define mediump\n"
  3496. "#define highp\n"
  3497. "#define flat\n"
  3498. "#define smooth\n"
  3499. "#define noperspective\n"
  3500. );
  3501. bx::write(&writer, code, codeLen);
  3502. bx::write(&writer, '\0');
  3503. }
  3504. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  3505. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3506. {
  3507. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3508. {
  3509. writeString(&writer
  3510. , "#version 300 es\n"
  3511. "precision mediump float;\n"
  3512. );
  3513. }
  3514. else
  3515. {
  3516. writeString(&writer, "#version 140\n");
  3517. }
  3518. if (m_type == GL_FRAGMENT_SHADER)
  3519. {
  3520. writeString(&writer, "#define varying in\n");
  3521. writeString(&writer, "#define texture2D texture\n");
  3522. writeString(&writer, "#define texture2DLod textureLod\n");
  3523. writeString(&writer, "#define texture2DProj textureProj\n");
  3524. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  3525. {
  3526. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3527. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  3528. }
  3529. else
  3530. {
  3531. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3532. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  3533. }
  3534. writeString(&writer, "#define texture3D texture\n");
  3535. writeString(&writer, "#define texture3DLod textureLod\n");
  3536. writeString(&writer, "#define textureCube texture\n");
  3537. writeString(&writer, "#define textureCubeLod textureLod\n");
  3538. uint32_t fragData = 0;
  3539. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  3540. {
  3541. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  3542. {
  3543. char tmpFragData[16];
  3544. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  3545. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  3546. }
  3547. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  3548. }
  3549. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  3550. {
  3551. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3552. {
  3553. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3554. }
  3555. else
  3556. {
  3557. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3558. }
  3559. }
  3560. if (0 != fragData)
  3561. {
  3562. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  3563. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  3564. }
  3565. else
  3566. {
  3567. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  3568. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  3569. }
  3570. }
  3571. else
  3572. {
  3573. writeString(&writer, "#define attribute in\n");
  3574. writeString(&writer, "#define varying out\n");
  3575. }
  3576. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3577. {
  3578. writeString(&writer
  3579. , "#define lowp\n"
  3580. "#define mediump\n"
  3581. "#define highp\n"
  3582. );
  3583. }
  3584. bx::write(&writer, code, codeLen);
  3585. bx::write(&writer, '\0');
  3586. }
  3587. code = temp;
  3588. }
  3589. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  3590. GL_CHECK(glCompileShader(m_id) );
  3591. GLint compiled = 0;
  3592. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  3593. if (0 == compiled)
  3594. {
  3595. BX_TRACE("\n####\n%s\n####", code);
  3596. GLsizei len;
  3597. char log[1024];
  3598. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  3599. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  3600. GL_CHECK(glDeleteShader(m_id) );
  3601. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  3602. }
  3603. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3604. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  3605. && NULL != glGetTranslatedShaderSourceANGLE)
  3606. {
  3607. GLsizei len;
  3608. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  3609. char* source = (char*)alloca(len);
  3610. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  3611. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  3612. }
  3613. }
  3614. }
  3615. void ShaderGL::destroy()
  3616. {
  3617. if (0 != m_id)
  3618. {
  3619. GL_CHECK(glDeleteShader(m_id) );
  3620. m_id = 0;
  3621. }
  3622. }
  3623. static void frameBufferValidate()
  3624. {
  3625. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3626. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  3627. , "glCheckFramebufferStatus failed 0x%08x: %s"
  3628. , complete
  3629. , glEnumName(complete)
  3630. );
  3631. BX_UNUSED(complete);
  3632. }
  3633. void FrameBufferGL::create(uint8_t _num, const TextureHandle* _handles)
  3634. {
  3635. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  3636. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  3637. // m_denseIdx = UINT16_MAX;
  3638. bool needResolve = false;
  3639. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  3640. uint32_t colorIdx = 0;
  3641. for (uint32_t ii = 0; ii < _num; ++ii)
  3642. {
  3643. TextureHandle handle = _handles[ii];
  3644. if (isValid(handle) )
  3645. {
  3646. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  3647. if (0 == colorIdx)
  3648. {
  3649. m_width = texture.m_width;
  3650. m_height = texture.m_height;
  3651. }
  3652. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  3653. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  3654. if (isDepth(format) )
  3655. {
  3656. const ImageBlockInfo& info = getBlockInfo(format);
  3657. if (0 < info.stencilBits)
  3658. {
  3659. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  3660. }
  3661. else if (0 == info.depthBits)
  3662. {
  3663. attachment = GL_STENCIL_ATTACHMENT;
  3664. }
  3665. else
  3666. {
  3667. attachment = GL_DEPTH_ATTACHMENT;
  3668. }
  3669. }
  3670. else
  3671. {
  3672. buffers[colorIdx] = attachment;
  3673. ++colorIdx;
  3674. }
  3675. if (0 != texture.m_rbo)
  3676. {
  3677. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  3678. , attachment
  3679. , GL_RENDERBUFFER
  3680. , texture.m_rbo
  3681. ) );
  3682. }
  3683. else
  3684. {
  3685. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  3686. , attachment
  3687. , texture.m_target
  3688. , texture.m_id
  3689. , 0
  3690. ) );
  3691. }
  3692. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  3693. }
  3694. }
  3695. m_num = colorIdx;
  3696. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  3697. {
  3698. if (0 == colorIdx)
  3699. {
  3700. // When only depth is attached disable draw buffer to avoid
  3701. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  3702. GL_CHECK(glDrawBuffer(GL_NONE) );
  3703. }
  3704. else
  3705. {
  3706. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  3707. }
  3708. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  3709. GL_CHECK(glReadBuffer(GL_NONE) );
  3710. }
  3711. frameBufferValidate();
  3712. if (needResolve)
  3713. {
  3714. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  3715. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  3716. colorIdx = 0;
  3717. for (uint32_t ii = 0; ii < _num; ++ii)
  3718. {
  3719. TextureHandle handle = _handles[ii];
  3720. if (isValid(handle) )
  3721. {
  3722. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  3723. if (0 != texture.m_id)
  3724. {
  3725. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  3726. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  3727. {
  3728. ++colorIdx;
  3729. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  3730. , attachment
  3731. , texture.m_target
  3732. , texture.m_id
  3733. , 0
  3734. ) );
  3735. }
  3736. }
  3737. }
  3738. }
  3739. frameBufferValidate();
  3740. }
  3741. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  3742. }
  3743. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  3744. {
  3745. BX_UNUSED(_depthFormat);
  3746. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  3747. m_width = _width;
  3748. m_height = _height;
  3749. m_denseIdx = _denseIdx;
  3750. }
  3751. uint16_t FrameBufferGL::destroy()
  3752. {
  3753. if (0 != m_num)
  3754. {
  3755. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  3756. memset(m_fbo, 0, sizeof(m_fbo) );
  3757. m_num = 0;
  3758. }
  3759. if (NULL != m_swapChain)
  3760. {
  3761. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  3762. m_swapChain = NULL;
  3763. }
  3764. uint16_t denseIdx = m_denseIdx;
  3765. m_denseIdx = UINT16_MAX;
  3766. return denseIdx;
  3767. }
  3768. void FrameBufferGL::resolve()
  3769. {
  3770. if (0 != m_fbo[1])
  3771. {
  3772. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  3773. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  3774. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  3775. GL_CHECK(glBlitFramebuffer(0
  3776. , 0
  3777. , m_width
  3778. , m_height
  3779. , 0
  3780. , 0
  3781. , m_width
  3782. , m_height
  3783. , GL_COLOR_BUFFER_BIT
  3784. , GL_LINEAR
  3785. ) );
  3786. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  3787. GL_CHECK(glReadBuffer(GL_NONE) );
  3788. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  3789. }
  3790. }
  3791. void FrameBufferGL::discard(uint8_t _flags)
  3792. {
  3793. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  3794. uint32_t idx = 0;
  3795. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  3796. {
  3797. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  3798. {
  3799. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  3800. {
  3801. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  3802. }
  3803. }
  3804. }
  3805. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  3806. if (BGFX_CLEAR_NONE != dsFlags)
  3807. {
  3808. if ( (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  3809. {
  3810. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  3811. }
  3812. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  3813. {
  3814. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  3815. }
  3816. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  3817. {
  3818. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  3819. }
  3820. }
  3821. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  3822. }
  3823. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  3824. {
  3825. if (1 < m_numWindows
  3826. && m_vaoSupport)
  3827. {
  3828. m_vaoSupport = false;
  3829. GL_CHECK(glBindVertexArray(0) );
  3830. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  3831. m_vao = 0;
  3832. m_vaoStateCache.invalidate();
  3833. }
  3834. m_glctx.makeCurrent(NULL);
  3835. const GLuint defaultVao = m_vao;
  3836. if (0 != defaultVao)
  3837. {
  3838. GL_CHECK(glBindVertexArray(defaultVao) );
  3839. }
  3840. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  3841. updateResolution(_render->m_resolution);
  3842. int64_t elapsed = -bx::getHPCounter();
  3843. int64_t captureElapsed = 0;
  3844. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3845. && (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  3846. && m_timerQuerySupport)
  3847. {
  3848. m_queries.begin(0, GL_TIME_ELAPSED);
  3849. }
  3850. if (0 < _render->m_iboffset)
  3851. {
  3852. TransientIndexBuffer* ib = _render->m_transientIb;
  3853. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data);
  3854. }
  3855. if (0 < _render->m_vboffset)
  3856. {
  3857. TransientVertexBuffer* vb = _render->m_transientVb;
  3858. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data);
  3859. }
  3860. _render->sort();
  3861. RenderDraw currentState;
  3862. currentState.clear();
  3863. currentState.m_flags = BGFX_STATE_NONE;
  3864. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  3865. const bool hmdEnabled = m_ovr.isEnabled() || m_ovr.isDebug();
  3866. _render->m_hmdEnabled = hmdEnabled;
  3867. if (hmdEnabled)
  3868. {
  3869. HMD& hmd = _render->m_hmd;
  3870. m_ovr.getEyePose(hmd);
  3871. }
  3872. ViewState viewState(_render, hmdEnabled);
  3873. uint16_t programIdx = invalidHandle;
  3874. SortKey key;
  3875. uint8_t view = 0xff;
  3876. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  3877. int32_t height = hmdEnabled
  3878. ? _render->m_hmd.height
  3879. : _render->m_resolution.m_height
  3880. ;
  3881. uint32_t blendFactor = 0;
  3882. uint8_t primIndex;
  3883. {
  3884. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  3885. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3886. }
  3887. PrimInfo prim = s_primInfo[primIndex];
  3888. uint32_t baseVertex = 0;
  3889. GLuint currentVao = 0;
  3890. bool wasCompute = false;
  3891. bool viewHasScissor = false;
  3892. Rect viewScissorRect;
  3893. viewScissorRect.clear();
  3894. uint8_t discardFlags = BGFX_CLEAR_NONE;
  3895. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  3896. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  3897. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  3898. ;
  3899. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  3900. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  3901. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  3902. uint32_t statsNumIndices = 0;
  3903. uint32_t statsKeyType[2] = {};
  3904. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  3905. {
  3906. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  3907. bool viewRestart = false;
  3908. uint8_t eye = 0;
  3909. uint8_t restartState = 0;
  3910. viewState.m_rect = _render->m_rect[0];
  3911. int32_t numItems = _render->m_num;
  3912. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  3913. {
  3914. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  3915. statsKeyType[isCompute]++;
  3916. const bool viewChanged = 0
  3917. || key.m_view != view
  3918. || item == numItems
  3919. ;
  3920. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  3921. ++item;
  3922. if (viewChanged)
  3923. {
  3924. if (1 == restartState)
  3925. {
  3926. restartState = 2;
  3927. item = restartItem;
  3928. restartItem = numItems;
  3929. view = 0xff;
  3930. continue;
  3931. }
  3932. view = key.m_view;
  3933. programIdx = invalidHandle;
  3934. if (_render->m_fb[view].idx != fbh.idx)
  3935. {
  3936. fbh = _render->m_fb[view];
  3937. height = hmdEnabled
  3938. ? _render->m_hmd.height
  3939. : _render->m_resolution.m_height
  3940. ;
  3941. height = setFrameBuffer(fbh, height, discardFlags);
  3942. }
  3943. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  3944. viewRestart &= hmdEnabled;
  3945. if (viewRestart)
  3946. {
  3947. if (0 == restartState)
  3948. {
  3949. restartState = 1;
  3950. restartItem = item - 1;
  3951. }
  3952. eye = (restartState - 1) & 1;
  3953. restartState &= 1;
  3954. }
  3955. else
  3956. {
  3957. eye = 0;
  3958. }
  3959. viewState.m_rect = _render->m_rect[view];
  3960. if (viewRestart)
  3961. {
  3962. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  3963. {
  3964. char* viewName = s_viewName[view];
  3965. viewName[3] = ' ';
  3966. viewName[4] = eye ? 'R' : 'L';
  3967. GL_CHECK(glInsertEventMarker(0, viewName) );
  3968. }
  3969. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  3970. viewState.m_rect.m_width /= 2;
  3971. }
  3972. else
  3973. {
  3974. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  3975. {
  3976. char* viewName = s_viewName[view];
  3977. viewName[3] = ' ';
  3978. viewName[4] = ' ';
  3979. GL_CHECK(glInsertEventMarker(0, viewName) );
  3980. }
  3981. }
  3982. const Rect& scissorRect = _render->m_scissor[view];
  3983. viewHasScissor = !scissorRect.isZero();
  3984. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  3985. GL_CHECK(glViewport(viewState.m_rect.m_x
  3986. , height-viewState.m_rect.m_height-viewState.m_rect.m_y
  3987. , viewState.m_rect.m_width
  3988. , viewState.m_rect.m_height
  3989. ) );
  3990. Clear& clear = _render->m_clear[view];
  3991. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  3992. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  3993. {
  3994. clearQuad(_clearQuad, viewState.m_rect, clear, height, _render->m_clearColor);
  3995. }
  3996. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  3997. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  3998. GL_CHECK(glDepthFunc(GL_LESS) );
  3999. GL_CHECK(glEnable(GL_CULL_FACE) );
  4000. GL_CHECK(glDisable(GL_BLEND) );
  4001. }
  4002. if (isCompute)
  4003. {
  4004. if (!wasCompute)
  4005. {
  4006. wasCompute = true;
  4007. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4008. {
  4009. char* viewName = s_viewName[view];
  4010. viewName[3] = 'C';
  4011. GL_CHECK(glInsertEventMarker(0, viewName) );
  4012. }
  4013. }
  4014. if (computeSupported)
  4015. {
  4016. const RenderCompute& compute = renderItem.compute;
  4017. ProgramGL& program = m_program[key.m_program];
  4018. GL_CHECK(glUseProgram(program.m_id) );
  4019. GLbitfield barrier = 0;
  4020. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  4021. {
  4022. const Binding& bind = compute.m_bind[ii];
  4023. if (invalidHandle != bind.m_idx)
  4024. {
  4025. switch (bind.m_type)
  4026. {
  4027. case Binding::Image:
  4028. {
  4029. const TextureGL& texture = m_textures[bind.m_idx];
  4030. GL_CHECK(glBindImageTexture(ii
  4031. , texture.m_id
  4032. , bind.m_un.m_compute.m_mip
  4033. , GL_FALSE
  4034. , 0
  4035. , s_access[bind.m_un.m_compute.m_access]
  4036. , s_imageFormat[bind.m_un.m_compute.m_format])
  4037. );
  4038. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  4039. }
  4040. break;
  4041. case Binding::IndexBuffer:
  4042. {
  4043. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  4044. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id));
  4045. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4046. }
  4047. break;
  4048. case Binding::VertexBuffer:
  4049. {
  4050. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  4051. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id));
  4052. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4053. }
  4054. break;
  4055. }
  4056. }
  4057. }
  4058. if (0 != barrier)
  4059. {
  4060. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  4061. rendererUpdateUniforms(this, _render->m_constantBuffer, compute.m_constBegin, compute.m_constEnd);
  4062. if (constantsChanged
  4063. && NULL != program.m_constantBuffer)
  4064. {
  4065. commit(*program.m_constantBuffer);
  4066. }
  4067. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  4068. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  4069. GL_CHECK(glMemoryBarrier(barrier) );
  4070. }
  4071. }
  4072. continue;
  4073. }
  4074. if (wasCompute)
  4075. {
  4076. wasCompute = false;
  4077. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4078. {
  4079. char* viewName = s_viewName[view];
  4080. viewName[3] = ' ';
  4081. GL_CHECK(glInsertEventMarker(0, viewName) );
  4082. }
  4083. }
  4084. const RenderDraw& draw = renderItem.draw;
  4085. const uint64_t newFlags = draw.m_flags;
  4086. uint64_t changedFlags = currentState.m_flags ^ draw.m_flags;
  4087. currentState.m_flags = newFlags;
  4088. const uint64_t newStencil = draw.m_stencil;
  4089. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  4090. currentState.m_stencil = newStencil;
  4091. if (viewChanged)
  4092. {
  4093. currentState.clear();
  4094. currentState.m_scissor = !draw.m_scissor;
  4095. changedFlags = BGFX_STATE_MASK;
  4096. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  4097. currentState.m_flags = newFlags;
  4098. currentState.m_stencil = newStencil;
  4099. }
  4100. uint16_t scissor = draw.m_scissor;
  4101. if (currentState.m_scissor != scissor)
  4102. {
  4103. currentState.m_scissor = scissor;
  4104. if (UINT16_MAX == scissor)
  4105. {
  4106. if (viewHasScissor)
  4107. {
  4108. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4109. GL_CHECK(glScissor(viewScissorRect.m_x
  4110. , height-viewScissorRect.m_height-viewScissorRect.m_y
  4111. , viewScissorRect.m_width
  4112. , viewScissorRect.m_height
  4113. ) );
  4114. }
  4115. else
  4116. {
  4117. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  4118. }
  4119. }
  4120. else
  4121. {
  4122. Rect scissorRect;
  4123. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  4124. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4125. GL_CHECK(glScissor(scissorRect.m_x
  4126. , height-scissorRect.m_height-scissorRect.m_y
  4127. , scissorRect.m_width
  4128. , scissorRect.m_height
  4129. ) );
  4130. }
  4131. }
  4132. if (0 != changedStencil)
  4133. {
  4134. if (0 != newStencil)
  4135. {
  4136. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  4137. uint32_t bstencil = unpackStencil(1, newStencil);
  4138. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  4139. // uint32_t bchanged = unpackStencil(1, changedStencil);
  4140. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  4141. // {
  4142. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4143. // GL_CHECK(glStencilMask(wmask) );
  4144. // }
  4145. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  4146. {
  4147. uint32_t stencil = unpackStencil(ii, newStencil);
  4148. uint32_t changed = unpackStencil(ii, changedStencil);
  4149. GLenum face = s_stencilFace[frontAndBack+ii];
  4150. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  4151. {
  4152. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  4153. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4154. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  4155. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask));
  4156. }
  4157. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  4158. {
  4159. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  4160. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  4161. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  4162. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  4163. }
  4164. }
  4165. }
  4166. else
  4167. {
  4168. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4169. }
  4170. }
  4171. if ( (0
  4172. | BGFX_STATE_CULL_MASK
  4173. | BGFX_STATE_DEPTH_WRITE
  4174. | BGFX_STATE_DEPTH_TEST_MASK
  4175. | BGFX_STATE_RGB_WRITE
  4176. | BGFX_STATE_ALPHA_WRITE
  4177. | BGFX_STATE_BLEND_MASK
  4178. | BGFX_STATE_BLEND_EQUATION_MASK
  4179. | BGFX_STATE_ALPHA_REF_MASK
  4180. | BGFX_STATE_PT_MASK
  4181. | BGFX_STATE_POINT_SIZE_MASK
  4182. | BGFX_STATE_MSAA
  4183. ) & changedFlags)
  4184. {
  4185. if (BGFX_STATE_CULL_MASK & changedFlags)
  4186. {
  4187. if (BGFX_STATE_CULL_CW & newFlags)
  4188. {
  4189. GL_CHECK(glEnable(GL_CULL_FACE) );
  4190. GL_CHECK(glCullFace(GL_BACK) );
  4191. }
  4192. else if (BGFX_STATE_CULL_CCW & newFlags)
  4193. {
  4194. GL_CHECK(glEnable(GL_CULL_FACE) );
  4195. GL_CHECK(glCullFace(GL_FRONT) );
  4196. }
  4197. else
  4198. {
  4199. GL_CHECK(glDisable(GL_CULL_FACE) );
  4200. }
  4201. }
  4202. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  4203. {
  4204. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  4205. }
  4206. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  4207. {
  4208. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  4209. if (0 != func)
  4210. {
  4211. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4212. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  4213. }
  4214. else
  4215. {
  4216. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  4217. }
  4218. }
  4219. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  4220. {
  4221. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  4222. viewState.m_alphaRef = ref/255.0f;
  4223. }
  4224. #if BGFX_CONFIG_RENDERER_OPENGL
  4225. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  4226. {
  4227. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  4228. GL_CHECK(glPointSize(pointSize) );
  4229. }
  4230. if (BGFX_STATE_MSAA & changedFlags)
  4231. {
  4232. if (BGFX_STATE_MSAA & newFlags)
  4233. {
  4234. GL_CHECK(glEnable(GL_MULTISAMPLE) );
  4235. }
  4236. else
  4237. {
  4238. GL_CHECK(glDisable(GL_MULTISAMPLE) );
  4239. }
  4240. }
  4241. #endif // BGFX_CONFIG_RENDERER_OPENGL
  4242. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  4243. {
  4244. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  4245. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  4246. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  4247. }
  4248. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & changedFlags
  4249. || blendFactor != draw.m_rgba)
  4250. {
  4251. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & newFlags
  4252. || blendFactor != draw.m_rgba)
  4253. {
  4254. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  4255. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  4256. && blendIndependentSupported
  4257. ;
  4258. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  4259. const uint32_t srcRGB = (blend )&0xf;
  4260. const uint32_t dstRGB = (blend>> 4)&0xf;
  4261. const uint32_t srcA = (blend>> 8)&0xf;
  4262. const uint32_t dstA = (blend>>12)&0xf;
  4263. const uint32_t equ = uint32_t((newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  4264. const uint32_t equRGB = (equ )&0x7;
  4265. const uint32_t equA = (equ>>3)&0x7;
  4266. const uint32_t numRt = getNumRt();
  4267. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4268. || 1 >= numRt
  4269. || !independent)
  4270. {
  4271. if (enabled)
  4272. {
  4273. GL_CHECK(glEnable(GL_BLEND) );
  4274. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  4275. , s_blendFactor[dstRGB].m_dst
  4276. , s_blendFactor[srcA].m_src
  4277. , s_blendFactor[dstA].m_dst
  4278. ) );
  4279. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  4280. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  4281. && blendFactor != draw.m_rgba)
  4282. {
  4283. const uint32_t rgba = draw.m_rgba;
  4284. GLclampf rr = ( (rgba>>24) )/255.0f;
  4285. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  4286. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  4287. GLclampf aa = ( (rgba )&0xff)/255.0f;
  4288. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  4289. }
  4290. }
  4291. else
  4292. {
  4293. GL_CHECK(glDisable(GL_BLEND) );
  4294. }
  4295. }
  4296. else
  4297. {
  4298. if (enabled)
  4299. {
  4300. GL_CHECK(glEnablei(GL_BLEND, 0) );
  4301. GL_CHECK(glBlendFuncSeparatei(0
  4302. , s_blendFactor[srcRGB].m_src
  4303. , s_blendFactor[dstRGB].m_dst
  4304. , s_blendFactor[srcA].m_src
  4305. , s_blendFactor[dstA].m_dst
  4306. ) );
  4307. GL_CHECK(glBlendEquationSeparatei(0
  4308. , s_blendEquation[equRGB]
  4309. , s_blendEquation[equA]
  4310. ) );
  4311. }
  4312. else
  4313. {
  4314. GL_CHECK(glDisablei(GL_BLEND, 0) );
  4315. }
  4316. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  4317. {
  4318. if (0 != (rgba&0x7ff) )
  4319. {
  4320. const uint32_t src = (rgba )&0xf;
  4321. const uint32_t dst = (rgba>>4)&0xf;
  4322. const uint32_t equation = (rgba>>8)&0x7;
  4323. GL_CHECK(glEnablei(GL_BLEND, ii) );
  4324. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  4325. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  4326. }
  4327. else
  4328. {
  4329. GL_CHECK(glDisablei(GL_BLEND, ii) );
  4330. }
  4331. }
  4332. }
  4333. }
  4334. else
  4335. {
  4336. GL_CHECK(glDisable(GL_BLEND) );
  4337. }
  4338. blendFactor = draw.m_rgba;
  4339. }
  4340. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  4341. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4342. prim = s_primInfo[primIndex];
  4343. }
  4344. bool programChanged = false;
  4345. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  4346. bool bindAttribs = false;
  4347. rendererUpdateUniforms(this, _render->m_constantBuffer, draw.m_constBegin, draw.m_constEnd);
  4348. if (key.m_program != programIdx)
  4349. {
  4350. programIdx = key.m_program;
  4351. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  4352. GL_CHECK(glUseProgram(id) );
  4353. programChanged =
  4354. constantsChanged =
  4355. bindAttribs = true;
  4356. }
  4357. if (invalidHandle != programIdx)
  4358. {
  4359. ProgramGL& program = m_program[programIdx];
  4360. if (constantsChanged
  4361. && NULL != program.m_constantBuffer)
  4362. {
  4363. commit(*program.m_constantBuffer);
  4364. }
  4365. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  4366. {
  4367. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  4368. {
  4369. const Binding& sampler = draw.m_bind[stage];
  4370. Binding& current = currentState.m_bind[stage];
  4371. if (current.m_idx != sampler.m_idx
  4372. || current.m_un.m_draw.m_flags != sampler.m_un.m_draw.m_flags
  4373. || programChanged)
  4374. {
  4375. if (invalidHandle != sampler.m_idx)
  4376. {
  4377. TextureGL& texture = m_textures[sampler.m_idx];
  4378. texture.commit(stage, sampler.m_un.m_draw.m_flags);
  4379. }
  4380. }
  4381. current = sampler;
  4382. }
  4383. }
  4384. if (0 != defaultVao
  4385. && 0 == draw.m_startVertex
  4386. && 0 == draw.m_instanceDataOffset)
  4387. {
  4388. if (programChanged
  4389. || baseVertex != draw.m_startVertex
  4390. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4391. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  4392. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4393. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  4394. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx)
  4395. {
  4396. bx::HashMurmur2A murmur;
  4397. murmur.begin();
  4398. murmur.add(draw.m_vertexBuffer.idx);
  4399. if (isValid(draw.m_vertexBuffer) )
  4400. {
  4401. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4402. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4403. murmur.add(decl);
  4404. }
  4405. murmur.add(draw.m_indexBuffer.idx);
  4406. murmur.add(draw.m_instanceDataBuffer.idx);
  4407. murmur.add(draw.m_instanceDataOffset);
  4408. murmur.add(draw.m_instanceDataStride);
  4409. murmur.add(programIdx);
  4410. uint32_t hash = murmur.end();
  4411. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4412. currentState.m_indexBuffer = draw.m_indexBuffer;
  4413. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4414. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4415. baseVertex = draw.m_startVertex;
  4416. GLuint id = m_vaoStateCache.find(hash);
  4417. if (UINT32_MAX != id)
  4418. {
  4419. currentVao = id;
  4420. GL_CHECK(glBindVertexArray(id) );
  4421. }
  4422. else
  4423. {
  4424. id = m_vaoStateCache.add(hash);
  4425. currentVao = id;
  4426. GL_CHECK(glBindVertexArray(id) );
  4427. program.add(hash);
  4428. if (isValid(draw.m_vertexBuffer) )
  4429. {
  4430. VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4431. vb.add(hash);
  4432. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4433. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4434. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4435. if (isValid(draw.m_instanceDataBuffer) )
  4436. {
  4437. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  4438. instanceVb.add(hash);
  4439. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  4440. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4441. }
  4442. }
  4443. else
  4444. {
  4445. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4446. }
  4447. if (isValid(draw.m_indexBuffer) )
  4448. {
  4449. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4450. ib.add(hash);
  4451. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4452. }
  4453. else
  4454. {
  4455. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4456. }
  4457. }
  4458. }
  4459. }
  4460. else
  4461. {
  4462. if (0 != defaultVao
  4463. && 0 != currentVao)
  4464. {
  4465. GL_CHECK(glBindVertexArray(defaultVao) );
  4466. currentState.m_vertexBuffer.idx = invalidHandle;
  4467. currentState.m_indexBuffer.idx = invalidHandle;
  4468. bindAttribs = true;
  4469. currentVao = 0;
  4470. }
  4471. if (programChanged
  4472. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4473. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  4474. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4475. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  4476. {
  4477. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4478. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  4479. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4480. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4481. uint16_t handle = draw.m_vertexBuffer.idx;
  4482. if (invalidHandle != handle)
  4483. {
  4484. VertexBufferGL& vb = m_vertexBuffers[handle];
  4485. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4486. bindAttribs = true;
  4487. }
  4488. else
  4489. {
  4490. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4491. }
  4492. }
  4493. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  4494. {
  4495. currentState.m_indexBuffer = draw.m_indexBuffer;
  4496. uint16_t handle = draw.m_indexBuffer.idx;
  4497. if (invalidHandle != handle)
  4498. {
  4499. IndexBufferGL& ib = m_indexBuffers[handle];
  4500. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4501. }
  4502. else
  4503. {
  4504. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4505. }
  4506. }
  4507. if (isValid(currentState.m_vertexBuffer) )
  4508. {
  4509. if (baseVertex != draw.m_startVertex
  4510. || bindAttribs)
  4511. {
  4512. baseVertex = draw.m_startVertex;
  4513. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4514. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4515. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4516. if (isValid(draw.m_instanceDataBuffer) )
  4517. {
  4518. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  4519. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4520. }
  4521. }
  4522. }
  4523. }
  4524. if (isValid(currentState.m_vertexBuffer) )
  4525. {
  4526. uint32_t numVertices = draw.m_numVertices;
  4527. if (UINT32_MAX == numVertices)
  4528. {
  4529. const VertexBufferGL& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  4530. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4531. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  4532. numVertices = vb.m_size/vertexDecl.m_stride;
  4533. }
  4534. uint32_t numIndices = 0;
  4535. uint32_t numPrimsSubmitted = 0;
  4536. uint32_t numInstances = 0;
  4537. uint32_t numPrimsRendered = 0;
  4538. if (isValid(draw.m_indexBuffer) )
  4539. {
  4540. if (UINT32_MAX == draw.m_numIndices)
  4541. {
  4542. numIndices = m_indexBuffers[draw.m_indexBuffer.idx].m_size/2;
  4543. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  4544. numInstances = draw.m_numInstances;
  4545. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4546. GL_CHECK(glDrawElementsInstanced(prim.m_type
  4547. , numIndices
  4548. , GL_UNSIGNED_SHORT
  4549. , (void*)0
  4550. , draw.m_numInstances
  4551. ) );
  4552. }
  4553. else if (prim.m_min <= draw.m_numIndices)
  4554. {
  4555. numIndices = draw.m_numIndices;
  4556. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  4557. numInstances = draw.m_numInstances;
  4558. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4559. GL_CHECK(glDrawElementsInstanced(prim.m_type
  4560. , numIndices
  4561. , GL_UNSIGNED_SHORT
  4562. , (void*)(uintptr_t)(draw.m_startIndex*2)
  4563. , draw.m_numInstances
  4564. ) );
  4565. }
  4566. }
  4567. else
  4568. {
  4569. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  4570. numInstances = draw.m_numInstances;
  4571. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4572. GL_CHECK(glDrawArraysInstanced(prim.m_type
  4573. , 0
  4574. , numVertices
  4575. , draw.m_numInstances
  4576. ) );
  4577. }
  4578. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  4579. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  4580. statsNumInstances[primIndex] += numInstances;
  4581. statsNumIndices += numIndices;
  4582. }
  4583. }
  4584. }
  4585. blitMsaaFbo();
  4586. if (0 < _render->m_num)
  4587. {
  4588. captureElapsed = -bx::getHPCounter();
  4589. capture();
  4590. captureElapsed += bx::getHPCounter();
  4591. }
  4592. }
  4593. m_glctx.makeCurrent(NULL);
  4594. int64_t now = bx::getHPCounter();
  4595. elapsed += now;
  4596. static int64_t last = now;
  4597. int64_t frameTime = now - last;
  4598. last = now;
  4599. static int64_t min = frameTime;
  4600. static int64_t max = frameTime;
  4601. min = min > frameTime ? frameTime : min;
  4602. max = max < frameTime ? frameTime : max;
  4603. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  4604. {
  4605. double elapsedGpuMs = 0.0;
  4606. uint64_t elapsedGl = 0;
  4607. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4608. && m_timerQuerySupport)
  4609. {
  4610. m_queries.end(GL_TIME_ELAPSED);
  4611. elapsedGl = m_queries.getResult(0);
  4612. elapsedGpuMs = double(elapsedGl)/1e6;
  4613. }
  4614. TextVideoMem& tvm = m_textVideoMem;
  4615. static int64_t next = now;
  4616. if (now >= next)
  4617. {
  4618. next = now + bx::getHPFrequency();
  4619. double freq = double(bx::getHPFrequency() );
  4620. double toMs = 1000.0/freq;
  4621. tvm.clear();
  4622. uint16_t pos = 0;
  4623. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  4624. , getRendererName()
  4625. );
  4626. tvm.printf(0, pos++, 0x0f, " Vendor: %s", m_vendor);
  4627. tvm.printf(0, pos++, 0x0f, " Renderer: %s", m_renderer);
  4628. tvm.printf(0, pos++, 0x0f, " Version: %s", m_version);
  4629. tvm.printf(0, pos++, 0x0f, "GLSL version: %s", m_glslVersion);
  4630. pos = 10;
  4631. tvm.printf(10, pos++, 0x8e, " Frame CPU: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  4632. , double(frameTime)*toMs
  4633. , double(min)*toMs
  4634. , double(max)*toMs
  4635. , freq/frameTime
  4636. );
  4637. char hmd[16];
  4638. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  4639. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  4640. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  4641. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  4642. , 0 != msaa ? '\xfe' : ' '
  4643. , 1<<msaa
  4644. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  4645. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  4646. );
  4647. double elapsedCpuMs = double(elapsed)*toMs;
  4648. tvm.printf(10, pos++, 0x8e, " Submitted: %4d (draw %4d, compute %4d) / CPU %3.4f [ms] %c GPU %3.4f [ms]"
  4649. , _render->m_num
  4650. , statsKeyType[0]
  4651. , statsKeyType[1]
  4652. , elapsedCpuMs
  4653. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  4654. , elapsedGpuMs
  4655. );
  4656. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  4657. {
  4658. tvm.printf(10, pos++, 0x8e, " %9s: %7d (#inst: %5d), submitted: %7d"
  4659. , s_primName[ii]
  4660. , statsNumPrimsRendered[ii]
  4661. , statsNumInstances[ii]
  4662. , statsNumPrimsSubmitted[ii]
  4663. );
  4664. }
  4665. if (NULL != m_renderdocdll)
  4666. {
  4667. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  4668. }
  4669. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  4670. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", _render->m_vboffset);
  4671. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", _render->m_iboffset);
  4672. pos++;
  4673. tvm.printf(10, pos++, 0x8e, " State cache: ");
  4674. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  4675. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  4676. , m_vaoStateCache.getCount()
  4677. , m_samplerStateCache.getCount()
  4678. );
  4679. pos++;
  4680. double captureMs = double(captureElapsed)*toMs;
  4681. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  4682. #if BGFX_CONFIG_RENDERER_OPENGL
  4683. if (s_extension[Extension::ATI_meminfo].m_supported)
  4684. {
  4685. GLint vboFree[4];
  4686. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  4687. GLint texFree[4];
  4688. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  4689. GLint rbfFree[4];
  4690. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  4691. pos++;
  4692. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb");
  4693. char tmp0[16];
  4694. char tmp1[16];
  4695. char tmp2[16];
  4696. char tmp3[16];
  4697. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  4698. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  4699. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  4700. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  4701. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  4702. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  4703. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  4704. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  4705. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  4706. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  4707. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  4708. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  4709. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  4710. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  4711. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  4712. }
  4713. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  4714. {
  4715. GLint dedicated;
  4716. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  4717. GLint totalAvail;
  4718. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  4719. GLint currAvail;
  4720. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  4721. GLint evictedCount;
  4722. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  4723. GLint evictedMemory;
  4724. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  4725. pos += 2;
  4726. char tmp0[16];
  4727. char tmp1[16];
  4728. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  4729. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s", tmp0);
  4730. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  4731. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  4732. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s", tmp0, tmp1);
  4733. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  4734. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  4735. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s", tmp0, tmp1);
  4736. }
  4737. #endif // BGFX_CONFIG_RENDERER_OPENGL
  4738. uint8_t attr[2] = { 0x89, 0x8a };
  4739. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  4740. pos++;
  4741. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", double(_render->m_waitSubmit)*toMs);
  4742. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", double(_render->m_waitRender)*toMs);
  4743. min = frameTime;
  4744. max = frameTime;
  4745. }
  4746. blit(this, _textVideoMemBlitter, tvm);
  4747. }
  4748. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  4749. {
  4750. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  4751. }
  4752. GL_CHECK(glFrameTerminatorGREMEDY() );
  4753. }
  4754. } } // namespace bgfx
  4755. #else
  4756. namespace bgfx { namespace gl
  4757. {
  4758. RendererContextI* rendererCreate()
  4759. {
  4760. return NULL;
  4761. }
  4762. void rendererDestroy()
  4763. {
  4764. }
  4765. } /* namespace gl */ } // namespace bgfx
  4766. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)