renderer_gl.cpp 139 KB

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