renderer_gl.cpp 95 KB

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