renderer_gl.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484
  1. /*
  2. * Copyright 2011-2013 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_OPENGLES2|BGFX_CONFIG_RENDERER_OPENGLES3|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 Extension
  14. {
  15. enum Enum
  16. {
  17. EXT_texture_filter_anisotropic,
  18. EXT_texture_format_BGRA8888,
  19. EXT_bgra,
  20. EXT_texture_compression_s3tc,
  21. EXT_texture_compression_dxt1,
  22. CHROMIUM_texture_compression_dxt3,
  23. CHROMIUM_texture_compression_dxt5,
  24. EXT_texture_compression_latc,
  25. EXT_texture_compression_rgtc,
  26. ARB_texture_float,
  27. OES_texture_float,
  28. OES_texture_float_linear,
  29. OES_texture_half_float,
  30. OES_texture_half_float_linear,
  31. EXT_texture_type_2_10_10_10_REV,
  32. EXT_texture_sRGB,
  33. ARB_texture_swizzle,
  34. EXT_texture_swizzle,
  35. ARB_texture_multisample,
  36. OES_standard_derivatives,
  37. ARB_get_program_binary,
  38. OES_get_program_binary,
  39. EXT_framebuffer_blit,
  40. ARB_timer_query,
  41. EXT_timer_query,
  42. ARB_framebuffer_sRGB,
  43. EXT_framebuffer_sRGB,
  44. ARB_multisample,
  45. CHROMIUM_framebuffer_multisample,
  46. ANGLE_translated_shader_source,
  47. ARB_instanced_arrays,
  48. ANGLE_instanced_arrays,
  49. ARB_half_float_vertex,
  50. OES_vertex_half_float,
  51. ARB_vertex_type_2_10_10_10_rev,
  52. OES_vertex_type_10_10_10_2,
  53. EXT_occlusion_query_boolean,
  54. ARB_vertex_array_object,
  55. OES_vertex_array_object,
  56. ATI_meminfo,
  57. NVX_gpu_memory_info,
  58. OES_rgb8_rgba8,
  59. EXT_texture_storage,
  60. EXT_blend_color,
  61. EXT_blend_subtract,
  62. EXT_blend_minmax,
  63. ARB_debug_output,
  64. Count
  65. };
  66. const char* m_name;
  67. bool m_supported;
  68. bool m_initialize;
  69. };
  70. static Extension s_extension[Extension::Count] =
  71. {
  72. { "GL_EXT_texture_filter_anisotropic", false, true },
  73. { "GL_EXT_texture_format_BGRA8888", false, true },
  74. { "GL_EXT_bgra", false, true },
  75. { "GL_EXT_texture_compression_s3tc", false, true },
  76. { "GL_EXT_texture_compression_dxt1", false, true },
  77. { "GL_CHROMIUM_texture_compression_dxt3", false, true },
  78. { "GL_CHROMIUM_texture_compression_dxt5", false, true },
  79. { "GL_EXT_texture_compression_latc", false, true },
  80. { "GL_EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  81. { "GL_ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  82. { "GL_OES_texture_float", false, true },
  83. { "GL_OES_texture_float_linear", false, true },
  84. { "GL_OES_texture_half_float", false, true },
  85. { "GL_OES_texture_half_float_linear", false, true },
  86. { "GL_EXT_texture_type_2_10_10_10_REV", false, true },
  87. { "GL_EXT_texture_sRGB", false, true },
  88. { "GL_ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  89. { "GL_EXT_texture_swizzle", false, true },
  90. { "GL_ARB_texture_multisample", false, true },
  91. { "GL_OES_standard_derivatives", false, true },
  92. { "GL_ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  93. { "GL_OES_get_program_binary", false, false },
  94. { "GL_EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  95. { "GL_ARB_timer_query", false, true },
  96. { "GL_EXT_timer_query", false, true },
  97. { "GL_ARB_framebuffer_sRGB", false, true },
  98. { "GL_EXT_framebuffer_sRGB", false, true },
  99. { "GL_ARB_multisample", false, true },
  100. { "GL_CHROMIUM_framebuffer_multisample", false, true },
  101. { "GL_ANGLE_translated_shader_source", false, true },
  102. { "GL_ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  103. { "GL_ANGLE_instanced_arrays", false, true },
  104. { "GL_ARB_half_float_vertex", false, true },
  105. { "GL_OES_vertex_half_float", false, true },
  106. { "GL_ARB_vertex_type_2_10_10_10_rev", false, true },
  107. { "GL_OES_vertex_type_10_10_10_2", false, true },
  108. { "GL_EXT_occlusion_query_boolean", false, true },
  109. { "GL_ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  110. { "OES_vertex_array_object", false, true },
  111. { "GL_ATI_meminfo", false, true },
  112. { "GL_NVX_gpu_memory_info", false, true },
  113. { "GL_OES_rgb8_rgba8", false, true },
  114. { "GL_EXT_texture_storage", false, true },
  115. { "GL_EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  116. { "GL_EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  117. { "GL_EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  118. { "GL_ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  119. };
  120. #if BGFX_CONFIG_RENDERER_OPENGLES3
  121. # define s_vertexAttribDivisor glVertexAttribDivisor
  122. # define s_drawArraysInstanced glDrawArraysInstanced
  123. # define s_drawElementsInstanced glDrawElementsInstanced
  124. #else
  125. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  126. {
  127. }
  128. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  129. {
  130. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  131. }
  132. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  133. {
  134. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  135. }
  136. static PFNGLVERTEXATTRIBDIVISORBGFXPROC s_vertexAttribDivisor = stubVertexAttribDivisor;
  137. static PFNGLDRAWARRAYSINSTANCEDBGFXPROC s_drawArraysInstanced = stubDrawArraysInstanced;
  138. static PFNGLDRAWELEMENTSINSTANCEDBGFXPROC s_drawElementsInstanced = stubDrawElementsInstanced;
  139. #endif // BGFX_CONFIG_RENDERER_OPENGLES3
  140. #if BGFX_CONFIG_DEBUG_GREMEDY
  141. static void GL_APIENTRY stubStringMarkerGREMEDY(GLsizei /*_len*/, const GLvoid* /*_string*/)
  142. {
  143. }
  144. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  145. {
  146. }
  147. #endif // BGFX_CONFIG_DEBUG_GREMEDY
  148. #if BX_PLATFORM_IOS
  149. PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES = NULL;
  150. PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES = NULL;
  151. PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES = NULL;
  152. PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES = NULL;
  153. PFNGLGETPROGRAMBINARYOESPROC glGetProgramBinaryOES = NULL;
  154. PFLGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstanced = NULL;
  155. PFLGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstanced = NULL;
  156. #endif // BX_PLATFORM_IOS
  157. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  158. static void rgbaToBgra(uint8_t* _data, uint32_t _width, uint32_t _height)
  159. {
  160. uint32_t dstpitch = _width*4;
  161. for (uint32_t yy = 0; yy < _height; ++yy)
  162. {
  163. uint8_t* dst = &_data[yy*dstpitch];
  164. for (uint32_t xx = 0; xx < _width; ++xx)
  165. {
  166. uint8_t tmp = dst[0];
  167. dst[0] = dst[2];
  168. dst[2] = tmp;
  169. dst += 4;
  170. }
  171. }
  172. }
  173. static const char* getGLString(GLenum _name)
  174. {
  175. const char* str = (const char*)glGetString(_name);
  176. glGetError(); // ignore error if glGetString returns NULL.
  177. if (NULL != str)
  178. {
  179. return str;
  180. }
  181. return "<unknown>";
  182. }
  183. static uint32_t getGLStringHash(GLenum _name)
  184. {
  185. const char* str = (const char*)glGetString(_name);
  186. glGetError(); // ignore error if glGetString returns NULL.
  187. if (NULL != str)
  188. {
  189. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  190. }
  191. return 0;
  192. }
  193. void dumpExtensions(const char* _extensions)
  194. {
  195. if (NULL != _extensions)
  196. {
  197. char name[1024];
  198. const char* pos = _extensions;
  199. const char* end = _extensions + strlen(_extensions);
  200. while (pos < end)
  201. {
  202. uint32_t len;
  203. const char* space = strchr(pos, ' ');
  204. if (NULL != space)
  205. {
  206. len = uint32_min(sizeof(name), (uint32_t)(space - pos) );
  207. }
  208. else
  209. {
  210. len = uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  211. }
  212. strncpy(name, pos, len);
  213. name[len] = '\0';
  214. BX_TRACE("\t%s", name);
  215. pos += len+1;
  216. }
  217. }
  218. }
  219. #if BGFX_CONFIG_RENDERER_OPENGL
  220. const char* toString(GLenum _enum)
  221. {
  222. switch (_enum)
  223. {
  224. case GL_DEBUG_SOURCE_API_ARB: return "API";
  225. case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: return "WinSys";
  226. case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: return "Shader";
  227. case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: return "3rdparty";
  228. case GL_DEBUG_SOURCE_APPLICATION_ARB: return "Application";
  229. case GL_DEBUG_SOURCE_OTHER_ARB: return "Other";
  230. case GL_DEBUG_TYPE_ERROR_ARB: return "Error";
  231. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: return "Deprecated behavior";
  232. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: return "Undefined behavior";
  233. case GL_DEBUG_TYPE_PORTABILITY_ARB: return "Portability";
  234. case GL_DEBUG_TYPE_PERFORMANCE_ARB: return "Performance";
  235. case GL_DEBUG_TYPE_OTHER_ARB: return "Other";
  236. case GL_DEBUG_SEVERITY_HIGH_ARB: return "High";
  237. case GL_DEBUG_SEVERITY_MEDIUM_ARB: return "Medium";
  238. case GL_DEBUG_SEVERITY_LOW_ARB: return "Low";
  239. default:
  240. break;
  241. }
  242. return "<unknown>";
  243. }
  244. static void APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, GLvoid* /*_userParam*/)
  245. {
  246. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  247. , toString(_source)
  248. , toString(_type)
  249. , _id
  250. , toString(_severity)
  251. , _message
  252. );
  253. BX_UNUSED(_source, _type, _id, _severity, _message);
  254. }
  255. #endif // BGFX_CONFIG_RENDERER_OPENGL
  256. struct RendererContext
  257. {
  258. RendererContext()
  259. : m_rtMsaa(false)
  260. , m_capture(NULL)
  261. , m_captureSize(0)
  262. , m_maxAnisotropy(0.0f)
  263. , m_maxMsaa(0)
  264. , m_vao(0)
  265. , m_vaoSupport(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  266. , m_programBinarySupport(false)
  267. , m_textureSwizzleSupport(false)
  268. , m_useClearQuad(true)
  269. , m_flip(false)
  270. , m_postSwapBuffers(NULL)
  271. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  272. , m_backBufferFbo(0)
  273. {
  274. m_rt.idx = invalidHandle;
  275. memset(&m_resolution, 0, sizeof(m_resolution) );
  276. }
  277. void updateResolution(const Resolution& _resolution)
  278. {
  279. if (m_resolution.m_width != _resolution.m_width
  280. || m_resolution.m_height != _resolution.m_height
  281. || m_resolution.m_flags != _resolution.m_flags)
  282. {
  283. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  284. m_textVideoMem.clear();
  285. m_resolution = _resolution;
  286. uint32_t msaa = 1<<( (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT);
  287. msaa = uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  288. bool vsync = !!(m_resolution.m_flags&BGFX_RESET_VSYNC);
  289. setRenderContextSize(_resolution.m_width, _resolution.m_height, msaa, vsync);
  290. updateCapture();
  291. }
  292. }
  293. uint32_t setRenderTarget(RenderTargetHandle _rt, uint32_t _height, bool _msaa = true)
  294. {
  295. if (m_rt.idx != invalidHandle
  296. && m_rt.idx != _rt.idx
  297. && m_rtMsaa)
  298. {
  299. RenderTarget& renderTarget = m_renderTargets[m_rt.idx];
  300. if (0 != renderTarget.m_fbo[1])
  301. {
  302. renderTarget.resolve();
  303. }
  304. }
  305. if (_rt.idx == invalidHandle)
  306. {
  307. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  308. }
  309. else
  310. {
  311. RenderTarget& renderTarget = m_renderTargets[_rt.idx];
  312. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, renderTarget.m_fbo[0]) );
  313. _height = renderTarget.m_height;
  314. }
  315. m_rt = _rt;
  316. m_rtMsaa = _msaa;
  317. return _height;
  318. }
  319. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  320. {
  321. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  322. if (1 < _msaa)
  323. {
  324. GL_CHECK(glGenFramebuffers(1, &m_backBufferFbo) );
  325. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  326. GL_CHECK(glGenRenderbuffers(3, m_backBufferRbos) );
  327. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_backBufferRbos[0]) );
  328. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  329. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_backBufferRbos[1]) );
  330. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  331. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_backBufferRbos[0]) );
  332. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_backBufferRbos[1]) );
  333. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  334. , "glCheckFramebufferStatus failed 0x%08x"
  335. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  336. );
  337. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  338. }
  339. #else
  340. BX_UNUSED(_width);
  341. BX_UNUSED(_height);
  342. BX_UNUSED(_msaa);
  343. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  344. }
  345. void destroyMsaaFbo()
  346. {
  347. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  348. if (0 != m_backBufferFbo)
  349. {
  350. GL_CHECK(glDeleteFramebuffers(1, &m_backBufferFbo) );
  351. GL_CHECK(glDeleteRenderbuffers(3, m_backBufferRbos) );
  352. m_backBufferFbo = 0;
  353. }
  354. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  355. }
  356. void blitMsaaFbo()
  357. {
  358. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  359. if (0 != m_backBufferFbo)
  360. {
  361. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  362. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_backBufferFbo) );
  363. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  364. uint32_t width = m_resolution.m_width;
  365. uint32_t height = m_resolution.m_height;
  366. GL_CHECK(glBlitFramebuffer(0
  367. , 0
  368. , width
  369. , height
  370. , 0
  371. , 0
  372. , width
  373. , height
  374. , GL_COLOR_BUFFER_BIT
  375. , GL_LINEAR
  376. ) );
  377. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  378. }
  379. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  380. }
  381. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _msaa = 0, bool _vsync = false)
  382. {
  383. if (_width != 0
  384. || _height != 0)
  385. {
  386. if (!m_glctx.isValid() )
  387. {
  388. m_glctx.create(_width, _height);
  389. }
  390. else
  391. {
  392. destroyMsaaFbo();
  393. m_glctx.resize(_width, _height, _vsync);
  394. createMsaaFbo(_width, _height, _msaa);
  395. }
  396. }
  397. m_flip = true;
  398. }
  399. void flip()
  400. {
  401. if (m_flip)
  402. {
  403. m_glctx.swap();
  404. }
  405. if (NULL != m_postSwapBuffers)
  406. {
  407. m_postSwapBuffers(m_resolution.m_width, m_resolution.m_height);
  408. }
  409. }
  410. void invalidateCache()
  411. {
  412. if (m_vaoSupport)
  413. {
  414. m_vaoCache.invalidate();
  415. }
  416. }
  417. void updateCapture()
  418. {
  419. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  420. {
  421. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  422. m_capture = g_realloc(m_capture, m_captureSize);
  423. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  424. }
  425. else
  426. {
  427. if (NULL != m_capture)
  428. {
  429. g_callback->captureEnd();
  430. g_free(m_capture);
  431. m_capture = NULL;
  432. m_captureSize = 0;
  433. }
  434. }
  435. }
  436. void capture()
  437. {
  438. if (NULL != m_capture)
  439. {
  440. GLint fmt = s_extension[Extension::EXT_texture_format_BGRA8888].m_supported ? GL_BGRA_EXT : GL_RGBA;
  441. GL_CHECK(glReadPixels(0
  442. , 0
  443. , m_resolution.m_width
  444. , m_resolution.m_height
  445. , fmt
  446. , GL_UNSIGNED_BYTE
  447. , m_capture
  448. ) );
  449. g_callback->captureFrame(m_capture, m_captureSize);
  450. }
  451. }
  452. void saveScreenShot(const char* _filePath)
  453. {
  454. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  455. uint8_t* data = (uint8_t*)g_realloc(NULL, length);
  456. GLint fmt = s_extension[Extension::EXT_texture_format_BGRA8888].m_supported ? GL_BGRA_EXT : GL_RGBA;
  457. uint32_t width = m_resolution.m_width;
  458. uint32_t height = m_resolution.m_height;
  459. GL_CHECK(glReadPixels(0
  460. , 0
  461. , width
  462. , height
  463. , fmt
  464. , GL_UNSIGNED_BYTE
  465. , data
  466. ) );
  467. if (GL_RGBA == fmt)
  468. {
  469. rgbaToBgra(data, width, height);
  470. }
  471. g_callback->screenShot(_filePath
  472. , width
  473. , height
  474. , width*4
  475. , data
  476. , length
  477. , true
  478. );
  479. g_free(data);
  480. }
  481. void init()
  482. {
  483. m_glctx.create(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  484. m_vendor = getGLString(GL_VENDOR);
  485. m_renderer = getGLString(GL_RENDERER);
  486. m_version = getGLString(GL_VERSION);
  487. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  488. #if BGFX_CONFIG_DEBUG_GREMEDY
  489. if (NULL == glStringMarkerGREMEDY
  490. || NULL == glFrameTerminatorGREMEDY)
  491. {
  492. glStringMarkerGREMEDY = stubStringMarkerGREMEDY;
  493. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  494. }
  495. #endif // BGFX_CONFIG_DEBUG_GREMEDY
  496. #if BGFX_CONFIG_RENDERER_OPENGL
  497. m_queries.create();
  498. #endif // BGFX_CONFIG_RENDERER_OPENGL
  499. }
  500. void shutdown()
  501. {
  502. invalidateCache();
  503. #if BGFX_CONFIG_RENDERER_OPENGL
  504. m_queries.destroy();
  505. #endif // BGFX_CONFIG_RENDERER_OPENGL
  506. destroyMsaaFbo();
  507. m_glctx.destroy();
  508. m_flip = false;
  509. }
  510. IndexBuffer m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  511. VertexBuffer m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  512. Shader m_vertexShaders[BGFX_CONFIG_MAX_VERTEX_SHADERS];
  513. Shader m_fragmentShaders[BGFX_CONFIG_MAX_FRAGMENT_SHADERS];
  514. Program m_program[BGFX_CONFIG_MAX_PROGRAMS];
  515. Texture m_textures[BGFX_CONFIG_MAX_TEXTURES];
  516. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  517. RenderTarget m_renderTargets[BGFX_CONFIG_MAX_RENDER_TARGETS];
  518. UniformRegistry m_uniformReg;
  519. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  520. #if BGFX_CONFIG_RENDERER_OPENGL
  521. Queries m_queries;
  522. #endif // BGFX_CONFIG_RENDERER_OPENGL
  523. VaoCache m_vaoCache;
  524. TextVideoMem m_textVideoMem;
  525. RenderTargetHandle m_rt;
  526. bool m_rtMsaa;
  527. Resolution m_resolution;
  528. void* m_capture;
  529. uint32_t m_captureSize;
  530. float m_maxAnisotropy;
  531. int32_t m_maxMsaa;
  532. GLuint m_vao;
  533. bool m_vaoSupport;
  534. bool m_programBinarySupport;
  535. bool m_textureSwizzleSupport;
  536. bool m_useClearQuad;
  537. bool m_flip;
  538. PostSwapBuffersFn m_postSwapBuffers;
  539. uint64_t m_hash;
  540. GLuint m_backBufferFbo;
  541. GLuint m_backBufferRbos[2];
  542. GlContext m_glctx;
  543. const char* m_vendor;
  544. const char* m_renderer;
  545. const char* m_version;
  546. const char* m_glslVersion;
  547. };
  548. RendererContext s_renderCtx;
  549. #if BX_PLATFORM_NACL
  550. static void GL_APIENTRY naclVertexAttribDivisor(GLuint _index, GLuint _divisor)
  551. {
  552. s_renderCtx.m_glctx.m_instancedArrays->VertexAttribDivisorANGLE(s_renderCtx.m_glctx.m_context, _index, _divisor);
  553. }
  554. static void GL_APIENTRY naclDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei _primcount)
  555. {
  556. s_renderCtx.m_glctx.m_instancedArrays->DrawArraysInstancedANGLE(s_renderCtx.m_glctx.m_context, _mode, _first, _count, _primcount);
  557. }
  558. static void GL_APIENTRY naclDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei _primcount)
  559. {
  560. s_renderCtx.m_glctx.m_instancedArrays->DrawElementsInstancedANGLE(s_renderCtx.m_glctx.m_context, _mode, _count, _type, _indices, _primcount);
  561. }
  562. void naclSetIntefraces(PP_Instance _instance, const PPB_Instance* _instInterface, const PPB_Graphics3D* _graphicsInterface, PostSwapBuffersFn _postSwapBuffers)
  563. {
  564. s_renderCtx.m_glctx.m_instance = _instance;
  565. s_renderCtx.m_glctx.m_instInterface = _instInterface;
  566. s_renderCtx.m_glctx.m_graphicsInterface = _graphicsInterface;
  567. s_renderCtx.m_postSwapBuffers = _postSwapBuffers;
  568. s_renderCtx.m_glctx.m_instancedArrays = glGetInstancedArraysInterfacePPAPI();
  569. s_renderCtx.setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  570. if (NULL != s_renderCtx.m_glctx.m_instancedArrays)
  571. {
  572. s_vertexAttribDivisor = naclVertexAttribDivisor;
  573. s_drawArraysInstanced = naclDrawArraysInstanced;
  574. s_drawElementsInstanced = naclDrawElementsInstanced;
  575. }
  576. }
  577. void naclSwapCompleteCb(void* /*_data*/, int32_t /*_result*/)
  578. {
  579. renderFrame();
  580. }
  581. #endif // BX_PLATFORM_
  582. static const GLenum s_primType[] =
  583. {
  584. GL_TRIANGLES,
  585. GL_LINES,
  586. GL_POINTS,
  587. };
  588. static const char* s_attribName[Attrib::Count] =
  589. {
  590. "a_position",
  591. "a_normal",
  592. "a_tangent",
  593. "a_color0",
  594. "a_color1",
  595. "a_indices",
  596. "a_weight",
  597. "a_texcoord0",
  598. "a_texcoord1",
  599. "a_texcoord2",
  600. "a_texcoord3",
  601. "a_texcoord4",
  602. "a_texcoord5",
  603. "a_texcoord6",
  604. "a_texcoord7",
  605. };
  606. static const char* s_instanceDataName[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT] =
  607. {
  608. "i_data0",
  609. "i_data1",
  610. "i_data2",
  611. "i_data3",
  612. "i_data4",
  613. };
  614. static const GLenum s_attribType[AttribType::Count] =
  615. {
  616. GL_UNSIGNED_BYTE,
  617. GL_SHORT,
  618. GL_HALF_FLOAT,
  619. GL_FLOAT,
  620. };
  621. struct Blend
  622. {
  623. GLenum m_src;
  624. GLenum m_dst;
  625. bool m_factor;
  626. };
  627. static const Blend s_blendFactor[] =
  628. {
  629. { 0, 0, false }, // ignored
  630. { GL_ZERO, GL_ZERO, false },
  631. { GL_ONE, GL_ONE, false },
  632. { GL_SRC_COLOR, GL_SRC_COLOR, false },
  633. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false },
  634. { GL_SRC_ALPHA, GL_SRC_ALPHA, false },
  635. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false },
  636. { GL_DST_ALPHA, GL_DST_ALPHA, false },
  637. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false },
  638. { GL_DST_COLOR, GL_DST_COLOR, false },
  639. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false },
  640. { GL_SRC_ALPHA_SATURATE, GL_ONE, false },
  641. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true },
  642. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true },
  643. };
  644. static const GLenum s_blendEquation[] =
  645. {
  646. GL_FUNC_ADD,
  647. GL_FUNC_SUBTRACT,
  648. GL_FUNC_REVERSE_SUBTRACT,
  649. GL_MIN,
  650. GL_MAX,
  651. };
  652. static const GLenum s_depthFunc[] =
  653. {
  654. 0, // ignored
  655. GL_LESS,
  656. GL_LEQUAL,
  657. GL_EQUAL,
  658. GL_GEQUAL,
  659. GL_GREATER,
  660. GL_NOTEQUAL,
  661. GL_NEVER,
  662. GL_ALWAYS,
  663. };
  664. static const GLenum s_stencilFunc[] =
  665. {
  666. 0, // ignored
  667. GL_LESS,
  668. GL_LEQUAL,
  669. GL_EQUAL,
  670. GL_GEQUAL,
  671. GL_GREATER,
  672. GL_NOTEQUAL,
  673. GL_NEVER,
  674. GL_ALWAYS,
  675. };
  676. static const GLenum s_stencilOp[] =
  677. {
  678. GL_ZERO,
  679. GL_KEEP,
  680. GL_REPLACE,
  681. GL_INCR_WRAP,
  682. GL_INCR,
  683. GL_DECR_WRAP,
  684. GL_DECR,
  685. GL_INVERT,
  686. };
  687. static const GLenum s_stencilFace[] =
  688. {
  689. GL_FRONT_AND_BACK,
  690. GL_FRONT,
  691. GL_BACK,
  692. };
  693. struct RenderTargetColorFormat
  694. {
  695. GLenum m_internalFmt;
  696. GLenum m_type;
  697. uint8_t m_bpp;
  698. };
  699. // Specifies the internal format of the texture.
  700. // Must be one of the following symbolic constants:
  701. // GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA.
  702. static const RenderTargetColorFormat s_colorFormat[] =
  703. {
  704. { 0, 0, 0 }, // ignored
  705. { GL_RGBA8, GL_UNSIGNED_BYTE, 32 },
  706. { GL_RGB10_A2, GL_UNSIGNED_INT_2_10_10_10_REV, 32 },
  707. { GL_RGBA16, GL_UNSIGNED_SHORT, 64 },
  708. { GL_RGBA16F, GL_HALF_FLOAT, 64 },
  709. { GL_R16F, GL_HALF_FLOAT, 16 },
  710. { GL_R32F, GL_FLOAT, 32 },
  711. };
  712. static const GLenum s_depthFormat[] =
  713. {
  714. 0, // ignored
  715. 0,
  716. };
  717. static const GLenum s_textureAddress[] =
  718. {
  719. GL_REPEAT,
  720. GL_MIRRORED_REPEAT,
  721. GL_CLAMP_TO_EDGE,
  722. };
  723. static const GLenum s_textureFilterMag[] =
  724. {
  725. GL_LINEAR,
  726. GL_NEAREST,
  727. GL_LINEAR,
  728. };
  729. static const GLenum s_textureFilterMin[][3] =
  730. {
  731. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  732. { GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_NEAREST },
  733. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  734. };
  735. struct TextureFormatInfo
  736. {
  737. GLenum m_internalFmt;
  738. GLenum m_fmt;
  739. GLenum m_type;
  740. uint8_t m_bpp;
  741. bool m_supported;
  742. };
  743. static TextureFormatInfo s_textureFormat[TextureFormat::Count] =
  744. {
  745. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, 4, false },
  746. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, 8, false },
  747. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, 8, false },
  748. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, 4, false },
  749. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, 8, false },
  750. { GL_ZERO, GL_ZERO, GL_ZERO, 0, true },
  751. { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, true },
  752. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, true },
  753. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, true },
  754. { GL_RGBA16, GL_RGBA, GL_UNSIGNED_BYTE, 64, true },
  755. { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 64, true },
  756. { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, true },
  757. { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, true },
  758. { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, true },
  759. { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 32, true },
  760. };
  761. const char* glslTypeName(GLuint _type)
  762. {
  763. #define GLSL_TYPE(_ty) case _ty: return #_ty
  764. switch (_type)
  765. {
  766. GLSL_TYPE(GL_FLOAT);
  767. GLSL_TYPE(GL_FLOAT_VEC2);
  768. GLSL_TYPE(GL_FLOAT_VEC3);
  769. GLSL_TYPE(GL_FLOAT_VEC4);
  770. GLSL_TYPE(GL_FLOAT_MAT2);
  771. GLSL_TYPE(GL_FLOAT_MAT3);
  772. GLSL_TYPE(GL_FLOAT_MAT4);
  773. // GLSL_TYPE(GL_FLOAT_MAT2x3);
  774. // GLSL_TYPE(GL_FLOAT_MAT2x4);
  775. // GLSL_TYPE(GL_FLOAT_MAT3x2);
  776. // GLSL_TYPE(GL_FLOAT_MAT3x4);
  777. // GLSL_TYPE(GL_FLOAT_MAT4x2);
  778. // GLSL_TYPE(GL_FLOAT_MAT4x3);
  779. // GLSL_TYPE(GL_SAMPLER_1D);
  780. GLSL_TYPE(GL_SAMPLER_2D);
  781. GLSL_TYPE(GL_SAMPLER_3D);
  782. GLSL_TYPE(GL_SAMPLER_CUBE);
  783. // GLSL_TYPE(GL_SAMPLER_1D_SHADOW);
  784. // GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  785. }
  786. #undef GLSL_TYPE
  787. return "UNKNOWN GLSL TYPE!";
  788. }
  789. const char* glEnumName(GLenum _enum)
  790. {
  791. #define GLENUM(_ty) case _ty: return #_ty
  792. switch (_enum)
  793. {
  794. GLENUM(GL_TEXTURE);
  795. GLENUM(GL_RENDERBUFFER);
  796. }
  797. #undef GLENUM
  798. return "UNKNOWN GLENUM!";
  799. }
  800. UniformType::Enum convertGlType(GLenum _type)
  801. {
  802. switch (_type)
  803. {
  804. case GL_FLOAT:
  805. return UniformType::Uniform1fv;
  806. case GL_FLOAT_VEC2:
  807. return UniformType::Uniform2fv;
  808. case GL_FLOAT_VEC3:
  809. return UniformType::Uniform3fv;
  810. case GL_FLOAT_VEC4:
  811. return UniformType::Uniform4fv;
  812. case GL_FLOAT_MAT2:
  813. break;
  814. case GL_FLOAT_MAT3:
  815. return UniformType::Uniform3x3fv;
  816. case GL_FLOAT_MAT4:
  817. return UniformType::Uniform4x4fv;
  818. // case GL_FLOAT_MAT2x3:
  819. // case GL_FLOAT_MAT2x4:
  820. // case GL_FLOAT_MAT3x2:
  821. // case GL_FLOAT_MAT3x4:
  822. // case GL_FLOAT_MAT4x2:
  823. // case GL_FLOAT_MAT4x3:
  824. // break;
  825. // case GL_SAMPLER_1D:
  826. case GL_SAMPLER_2D:
  827. case GL_SAMPLER_3D:
  828. case GL_SAMPLER_CUBE:
  829. // case GL_SAMPLER_1D_SHADOW:
  830. // case GL_SAMPLER_2D_SHADOW:
  831. return UniformType::Uniform1iv;
  832. };
  833. return UniformType::End;
  834. }
  835. void Program::create(const Shader& _vsh, const Shader& _fsh)
  836. {
  837. m_id = glCreateProgram();
  838. BX_TRACE("program create: %d: %d, %d", m_id, _vsh.m_id, _fsh.m_id);
  839. bool cached = false;
  840. uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  841. id ^= s_renderCtx.m_hash;
  842. if (s_renderCtx.m_programBinarySupport)
  843. {
  844. uint32_t length = g_callback->cacheReadSize(id);
  845. cached = length > 0;
  846. if (cached)
  847. {
  848. void* data = g_realloc(NULL, length);
  849. if (g_callback->cacheRead(id, data, length) )
  850. {
  851. bx::MemoryReader reader(data, length);
  852. GLenum format;
  853. bx::read(&reader, format);
  854. GL_CHECK(glProgramBinary(m_id, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  855. }
  856. g_free(data);
  857. }
  858. #if BGFX_CONFIG_RENDERER_OPENGL
  859. GL_CHECK(glProgramParameteri(m_id, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  860. #endif // BGFX_CONFIG_RENDERER_OPENGL
  861. }
  862. if (!cached)
  863. {
  864. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  865. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  866. GL_CHECK(glLinkProgram(m_id) );
  867. GLint linked = 0;
  868. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  869. if (0 == linked)
  870. {
  871. char log[1024];
  872. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  873. BX_TRACE("%d: %s", linked, log);
  874. GL_CHECK(glDeleteProgram(m_id) );
  875. return;
  876. }
  877. if (s_renderCtx.m_programBinarySupport)
  878. {
  879. GLint programLength;
  880. GLenum format;
  881. GL_CHECK(glGetProgramiv(m_id, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  882. if (0 < programLength)
  883. {
  884. uint32_t length = programLength + 4;
  885. uint8_t* data = (uint8_t*)g_realloc(NULL, length);
  886. GL_CHECK(glGetProgramBinary(m_id, programLength, NULL, &format, &data[4]) );
  887. *(uint32_t*)data = format;
  888. g_callback->cacheWrite(id, data, length);
  889. g_free(data);
  890. }
  891. }
  892. }
  893. init();
  894. }
  895. void Program::destroy()
  896. {
  897. GL_CHECK(glUseProgram(0) );
  898. GL_CHECK(glDeleteProgram(m_id) );
  899. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  900. }
  901. void Program::init()
  902. {
  903. GLint activeAttribs;
  904. GLint activeUniforms;
  905. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs) );
  906. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  907. GLint max0, max1;
  908. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  909. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  910. GLint maxLength = uint32_max(max0, max1);
  911. char* name = (char*)g_realloc(NULL, maxLength + 1);
  912. BX_TRACE("Program %d", m_id);
  913. BX_TRACE("Attributes:");
  914. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  915. {
  916. GLint size;
  917. GLenum type;
  918. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  919. BX_TRACE("\t%s %s is at location %d"
  920. , glslTypeName(type)
  921. , name
  922. , glGetAttribLocation(m_id, name)
  923. );
  924. }
  925. m_numPredefined = 0;
  926. m_constantBuffer = ConstantBuffer::create(1024);
  927. m_numSamplers = 0;
  928. BX_TRACE("Uniforms:");
  929. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  930. {
  931. GLint num;
  932. GLenum gltype;
  933. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  934. GLint loc = glGetUniformLocation(m_id, name);
  935. int offset = 0;
  936. char* array = strchr(name, '[');
  937. if (NULL != array)
  938. {
  939. BX_TRACE("--- %s", name);
  940. *array = '\0';
  941. array++;
  942. char* end = strchr(array, ']');
  943. *end = '\0';
  944. offset = atoi(array);
  945. }
  946. if (GL_SAMPLER_2D == gltype)
  947. {
  948. BX_TRACE("Sampler %d at %d.", m_numSamplers, loc);
  949. m_sampler[m_numSamplers] = loc;
  950. m_numSamplers++;
  951. }
  952. const void* data = NULL;
  953. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  954. if (PredefinedUniform::Count != predefined)
  955. {
  956. m_predefined[m_numPredefined].m_loc = loc;
  957. m_predefined[m_numPredefined].m_type = predefined;
  958. m_predefined[m_numPredefined].m_count = num;
  959. m_numPredefined++;
  960. }
  961. else
  962. {
  963. const UniformInfo* info = s_renderCtx.m_uniformReg.find(name);
  964. if (NULL != info)
  965. {
  966. data = info->m_data;
  967. UniformType::Enum type = convertGlType(gltype);
  968. m_constantBuffer->writeUniformRef(type, 0, data, num);
  969. m_constantBuffer->write(loc);
  970. BX_TRACE("store %s %p", name, data);
  971. }
  972. }
  973. BX_TRACE("\tuniform %s %s%s is at location %d, size %d (%p), offset %d"
  974. , glslTypeName(gltype)
  975. , name
  976. , PredefinedUniform::Count != predefined ? "*" : ""
  977. , loc
  978. , num
  979. , data
  980. , offset
  981. );
  982. BX_UNUSED(offset);
  983. }
  984. m_constantBuffer->finish();
  985. g_free(name);
  986. memset(m_attributes, 0xff, sizeof(m_attributes) );
  987. uint32_t used = 0;
  988. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  989. {
  990. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  991. if (-1 != loc)
  992. {
  993. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  994. m_attributes[ii] = loc;
  995. m_used[used++] = ii;
  996. }
  997. }
  998. m_used[used] = Attrib::Count;
  999. used = 0;
  1000. for (uint32_t ii = 0; ii < countof(s_instanceDataName); ++ii)
  1001. {
  1002. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  1003. if (GLuint(-1) != loc )
  1004. {
  1005. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  1006. m_instanceData[used++] = loc;
  1007. }
  1008. }
  1009. m_instanceData[used] = 0xffff;
  1010. }
  1011. void Program::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  1012. {
  1013. uint32_t enabled = 0;
  1014. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  1015. {
  1016. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  1017. GLint loc = m_attributes[attr];
  1018. uint8_t num;
  1019. AttribType::Enum type;
  1020. bool normalized;
  1021. bool asInt;
  1022. _vertexDecl.decode(attr, num, type, normalized, asInt);
  1023. if (-1 != loc
  1024. && 0xff != _vertexDecl.m_attributes[attr])
  1025. {
  1026. GL_CHECK(glEnableVertexAttribArray(loc) );
  1027. enabled |= 1<<attr;
  1028. GL_CHECK(s_vertexAttribDivisor(loc, 0) );
  1029. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  1030. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  1031. }
  1032. else
  1033. {
  1034. // GL_CHECK(glDisableVertexAttribArray(loc) );
  1035. switch (num)
  1036. {
  1037. case 1:
  1038. GL_CHECK(glVertexAttrib1f(loc, 0.0f) );
  1039. break;
  1040. case 2:
  1041. GL_CHECK(glVertexAttrib2f(loc, 0.0f, 0.0f) );
  1042. break;
  1043. case 3:
  1044. GL_CHECK(glVertexAttrib3f(loc, 0.0f, 0.0f, 0.0f) );
  1045. break;
  1046. case 4:
  1047. GL_CHECK(glVertexAttrib4f(loc, 0.0f, 0.0f, 0.0f, 0.0f) );
  1048. break;
  1049. default:
  1050. BX_CHECK(false, "You should not be here!");
  1051. break;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. void Program::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  1057. {
  1058. uint32_t baseVertex = _baseVertex;
  1059. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  1060. {
  1061. GLint loc = m_instanceData[ii];
  1062. GL_CHECK(glEnableVertexAttribArray(loc) );
  1063. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  1064. GL_CHECK(s_vertexAttribDivisor(loc, 1) );
  1065. baseVertex += 16;
  1066. }
  1067. }
  1068. void IndexBuffer::destroy()
  1069. {
  1070. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  1071. GL_CHECK(glDeleteBuffers(1, &m_id) );
  1072. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  1073. }
  1074. void VertexBuffer::destroy()
  1075. {
  1076. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  1077. GL_CHECK(glDeleteBuffers(1, &m_id) );
  1078. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  1079. }
  1080. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _pixels)
  1081. {
  1082. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1083. if (_target == GL_TEXTURE_3D)
  1084. {
  1085. GL_CHECK(glTexImage3D(_target
  1086. , _level
  1087. , _internalFormat
  1088. , _width
  1089. , _height
  1090. , _depth
  1091. , _border
  1092. , _format
  1093. , _type
  1094. , _pixels
  1095. ) );
  1096. }
  1097. else
  1098. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1099. {
  1100. BX_UNUSED(_depth);
  1101. GL_CHECK(glTexImage2D(_target
  1102. , _level
  1103. , _internalFormat
  1104. , _width
  1105. , _height
  1106. , _border
  1107. , _format
  1108. , _type
  1109. , _pixels
  1110. ) );
  1111. }
  1112. }
  1113. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  1114. {
  1115. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1116. if (_target == GL_TEXTURE_3D)
  1117. {
  1118. GL_CHECK(glCompressedTexImage3D(_target
  1119. , _level
  1120. , _internalformat
  1121. , _width
  1122. , _height
  1123. , _depth
  1124. , _border
  1125. , _imageSize
  1126. , _data
  1127. ) );
  1128. }
  1129. else
  1130. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1131. {
  1132. BX_UNUSED(_depth);
  1133. GL_CHECK(glCompressedTexImage2D(_target
  1134. , _level
  1135. , _internalformat
  1136. , _width
  1137. , _height
  1138. , _border
  1139. , _imageSize
  1140. , _data
  1141. ) );
  1142. }
  1143. }
  1144. void Texture::init(GLenum _target, uint8_t _numMips, uint32_t _flags)
  1145. {
  1146. m_target = _target;
  1147. GL_CHECK(glGenTextures(1, &m_id) );
  1148. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1149. GL_CHECK(glBindTexture(_target, m_id) );
  1150. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_S, s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  1151. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_T, s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  1152. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1153. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MAX_LEVEL, _numMips-1) );
  1154. if (_target == GL_TEXTURE_3D)
  1155. {
  1156. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_R, s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  1157. }
  1158. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1159. uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  1160. uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  1161. uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  1162. GLenum minFilter = s_textureFilterMin[min][1 < _numMips ? mip+1 : 0];
  1163. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MAG_FILTER, s_textureFilterMag[mag]) );
  1164. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MIN_FILTER, minFilter) );
  1165. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  1166. && 0.0f < s_renderCtx.m_maxAnisotropy)
  1167. {
  1168. GL_CHECK(glTexParameterf(_target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderCtx.m_maxAnisotropy) );
  1169. }
  1170. }
  1171. void Texture::create(const Memory* _mem, uint32_t _flags)
  1172. {
  1173. Dds dds;
  1174. if (parseDds(dds, _mem) )
  1175. {
  1176. uint8_t numMips = dds.m_numMips;
  1177. if (dds.m_cubeMap)
  1178. {
  1179. init(GL_TEXTURE_CUBE_MAP, numMips, _flags);
  1180. }
  1181. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1182. else if (dds.m_depth > 1)
  1183. {
  1184. init(GL_TEXTURE_3D, numMips, _flags);
  1185. }
  1186. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1187. else
  1188. {
  1189. init(GL_TEXTURE_2D, numMips, _flags);
  1190. }
  1191. const TextureFormatInfo& tfi = s_textureFormat[dds.m_type];
  1192. GLenum internalFmt = tfi.m_internalFmt;
  1193. m_fmt = tfi.m_fmt;
  1194. m_type = tfi.m_type;
  1195. GLenum target = m_target;
  1196. if (dds.m_cubeMap)
  1197. {
  1198. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  1199. }
  1200. if (!tfi.m_supported
  1201. || TextureFormat::Unknown < dds.m_type)
  1202. {
  1203. uint8_t textureFormat = dds.m_type;
  1204. bool decompress = TextureFormat::Unknown > textureFormat;
  1205. uint32_t bpp = tfi.m_bpp;
  1206. if (decompress)
  1207. {
  1208. textureFormat = TextureFormat::BGRA8;
  1209. const TextureFormatInfo& tfi = s_textureFormat[textureFormat];
  1210. internalFmt = tfi.m_internalFmt;
  1211. m_fmt = tfi.m_fmt;
  1212. m_type = tfi.m_type;
  1213. bpp = tfi.m_bpp;
  1214. }
  1215. bool swizzle = GL_RGBA == m_fmt;
  1216. #if BGFX_CONFIG_RENDERER_OPENGL
  1217. if (swizzle
  1218. && s_renderCtx.m_textureSwizzleSupport)
  1219. {
  1220. swizzle = false;
  1221. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  1222. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  1223. }
  1224. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1225. uint8_t* bits = (uint8_t*)g_realloc(NULL, dds.m_width*dds.m_height*bpp/8);
  1226. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1227. {
  1228. uint32_t width = dds.m_width;
  1229. uint32_t height = dds.m_height;
  1230. uint32_t depth = dds.m_depth;
  1231. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  1232. {
  1233. width = uint32_max(1, width);
  1234. height = uint32_max(1, height);
  1235. depth = uint32_max(1, depth);
  1236. Mip mip;
  1237. if (getRawImageData(dds, side, lod, _mem, mip) )
  1238. {
  1239. mip.decode(bits);
  1240. if (swizzle)
  1241. {
  1242. rgbaToBgra(bits, width, height);
  1243. }
  1244. texImage(target+side
  1245. , lod
  1246. , internalFmt
  1247. , width
  1248. , height
  1249. , depth
  1250. , 0
  1251. , m_fmt
  1252. , m_type
  1253. , bits
  1254. );
  1255. }
  1256. width >>= 1;
  1257. height >>= 1;
  1258. depth >>= 1;
  1259. }
  1260. }
  1261. g_free(bits);
  1262. }
  1263. else
  1264. {
  1265. m_compressed = true;
  1266. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1267. {
  1268. uint32_t width = dds.m_width;
  1269. uint32_t height = dds.m_height;
  1270. uint32_t depth = dds.m_depth;
  1271. for (uint32_t ii = 0, num = numMips; ii < num; ++ii)
  1272. {
  1273. width = uint32_max(1, width);
  1274. height = uint32_max(1, height);
  1275. depth = uint32_max(1, depth);
  1276. Mip mip;
  1277. if (getRawImageData(dds, side, ii, _mem, mip) )
  1278. {
  1279. compressedTexImage(target+side
  1280. , ii
  1281. , internalFmt
  1282. , width
  1283. , height
  1284. , depth
  1285. , 0
  1286. , mip.m_size
  1287. , mip.m_data
  1288. );
  1289. }
  1290. width >>= 1;
  1291. height >>= 1;
  1292. depth >>= 1;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. else
  1298. {
  1299. bx::MemoryReader reader(_mem->data, _mem->size);
  1300. uint32_t magic;
  1301. bx::read(&reader, magic);
  1302. if (BGFX_CHUNK_MAGIC_TEX == magic)
  1303. {
  1304. TextureCreate tc;
  1305. bx::read(&reader, tc);
  1306. uint8_t numMips = tc.m_numMips;
  1307. if (tc.m_cubeMap)
  1308. {
  1309. init(GL_TEXTURE_CUBE_MAP, numMips, _flags);
  1310. }
  1311. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1312. else if (tc.m_depth > 1)
  1313. {
  1314. init(GL_TEXTURE_3D, numMips, _flags);
  1315. }
  1316. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1317. else
  1318. {
  1319. init(GL_TEXTURE_2D, numMips, _flags);
  1320. }
  1321. const TextureFormatInfo& tfi = s_textureFormat[tc.m_format];
  1322. GLenum internalFmt = tfi.m_internalFmt;
  1323. m_fmt = tfi.m_fmt;
  1324. m_type = tfi.m_type;
  1325. m_compressed = tc.m_format < TextureFormat::Unknown;
  1326. GLenum target = m_target;
  1327. if (tc.m_cubeMap)
  1328. {
  1329. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  1330. }
  1331. uint32_t bpp = tfi.m_bpp;
  1332. uint8_t* data = NULL != tc.m_mem ? tc.m_mem->data : NULL;
  1333. uint32_t min = m_compressed ? 4 : 1;
  1334. bool swizzle = GL_RGBA == m_fmt;
  1335. #if BGFX_CONFIG_RENDERER_OPENGL
  1336. if (swizzle
  1337. && s_renderCtx.m_textureSwizzleSupport)
  1338. {
  1339. swizzle = false;
  1340. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  1341. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  1342. }
  1343. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1344. for (uint8_t side = 0, numSides = tc.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1345. {
  1346. uint32_t width = tc.m_width;
  1347. uint32_t height = tc.m_height;
  1348. uint32_t depth = tc.m_depth;
  1349. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  1350. {
  1351. width = uint32_max(width, min);
  1352. height = uint32_max(height, min);
  1353. depth = uint32_max(1, depth);
  1354. uint32_t size = width*height*bpp/8;
  1355. if (m_compressed)
  1356. {
  1357. compressedTexImage(target+side
  1358. , lod
  1359. , internalFmt
  1360. , width
  1361. , height
  1362. , depth
  1363. , 0
  1364. , size
  1365. , data
  1366. );
  1367. }
  1368. else
  1369. {
  1370. if (NULL != data
  1371. && swizzle)
  1372. {
  1373. rgbaToBgra(data, width, height);
  1374. }
  1375. texImage(target+side
  1376. , lod
  1377. , internalFmt
  1378. , width
  1379. , height
  1380. , depth
  1381. , 0
  1382. , m_fmt
  1383. , m_type
  1384. , data
  1385. );
  1386. }
  1387. if (NULL != data)
  1388. {
  1389. data += size;
  1390. }
  1391. width >>= 1;
  1392. height >>= 1;
  1393. depth >>= 1;
  1394. }
  1395. }
  1396. if (NULL != tc.m_mem)
  1397. {
  1398. release(tc.m_mem);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. //
  1404. }
  1405. }
  1406. GL_CHECK(glBindTexture(m_target, 0) );
  1407. }
  1408. void Texture::createColor(uint32_t _colorFormat, uint32_t _width, uint32_t _height, GLenum _min, GLenum _mag)
  1409. {
  1410. const RenderTargetColorFormat& rtcf = s_colorFormat[_colorFormat];
  1411. GLenum internalFormat = rtcf.m_internalFmt;
  1412. GLenum type = rtcf.m_type;
  1413. m_target = GL_TEXTURE_2D;
  1414. GL_CHECK(glGenTextures(1, &m_id) );
  1415. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1416. GL_CHECK(glBindTexture(m_target, m_id) );
  1417. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1418. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, 0) );
  1419. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1420. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, _min) );
  1421. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, _mag) );
  1422. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1423. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1424. GL_CHECK(glTexImage2D(m_target
  1425. , 0
  1426. , internalFormat
  1427. , _width
  1428. , _height
  1429. , 0
  1430. , GL_RGBA
  1431. , type
  1432. , NULL
  1433. ) );
  1434. GL_CHECK(glBindTexture(m_target, 0) );
  1435. }
  1436. void Texture::createDepth(uint32_t _width, uint32_t _height)
  1437. {
  1438. m_target = GL_TEXTURE_2D;
  1439. GL_CHECK(glGenTextures(1, &m_id) );
  1440. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1441. GL_CHECK(glBindTexture(m_target, m_id) );
  1442. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1443. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, 0) );
  1444. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1445. // GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  1446. // GL_CHECK(glTexParameteri(m_target, GL_DEPTH_TEXTURE_MODE, GL_NONE) );
  1447. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  1448. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  1449. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1450. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1451. // OpenGL ES 2.0 doesn't support GL_DEPTH_COMPONENT... this will fail.
  1452. GL_CHECK(glTexImage2D(m_target
  1453. , 0
  1454. , GL_DEPTH_COMPONENT
  1455. , _width
  1456. , _height
  1457. , 0
  1458. , GL_DEPTH_COMPONENT
  1459. , GL_FLOAT
  1460. , NULL
  1461. ) );
  1462. GL_CHECK(glBindTexture(m_target, 0) );
  1463. }
  1464. void Texture::destroy()
  1465. {
  1466. if (0 != m_id)
  1467. {
  1468. GL_CHECK(glBindTexture(m_target, 0) );
  1469. GL_CHECK(glDeleteTextures(1, &m_id) );
  1470. m_id = 0;
  1471. }
  1472. }
  1473. void Texture::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, const Memory* _mem)
  1474. {
  1475. BX_UNUSED(_z);
  1476. BX_UNUSED(_depth);
  1477. GL_CHECK(glBindTexture(m_target, m_id) );
  1478. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  1479. switch (m_target)
  1480. {
  1481. case GL_TEXTURE_2D:
  1482. if (m_compressed)
  1483. {
  1484. GL_CHECK(glCompressedTexSubImage2D(m_target
  1485. , _mip
  1486. , _rect.m_x
  1487. , _rect.m_y
  1488. , _rect.m_width
  1489. , _rect.m_height
  1490. , m_fmt
  1491. , _mem->size
  1492. , _mem->data
  1493. ) );
  1494. }
  1495. else
  1496. {
  1497. GL_CHECK(glTexSubImage2D(m_target
  1498. , _mip
  1499. , _rect.m_x
  1500. , _rect.m_y
  1501. , _rect.m_width
  1502. , _rect.m_height
  1503. , m_fmt
  1504. , m_type
  1505. , _mem->data
  1506. ) );
  1507. }
  1508. break;
  1509. case GL_TEXTURE_CUBE_MAP:
  1510. if (m_compressed)
  1511. {
  1512. GL_CHECK(glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+_side
  1513. , _mip
  1514. , _rect.m_x
  1515. , _rect.m_y
  1516. , _rect.m_width
  1517. , _rect.m_height
  1518. , m_fmt
  1519. , _mem->size
  1520. , _mem->data
  1521. ) );
  1522. }
  1523. else
  1524. {
  1525. GL_CHECK(glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+_side
  1526. , _mip
  1527. , _rect.m_x
  1528. , _rect.m_y
  1529. , _rect.m_width
  1530. , _rect.m_height
  1531. , m_fmt
  1532. , m_type
  1533. , _mem->data
  1534. ) );
  1535. }
  1536. break;
  1537. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1538. case GL_TEXTURE_3D:
  1539. if (m_compressed)
  1540. {
  1541. GL_CHECK(glCompressedTexSubImage3D(m_target
  1542. , _mip
  1543. , _rect.m_x
  1544. , _rect.m_y
  1545. , _z
  1546. , _rect.m_width
  1547. , _rect.m_height
  1548. , _depth
  1549. , m_fmt
  1550. , _mem->size
  1551. , _mem->data
  1552. ) );
  1553. }
  1554. else
  1555. {
  1556. GL_CHECK(glTexSubImage3D(m_target
  1557. , _mip
  1558. , _rect.m_x
  1559. , _rect.m_y
  1560. , _z
  1561. , _rect.m_width
  1562. , _rect.m_height
  1563. , _depth
  1564. , m_fmt
  1565. , m_type
  1566. , _mem->data
  1567. ) );
  1568. }
  1569. break;
  1570. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1571. }
  1572. }
  1573. void RenderTarget::create(uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1574. {
  1575. BX_TRACE("Create render target %dx%d 0x%02x", _width, _height, _flags);
  1576. m_width = _width;
  1577. m_height = _height;
  1578. uint32_t msaa = (_flags&BGFX_RENDER_TARGET_MSAA_MASK)>>BGFX_RENDER_TARGET_MSAA_SHIFT;
  1579. m_msaa = uint32_min(s_renderCtx.m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  1580. uint32_t colorFormat = (_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1581. uint32_t depthFormat = (_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1582. GLenum minFilter = s_textureFilterMin[(_textureFlags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT][0];
  1583. GLenum magFilter = s_textureFilterMag[(_textureFlags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  1584. if (0 < colorFormat)
  1585. {
  1586. m_color.createColor(colorFormat, _width, _height, minFilter, magFilter);
  1587. }
  1588. #if 0 // GLES can't create texture with depth texture format...
  1589. if (0 < depthFormat)
  1590. {
  1591. m_depth.createDepth(_width, _height);
  1592. }
  1593. #endif //
  1594. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1595. if (0 < colorFormat
  1596. && 0 != m_msaa)
  1597. {
  1598. GL_CHECK(glGenFramebuffers(2, m_fbo) );
  1599. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1600. GL_CHECK(glGenRenderbuffers(1, &m_colorRbo) );
  1601. BX_CHECK(0 != m_colorRbo, "Failed to generate color renderbuffer id.");
  1602. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_colorRbo) );
  1603. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaa, s_colorFormat[colorFormat].m_internalFmt, _width, _height) );
  1604. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  1605. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  1606. , GL_COLOR_ATTACHMENT0
  1607. , GL_RENDERBUFFER
  1608. , m_colorRbo
  1609. ) );
  1610. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  1611. }
  1612. else
  1613. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1614. {
  1615. GL_CHECK(glGenFramebuffers(1, m_fbo) );
  1616. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1617. }
  1618. if (0 < colorFormat)
  1619. {
  1620. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1621. , GL_COLOR_ATTACHMENT0
  1622. , m_color.m_target
  1623. , m_color.m_id
  1624. , 0
  1625. ) );
  1626. }
  1627. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1628. , "glCheckFramebufferStatus failed 0x%08x"
  1629. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1630. );
  1631. if (0 < depthFormat)
  1632. {
  1633. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1634. if (0 < colorFormat)
  1635. {
  1636. #if BGFX_CONFIG_RENDERER_OPENGL
  1637. GLenum depthComponent = GL_DEPTH_COMPONENT32;
  1638. #else
  1639. GLenum depthComponent = GL_DEPTH_COMPONENT16;
  1640. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1641. GL_CHECK(glGenRenderbuffers(1, &m_depthRbo) );
  1642. BX_CHECK(0 != m_depthRbo, "Failed to generate renderbuffer id.");
  1643. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_depthRbo) );
  1644. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1645. if (0 != m_msaa)
  1646. {
  1647. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaa, depthComponent, _width, _height) );
  1648. }
  1649. else
  1650. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1651. {
  1652. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, depthComponent, _width, _height) );
  1653. }
  1654. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  1655. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  1656. , GL_DEPTH_ATTACHMENT
  1657. , GL_RENDERBUFFER
  1658. , m_depthRbo
  1659. ) );
  1660. }
  1661. else
  1662. {
  1663. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1664. , GL_DEPTH_ATTACHMENT
  1665. , m_depth.m_target
  1666. , m_depth.m_id
  1667. , 0
  1668. ) );
  1669. }
  1670. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1671. , "glCheckFramebufferStatus failed 0x%08x"
  1672. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1673. );
  1674. }
  1675. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_backBufferFbo) );
  1676. }
  1677. void RenderTarget::destroy()
  1678. {
  1679. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  1680. memset(m_fbo, 0, sizeof(m_fbo) );
  1681. if (0 != m_colorRbo)
  1682. {
  1683. GL_CHECK(glDeleteRenderbuffers(1, &m_colorRbo) );
  1684. m_colorRbo = 0;
  1685. }
  1686. if (0 != m_depthRbo)
  1687. {
  1688. GL_CHECK(glDeleteRenderbuffers(1, &m_depthRbo) );
  1689. m_depthRbo = 0;
  1690. }
  1691. m_color.destroy();
  1692. m_depth.destroy();
  1693. }
  1694. void RenderTarget::resolve()
  1695. {
  1696. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1697. BX_CHECK(0 != m_fbo[1], "Can resolve without two framebuffers.");
  1698. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  1699. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  1700. GL_CHECK(glBlitFramebuffer(0
  1701. , 0
  1702. , m_width
  1703. , m_height
  1704. , 0
  1705. , 0
  1706. , m_width
  1707. , m_height
  1708. , GL_COLOR_BUFFER_BIT
  1709. , GL_LINEAR
  1710. ) );
  1711. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_backBufferFbo) );
  1712. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1713. }
  1714. void ConstantBuffer::commit()
  1715. {
  1716. reset();
  1717. do
  1718. {
  1719. uint32_t opcode = read();
  1720. if (UniformType::End == opcode)
  1721. {
  1722. break;
  1723. }
  1724. UniformType::Enum type;
  1725. uint16_t ignore;
  1726. uint16_t num;
  1727. uint16_t copy;
  1728. decodeOpcode(opcode, type, ignore, num, copy);
  1729. const char* data;
  1730. if (copy)
  1731. {
  1732. data = read(g_uniformTypeSize[type]*num);
  1733. }
  1734. else
  1735. {
  1736. memcpy(&data, read(sizeof(void*) ), sizeof(void*) );
  1737. }
  1738. uint32_t loc = read();
  1739. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  1740. case UniformType::_uniform: \
  1741. { \
  1742. _type* value = (_type*)data; \
  1743. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  1744. } \
  1745. break;
  1746. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  1747. case UniformType::_uniform: \
  1748. { \
  1749. _type* value = (_type*)data; \
  1750. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  1751. } \
  1752. break;
  1753. switch (type)
  1754. {
  1755. // case ConstantType::Uniform1iv:
  1756. // {
  1757. // int* value = (int*)data;
  1758. // BX_TRACE("Uniform1iv sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  1759. // GL_CHECK(glUniform1iv(loc, num, value) );
  1760. // }
  1761. // break;
  1762. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  1763. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  1764. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  1765. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  1766. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  1767. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  1768. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  1769. CASE_IMPLEMENT_UNIFORM_T(Uniform3x3fv, Matrix3fv, F, float);
  1770. CASE_IMPLEMENT_UNIFORM_T(Uniform4x4fv, Matrix4fv, F, float);
  1771. case UniformType::End:
  1772. break;
  1773. default:
  1774. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", m_pos, opcode, type, loc, num, copy);
  1775. break;
  1776. }
  1777. #undef CASE_IMPLEMENT_UNIFORM
  1778. #undef CASE_IMPLEMENT_UNIFORM_T
  1779. } while (true);
  1780. }
  1781. void TextVideoMemBlitter::setup()
  1782. {
  1783. if (0 != s_renderCtx.m_vao)
  1784. {
  1785. GL_CHECK(glBindVertexArray(s_renderCtx.m_vao) );
  1786. }
  1787. uint32_t width = s_renderCtx.m_resolution.m_width;
  1788. uint32_t height = s_renderCtx.m_resolution.m_height;
  1789. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1790. GL_CHECK(glViewport(0, 0, width, height) );
  1791. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1792. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1793. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1794. GL_CHECK(glDisable(GL_CULL_FACE) );
  1795. GL_CHECK(glDisable(GL_BLEND) );
  1796. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1797. Program& program = s_renderCtx.m_program[m_program.idx];
  1798. GL_CHECK(glUseProgram(program.m_id) );
  1799. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  1800. float proj[16];
  1801. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1802. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  1803. , 1
  1804. , GL_FALSE
  1805. , proj
  1806. ) );
  1807. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1808. GL_CHECK(glBindTexture(GL_TEXTURE_2D, s_renderCtx.m_textures[m_texture.idx].m_id) );
  1809. }
  1810. void TextVideoMemBlitter::render(uint32_t _numIndices)
  1811. {
  1812. uint32_t numVertices = _numIndices*4/6;
  1813. s_renderCtx.m_indexBuffers[m_ib->handle.idx].update(0, _numIndices*2, m_ib->data);
  1814. s_renderCtx.m_vertexBuffers[m_vb->handle.idx].update(0, numVertices*m_decl.m_stride, m_vb->data);
  1815. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[m_vb->handle.idx];
  1816. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1817. IndexBuffer& ib = s_renderCtx.m_indexBuffers[m_ib->handle.idx];
  1818. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1819. Program& program = s_renderCtx.m_program[m_program.idx];
  1820. program.bindAttributes(m_decl, 0);
  1821. GL_CHECK(glDrawElements(GL_TRIANGLES
  1822. , _numIndices
  1823. , GL_UNSIGNED_SHORT
  1824. , (void*)0
  1825. ) );
  1826. }
  1827. void ClearQuad::clear(const Rect& _rect, const Clear& _clear, uint32_t _height)
  1828. {
  1829. #if BGFX_CONFIG_CLEAR_QUAD
  1830. if (s_renderCtx.m_useClearQuad)
  1831. {
  1832. GL_CHECK(glDisable(GL_CULL_FACE) );
  1833. GL_CHECK(glDisable(GL_BLEND) );
  1834. GLboolean colorMask = !!(BGFX_CLEAR_COLOR_BIT & _clear.m_flags);
  1835. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  1836. if (BGFX_CLEAR_DEPTH_BIT & _clear.m_flags)
  1837. {
  1838. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  1839. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1840. GL_CHECK(glDepthMask(GL_TRUE) );
  1841. }
  1842. else
  1843. {
  1844. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1845. }
  1846. if (BGFX_CLEAR_STENCIL_BIT & _clear.m_flags)
  1847. {
  1848. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  1849. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  1850. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  1851. }
  1852. else
  1853. {
  1854. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1855. }
  1856. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[m_vb->handle.idx];
  1857. VertexDecl& vertexDecl = s_renderCtx.m_vertexDecls[m_vb->decl.idx];
  1858. {
  1859. struct Vertex
  1860. {
  1861. float m_x;
  1862. float m_y;
  1863. float m_z;
  1864. uint32_t m_abgr;
  1865. } * vertex = (Vertex*)m_vb->data;
  1866. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  1867. const uint32_t abgr = bx::endianSwap(_clear.m_rgba);
  1868. const float depth = _clear.m_depth;
  1869. vertex->m_x = -1.0f;
  1870. vertex->m_y = -1.0f;
  1871. vertex->m_z = depth;
  1872. vertex->m_abgr = abgr;
  1873. vertex++;
  1874. vertex->m_x = 1.0f;
  1875. vertex->m_y = -1.0f;
  1876. vertex->m_z = depth;
  1877. vertex->m_abgr = abgr;
  1878. vertex++;
  1879. vertex->m_x = 1.0f;
  1880. vertex->m_y = 1.0f;
  1881. vertex->m_z = depth;
  1882. vertex->m_abgr = abgr;
  1883. vertex++;
  1884. vertex->m_x = -1.0f;
  1885. vertex->m_y = 1.0f;
  1886. vertex->m_z = depth;
  1887. vertex->m_abgr = abgr;
  1888. }
  1889. s_renderCtx.m_vertexBuffers[m_vb->handle.idx].update(0, 4*m_decl.m_stride, m_vb->data);
  1890. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1891. IndexBuffer& ib = s_renderCtx.m_indexBuffers[m_ib.idx];
  1892. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1893. Program& program = s_renderCtx.m_program[m_program.idx];
  1894. GL_CHECK(glUseProgram(program.m_id) );
  1895. program.bindAttributes(vertexDecl, 0);
  1896. GL_CHECK(glDrawElements(GL_TRIANGLES
  1897. , 6
  1898. , GL_UNSIGNED_SHORT
  1899. , (void*)0
  1900. ) );
  1901. }
  1902. else
  1903. #endif // BGFX_CONFIG_CLEAR_QUAD
  1904. {
  1905. GLuint flags = 0;
  1906. if (BGFX_CLEAR_COLOR_BIT & _clear.m_flags)
  1907. {
  1908. flags |= GL_COLOR_BUFFER_BIT;
  1909. uint32_t rgba = _clear.m_rgba;
  1910. float rr = (rgba>>24)/255.0f;
  1911. float gg = ( (rgba>>16)&0xff)/255.0f;
  1912. float bb = ( (rgba>>8)&0xff)/255.0f;
  1913. float aa = (rgba&0xff)/255.0f;
  1914. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  1915. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1916. }
  1917. if (BGFX_CLEAR_DEPTH_BIT & _clear.m_flags)
  1918. {
  1919. flags |= GL_DEPTH_BUFFER_BIT;
  1920. GL_CHECK(glClearDepth(_clear.m_depth) );
  1921. GL_CHECK(glDepthMask(GL_TRUE) );
  1922. }
  1923. if (BGFX_CLEAR_STENCIL_BIT & _clear.m_flags)
  1924. {
  1925. flags |= GL_STENCIL_BUFFER_BIT;
  1926. GL_CHECK(glClearStencil(_clear.m_stencil) );
  1927. }
  1928. if (0 != flags)
  1929. {
  1930. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  1931. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  1932. GL_CHECK(glClear(flags) );
  1933. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1934. }
  1935. }
  1936. }
  1937. void Context::flip()
  1938. {
  1939. s_renderCtx.flip();
  1940. }
  1941. GLint glGet(GLenum _pname)
  1942. {
  1943. GLint result;
  1944. GL_CHECK(glGetIntegerv(_pname, &result) );
  1945. return result;
  1946. }
  1947. void Context::rendererInit()
  1948. {
  1949. s_renderCtx.init();
  1950. #if BGFX_CONFIG_DEBUG
  1951. GLint numCmpFormats;
  1952. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1953. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1954. if (0 < numCmpFormats)
  1955. {
  1956. GLint* formats = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1957. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats) );
  1958. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1959. {
  1960. BX_TRACE(" %3d: %8x", ii, formats[ii]);
  1961. }
  1962. }
  1963. # define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1964. BX_TRACE("Defaults:");
  1965. # if BX_PLATFORM_OSX
  1966. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1967. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1968. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1969. # else
  1970. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1971. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1972. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1973. # endif
  1974. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1975. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1976. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1977. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1978. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1979. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1980. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1981. BX_TRACE(" Vendor: %s", s_renderCtx.m_vendor);
  1982. BX_TRACE(" Renderer: %s", s_renderCtx.m_renderer);
  1983. BX_TRACE(" Version: %s", s_renderCtx.m_version);
  1984. BX_TRACE("GLSL version: %s", s_renderCtx.m_glslVersion);
  1985. #endif // BGFX_CONFIG_DEBUG
  1986. // Initial binary shader hash depends on driver version.
  1987. s_renderCtx.m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1988. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1989. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1990. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1991. ;
  1992. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1993. glGetError(); // ignore error if glGetString returns NULL.
  1994. if (NULL != extensions)
  1995. {
  1996. char name[1024];
  1997. const char* pos = extensions;
  1998. const char* end = extensions + strlen(extensions);
  1999. while (pos < end)
  2000. {
  2001. uint32_t len;
  2002. const char* space = strchr(pos, ' ');
  2003. if (NULL != space)
  2004. {
  2005. len = uint32_min(sizeof(name), (uint32_t)(space - pos) );
  2006. }
  2007. else
  2008. {
  2009. len = uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  2010. }
  2011. strncpy(name, pos, len);
  2012. name[len] = '\0';
  2013. bool supported = false;
  2014. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  2015. {
  2016. Extension& extension = s_extension[ii];
  2017. if (!extension.m_supported
  2018. && extension.m_initialize)
  2019. {
  2020. if (0 == strcmp(name, extension.m_name) )
  2021. {
  2022. extension.m_supported = true;
  2023. supported = true;
  2024. break;
  2025. }
  2026. }
  2027. }
  2028. BX_TRACE("GL_EXTENSION%s: %s", supported ? " (supported)" : "", name);
  2029. BX_UNUSED(supported);
  2030. pos += len+1;
  2031. }
  2032. BX_TRACE("Supported extensions:");
  2033. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  2034. {
  2035. if (s_extension[ii].m_supported)
  2036. {
  2037. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  2038. }
  2039. }
  2040. }
  2041. bool bc123Supported = s_extension[Extension::EXT_texture_compression_s3tc].m_supported;
  2042. s_textureFormat[TextureFormat::BC1].m_supported = bc123Supported || s_extension[Extension::EXT_texture_compression_dxt1].m_supported;
  2043. s_textureFormat[TextureFormat::BC2].m_supported = bc123Supported || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported;
  2044. s_textureFormat[TextureFormat::BC3].m_supported = bc123Supported || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported;
  2045. bool bc45Supported = s_extension[Extension::EXT_texture_compression_latc].m_supported
  2046. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported
  2047. ;
  2048. s_textureFormat[TextureFormat::BC4].m_supported = bc45Supported;
  2049. s_textureFormat[TextureFormat::BC5].m_supported = bc45Supported;
  2050. s_renderCtx.m_vaoSupport = !!BGFX_CONFIG_RENDERER_OPENGLES3
  2051. || s_extension[Extension::ARB_vertex_array_object].m_supported
  2052. || s_extension[Extension::OES_vertex_array_object].m_supported
  2053. ;
  2054. s_renderCtx.m_programBinarySupport = !!BGFX_CONFIG_RENDERER_OPENGLES3
  2055. || s_extension[Extension::ARB_get_program_binary].m_supported
  2056. || s_extension[Extension::OES_get_program_binary].m_supported
  2057. ;
  2058. s_renderCtx.m_textureSwizzleSupport = false
  2059. || s_extension[Extension::ARB_texture_swizzle].m_supported
  2060. || s_extension[Extension::EXT_texture_swizzle].m_supported
  2061. ;
  2062. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  2063. {
  2064. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &s_renderCtx.m_maxAnisotropy) );
  2065. }
  2066. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  2067. if (s_extension[Extension::ARB_texture_multisample].m_supported)
  2068. {
  2069. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &s_renderCtx.m_maxMsaa) );
  2070. }
  2071. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  2072. if (s_extension[Extension::EXT_texture_format_BGRA8888].m_supported
  2073. || s_extension[Extension::EXT_bgra].m_supported)
  2074. {
  2075. s_textureFormat[TextureFormat::BGRX8].m_fmt = GL_BGRA_EXT;
  2076. s_textureFormat[TextureFormat::BGRA8].m_fmt = GL_BGRA_EXT;
  2077. // Mixing GLES and GL extensions here. OpenGL EXT_bgra wants
  2078. // format to be BGRA but internal format to stay RGBA, but
  2079. // EXT_texture_format_BGRA8888 wants both format and internal
  2080. // format to be BGRA.
  2081. //
  2082. // Reference:
  2083. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  2084. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  2085. if (!s_extension[Extension::EXT_bgra].m_supported)
  2086. {
  2087. s_textureFormat[TextureFormat::BGRX8].m_internalFmt = GL_BGRA_EXT;
  2088. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA_EXT;
  2089. }
  2090. }
  2091. if (s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  2092. {
  2093. s_textureFormat[TextureFormat::BC4].m_fmt = GL_COMPRESSED_RED_RGTC1_EXT;
  2094. s_textureFormat[TextureFormat::BC4].m_internalFmt = GL_COMPRESSED_RED_RGTC1_EXT;
  2095. s_textureFormat[TextureFormat::BC5].m_fmt = GL_COMPRESSED_RED_GREEN_RGTC2_EXT;
  2096. s_textureFormat[TextureFormat::BC5].m_internalFmt = GL_COMPRESSED_RED_GREEN_RGTC2_EXT;
  2097. }
  2098. #if !BGFX_CONFIG_RENDERER_OPENGLES3
  2099. s_vertexAttribDivisor = stubVertexAttribDivisor;
  2100. s_drawArraysInstanced = stubDrawArraysInstanced;
  2101. s_drawElementsInstanced = stubDrawElementsInstanced;
  2102. if (s_extension[Extension::ARB_instanced_arrays].m_supported
  2103. || s_extension[Extension::ANGLE_instanced_arrays].m_supported)
  2104. {
  2105. if (NULL != glVertexAttribDivisor
  2106. && NULL != glDrawArraysInstanced
  2107. && NULL != glDrawElementsInstanced)
  2108. {
  2109. s_vertexAttribDivisor = glVertexAttribDivisor;
  2110. s_drawArraysInstanced = glDrawArraysInstanced;
  2111. s_drawElementsInstanced = glDrawElementsInstanced;
  2112. }
  2113. }
  2114. #endif // !BGFX_CONFIG_RENDERER_OPENGLES3
  2115. if (s_renderCtx.m_vaoSupport)
  2116. {
  2117. GL_CHECK(glGenVertexArrays(1, &s_renderCtx.m_vao) );
  2118. }
  2119. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  2120. s_textureFormat[TextureFormat::L8].m_internalFmt = GL_R8;
  2121. s_textureFormat[TextureFormat::L8].m_fmt = GL_RED;
  2122. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  2123. #if BGFX_CONFIG_RENDERER_OPENGL
  2124. if (s_extension[Extension::ARB_debug_output].m_supported)
  2125. {
  2126. GL_CHECK(glDebugMessageCallbackARB(debugProcCb, NULL) );
  2127. GL_CHECK(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_TRUE) );
  2128. }
  2129. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2130. }
  2131. void Context::rendererShutdown()
  2132. {
  2133. if (s_renderCtx.m_vaoSupport)
  2134. {
  2135. GL_CHECK(glBindVertexArray(0) );
  2136. GL_CHECK(glDeleteVertexArrays(1, &s_renderCtx.m_vao) );
  2137. s_renderCtx.m_vao = 0;
  2138. }
  2139. s_renderCtx.shutdown();
  2140. }
  2141. void Context::rendererCreateIndexBuffer(IndexBufferHandle _handle, Memory* _mem)
  2142. {
  2143. s_renderCtx.m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  2144. }
  2145. void Context::rendererDestroyIndexBuffer(IndexBufferHandle _handle)
  2146. {
  2147. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  2148. }
  2149. void Context::rendererCreateVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl)
  2150. {
  2151. VertexDecl& decl = s_renderCtx.m_vertexDecls[_handle.idx];
  2152. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  2153. dump(decl);
  2154. }
  2155. void Context::rendererDestroyVertexDecl(VertexDeclHandle /*_handle*/)
  2156. {
  2157. }
  2158. void Context::rendererCreateVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle)
  2159. {
  2160. s_renderCtx.m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  2161. }
  2162. void Context::rendererDestroyVertexBuffer(VertexBufferHandle _handle)
  2163. {
  2164. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  2165. }
  2166. void Context::rendererCreateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size)
  2167. {
  2168. s_renderCtx.m_indexBuffers[_handle.idx].create(_size, NULL);
  2169. }
  2170. void Context::rendererUpdateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  2171. {
  2172. s_renderCtx.m_indexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  2173. }
  2174. void Context::rendererDestroyDynamicIndexBuffer(IndexBufferHandle _handle)
  2175. {
  2176. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  2177. }
  2178. void Context::rendererCreateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size)
  2179. {
  2180. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  2181. s_renderCtx.m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  2182. }
  2183. void Context::rendererUpdateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  2184. {
  2185. s_renderCtx.m_vertexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  2186. }
  2187. void Context::rendererDestroyDynamicVertexBuffer(VertexBufferHandle _handle)
  2188. {
  2189. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  2190. }
  2191. void Context::rendererCreateVertexShader(VertexShaderHandle _handle, Memory* _mem)
  2192. {
  2193. s_renderCtx.m_vertexShaders[_handle.idx].create(GL_VERTEX_SHADER, _mem);
  2194. }
  2195. void Context::rendererDestroyVertexShader(VertexShaderHandle _handle)
  2196. {
  2197. s_renderCtx.m_vertexShaders[_handle.idx].destroy();
  2198. }
  2199. void Context::rendererCreateFragmentShader(FragmentShaderHandle _handle, Memory* _mem)
  2200. {
  2201. s_renderCtx.m_fragmentShaders[_handle.idx].create(GL_FRAGMENT_SHADER, _mem);
  2202. }
  2203. void Context::rendererDestroyFragmentShader(FragmentShaderHandle _handle)
  2204. {
  2205. s_renderCtx.m_fragmentShaders[_handle.idx].destroy();
  2206. }
  2207. void Context::rendererCreateProgram(ProgramHandle _handle, VertexShaderHandle _vsh, FragmentShaderHandle _fsh)
  2208. {
  2209. s_renderCtx.m_program[_handle.idx].create(s_renderCtx.m_vertexShaders[_vsh.idx], s_renderCtx.m_fragmentShaders[_fsh.idx]);
  2210. }
  2211. void Context::rendererDestroyProgram(FragmentShaderHandle _handle)
  2212. {
  2213. s_renderCtx.m_program[_handle.idx].destroy();
  2214. }
  2215. void Context::rendererCreateTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags)
  2216. {
  2217. s_renderCtx.m_textures[_handle.idx].create(_mem, _flags);
  2218. }
  2219. void Context::rendererUpdateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/)
  2220. {
  2221. }
  2222. void Context::rendererUpdateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, const Memory* _mem)
  2223. {
  2224. s_renderCtx.m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _mem);
  2225. }
  2226. void Context::rendererUpdateTextureEnd()
  2227. {
  2228. }
  2229. void Context::rendererDestroyTexture(TextureHandle _handle)
  2230. {
  2231. s_renderCtx.m_textures[_handle.idx].destroy();
  2232. }
  2233. void Context::rendererCreateRenderTarget(RenderTargetHandle _handle, uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  2234. {
  2235. s_renderCtx.m_renderTargets[_handle.idx].create(_width, _height, _flags, _textureFlags);
  2236. }
  2237. void Context::rendererDestroyRenderTarget(RenderTargetHandle _handle)
  2238. {
  2239. s_renderCtx.m_renderTargets[_handle.idx].destroy();
  2240. }
  2241. void Context::rendererCreateUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name)
  2242. {
  2243. uint32_t size = g_uniformTypeSize[_type]*_num;
  2244. void* data = g_realloc(NULL, size);
  2245. memset(data, 0, size);
  2246. s_renderCtx.m_uniforms[_handle.idx] = data;
  2247. s_renderCtx.m_uniformReg.add(_name, s_renderCtx.m_uniforms[_handle.idx]);
  2248. }
  2249. void Context::rendererDestroyUniform(UniformHandle _handle)
  2250. {
  2251. g_free(s_renderCtx.m_uniforms[_handle.idx]);
  2252. }
  2253. void Context::rendererSaveScreenShot(const char* _filePath)
  2254. {
  2255. s_renderCtx.saveScreenShot(_filePath);
  2256. }
  2257. void Context::rendererUpdateViewName(uint8_t _id, const char* _name)
  2258. {
  2259. bx::strlcpy(&s_viewName[_id][0], _name, sizeof(s_viewName[0][0]) );
  2260. }
  2261. void Context::rendererUpdateUniform(uint16_t _loc, const void* _data, uint32_t _size)
  2262. {
  2263. memcpy(s_renderCtx.m_uniforms[_loc], _data, _size);
  2264. }
  2265. void Context::rendererSetMarker(const char* _marker, uint32_t /*_size*/)
  2266. {
  2267. GREMEDY_SETMARKER(_marker);
  2268. }
  2269. void Context::rendererSubmit()
  2270. {
  2271. const GLuint defaultVao = s_renderCtx.m_vaoSupport;
  2272. if (0 != defaultVao)
  2273. {
  2274. GL_CHECK(glBindVertexArray(defaultVao) );
  2275. }
  2276. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  2277. s_renderCtx.updateResolution(m_render->m_resolution);
  2278. int64_t elapsed = -bx::getHPCounter();
  2279. int64_t captureElapsed = 0;
  2280. #if BGFX_CONFIG_RENDERER_OPENGL
  2281. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2282. {
  2283. s_renderCtx.m_queries.begin(0, GL_TIME_ELAPSED);
  2284. }
  2285. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2286. if (0 < m_render->m_iboffset)
  2287. {
  2288. TransientIndexBuffer* ib = m_render->m_transientIb;
  2289. s_renderCtx.m_indexBuffers[ib->handle.idx].update(0, m_render->m_iboffset, ib->data);
  2290. }
  2291. if (0 < m_render->m_vboffset)
  2292. {
  2293. TransientVertexBuffer* vb = m_render->m_transientVb;
  2294. s_renderCtx.m_vertexBuffers[vb->handle.idx].update(0, m_render->m_vboffset, vb->data);
  2295. }
  2296. m_render->sort();
  2297. RenderState currentState;
  2298. currentState.reset();
  2299. currentState.m_flags = BGFX_STATE_NONE;
  2300. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  2301. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  2302. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  2303. {
  2304. mtxMul(viewProj[ii].val, m_render->m_view[ii].val, m_render->m_proj[ii].val);
  2305. }
  2306. uint16_t programIdx = invalidHandle;
  2307. SortKey key;
  2308. uint8_t view = 0xff;
  2309. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  2310. int32_t height = m_render->m_resolution.m_height;
  2311. float alphaRef = 0.0f;
  2312. uint32_t blendFactor = 0;
  2313. GLenum primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : GL_TRIANGLES;
  2314. uint32_t primNumVerts = 3;
  2315. uint32_t baseVertex = 0;
  2316. GLuint currentVao = 0;
  2317. uint32_t statsNumPrimsSubmitted = 0;
  2318. uint32_t statsNumIndices = 0;
  2319. uint32_t statsNumInstances = 0;
  2320. uint32_t statsNumPrimsRendered = 0;
  2321. if (0 == (m_render->m_debug&BGFX_DEBUG_IFH) )
  2322. {
  2323. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_backBufferFbo) );
  2324. for (uint32_t item = 0, numItems = m_render->m_num; item < numItems; ++item)
  2325. {
  2326. key.decode(m_render->m_sortKeys[item]);
  2327. const RenderState& state = m_render->m_renderState[m_render->m_sortValues[item] ];
  2328. const uint64_t newFlags = state.m_flags;
  2329. uint64_t changedFlags = currentState.m_flags ^ state.m_flags;
  2330. currentState.m_flags = newFlags;
  2331. const uint64_t newStencil = state.m_stencil;
  2332. uint64_t changedStencil = currentState.m_stencil ^ state.m_stencil;
  2333. currentState.m_stencil = newStencil;
  2334. if (key.m_view != view)
  2335. {
  2336. currentState.clear();
  2337. changedFlags = BGFX_STATE_MASK;
  2338. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  2339. currentState.m_flags = newFlags;
  2340. GREMEDY_SETMARKER(s_viewName[key.m_view]);
  2341. view = key.m_view;
  2342. programIdx = invalidHandle;
  2343. if (m_render->m_rt[view].idx != rt.idx)
  2344. {
  2345. rt = m_render->m_rt[view];
  2346. height = s_renderCtx.setRenderTarget(rt, m_render->m_resolution.m_height);
  2347. }
  2348. Rect& rect = m_render->m_rect[view];
  2349. GL_CHECK(glViewport(rect.m_x, height-rect.m_height-rect.m_y, rect.m_width, rect.m_height) );
  2350. Clear& clear = m_render->m_clear[view];
  2351. if (BGFX_CLEAR_NONE != clear.m_flags)
  2352. {
  2353. m_clearQuad.clear(rect, clear, height);
  2354. }
  2355. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2356. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2357. GL_CHECK(glDepthFunc(GL_LESS) );
  2358. GL_CHECK(glEnable(GL_CULL_FACE) );
  2359. GL_CHECK(glDisable(GL_BLEND) );
  2360. }
  2361. if (0 != changedStencil)
  2362. {
  2363. if (0 != newStencil)
  2364. {
  2365. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2366. uint32_t bstencil = unpackStencil(1, newStencil);
  2367. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  2368. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2369. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2370. // {
  2371. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2372. // GL_CHECK(glStencilMask(wmask) );
  2373. // }
  2374. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2375. {
  2376. uint32_t stencil = unpackStencil(ii, newStencil);
  2377. uint32_t changed = unpackStencil(ii, changedStencil);
  2378. GLenum face = s_stencilFace[frontAndBack+ii];
  2379. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2380. {
  2381. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2382. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2383. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2384. GL_CHECK(glStencilFuncSeparate(face, s_stencilFunc[func], ref, mask));
  2385. }
  2386. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2387. {
  2388. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2389. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2390. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2391. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  2392. }
  2393. }
  2394. }
  2395. else
  2396. {
  2397. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2398. }
  2399. }
  2400. if ( (0
  2401. | BGFX_STATE_CULL_MASK
  2402. | BGFX_STATE_DEPTH_WRITE
  2403. | BGFX_STATE_DEPTH_TEST_MASK
  2404. | BGFX_STATE_ALPHA_MASK
  2405. | BGFX_STATE_RGB_WRITE
  2406. | BGFX_STATE_BLEND_MASK
  2407. | BGFX_STATE_BLEND_EQUATION_MASK
  2408. | BGFX_STATE_ALPHA_REF_MASK
  2409. | BGFX_STATE_PT_MASK
  2410. | BGFX_STATE_POINT_SIZE_MASK
  2411. | BGFX_STATE_MSAA
  2412. ) & changedFlags)
  2413. {
  2414. if (BGFX_STATE_CULL_MASK & changedFlags)
  2415. {
  2416. if (BGFX_STATE_CULL_CW & newFlags)
  2417. {
  2418. GL_CHECK(glEnable(GL_CULL_FACE) );
  2419. GL_CHECK(glCullFace(GL_BACK) );
  2420. }
  2421. else if (BGFX_STATE_CULL_CCW & newFlags)
  2422. {
  2423. GL_CHECK(glEnable(GL_CULL_FACE) );
  2424. GL_CHECK(glCullFace(GL_FRONT) );
  2425. }
  2426. else
  2427. {
  2428. GL_CHECK(glDisable(GL_CULL_FACE) );
  2429. }
  2430. }
  2431. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2432. {
  2433. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2434. }
  2435. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2436. {
  2437. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2438. if (0 != func)
  2439. {
  2440. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2441. GL_CHECK(glDepthFunc(s_depthFunc[func]) );
  2442. }
  2443. else
  2444. {
  2445. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2446. }
  2447. }
  2448. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  2449. {
  2450. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  2451. alphaRef = ref/255.0f;
  2452. }
  2453. #if BGFX_CONFIG_RENDERER_OPENGL
  2454. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  2455. {
  2456. float pointSize = (float)(uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  2457. GL_CHECK(glPointSize(pointSize) );
  2458. }
  2459. if (BGFX_STATE_MSAA & changedFlags)
  2460. {
  2461. if (BGFX_STATE_MSAA & newFlags)
  2462. {
  2463. GL_CHECK(glEnable(GL_MULTISAMPLE) );
  2464. }
  2465. else
  2466. {
  2467. GL_CHECK(glDisable(GL_MULTISAMPLE) );
  2468. }
  2469. }
  2470. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2471. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  2472. {
  2473. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  2474. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  2475. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  2476. }
  2477. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags)
  2478. {
  2479. if (BGFX_STATE_BLEND_MASK & newFlags)
  2480. {
  2481. uint32_t blend = (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT;
  2482. uint32_t equation = (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT;
  2483. uint32_t src = blend&0xf;
  2484. uint32_t dst = (blend>>4)&0xf;
  2485. GL_CHECK(glEnable(GL_BLEND) );
  2486. GL_CHECK(glBlendFunc(s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  2487. GL_CHECK(glBlendEquation(s_blendEquation[equation]) );
  2488. if ( (s_blendFactor[src].m_factor || s_blendFactor[dst].m_factor)
  2489. && blendFactor != state.m_rgba)
  2490. {
  2491. blendFactor = state.m_rgba;
  2492. GLclampf rr = (blendFactor>>24)/255.0f;
  2493. GLclampf gg = ( (blendFactor>>16)&0xff)/255.0f;
  2494. GLclampf bb = ( (blendFactor>>8)&0xff)/255.0f;
  2495. GLclampf aa = (blendFactor&0xff)/255.0f;
  2496. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  2497. }
  2498. }
  2499. else
  2500. {
  2501. GL_CHECK(glDisable(GL_BLEND) );
  2502. }
  2503. }
  2504. uint8_t primIndex = uint8_t( (newFlags&BGFX_STATE_PT_MASK)>>BGFX_STATE_PT_SHIFT);
  2505. primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : s_primType[primIndex];
  2506. primNumVerts = 3-primIndex;
  2507. }
  2508. bool programChanged = false;
  2509. bool constantsChanged = state.m_constBegin < state.m_constEnd;
  2510. bool bindAttribs = false;
  2511. rendererUpdateUniforms(m_render->m_constantBuffer, state.m_constBegin, state.m_constEnd);
  2512. if (key.m_program != programIdx)
  2513. {
  2514. programIdx = key.m_program;
  2515. GLuint id = invalidHandle == programIdx ? 0 : s_renderCtx.m_program[programIdx].m_id;
  2516. GL_CHECK(glUseProgram(id) );
  2517. programChanged =
  2518. constantsChanged =
  2519. bindAttribs = true;
  2520. }
  2521. if (invalidHandle != programIdx)
  2522. {
  2523. Program& program = s_renderCtx.m_program[programIdx];
  2524. if (constantsChanged)
  2525. {
  2526. program.commit();
  2527. }
  2528. for (uint32_t ii = 0, num = program.m_numPredefined; ii < num; ++ii)
  2529. {
  2530. PredefinedUniform& predefined = program.m_predefined[ii];
  2531. switch (predefined.m_type)
  2532. {
  2533. case PredefinedUniform::ViewRect:
  2534. {
  2535. float rect[4];
  2536. rect[0] = m_render->m_rect[view].m_x;
  2537. rect[1] = m_render->m_rect[view].m_y;
  2538. rect[2] = m_render->m_rect[view].m_width;
  2539. rect[3] = m_render->m_rect[view].m_height;
  2540. GL_CHECK(glUniform4fv(predefined.m_loc
  2541. , 1
  2542. , &rect[0]
  2543. ) );
  2544. }
  2545. break;
  2546. case PredefinedUniform::ViewTexel:
  2547. {
  2548. float rect[4];
  2549. rect[0] = 1.0f/float(m_render->m_rect[view].m_width);
  2550. rect[1] = 1.0f/float(m_render->m_rect[view].m_height);
  2551. GL_CHECK(glUniform4fv(predefined.m_loc
  2552. , 1
  2553. , &rect[0]
  2554. ) );
  2555. }
  2556. break;
  2557. case PredefinedUniform::View:
  2558. {
  2559. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2560. , 1
  2561. , GL_FALSE
  2562. , m_render->m_view[view].val
  2563. ) );
  2564. }
  2565. break;
  2566. case PredefinedUniform::ViewProj:
  2567. {
  2568. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2569. , 1
  2570. , GL_FALSE
  2571. , viewProj[view].val
  2572. ) );
  2573. }
  2574. break;
  2575. case PredefinedUniform::Model:
  2576. {
  2577. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2578. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2579. , uint32_min(predefined.m_count, state.m_num)
  2580. , GL_FALSE
  2581. , model.val
  2582. ) );
  2583. }
  2584. break;
  2585. case PredefinedUniform::ModelView:
  2586. {
  2587. Matrix4 modelView;
  2588. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2589. mtxMul(modelView.val, model.val, m_render->m_view[view].val);
  2590. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2591. , 1
  2592. , GL_FALSE
  2593. , modelView.val
  2594. ) );
  2595. }
  2596. break;
  2597. case PredefinedUniform::ModelViewProj:
  2598. {
  2599. Matrix4 modelViewProj;
  2600. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2601. mtxMul(modelViewProj.val, model.val, viewProj[view].val);
  2602. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2603. , 1
  2604. , GL_FALSE
  2605. , modelViewProj.val
  2606. ) );
  2607. }
  2608. break;
  2609. case PredefinedUniform::ModelViewProjX:
  2610. {
  2611. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2612. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2613. {
  2614. 0.5f, 0.0f, 0.0f, 0.0f,
  2615. 0.0f, 0.5f, 0.0f, 0.0f,
  2616. 0.0f, 0.0f, 0.5f, 0.0f,
  2617. 0.5f, 0.5f, 0.5f, 1.0f,
  2618. };
  2619. uint8_t other = m_render->m_other[view];
  2620. Matrix4 viewProjBias;
  2621. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2622. Matrix4 modelViewProj;
  2623. mtxMul(modelViewProj.val, model.val, viewProjBias.val);
  2624. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2625. , 1
  2626. , GL_FALSE
  2627. , modelViewProj.val
  2628. ) );
  2629. }
  2630. break;
  2631. case PredefinedUniform::ViewProjX:
  2632. {
  2633. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2634. {
  2635. 0.5f, 0.0f, 0.0f, 0.0f,
  2636. 0.0f, 0.5f, 0.0f, 0.0f,
  2637. 0.0f, 0.0f, 0.5f, 0.0f,
  2638. 0.5f, 0.5f, 0.5f, 1.0f,
  2639. };
  2640. uint8_t other = m_render->m_other[view];
  2641. Matrix4 viewProjBias;
  2642. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2643. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2644. , 1
  2645. , GL_FALSE
  2646. , viewProjBias.val
  2647. ) );
  2648. }
  2649. break;
  2650. case PredefinedUniform::AlphaRef:
  2651. {
  2652. GL_CHECK(glUniform1f(predefined.m_loc, alphaRef) );
  2653. }
  2654. break;
  2655. case PredefinedUniform::Count:
  2656. break;
  2657. }
  2658. }
  2659. // if (BGFX_STATE_TEX_MASK & changedFlags)
  2660. {
  2661. uint64_t flag = BGFX_STATE_TEX0;
  2662. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  2663. {
  2664. const Sampler& sampler = state.m_sampler[stage];
  2665. Sampler& current = currentState.m_sampler[stage];
  2666. if (current.m_idx != sampler.m_idx
  2667. || current.m_flags != sampler.m_flags
  2668. || programChanged)
  2669. {
  2670. if (invalidHandle != sampler.m_idx)
  2671. {
  2672. GL_CHECK(glActiveTexture(GL_TEXTURE0+stage) );
  2673. switch (sampler.m_flags&BGFX_SAMPLER_TYPE_MASK)
  2674. {
  2675. case BGFX_SAMPLER_TEXTURE:
  2676. {
  2677. const Texture& texture = s_renderCtx.m_textures[sampler.m_idx];
  2678. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  2679. }
  2680. break;
  2681. case BGFX_SAMPLER_RENDERTARGET_COLOR:
  2682. {
  2683. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  2684. GL_CHECK(glBindTexture(rt.m_color.m_target, rt.m_color.m_id) );
  2685. }
  2686. break;
  2687. case BGFX_SAMPLER_RENDERTARGET_DEPTH:
  2688. {
  2689. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  2690. GL_CHECK(glBindTexture(rt.m_depth.m_target, rt.m_depth.m_id) );
  2691. }
  2692. break;
  2693. }
  2694. }
  2695. }
  2696. current = sampler;
  2697. flag <<= 1;
  2698. }
  2699. }
  2700. if (0 != defaultVao
  2701. && 0 == state.m_startVertex
  2702. && 0 == state.m_instanceDataOffset)
  2703. {
  2704. if (programChanged
  2705. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx
  2706. || currentState.m_indexBuffer.idx != state.m_indexBuffer.idx
  2707. || currentState.m_instanceDataBuffer.idx != state.m_instanceDataBuffer.idx)
  2708. {
  2709. bx::HashMurmur2A murmur;
  2710. murmur.begin();
  2711. murmur.add(state.m_vertexBuffer.idx);
  2712. murmur.add(state.m_indexBuffer.idx);
  2713. murmur.add(state.m_instanceDataBuffer.idx);
  2714. murmur.add(programIdx);
  2715. uint32_t hash = murmur.end();
  2716. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2717. currentState.m_indexBuffer = state.m_indexBuffer;
  2718. baseVertex = state.m_startVertex;
  2719. GLuint id = s_renderCtx.m_vaoCache.find(hash);
  2720. if (UINT32_MAX != id)
  2721. {
  2722. currentVao = id;
  2723. GL_CHECK(glBindVertexArray(id) );
  2724. }
  2725. else
  2726. {
  2727. id = s_renderCtx.m_vaoCache.add(hash);
  2728. currentVao = id;
  2729. GL_CHECK(glBindVertexArray(id) );
  2730. Program& program = s_renderCtx.m_program[programIdx];
  2731. program.add(hash);
  2732. if (invalidHandle != state.m_vertexBuffer.idx)
  2733. {
  2734. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[state.m_vertexBuffer.idx];
  2735. vb.add(hash);
  2736. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2737. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2738. program.bindAttributes(s_renderCtx.m_vertexDecls[decl], state.m_startVertex);
  2739. if (invalidHandle != state.m_instanceDataBuffer.idx)
  2740. {
  2741. VertexBuffer& instanceVb = s_renderCtx.m_vertexBuffers[state.m_instanceDataBuffer.idx];
  2742. instanceVb.add(hash);
  2743. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  2744. program.bindInstanceData(state.m_instanceDataStride, state.m_instanceDataOffset);
  2745. }
  2746. }
  2747. else
  2748. {
  2749. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  2750. }
  2751. if (invalidHandle != state.m_indexBuffer.idx)
  2752. {
  2753. IndexBuffer& ib = s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx];
  2754. ib.add(hash);
  2755. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2756. }
  2757. else
  2758. {
  2759. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2760. }
  2761. }
  2762. }
  2763. }
  2764. else
  2765. {
  2766. if (0 != defaultVao
  2767. && 0 != currentVao)
  2768. {
  2769. GL_CHECK(glBindVertexArray(defaultVao) );
  2770. currentState.m_vertexBuffer.idx = invalidHandle;
  2771. currentState.m_indexBuffer.idx = invalidHandle;
  2772. bindAttribs = true;
  2773. currentVao = 0;
  2774. }
  2775. if (programChanged
  2776. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx)
  2777. {
  2778. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2779. uint16_t handle = state.m_vertexBuffer.idx;
  2780. if (invalidHandle != handle)
  2781. {
  2782. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[handle];
  2783. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2784. bindAttribs = true;
  2785. }
  2786. else
  2787. {
  2788. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  2789. }
  2790. }
  2791. if (currentState.m_indexBuffer.idx != state.m_indexBuffer.idx)
  2792. {
  2793. currentState.m_indexBuffer = state.m_indexBuffer;
  2794. uint16_t handle = state.m_indexBuffer.idx;
  2795. if (invalidHandle != handle)
  2796. {
  2797. IndexBuffer& ib = s_renderCtx.m_indexBuffers[handle];
  2798. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2799. }
  2800. else
  2801. {
  2802. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2803. }
  2804. }
  2805. if (invalidHandle != currentState.m_vertexBuffer.idx)
  2806. {
  2807. if (baseVertex != state.m_startVertex
  2808. || bindAttribs)
  2809. {
  2810. baseVertex = state.m_startVertex;
  2811. const VertexBuffer& vb = s_renderCtx.m_vertexBuffers[state.m_vertexBuffer.idx];
  2812. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2813. const Program& program = s_renderCtx.m_program[programIdx];
  2814. program.bindAttributes(s_renderCtx.m_vertexDecls[decl], state.m_startVertex);
  2815. if (invalidHandle != state.m_instanceDataBuffer.idx)
  2816. {
  2817. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, s_renderCtx.m_vertexBuffers[state.m_instanceDataBuffer.idx].m_id) );
  2818. program.bindInstanceData(state.m_instanceDataStride, state.m_instanceDataOffset);
  2819. }
  2820. }
  2821. }
  2822. }
  2823. if (invalidHandle != currentState.m_vertexBuffer.idx)
  2824. {
  2825. uint32_t numVertices = state.m_numVertices;
  2826. if (UINT32_C(0xffffffff) == numVertices)
  2827. {
  2828. const VertexBuffer& vb = s_renderCtx.m_vertexBuffers[currentState.m_vertexBuffer.idx];
  2829. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2830. const VertexDecl& vertexDecl = s_renderCtx.m_vertexDecls[decl];
  2831. numVertices = vb.m_size/vertexDecl.m_stride;
  2832. }
  2833. uint32_t numIndices = 0;
  2834. uint32_t numPrimsSubmitted = 0;
  2835. uint32_t numInstances = 0;
  2836. uint32_t numPrimsRendered = 0;
  2837. if (invalidHandle != state.m_indexBuffer.idx)
  2838. {
  2839. if (UINT32_MAX == state.m_numIndices)
  2840. {
  2841. numIndices = s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx].m_size/2;
  2842. numPrimsSubmitted = numIndices/primNumVerts;
  2843. numInstances = state.m_numInstances;
  2844. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2845. GL_CHECK(s_drawElementsInstanced(primType
  2846. , numIndices
  2847. , GL_UNSIGNED_SHORT
  2848. , (void*)0
  2849. , state.m_numInstances
  2850. ) );
  2851. }
  2852. else if (primNumVerts <= state.m_numIndices)
  2853. {
  2854. numIndices = state.m_numIndices;
  2855. numPrimsSubmitted = numIndices/primNumVerts;
  2856. numInstances = state.m_numInstances;
  2857. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2858. GL_CHECK(s_drawElementsInstanced(primType
  2859. , numIndices
  2860. , GL_UNSIGNED_SHORT
  2861. , (void*)(uintptr_t)(state.m_startIndex*2)
  2862. , state.m_numInstances
  2863. ) );
  2864. }
  2865. }
  2866. else
  2867. {
  2868. numPrimsSubmitted = numVertices/primNumVerts;
  2869. numInstances = state.m_numInstances;
  2870. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2871. GL_CHECK(s_drawArraysInstanced(primType
  2872. , 0
  2873. , numVertices
  2874. , state.m_numInstances
  2875. ) );
  2876. }
  2877. statsNumPrimsSubmitted += numPrimsSubmitted;
  2878. statsNumIndices += numIndices;
  2879. statsNumInstances += numInstances;
  2880. statsNumPrimsRendered += numPrimsRendered;
  2881. }
  2882. }
  2883. }
  2884. s_renderCtx.blitMsaaFbo();
  2885. if (0 < m_render->m_num)
  2886. {
  2887. captureElapsed = -bx::getHPCounter();
  2888. s_renderCtx.capture();
  2889. captureElapsed += bx::getHPCounter();
  2890. }
  2891. }
  2892. int64_t now = bx::getHPCounter();
  2893. elapsed += now;
  2894. static int64_t last = now;
  2895. int64_t frameTime = now - last;
  2896. last = now;
  2897. static int64_t min = frameTime;
  2898. static int64_t max = frameTime;
  2899. min = min > frameTime ? frameTime : min;
  2900. max = max < frameTime ? frameTime : max;
  2901. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2902. {
  2903. double elapsedGpuMs = 0.0;
  2904. #if BGFX_CONFIG_RENDERER_OPENGL
  2905. s_renderCtx.m_queries.end(GL_TIME_ELAPSED);
  2906. uint64_t elapsedGl = s_renderCtx.m_queries.getResult(0);
  2907. elapsedGpuMs = double(elapsedGl)/1e6;
  2908. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2909. TextVideoMem& tvm = s_renderCtx.m_textVideoMem;
  2910. static int64_t next = now;
  2911. if (now >= next)
  2912. {
  2913. next = now + bx::getHPFrequency();
  2914. double freq = double(bx::getHPFrequency() );
  2915. double toMs = 1000.0/freq;
  2916. tvm.clear();
  2917. uint16_t pos = 0;
  2918. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " " BGFX_RENDERER_NAME " ");
  2919. tvm.printf(0, pos++, 0x0f, " Vendor: %s", s_renderCtx.m_vendor);
  2920. tvm.printf(0, pos++, 0x0f, " Renderer: %s", s_renderCtx.m_renderer);
  2921. tvm.printf(0, pos++, 0x0f, " Version: %s", s_renderCtx.m_version);
  2922. tvm.printf(0, pos++, 0x0f, "GLSL version: %s", s_renderCtx.m_glslVersion);
  2923. pos = 10;
  2924. tvm.printf(10, pos++, 0x8e, " Frame CPU: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS%s"
  2925. , double(frameTime)*toMs
  2926. , double(min)*toMs
  2927. , double(max)*toMs
  2928. , freq/frameTime
  2929. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? " (vsync)" : ""
  2930. );
  2931. double elapsedCpuMs = double(elapsed)*toMs;
  2932. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / CPU %3.4f [ms] %c GPU %3.4f [ms]"
  2933. , m_render->m_num
  2934. , elapsedCpuMs
  2935. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  2936. , elapsedGpuMs
  2937. );
  2938. tvm.printf(10, pos++, 0x8e, " Prims: %7d (#inst: %5d), submitted: %7d"
  2939. , statsNumPrimsRendered
  2940. , statsNumInstances
  2941. , statsNumPrimsSubmitted
  2942. );
  2943. double captureMs = double(captureElapsed)*toMs;
  2944. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  2945. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2946. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", m_render->m_vboffset);
  2947. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", m_render->m_iboffset);
  2948. #if BGFX_CONFIG_RENDERER_OPENGL
  2949. if (s_extension[Extension::ATI_meminfo].m_supported)
  2950. {
  2951. GLint vboFree[4];
  2952. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  2953. GLint texFree[4];
  2954. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  2955. GLint rbfFree[4];
  2956. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  2957. pos++;
  2958. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb");
  2959. tvm.printf(10, pos++, 0x8e, " VBO: %7d, %7d, %7d, %7d", vboFree[0], vboFree[1], vboFree[2], vboFree[3]);
  2960. tvm.printf(10, pos++, 0x8e, " Texture: %7d, %7d, %7d, %7d", texFree[0], texFree[1], texFree[2], texFree[3]);
  2961. tvm.printf(10, pos++, 0x8e, " Render Buffer: %7d, %7d, %7d, %7d", rbfFree[0], rbfFree[1], rbfFree[2], rbfFree[3]);
  2962. }
  2963. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  2964. {
  2965. GLint dedicated;
  2966. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  2967. GLint totalAvail;
  2968. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  2969. GLint currAvail;
  2970. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  2971. GLint evictedCount;
  2972. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  2973. GLint evictedMemory;
  2974. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  2975. pos++;
  2976. tvm.printf(10, pos++, 0x8c, "----------|");
  2977. tvm.printf(10, pos++, 0x8e, " Dedicated: %7d", dedicated);
  2978. tvm.printf(10, pos++, 0x8e, " Available: %7d (%7d)", currAvail, totalAvail);
  2979. tvm.printf(10, pos++, 0x8e, " Eviction: %7d / %7d", evictedCount, evictedMemory);
  2980. }
  2981. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2982. uint8_t attr[2] = { 0x89, 0x8a };
  2983. uint8_t attrIndex = m_render->m_waitSubmit < m_render->m_waitRender;
  2984. pos++;
  2985. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", double(m_render->m_waitSubmit)*toMs);
  2986. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", double(m_render->m_waitRender)*toMs);
  2987. min = frameTime;
  2988. max = frameTime;
  2989. }
  2990. m_textVideoMemBlitter.blit(tvm);
  2991. }
  2992. else if (m_render->m_debug & BGFX_DEBUG_TEXT)
  2993. {
  2994. m_textVideoMemBlitter.blit(m_render->m_textVideoMem);
  2995. }
  2996. GREMEDY_FRAMETERMINATOR();
  2997. }
  2998. }
  2999. #endif // (BGFX_CONFIG_RENDERER_OPENGLES2|BGFX_CONFIG_RENDERER_OPENGLES3|BGFX_CONFIG_RENDERER_OPENGL)