gl_rasterizer.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <bitset>
  7. #include <memory>
  8. #include <string>
  9. #include <string_view>
  10. #include <tuple>
  11. #include <utility>
  12. #include <glad/glad.h>
  13. #include "common/alignment.h"
  14. #include "common/assert.h"
  15. #include "common/logging/log.h"
  16. #include "common/math_util.h"
  17. #include "common/microprofile.h"
  18. #include "common/scope_exit.h"
  19. #include "core/core.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/memory.h"
  22. #include "core/settings.h"
  23. #include "video_core/engines/kepler_compute.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/engines/shader_type.h"
  26. #include "video_core/memory_manager.h"
  27. #include "video_core/renderer_opengl/gl_query_cache.h"
  28. #include "video_core/renderer_opengl/gl_rasterizer.h"
  29. #include "video_core/renderer_opengl/gl_shader_cache.h"
  30. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  31. #include "video_core/renderer_opengl/renderer_opengl.h"
  32. namespace OpenGL {
  33. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  34. using Tegra::Engines::ShaderType;
  35. using VideoCore::Surface::PixelFormat;
  36. using VideoCore::Surface::SurfaceTarget;
  37. using VideoCore::Surface::SurfaceType;
  38. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  43. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  45. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  46. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  47. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  48. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  49. namespace {
  50. constexpr std::size_t NUM_CONST_BUFFERS_PER_STAGE = 18;
  51. constexpr std::size_t NUM_CONST_BUFFERS_BYTES_PER_STAGE =
  52. NUM_CONST_BUFFERS_PER_STAGE * Maxwell::MaxConstBufferSize;
  53. constexpr std::size_t TOTAL_CONST_BUFFER_BYTES =
  54. NUM_CONST_BUFFERS_BYTES_PER_STAGE * Maxwell::MaxShaderStage;
  55. constexpr std::size_t NumSupportedVertexAttributes = 16;
  56. template <typename Engine, typename Entry>
  57. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  58. ShaderType shader_type, std::size_t index = 0) {
  59. if (entry.is_bindless) {
  60. const auto tex_handle = engine.AccessConstBuffer32(shader_type, entry.buffer, entry.offset);
  61. return engine.GetTextureInfo(tex_handle);
  62. }
  63. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  64. const u32 offset = entry.offset + static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  65. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  66. return engine.GetStageTexture(shader_type, offset);
  67. } else {
  68. return engine.GetTexture(offset);
  69. }
  70. }
  71. std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
  72. const ConstBufferEntry& entry) {
  73. if (!entry.IsIndirect()) {
  74. return entry.GetSize();
  75. }
  76. if (buffer.size > Maxwell::MaxConstBufferSize) {
  77. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", buffer.size,
  78. Maxwell::MaxConstBufferSize);
  79. return Maxwell::MaxConstBufferSize;
  80. }
  81. return buffer.size;
  82. }
  83. void oglEnable(GLenum cap, bool state) {
  84. (state ? glEnable : glDisable)(cap);
  85. }
  86. } // Anonymous namespace
  87. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  88. const Device& device, ScreenInfo& info,
  89. ProgramManager& program_manager, StateTracker& state_tracker)
  90. : RasterizerAccelerated{system.Memory()}, device{device}, texture_cache{system, *this, device,
  91. state_tracker},
  92. shader_cache{*this, system, emu_window, device}, query_cache{system, *this},
  93. buffer_cache{*this, system, device, STREAM_BUFFER_SIZE},
  94. fence_manager{system, *this, texture_cache, buffer_cache, query_cache}, system{system},
  95. screen_info{info}, program_manager{program_manager}, state_tracker{state_tracker} {
  96. CheckExtensions();
  97. unified_uniform_buffer.Create();
  98. glNamedBufferStorage(unified_uniform_buffer.handle, TOTAL_CONST_BUFFER_BYTES, nullptr, 0);
  99. if (device.UseAssemblyShaders()) {
  100. glCreateBuffers(static_cast<GLsizei>(staging_cbufs.size()), staging_cbufs.data());
  101. for (const GLuint cbuf : staging_cbufs) {
  102. glNamedBufferStorage(cbuf, static_cast<GLsizeiptr>(Maxwell::MaxConstBufferSize),
  103. nullptr, 0);
  104. }
  105. }
  106. }
  107. RasterizerOpenGL::~RasterizerOpenGL() {
  108. if (device.UseAssemblyShaders()) {
  109. glDeleteBuffers(static_cast<GLsizei>(staging_cbufs.size()), staging_cbufs.data());
  110. }
  111. }
  112. void RasterizerOpenGL::CheckExtensions() {
  113. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  114. LOG_WARNING(
  115. Render_OpenGL,
  116. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  117. }
  118. }
  119. void RasterizerOpenGL::SetupVertexFormat() {
  120. auto& gpu = system.GPU().Maxwell3D();
  121. auto& flags = gpu.dirty.flags;
  122. if (!flags[Dirty::VertexFormats]) {
  123. return;
  124. }
  125. flags[Dirty::VertexFormats] = false;
  126. MICROPROFILE_SCOPE(OpenGL_VAO);
  127. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  128. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  129. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  130. // avoid OpenGL errors.
  131. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  132. // assume every shader uses them all.
  133. for (std::size_t index = 0; index < NumSupportedVertexAttributes; ++index) {
  134. if (!flags[Dirty::VertexFormat0 + index]) {
  135. continue;
  136. }
  137. flags[Dirty::VertexFormat0 + index] = false;
  138. const auto attrib = gpu.regs.vertex_attrib_format[index];
  139. const auto gl_index = static_cast<GLuint>(index);
  140. // Disable constant attributes.
  141. if (attrib.IsConstant()) {
  142. glDisableVertexAttribArray(gl_index);
  143. continue;
  144. }
  145. glEnableVertexAttribArray(gl_index);
  146. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  147. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  148. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  149. MaxwellToGL::VertexType(attrib), attrib.offset);
  150. } else {
  151. glVertexAttribFormat(gl_index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  152. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  153. }
  154. glVertexAttribBinding(gl_index, attrib.buffer);
  155. }
  156. }
  157. void RasterizerOpenGL::SetupVertexBuffer() {
  158. auto& gpu = system.GPU().Maxwell3D();
  159. auto& flags = gpu.dirty.flags;
  160. if (!flags[Dirty::VertexBuffers]) {
  161. return;
  162. }
  163. flags[Dirty::VertexBuffers] = false;
  164. MICROPROFILE_SCOPE(OpenGL_VB);
  165. // Upload all guest vertex arrays sequentially to our buffer
  166. const auto& regs = gpu.regs;
  167. for (std::size_t index = 0; index < Maxwell::NumVertexArrays; ++index) {
  168. if (!flags[Dirty::VertexBuffer0 + index]) {
  169. continue;
  170. }
  171. flags[Dirty::VertexBuffer0 + index] = false;
  172. const auto& vertex_array = regs.vertex_array[index];
  173. if (!vertex_array.IsEnabled()) {
  174. continue;
  175. }
  176. const GPUVAddr start = vertex_array.StartAddress();
  177. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  178. ASSERT(end >= start);
  179. const u64 size = end - start;
  180. if (size == 0) {
  181. glBindVertexBuffer(static_cast<GLuint>(index), 0, 0, vertex_array.stride);
  182. continue;
  183. }
  184. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  185. glBindVertexBuffer(static_cast<GLuint>(index), vertex_buffer, vertex_buffer_offset,
  186. vertex_array.stride);
  187. }
  188. }
  189. void RasterizerOpenGL::SetupVertexInstances() {
  190. auto& gpu = system.GPU().Maxwell3D();
  191. auto& flags = gpu.dirty.flags;
  192. if (!flags[Dirty::VertexInstances]) {
  193. return;
  194. }
  195. flags[Dirty::VertexInstances] = false;
  196. const auto& regs = gpu.regs;
  197. for (std::size_t index = 0; index < NumSupportedVertexAttributes; ++index) {
  198. if (!flags[Dirty::VertexInstance0 + index]) {
  199. continue;
  200. }
  201. flags[Dirty::VertexInstance0 + index] = false;
  202. const auto gl_index = static_cast<GLuint>(index);
  203. const bool instancing_enabled = regs.instanced_arrays.IsInstancingEnabled(gl_index);
  204. const GLuint divisor = instancing_enabled ? regs.vertex_array[index].divisor : 0;
  205. glVertexBindingDivisor(gl_index, divisor);
  206. }
  207. }
  208. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  209. MICROPROFILE_SCOPE(OpenGL_Index);
  210. const auto& regs = system.GPU().Maxwell3D().regs;
  211. const std::size_t size = CalculateIndexBufferSize();
  212. const auto [buffer, offset] = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  213. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer);
  214. return offset;
  215. }
  216. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  217. MICROPROFILE_SCOPE(OpenGL_Shader);
  218. auto& gpu = system.GPU().Maxwell3D();
  219. std::size_t num_ssbos = 0;
  220. u32 clip_distances = 0;
  221. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  222. const auto& shader_config = gpu.regs.shader_config[index];
  223. const auto program{static_cast<Maxwell::ShaderProgram>(index)};
  224. // Skip stages that are not enabled
  225. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  226. switch (program) {
  227. case Maxwell::ShaderProgram::Geometry:
  228. program_manager.UseGeometryShader(0);
  229. break;
  230. case Maxwell::ShaderProgram::Fragment:
  231. program_manager.UseFragmentShader(0);
  232. break;
  233. default:
  234. break;
  235. }
  236. continue;
  237. }
  238. // Currently this stages are not supported in the OpenGL backend.
  239. // Todo(Blinkhawk): Port tesselation shaders from Vulkan to OpenGL
  240. if (program == Maxwell::ShaderProgram::TesselationControl) {
  241. continue;
  242. } else if (program == Maxwell::ShaderProgram::TesselationEval) {
  243. continue;
  244. }
  245. Shader shader{shader_cache.GetStageProgram(program)};
  246. if (device.UseAssemblyShaders()) {
  247. // Check for ARB limitation. We only have 16 SSBOs per context state. To workaround this
  248. // all stages share the same bindings.
  249. const std::size_t num_stage_ssbos = shader->GetEntries().global_memory_entries.size();
  250. ASSERT_MSG(num_stage_ssbos == 0 || num_ssbos == 0, "SSBOs on more than one stage");
  251. num_ssbos += num_stage_ssbos;
  252. }
  253. // Stage indices are 0 - 5
  254. const std::size_t stage = index == 0 ? 0 : index - 1;
  255. SetupDrawConstBuffers(stage, shader);
  256. SetupDrawGlobalMemory(stage, shader);
  257. SetupDrawTextures(stage, shader);
  258. SetupDrawImages(stage, shader);
  259. const GLuint program_handle = shader->GetHandle();
  260. switch (program) {
  261. case Maxwell::ShaderProgram::VertexA:
  262. case Maxwell::ShaderProgram::VertexB:
  263. program_manager.UseVertexShader(program_handle);
  264. break;
  265. case Maxwell::ShaderProgram::Geometry:
  266. program_manager.UseGeometryShader(program_handle);
  267. break;
  268. case Maxwell::ShaderProgram::Fragment:
  269. program_manager.UseFragmentShader(program_handle);
  270. break;
  271. default:
  272. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  273. shader_config.enable.Value(), shader_config.offset);
  274. }
  275. // Workaround for Intel drivers.
  276. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  277. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  278. // clip distances only when it's written by a shader stage.
  279. clip_distances |= shader->GetEntries().clip_distances;
  280. // When VertexA is enabled, we have dual vertex shaders
  281. if (program == Maxwell::ShaderProgram::VertexA) {
  282. // VertexB was combined with VertexA, so we skip the VertexB iteration
  283. ++index;
  284. }
  285. }
  286. SyncClipEnabled(clip_distances);
  287. gpu.dirty.flags[Dirty::Shaders] = false;
  288. }
  289. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  290. const auto& regs = system.GPU().Maxwell3D().regs;
  291. std::size_t size = 0;
  292. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  293. if (!regs.vertex_array[index].IsEnabled())
  294. continue;
  295. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  296. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  297. size += end - start;
  298. ASSERT(end >= start);
  299. }
  300. return size;
  301. }
  302. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  303. const auto& regs = system.GPU().Maxwell3D().regs;
  304. return static_cast<std::size_t>(regs.index_array.count) *
  305. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  306. }
  307. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  308. const VideoCore::DiskResourceLoadCallback& callback) {
  309. shader_cache.LoadDiskCache(stop_loading, callback);
  310. }
  311. void RasterizerOpenGL::SetupDirtyFlags() {
  312. state_tracker.Initialize();
  313. }
  314. void RasterizerOpenGL::ConfigureFramebuffers() {
  315. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  316. auto& gpu = system.GPU().Maxwell3D();
  317. if (!gpu.dirty.flags[VideoCommon::Dirty::RenderTargets]) {
  318. return;
  319. }
  320. gpu.dirty.flags[VideoCommon::Dirty::RenderTargets] = false;
  321. texture_cache.GuardRenderTargets(true);
  322. View depth_surface = texture_cache.GetDepthBufferSurface(true);
  323. const auto& regs = gpu.regs;
  324. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  325. // Bind the framebuffer surfaces
  326. FramebufferCacheKey key;
  327. const auto colors_count = static_cast<std::size_t>(regs.rt_control.count);
  328. for (std::size_t index = 0; index < colors_count; ++index) {
  329. View color_surface{texture_cache.GetColorBufferSurface(index, true)};
  330. if (!color_surface) {
  331. continue;
  332. }
  333. // Assume that a surface will be written to if it is used as a framebuffer, even
  334. // if the shader doesn't actually write to it.
  335. texture_cache.MarkColorBufferInUse(index);
  336. key.SetAttachment(index, regs.rt_control.GetMap(index));
  337. key.colors[index] = std::move(color_surface);
  338. }
  339. if (depth_surface) {
  340. // Assume that a surface will be written to if it is used as a framebuffer, even if
  341. // the shader doesn't actually write to it.
  342. texture_cache.MarkDepthBufferInUse();
  343. key.zeta = std::move(depth_surface);
  344. }
  345. texture_cache.GuardRenderTargets(false);
  346. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  347. }
  348. void RasterizerOpenGL::ConfigureClearFramebuffer(bool using_color, bool using_depth_stencil) {
  349. auto& gpu = system.GPU().Maxwell3D();
  350. const auto& regs = gpu.regs;
  351. texture_cache.GuardRenderTargets(true);
  352. View color_surface;
  353. if (using_color) {
  354. // Determine if we have to preserve the contents.
  355. // First we have to make sure all clear masks are enabled.
  356. bool preserve_contents = !regs.clear_buffers.R || !regs.clear_buffers.G ||
  357. !regs.clear_buffers.B || !regs.clear_buffers.A;
  358. const std::size_t index = regs.clear_buffers.RT;
  359. if (regs.clear_flags.scissor) {
  360. // Then we have to confirm scissor testing clears the whole image.
  361. const auto& scissor = regs.scissor_test[0];
  362. preserve_contents |= scissor.min_x > 0;
  363. preserve_contents |= scissor.min_y > 0;
  364. preserve_contents |= scissor.max_x < regs.rt[index].width;
  365. preserve_contents |= scissor.max_y < regs.rt[index].height;
  366. }
  367. color_surface = texture_cache.GetColorBufferSurface(index, preserve_contents);
  368. texture_cache.MarkColorBufferInUse(index);
  369. }
  370. View depth_surface;
  371. if (using_depth_stencil) {
  372. bool preserve_contents = false;
  373. if (regs.clear_flags.scissor) {
  374. // For depth stencil clears we only have to confirm scissor test covers the whole image.
  375. const auto& scissor = regs.scissor_test[0];
  376. preserve_contents |= scissor.min_x > 0;
  377. preserve_contents |= scissor.min_y > 0;
  378. preserve_contents |= scissor.max_x < regs.zeta_width;
  379. preserve_contents |= scissor.max_y < regs.zeta_height;
  380. }
  381. depth_surface = texture_cache.GetDepthBufferSurface(preserve_contents);
  382. texture_cache.MarkDepthBufferInUse();
  383. }
  384. texture_cache.GuardRenderTargets(false);
  385. FramebufferCacheKey key;
  386. key.colors[0] = std::move(color_surface);
  387. key.zeta = std::move(depth_surface);
  388. state_tracker.NotifyFramebuffer();
  389. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  390. }
  391. void RasterizerOpenGL::Clear() {
  392. const auto& gpu = system.GPU().Maxwell3D();
  393. if (!gpu.ShouldExecute()) {
  394. return;
  395. }
  396. const auto& regs = gpu.regs;
  397. bool use_color{};
  398. bool use_depth{};
  399. bool use_stencil{};
  400. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  401. regs.clear_buffers.A) {
  402. use_color = true;
  403. state_tracker.NotifyColorMask0();
  404. glColorMaski(0, regs.clear_buffers.R != 0, regs.clear_buffers.G != 0,
  405. regs.clear_buffers.B != 0, regs.clear_buffers.A != 0);
  406. // TODO(Rodrigo): Determine if clamping is used on clears
  407. SyncFragmentColorClampState();
  408. SyncFramebufferSRGB();
  409. }
  410. if (regs.clear_buffers.Z) {
  411. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  412. use_depth = true;
  413. state_tracker.NotifyDepthMask();
  414. glDepthMask(GL_TRUE);
  415. }
  416. if (regs.clear_buffers.S) {
  417. ASSERT_MSG(regs.zeta_enable, "Tried to clear stencil but buffer is not enabled!");
  418. use_stencil = true;
  419. }
  420. if (!use_color && !use_depth && !use_stencil) {
  421. // No color surface nor depth/stencil surface are enabled
  422. return;
  423. }
  424. SyncRasterizeEnable();
  425. SyncStencilTestState();
  426. if (regs.clear_flags.scissor) {
  427. SyncScissorTest();
  428. } else {
  429. state_tracker.NotifyScissor0();
  430. glDisablei(GL_SCISSOR_TEST, 0);
  431. }
  432. UNIMPLEMENTED_IF(regs.clear_flags.viewport);
  433. ConfigureClearFramebuffer(use_color, use_depth || use_stencil);
  434. if (use_color) {
  435. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  436. }
  437. if (use_depth && use_stencil) {
  438. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  439. } else if (use_depth) {
  440. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  441. } else if (use_stencil) {
  442. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  443. }
  444. ++num_queued_commands;
  445. }
  446. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  447. MICROPROFILE_SCOPE(OpenGL_Drawing);
  448. auto& gpu = system.GPU().Maxwell3D();
  449. query_cache.UpdateCounters();
  450. SyncViewport();
  451. SyncRasterizeEnable();
  452. SyncPolygonModes();
  453. SyncColorMask();
  454. SyncFragmentColorClampState();
  455. SyncMultiSampleState();
  456. SyncDepthTestState();
  457. SyncDepthClamp();
  458. SyncStencilTestState();
  459. SyncBlendState();
  460. SyncLogicOpState();
  461. SyncCullMode();
  462. SyncPrimitiveRestart();
  463. SyncScissorTest();
  464. SyncPointState();
  465. SyncLineState();
  466. SyncPolygonOffset();
  467. SyncAlphaTest();
  468. SyncFramebufferSRGB();
  469. buffer_cache.Acquire();
  470. current_cbuf = 0;
  471. std::size_t buffer_size = CalculateVertexArraysSize();
  472. // Add space for index buffer
  473. if (is_indexed) {
  474. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  475. }
  476. // Uniform space for the 5 shader stages
  477. buffer_size =
  478. Common::AlignUp<std::size_t>(buffer_size, 4) +
  479. (sizeof(MaxwellUniformData) + device.GetUniformBufferAlignment()) * Maxwell::MaxShaderStage;
  480. // Add space for at least 18 constant buffers
  481. buffer_size += Maxwell::MaxConstBuffers *
  482. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  483. // Prepare the vertex array.
  484. buffer_cache.Map(buffer_size);
  485. // Prepare vertex array format.
  486. SetupVertexFormat();
  487. // Upload vertex and index data.
  488. SetupVertexBuffer();
  489. SetupVertexInstances();
  490. GLintptr index_buffer_offset = 0;
  491. if (is_indexed) {
  492. index_buffer_offset = SetupIndexBuffer();
  493. }
  494. // Setup emulation uniform buffer.
  495. if (!device.UseAssemblyShaders()) {
  496. MaxwellUniformData ubo;
  497. ubo.SetFromRegs(gpu);
  498. const auto [buffer, offset] =
  499. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  500. glBindBufferRange(GL_UNIFORM_BUFFER, EmulationUniformBlockBinding, buffer, offset,
  501. static_cast<GLsizeiptr>(sizeof(ubo)));
  502. }
  503. // Setup shaders and their used resources.
  504. texture_cache.GuardSamplers(true);
  505. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
  506. SetupShaders(primitive_mode);
  507. texture_cache.GuardSamplers(false);
  508. ConfigureFramebuffers();
  509. // Signal the buffer cache that we are not going to upload more things.
  510. buffer_cache.Unmap();
  511. program_manager.BindGraphicsPipeline();
  512. if (texture_cache.TextureBarrier()) {
  513. glTextureBarrier();
  514. }
  515. BeginTransformFeedback(primitive_mode);
  516. const GLuint base_instance = static_cast<GLuint>(gpu.regs.vb_base_instance);
  517. const GLsizei num_instances =
  518. static_cast<GLsizei>(is_instanced ? gpu.mme_draw.instance_count : 1);
  519. if (is_indexed) {
  520. const GLint base_vertex = static_cast<GLint>(gpu.regs.vb_element_base);
  521. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.index_array.count);
  522. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  523. const GLenum format = MaxwellToGL::IndexFormat(gpu.regs.index_array.format);
  524. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  525. glDrawElements(primitive_mode, num_vertices, format, offset);
  526. } else if (num_instances == 1 && base_instance == 0) {
  527. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  528. } else if (base_vertex == 0 && base_instance == 0) {
  529. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  530. } else if (base_vertex == 0) {
  531. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  532. num_instances, base_instance);
  533. } else if (base_instance == 0) {
  534. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  535. num_instances, base_vertex);
  536. } else {
  537. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  538. offset, num_instances, base_vertex,
  539. base_instance);
  540. }
  541. } else {
  542. const GLint base_vertex = static_cast<GLint>(gpu.regs.vertex_buffer.first);
  543. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.vertex_buffer.count);
  544. if (num_instances == 1 && base_instance == 0) {
  545. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  546. } else if (base_instance == 0) {
  547. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  548. } else {
  549. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  550. num_instances, base_instance);
  551. }
  552. }
  553. EndTransformFeedback();
  554. ++num_queued_commands;
  555. system.GPU().TickWork();
  556. }
  557. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  558. buffer_cache.Acquire();
  559. current_cbuf = 0;
  560. auto kernel = shader_cache.GetComputeKernel(code_addr);
  561. SetupComputeTextures(kernel);
  562. SetupComputeImages(kernel);
  563. const std::size_t buffer_size =
  564. Tegra::Engines::KeplerCompute::NumConstBuffers *
  565. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  566. buffer_cache.Map(buffer_size);
  567. SetupComputeConstBuffers(kernel);
  568. SetupComputeGlobalMemory(kernel);
  569. buffer_cache.Unmap();
  570. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  571. program_manager.BindCompute(kernel->GetHandle());
  572. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  573. ++num_queued_commands;
  574. }
  575. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  576. query_cache.ResetCounter(type);
  577. }
  578. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  579. std::optional<u64> timestamp) {
  580. query_cache.Query(gpu_addr, type, timestamp);
  581. }
  582. void RasterizerOpenGL::FlushAll() {}
  583. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  584. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  585. if (addr == 0 || size == 0) {
  586. return;
  587. }
  588. texture_cache.FlushRegion(addr, size);
  589. buffer_cache.FlushRegion(addr, size);
  590. query_cache.FlushRegion(addr, size);
  591. }
  592. bool RasterizerOpenGL::MustFlushRegion(VAddr addr, u64 size) {
  593. if (!Settings::IsGPULevelHigh()) {
  594. return buffer_cache.MustFlushRegion(addr, size);
  595. }
  596. return texture_cache.MustFlushRegion(addr, size) || buffer_cache.MustFlushRegion(addr, size);
  597. }
  598. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  599. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  600. if (addr == 0 || size == 0) {
  601. return;
  602. }
  603. texture_cache.InvalidateRegion(addr, size);
  604. shader_cache.InvalidateRegion(addr, size);
  605. buffer_cache.InvalidateRegion(addr, size);
  606. query_cache.InvalidateRegion(addr, size);
  607. }
  608. void RasterizerOpenGL::OnCPUWrite(VAddr addr, u64 size) {
  609. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  610. if (addr == 0 || size == 0) {
  611. return;
  612. }
  613. texture_cache.OnCPUWrite(addr, size);
  614. shader_cache.OnCPUWrite(addr, size);
  615. buffer_cache.OnCPUWrite(addr, size);
  616. }
  617. void RasterizerOpenGL::SyncGuestHost() {
  618. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  619. texture_cache.SyncGuestHost();
  620. buffer_cache.SyncGuestHost();
  621. shader_cache.SyncGuestHost();
  622. }
  623. void RasterizerOpenGL::SignalSemaphore(GPUVAddr addr, u32 value) {
  624. auto& gpu{system.GPU()};
  625. if (!gpu.IsAsync()) {
  626. auto& memory_manager{gpu.MemoryManager()};
  627. memory_manager.Write<u32>(addr, value);
  628. return;
  629. }
  630. fence_manager.SignalSemaphore(addr, value);
  631. }
  632. void RasterizerOpenGL::SignalSyncPoint(u32 value) {
  633. auto& gpu{system.GPU()};
  634. if (!gpu.IsAsync()) {
  635. gpu.IncrementSyncPoint(value);
  636. return;
  637. }
  638. fence_manager.SignalSyncPoint(value);
  639. }
  640. void RasterizerOpenGL::ReleaseFences() {
  641. auto& gpu{system.GPU()};
  642. if (!gpu.IsAsync()) {
  643. return;
  644. }
  645. fence_manager.WaitPendingFences();
  646. }
  647. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  648. if (Settings::IsGPULevelExtreme()) {
  649. FlushRegion(addr, size);
  650. }
  651. InvalidateRegion(addr, size);
  652. }
  653. void RasterizerOpenGL::WaitForIdle() {
  654. // Place a barrier on everything that is not framebuffer related.
  655. // This is related to another flag that is not currently implemented.
  656. glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT | GL_ELEMENT_ARRAY_BARRIER_BIT |
  657. GL_UNIFORM_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT |
  658. GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL_COMMAND_BARRIER_BIT |
  659. GL_PIXEL_BUFFER_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT |
  660. GL_BUFFER_UPDATE_BARRIER_BIT | GL_TRANSFORM_FEEDBACK_BARRIER_BIT |
  661. GL_SHADER_STORAGE_BARRIER_BIT | GL_QUERY_BUFFER_BARRIER_BIT);
  662. }
  663. void RasterizerOpenGL::FlushCommands() {
  664. // Only flush when we have commands queued to OpenGL.
  665. if (num_queued_commands == 0) {
  666. return;
  667. }
  668. num_queued_commands = 0;
  669. glFlush();
  670. }
  671. void RasterizerOpenGL::TickFrame() {
  672. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  673. num_queued_commands = 0;
  674. buffer_cache.TickFrame();
  675. }
  676. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  677. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  678. const Tegra::Engines::Fermi2D::Config& copy_config) {
  679. MICROPROFILE_SCOPE(OpenGL_Blits);
  680. texture_cache.DoFermiCopy(src, dst, copy_config);
  681. return true;
  682. }
  683. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  684. VAddr framebuffer_addr, u32 pixel_stride) {
  685. if (!framebuffer_addr) {
  686. return {};
  687. }
  688. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  689. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  690. if (!surface) {
  691. return {};
  692. }
  693. // Verify that the cached surface is the same size and format as the requested framebuffer
  694. const auto& params{surface->GetSurfaceParams()};
  695. const auto& pixel_format{
  696. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  697. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  698. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  699. if (params.pixel_format != pixel_format) {
  700. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  701. }
  702. screen_info.display_texture = surface->GetTexture();
  703. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  704. return true;
  705. }
  706. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, const Shader& shader) {
  707. static constexpr std::array PARAMETER_LUT = {
  708. GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV, GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV,
  709. GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV, GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV,
  710. GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV};
  711. MICROPROFILE_SCOPE(OpenGL_UBO);
  712. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  713. const auto& shader_stage = stages[stage_index];
  714. const auto& entries = shader->GetEntries();
  715. const bool use_unified = entries.use_unified_uniforms;
  716. const std::size_t base_unified_offset = stage_index * NUM_CONST_BUFFERS_BYTES_PER_STAGE;
  717. const auto base_bindings = device.GetBaseBindings(stage_index);
  718. u32 binding = device.UseAssemblyShaders() ? 0 : base_bindings.uniform_buffer;
  719. for (const auto& entry : entries.const_buffers) {
  720. const u32 index = entry.GetIndex();
  721. const auto& buffer = shader_stage.const_buffers[index];
  722. SetupConstBuffer(PARAMETER_LUT[stage_index], binding, buffer, entry, use_unified,
  723. base_unified_offset + index * Maxwell::MaxConstBufferSize);
  724. ++binding;
  725. }
  726. if (use_unified) {
  727. const u32 index = static_cast<u32>(base_bindings.shader_storage_buffer +
  728. entries.global_memory_entries.size());
  729. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, unified_uniform_buffer.handle,
  730. base_unified_offset, NUM_CONST_BUFFERS_BYTES_PER_STAGE);
  731. }
  732. }
  733. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  734. MICROPROFILE_SCOPE(OpenGL_UBO);
  735. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  736. const auto& entries = kernel->GetEntries();
  737. const bool use_unified = entries.use_unified_uniforms;
  738. u32 binding = 0;
  739. for (const auto& entry : entries.const_buffers) {
  740. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  741. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  742. Tegra::Engines::ConstBufferInfo buffer;
  743. buffer.address = config.Address();
  744. buffer.size = config.size;
  745. buffer.enabled = mask[entry.GetIndex()];
  746. SetupConstBuffer(GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV, binding, buffer, entry,
  747. use_unified, entry.GetIndex() * Maxwell::MaxConstBufferSize);
  748. ++binding;
  749. }
  750. if (use_unified) {
  751. const GLuint index = static_cast<GLuint>(entries.global_memory_entries.size());
  752. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, unified_uniform_buffer.handle, 0,
  753. NUM_CONST_BUFFERS_BYTES_PER_STAGE);
  754. }
  755. }
  756. void RasterizerOpenGL::SetupConstBuffer(GLenum stage, u32 binding,
  757. const Tegra::Engines::ConstBufferInfo& buffer,
  758. const ConstBufferEntry& entry, bool use_unified,
  759. std::size_t unified_offset) {
  760. if (!buffer.enabled) {
  761. // Set values to zero to unbind buffers
  762. if (device.UseAssemblyShaders()) {
  763. glBindBufferRangeNV(stage, entry.GetIndex(), 0, 0, 0);
  764. } else {
  765. glBindBufferRange(GL_UNIFORM_BUFFER, binding,
  766. buffer_cache.GetEmptyBuffer(sizeof(float)), 0, sizeof(float));
  767. }
  768. return;
  769. }
  770. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  771. // UBO alignment requirements.
  772. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  773. const bool fast_upload = !use_unified && device.HasFastBufferSubData();
  774. const std::size_t alignment = use_unified ? 4 : device.GetUniformBufferAlignment();
  775. const GPUVAddr gpu_addr = buffer.address;
  776. auto [cbuf, offset] = buffer_cache.UploadMemory(gpu_addr, size, alignment, false, fast_upload);
  777. if (device.UseAssemblyShaders()) {
  778. UNIMPLEMENTED_IF(use_unified);
  779. if (offset != 0) {
  780. const GLuint staging_cbuf = staging_cbufs[current_cbuf++];
  781. glCopyNamedBufferSubData(cbuf, staging_cbuf, offset, 0, size);
  782. cbuf = staging_cbuf;
  783. offset = 0;
  784. }
  785. glBindBufferRangeNV(stage, binding, cbuf, offset, size);
  786. return;
  787. }
  788. if (use_unified) {
  789. glCopyNamedBufferSubData(cbuf, unified_uniform_buffer.handle, offset, unified_offset, size);
  790. } else {
  791. glBindBufferRange(GL_UNIFORM_BUFFER, binding, cbuf, offset, size);
  792. }
  793. }
  794. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, const Shader& shader) {
  795. auto& gpu{system.GPU()};
  796. auto& memory_manager{gpu.MemoryManager()};
  797. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage_index]};
  798. u32 binding =
  799. device.UseAssemblyShaders() ? 0 : device.GetBaseBindings(stage_index).shader_storage_buffer;
  800. for (const auto& entry : shader->GetEntries().global_memory_entries) {
  801. const GPUVAddr addr{cbufs.const_buffers[entry.cbuf_index].address + entry.cbuf_offset};
  802. const GPUVAddr gpu_addr{memory_manager.Read<u64>(addr)};
  803. const u32 size{memory_manager.Read<u32>(addr + 8)};
  804. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  805. }
  806. }
  807. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  808. auto& gpu{system.GPU()};
  809. auto& memory_manager{gpu.MemoryManager()};
  810. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  811. u32 binding = 0;
  812. for (const auto& entry : kernel->GetEntries().global_memory_entries) {
  813. const auto addr{cbufs[entry.cbuf_index].Address() + entry.cbuf_offset};
  814. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  815. const auto size{memory_manager.Read<u32>(addr + 8)};
  816. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  817. }
  818. }
  819. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GlobalMemoryEntry& entry,
  820. GPUVAddr gpu_addr, std::size_t size) {
  821. const auto alignment{device.GetShaderStorageBufferAlignment()};
  822. const auto [ssbo, buffer_offset] =
  823. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.is_written);
  824. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, binding, ssbo, buffer_offset,
  825. static_cast<GLsizeiptr>(size));
  826. }
  827. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, const Shader& shader) {
  828. MICROPROFILE_SCOPE(OpenGL_Texture);
  829. const auto& maxwell3d = system.GPU().Maxwell3D();
  830. u32 binding = device.GetBaseBindings(stage_index).sampler;
  831. for (const auto& entry : shader->GetEntries().samplers) {
  832. const auto shader_type = static_cast<ShaderType>(stage_index);
  833. for (std::size_t i = 0; i < entry.size; ++i) {
  834. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  835. SetupTexture(binding++, texture, entry);
  836. }
  837. }
  838. }
  839. void RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) {
  840. MICROPROFILE_SCOPE(OpenGL_Texture);
  841. const auto& compute = system.GPU().KeplerCompute();
  842. u32 binding = 0;
  843. for (const auto& entry : kernel->GetEntries().samplers) {
  844. for (std::size_t i = 0; i < entry.size; ++i) {
  845. const auto texture = GetTextureInfo(compute, entry, ShaderType::Compute, i);
  846. SetupTexture(binding++, texture, entry);
  847. }
  848. }
  849. }
  850. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  851. const SamplerEntry& entry) {
  852. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  853. if (!view) {
  854. // Can occur when texture addr is null or its memory is unmapped/invalid
  855. glBindSampler(binding, 0);
  856. glBindTextureUnit(binding, 0);
  857. return;
  858. }
  859. const GLuint handle = view->GetTexture(texture.tic.x_source, texture.tic.y_source,
  860. texture.tic.z_source, texture.tic.w_source);
  861. glBindTextureUnit(binding, handle);
  862. if (!view->GetSurfaceParams().IsBuffer()) {
  863. glBindSampler(binding, sampler_cache.GetSampler(texture.tsc));
  864. }
  865. }
  866. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, const Shader& shader) {
  867. const auto& maxwell3d = system.GPU().Maxwell3D();
  868. u32 binding = device.GetBaseBindings(stage_index).image;
  869. for (const auto& entry : shader->GetEntries().images) {
  870. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  871. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  872. SetupImage(binding++, tic, entry);
  873. }
  874. }
  875. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  876. const auto& compute = system.GPU().KeplerCompute();
  877. u32 binding = 0;
  878. for (const auto& entry : shader->GetEntries().images) {
  879. const auto tic = GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute).tic;
  880. SetupImage(binding++, tic, entry);
  881. }
  882. }
  883. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  884. const ImageEntry& entry) {
  885. const auto view = texture_cache.GetImageSurface(tic, entry);
  886. if (!view) {
  887. glBindImageTexture(binding, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R8);
  888. return;
  889. }
  890. if (entry.is_written) {
  891. view->MarkAsModified(texture_cache.Tick());
  892. }
  893. const GLuint handle = view->GetTexture(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  894. glBindImageTexture(binding, handle, 0, GL_TRUE, 0, GL_READ_WRITE, view->GetFormat());
  895. }
  896. void RasterizerOpenGL::SyncViewport() {
  897. auto& gpu = system.GPU().Maxwell3D();
  898. auto& flags = gpu.dirty.flags;
  899. const auto& regs = gpu.regs;
  900. const bool dirty_viewport = flags[Dirty::Viewports];
  901. if (dirty_viewport || flags[Dirty::ClipControl]) {
  902. flags[Dirty::ClipControl] = false;
  903. bool flip_y = false;
  904. if (regs.viewport_transform[0].scale_y < 0.0) {
  905. flip_y = !flip_y;
  906. }
  907. if (regs.screen_y_control.y_negate != 0) {
  908. flip_y = !flip_y;
  909. }
  910. glClipControl(flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT,
  911. regs.depth_mode == Maxwell::DepthMode::ZeroToOne ? GL_ZERO_TO_ONE
  912. : GL_NEGATIVE_ONE_TO_ONE);
  913. }
  914. if (dirty_viewport) {
  915. flags[Dirty::Viewports] = false;
  916. const bool force = flags[Dirty::ViewportTransform];
  917. flags[Dirty::ViewportTransform] = false;
  918. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  919. if (!force && !flags[Dirty::Viewport0 + i]) {
  920. continue;
  921. }
  922. flags[Dirty::Viewport0 + i] = false;
  923. const auto& src = regs.viewport_transform[i];
  924. const Common::Rectangle<f32> rect{src.GetRect()};
  925. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  926. rect.GetHeight());
  927. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  928. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  929. const GLdouble far_depth = src.translate_z + src.scale_z;
  930. glDepthRangeIndexed(static_cast<GLuint>(i), near_depth, far_depth);
  931. if (!GLAD_GL_NV_viewport_swizzle) {
  932. continue;
  933. }
  934. glViewportSwizzleNV(static_cast<GLuint>(i), MaxwellToGL::ViewportSwizzle(src.swizzle.x),
  935. MaxwellToGL::ViewportSwizzle(src.swizzle.y),
  936. MaxwellToGL::ViewportSwizzle(src.swizzle.z),
  937. MaxwellToGL::ViewportSwizzle(src.swizzle.w));
  938. }
  939. }
  940. }
  941. void RasterizerOpenGL::SyncDepthClamp() {
  942. auto& gpu = system.GPU().Maxwell3D();
  943. auto& flags = gpu.dirty.flags;
  944. if (!flags[Dirty::DepthClampEnabled]) {
  945. return;
  946. }
  947. flags[Dirty::DepthClampEnabled] = false;
  948. oglEnable(GL_DEPTH_CLAMP, gpu.regs.view_volume_clip_control.depth_clamp_disabled == 0);
  949. }
  950. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  951. auto& gpu = system.GPU().Maxwell3D();
  952. auto& flags = gpu.dirty.flags;
  953. if (!flags[Dirty::ClipDistances] && !flags[Dirty::Shaders]) {
  954. return;
  955. }
  956. flags[Dirty::ClipDistances] = false;
  957. clip_mask &= gpu.regs.clip_distance_enabled;
  958. if (clip_mask == last_clip_distance_mask) {
  959. return;
  960. }
  961. last_clip_distance_mask = clip_mask;
  962. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  963. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  964. }
  965. }
  966. void RasterizerOpenGL::SyncClipCoef() {
  967. UNIMPLEMENTED();
  968. }
  969. void RasterizerOpenGL::SyncCullMode() {
  970. auto& gpu = system.GPU().Maxwell3D();
  971. auto& flags = gpu.dirty.flags;
  972. const auto& regs = gpu.regs;
  973. if (flags[Dirty::CullTest]) {
  974. flags[Dirty::CullTest] = false;
  975. if (regs.cull_test_enabled) {
  976. glEnable(GL_CULL_FACE);
  977. glCullFace(MaxwellToGL::CullFace(regs.cull_face));
  978. } else {
  979. glDisable(GL_CULL_FACE);
  980. }
  981. }
  982. if (flags[Dirty::FrontFace]) {
  983. flags[Dirty::FrontFace] = false;
  984. glFrontFace(MaxwellToGL::FrontFace(regs.front_face));
  985. }
  986. }
  987. void RasterizerOpenGL::SyncPrimitiveRestart() {
  988. auto& gpu = system.GPU().Maxwell3D();
  989. auto& flags = gpu.dirty.flags;
  990. if (!flags[Dirty::PrimitiveRestart]) {
  991. return;
  992. }
  993. flags[Dirty::PrimitiveRestart] = false;
  994. if (gpu.regs.primitive_restart.enabled) {
  995. glEnable(GL_PRIMITIVE_RESTART);
  996. glPrimitiveRestartIndex(gpu.regs.primitive_restart.index);
  997. } else {
  998. glDisable(GL_PRIMITIVE_RESTART);
  999. }
  1000. }
  1001. void RasterizerOpenGL::SyncDepthTestState() {
  1002. auto& gpu = system.GPU().Maxwell3D();
  1003. auto& flags = gpu.dirty.flags;
  1004. const auto& regs = gpu.regs;
  1005. if (flags[Dirty::DepthMask]) {
  1006. flags[Dirty::DepthMask] = false;
  1007. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  1008. }
  1009. if (flags[Dirty::DepthTest]) {
  1010. flags[Dirty::DepthTest] = false;
  1011. if (regs.depth_test_enable) {
  1012. glEnable(GL_DEPTH_TEST);
  1013. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  1014. } else {
  1015. glDisable(GL_DEPTH_TEST);
  1016. }
  1017. }
  1018. }
  1019. void RasterizerOpenGL::SyncStencilTestState() {
  1020. auto& gpu = system.GPU().Maxwell3D();
  1021. auto& flags = gpu.dirty.flags;
  1022. if (!flags[Dirty::StencilTest]) {
  1023. return;
  1024. }
  1025. flags[Dirty::StencilTest] = false;
  1026. const auto& regs = gpu.regs;
  1027. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  1028. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_func_func),
  1029. regs.stencil_front_func_ref, regs.stencil_front_func_mask);
  1030. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op_fail),
  1031. MaxwellToGL::StencilOp(regs.stencil_front_op_zfail),
  1032. MaxwellToGL::StencilOp(regs.stencil_front_op_zpass));
  1033. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  1034. if (regs.stencil_two_side_enable) {
  1035. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_func_func),
  1036. regs.stencil_back_func_ref, regs.stencil_back_func_mask);
  1037. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op_fail),
  1038. MaxwellToGL::StencilOp(regs.stencil_back_op_zfail),
  1039. MaxwellToGL::StencilOp(regs.stencil_back_op_zpass));
  1040. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  1041. } else {
  1042. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  1043. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  1044. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  1045. }
  1046. }
  1047. void RasterizerOpenGL::SyncRasterizeEnable() {
  1048. auto& gpu = system.GPU().Maxwell3D();
  1049. auto& flags = gpu.dirty.flags;
  1050. if (!flags[Dirty::RasterizeEnable]) {
  1051. return;
  1052. }
  1053. flags[Dirty::RasterizeEnable] = false;
  1054. oglEnable(GL_RASTERIZER_DISCARD, gpu.regs.rasterize_enable == 0);
  1055. }
  1056. void RasterizerOpenGL::SyncPolygonModes() {
  1057. auto& gpu = system.GPU().Maxwell3D();
  1058. auto& flags = gpu.dirty.flags;
  1059. if (!flags[Dirty::PolygonModes]) {
  1060. return;
  1061. }
  1062. flags[Dirty::PolygonModes] = false;
  1063. if (gpu.regs.fill_rectangle) {
  1064. if (!GLAD_GL_NV_fill_rectangle) {
  1065. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  1066. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1067. return;
  1068. }
  1069. flags[Dirty::PolygonModeFront] = true;
  1070. flags[Dirty::PolygonModeBack] = true;
  1071. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  1072. return;
  1073. }
  1074. if (gpu.regs.polygon_mode_front == gpu.regs.polygon_mode_back) {
  1075. flags[Dirty::PolygonModeFront] = false;
  1076. flags[Dirty::PolygonModeBack] = false;
  1077. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  1078. return;
  1079. }
  1080. if (flags[Dirty::PolygonModeFront]) {
  1081. flags[Dirty::PolygonModeFront] = false;
  1082. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  1083. }
  1084. if (flags[Dirty::PolygonModeBack]) {
  1085. flags[Dirty::PolygonModeBack] = false;
  1086. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_back));
  1087. }
  1088. }
  1089. void RasterizerOpenGL::SyncColorMask() {
  1090. auto& gpu = system.GPU().Maxwell3D();
  1091. auto& flags = gpu.dirty.flags;
  1092. if (!flags[Dirty::ColorMasks]) {
  1093. return;
  1094. }
  1095. flags[Dirty::ColorMasks] = false;
  1096. const bool force = flags[Dirty::ColorMaskCommon];
  1097. flags[Dirty::ColorMaskCommon] = false;
  1098. const auto& regs = gpu.regs;
  1099. if (regs.color_mask_common) {
  1100. if (!force && !flags[Dirty::ColorMask0]) {
  1101. return;
  1102. }
  1103. flags[Dirty::ColorMask0] = false;
  1104. auto& mask = regs.color_mask[0];
  1105. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  1106. return;
  1107. }
  1108. // Path without color_mask_common set
  1109. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1110. if (!force && !flags[Dirty::ColorMask0 + i]) {
  1111. continue;
  1112. }
  1113. flags[Dirty::ColorMask0 + i] = false;
  1114. const auto& mask = regs.color_mask[i];
  1115. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  1116. }
  1117. }
  1118. void RasterizerOpenGL::SyncMultiSampleState() {
  1119. auto& gpu = system.GPU().Maxwell3D();
  1120. auto& flags = gpu.dirty.flags;
  1121. if (!flags[Dirty::MultisampleControl]) {
  1122. return;
  1123. }
  1124. flags[Dirty::MultisampleControl] = false;
  1125. const auto& regs = system.GPU().Maxwell3D().regs;
  1126. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  1127. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  1128. }
  1129. void RasterizerOpenGL::SyncFragmentColorClampState() {
  1130. auto& gpu = system.GPU().Maxwell3D();
  1131. auto& flags = gpu.dirty.flags;
  1132. if (!flags[Dirty::FragmentClampColor]) {
  1133. return;
  1134. }
  1135. flags[Dirty::FragmentClampColor] = false;
  1136. glClampColor(GL_CLAMP_FRAGMENT_COLOR, gpu.regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  1137. }
  1138. void RasterizerOpenGL::SyncBlendState() {
  1139. auto& gpu = system.GPU().Maxwell3D();
  1140. auto& flags = gpu.dirty.flags;
  1141. const auto& regs = gpu.regs;
  1142. if (flags[Dirty::BlendColor]) {
  1143. flags[Dirty::BlendColor] = false;
  1144. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1145. regs.blend_color.a);
  1146. }
  1147. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  1148. if (!flags[Dirty::BlendStates]) {
  1149. return;
  1150. }
  1151. flags[Dirty::BlendStates] = false;
  1152. if (!regs.independent_blend_enable) {
  1153. if (!regs.blend.enable[0]) {
  1154. glDisable(GL_BLEND);
  1155. return;
  1156. }
  1157. glEnable(GL_BLEND);
  1158. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb),
  1159. MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb),
  1160. MaxwellToGL::BlendFunc(regs.blend.factor_source_a),
  1161. MaxwellToGL::BlendFunc(regs.blend.factor_dest_a));
  1162. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.equation_rgb),
  1163. MaxwellToGL::BlendEquation(regs.blend.equation_a));
  1164. return;
  1165. }
  1166. const bool force = flags[Dirty::BlendIndependentEnabled];
  1167. flags[Dirty::BlendIndependentEnabled] = false;
  1168. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1169. if (!force && !flags[Dirty::BlendState0 + i]) {
  1170. continue;
  1171. }
  1172. flags[Dirty::BlendState0 + i] = false;
  1173. if (!regs.blend.enable[i]) {
  1174. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  1175. continue;
  1176. }
  1177. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  1178. const auto& src = regs.independent_blend[i];
  1179. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.factor_source_rgb),
  1180. MaxwellToGL::BlendFunc(src.factor_dest_rgb),
  1181. MaxwellToGL::BlendFunc(src.factor_source_a),
  1182. MaxwellToGL::BlendFunc(src.factor_dest_a));
  1183. glBlendEquationSeparatei(static_cast<GLuint>(i),
  1184. MaxwellToGL::BlendEquation(src.equation_rgb),
  1185. MaxwellToGL::BlendEquation(src.equation_a));
  1186. }
  1187. }
  1188. void RasterizerOpenGL::SyncLogicOpState() {
  1189. auto& gpu = system.GPU().Maxwell3D();
  1190. auto& flags = gpu.dirty.flags;
  1191. if (!flags[Dirty::LogicOp]) {
  1192. return;
  1193. }
  1194. flags[Dirty::LogicOp] = false;
  1195. const auto& regs = gpu.regs;
  1196. if (regs.logic_op.enable) {
  1197. glEnable(GL_COLOR_LOGIC_OP);
  1198. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  1199. } else {
  1200. glDisable(GL_COLOR_LOGIC_OP);
  1201. }
  1202. }
  1203. void RasterizerOpenGL::SyncScissorTest() {
  1204. auto& gpu = system.GPU().Maxwell3D();
  1205. auto& flags = gpu.dirty.flags;
  1206. if (!flags[Dirty::Scissors]) {
  1207. return;
  1208. }
  1209. flags[Dirty::Scissors] = false;
  1210. const auto& regs = gpu.regs;
  1211. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  1212. if (!flags[Dirty::Scissor0 + index]) {
  1213. continue;
  1214. }
  1215. flags[Dirty::Scissor0 + index] = false;
  1216. const auto& src = regs.scissor_test[index];
  1217. if (src.enable) {
  1218. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1219. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y,
  1220. src.max_x - src.min_x, src.max_y - src.min_y);
  1221. } else {
  1222. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1223. }
  1224. }
  1225. }
  1226. void RasterizerOpenGL::SyncPointState() {
  1227. auto& gpu = system.GPU().Maxwell3D();
  1228. auto& flags = gpu.dirty.flags;
  1229. if (!flags[Dirty::PointSize]) {
  1230. return;
  1231. }
  1232. flags[Dirty::PointSize] = false;
  1233. oglEnable(GL_POINT_SPRITE, gpu.regs.point_sprite_enable);
  1234. if (gpu.regs.vp_point_size.enable) {
  1235. // By definition of GL_POINT_SIZE, it only matters if GL_PROGRAM_POINT_SIZE is disabled.
  1236. glEnable(GL_PROGRAM_POINT_SIZE);
  1237. return;
  1238. }
  1239. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1240. // in OpenGL).
  1241. glPointSize(std::max(1.0f, gpu.regs.point_size));
  1242. glDisable(GL_PROGRAM_POINT_SIZE);
  1243. }
  1244. void RasterizerOpenGL::SyncLineState() {
  1245. auto& gpu = system.GPU().Maxwell3D();
  1246. auto& flags = gpu.dirty.flags;
  1247. if (!flags[Dirty::LineWidth]) {
  1248. return;
  1249. }
  1250. flags[Dirty::LineWidth] = false;
  1251. const auto& regs = gpu.regs;
  1252. oglEnable(GL_LINE_SMOOTH, regs.line_smooth_enable);
  1253. glLineWidth(regs.line_smooth_enable ? regs.line_width_smooth : regs.line_width_aliased);
  1254. }
  1255. void RasterizerOpenGL::SyncPolygonOffset() {
  1256. auto& gpu = system.GPU().Maxwell3D();
  1257. auto& flags = gpu.dirty.flags;
  1258. if (!flags[Dirty::PolygonOffset]) {
  1259. return;
  1260. }
  1261. flags[Dirty::PolygonOffset] = false;
  1262. const auto& regs = gpu.regs;
  1263. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  1264. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  1265. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  1266. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  1267. regs.polygon_offset_point_enable) {
  1268. // Hardware divides polygon offset units by two
  1269. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  1270. regs.polygon_offset_clamp);
  1271. }
  1272. }
  1273. void RasterizerOpenGL::SyncAlphaTest() {
  1274. auto& gpu = system.GPU().Maxwell3D();
  1275. auto& flags = gpu.dirty.flags;
  1276. if (!flags[Dirty::AlphaTest]) {
  1277. return;
  1278. }
  1279. flags[Dirty::AlphaTest] = false;
  1280. const auto& regs = gpu.regs;
  1281. if (regs.alpha_test_enabled && regs.rt_control.count > 1) {
  1282. LOG_WARNING(Render_OpenGL, "Alpha testing with more than one render target is not tested");
  1283. }
  1284. if (regs.alpha_test_enabled) {
  1285. glEnable(GL_ALPHA_TEST);
  1286. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  1287. } else {
  1288. glDisable(GL_ALPHA_TEST);
  1289. }
  1290. }
  1291. void RasterizerOpenGL::SyncFramebufferSRGB() {
  1292. auto& gpu = system.GPU().Maxwell3D();
  1293. auto& flags = gpu.dirty.flags;
  1294. if (!flags[Dirty::FramebufferSRGB]) {
  1295. return;
  1296. }
  1297. flags[Dirty::FramebufferSRGB] = false;
  1298. oglEnable(GL_FRAMEBUFFER_SRGB, gpu.regs.framebuffer_srgb);
  1299. }
  1300. void RasterizerOpenGL::BeginTransformFeedback(GLenum primitive_mode) {
  1301. const auto& regs = system.GPU().Maxwell3D().regs;
  1302. if (regs.tfb_enabled == 0) {
  1303. return;
  1304. }
  1305. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  1306. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  1307. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  1308. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1309. const auto& binding = regs.tfb_bindings[index];
  1310. if (!binding.buffer_enable) {
  1311. if (enabled_transform_feedback_buffers[index]) {
  1312. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), 0, 0,
  1313. 0);
  1314. }
  1315. enabled_transform_feedback_buffers[index] = false;
  1316. continue;
  1317. }
  1318. enabled_transform_feedback_buffers[index] = true;
  1319. auto& tfb_buffer = transform_feedback_buffers[index];
  1320. tfb_buffer.Create();
  1321. const GLuint handle = tfb_buffer.handle;
  1322. const std::size_t size = binding.buffer_size;
  1323. glNamedBufferData(handle, static_cast<GLsizeiptr>(size), nullptr, GL_STREAM_COPY);
  1324. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), handle, 0,
  1325. static_cast<GLsizeiptr>(size));
  1326. }
  1327. glBeginTransformFeedback(GL_POINTS);
  1328. }
  1329. void RasterizerOpenGL::EndTransformFeedback() {
  1330. const auto& regs = system.GPU().Maxwell3D().regs;
  1331. if (regs.tfb_enabled == 0) {
  1332. return;
  1333. }
  1334. glEndTransformFeedback();
  1335. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1336. const auto& binding = regs.tfb_bindings[index];
  1337. if (!binding.buffer_enable) {
  1338. continue;
  1339. }
  1340. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  1341. const GLuint handle = transform_feedback_buffers[index].handle;
  1342. const GPUVAddr gpu_addr = binding.Address();
  1343. const std::size_t size = binding.buffer_size;
  1344. const auto [dest_buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  1345. glCopyNamedBufferSubData(handle, dest_buffer, 0, offset, static_cast<GLsizeiptr>(size));
  1346. }
  1347. }
  1348. } // namespace OpenGL