gl_rasterizer.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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 <memory>
  7. #include <string>
  8. #include <string_view>
  9. #include <tuple>
  10. #include <utility>
  11. #include <glad/glad.h>
  12. #include "common/alignment.h"
  13. #include "common/assert.h"
  14. #include "common/logging/log.h"
  15. #include "common/math_util.h"
  16. #include "common/microprofile.h"
  17. #include "common/scope_exit.h"
  18. #include "core/core.h"
  19. #include "core/hle/kernel/process.h"
  20. #include "core/settings.h"
  21. #include "video_core/engines/maxwell_3d.h"
  22. #include "video_core/renderer_opengl/gl_rasterizer.h"
  23. #include "video_core/renderer_opengl/gl_shader_cache.h"
  24. #include "video_core/renderer_opengl/gl_shader_gen.h"
  25. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  26. #include "video_core/renderer_opengl/renderer_opengl.h"
  27. namespace OpenGL {
  28. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  29. using PixelFormat = VideoCore::Surface::PixelFormat;
  30. using SurfaceType = VideoCore::Surface::SurfaceType;
  31. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  32. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  33. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  34. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  35. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  36. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  41. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  42. struct DrawParameters {
  43. GLenum primitive_mode;
  44. GLsizei count;
  45. GLint current_instance;
  46. bool use_indexed;
  47. GLint vertex_first;
  48. GLenum index_format;
  49. GLint base_vertex;
  50. GLintptr index_buffer_offset;
  51. void DispatchDraw() const {
  52. if (use_indexed) {
  53. const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
  54. if (current_instance > 0) {
  55. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
  56. index_buffer_ptr, 1, base_vertex,
  57. current_instance);
  58. } else {
  59. glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
  60. base_vertex);
  61. }
  62. } else {
  63. if (current_instance > 0) {
  64. glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
  65. current_instance);
  66. } else {
  67. glDrawArrays(primitive_mode, vertex_first, count);
  68. }
  69. }
  70. }
  71. };
  72. struct FramebufferCacheKey {
  73. bool is_single_buffer = false;
  74. bool stencil_enable = false;
  75. std::array<GLenum, Maxwell::NumRenderTargets> color_attachments{};
  76. std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> colors{};
  77. u32 colors_count = 0;
  78. GLuint zeta = 0;
  79. auto Tie() const {
  80. return std::tie(is_single_buffer, stencil_enable, color_attachments, colors, colors_count,
  81. zeta);
  82. }
  83. bool operator<(const FramebufferCacheKey& rhs) const {
  84. return Tie() < rhs.Tie();
  85. }
  86. };
  87. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  88. ScreenInfo& info)
  89. : res_cache{*this}, shader_cache{*this, system, emu_window, device},
  90. global_cache{*this}, system{system}, screen_info{info},
  91. buffer_cache(*this, STREAM_BUFFER_SIZE) {
  92. OpenGLState::ApplyDefaultState();
  93. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  94. state.draw.shader_program = 0;
  95. state.Apply();
  96. LOG_DEBUG(Render_OpenGL, "Sync fixed function OpenGL state here");
  97. CheckExtensions();
  98. }
  99. RasterizerOpenGL::~RasterizerOpenGL() {}
  100. void RasterizerOpenGL::CheckExtensions() {
  101. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  102. LOG_WARNING(
  103. Render_OpenGL,
  104. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  105. }
  106. if (!GLAD_GL_ARB_buffer_storage) {
  107. LOG_WARNING(
  108. Render_OpenGL,
  109. "Buffer storage control is not supported! This can cause performance degradation.");
  110. }
  111. }
  112. GLuint RasterizerOpenGL::SetupVertexFormat() {
  113. auto& gpu = system.GPU().Maxwell3D();
  114. const auto& regs = gpu.regs;
  115. if (!gpu.dirty_flags.vertex_attrib_format) {
  116. return state.draw.vertex_array;
  117. }
  118. gpu.dirty_flags.vertex_attrib_format = false;
  119. MICROPROFILE_SCOPE(OpenGL_VAO);
  120. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  121. auto& vao_entry = iter->second;
  122. if (is_cache_miss) {
  123. vao_entry.Create();
  124. const GLuint vao = vao_entry.handle;
  125. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  126. // that fails to properly create the vertex array if it's not bound even after creating it
  127. // with glCreateVertexArrays
  128. state.draw.vertex_array = vao;
  129. state.ApplyVertexArrayState();
  130. glVertexArrayElementBuffer(vao, buffer_cache.GetHandle());
  131. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  132. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  133. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  134. // for now to avoid OpenGL errors.
  135. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  136. // assume every shader uses them all.
  137. for (u32 index = 0; index < 16; ++index) {
  138. const auto& attrib = regs.vertex_attrib_format[index];
  139. // Ignore invalid attributes.
  140. if (!attrib.IsValid())
  141. continue;
  142. const auto& buffer = regs.vertex_array[attrib.buffer];
  143. LOG_TRACE(Render_OpenGL,
  144. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  145. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  146. attrib.offset.Value(), attrib.IsNormalized());
  147. ASSERT(buffer.IsEnabled());
  148. glEnableVertexArrayAttrib(vao, index);
  149. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  150. attrib.type ==
  151. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  152. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  153. MaxwellToGL::VertexType(attrib), attrib.offset);
  154. } else {
  155. glVertexArrayAttribFormat(
  156. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  157. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  158. }
  159. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  160. }
  161. }
  162. // Rebinding the VAO invalidates the vertex buffer bindings.
  163. gpu.dirty_flags.vertex_array.set();
  164. state.draw.vertex_array = vao_entry.handle;
  165. return vao_entry.handle;
  166. }
  167. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  168. auto& gpu = system.GPU().Maxwell3D();
  169. const auto& regs = gpu.regs;
  170. if (gpu.dirty_flags.vertex_array.none())
  171. return;
  172. MICROPROFILE_SCOPE(OpenGL_VB);
  173. // Upload all guest vertex arrays sequentially to our buffer
  174. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  175. if (!gpu.dirty_flags.vertex_array[index])
  176. continue;
  177. const auto& vertex_array = regs.vertex_array[index];
  178. if (!vertex_array.IsEnabled())
  179. continue;
  180. const GPUVAddr start = vertex_array.StartAddress();
  181. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  182. ASSERT(end > start);
  183. const u64 size = end - start + 1;
  184. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  185. // Bind the vertex array to the buffer at the current offset.
  186. glVertexArrayVertexBuffer(vao, index, buffer_cache.GetHandle(), vertex_buffer_offset,
  187. vertex_array.stride);
  188. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  189. // Enable vertex buffer instancing with the specified divisor.
  190. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  191. } else {
  192. // Disable the vertex buffer instancing.
  193. glVertexArrayBindingDivisor(vao, index, 0);
  194. }
  195. }
  196. gpu.dirty_flags.vertex_array.reset();
  197. }
  198. DrawParameters RasterizerOpenGL::SetupDraw() {
  199. const auto& gpu = system.GPU().Maxwell3D();
  200. const auto& regs = gpu.regs;
  201. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  202. DrawParameters params{};
  203. params.current_instance = gpu.state.current_instance;
  204. params.use_indexed = is_indexed;
  205. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  206. if (is_indexed) {
  207. MICROPROFILE_SCOPE(OpenGL_Index);
  208. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  209. params.count = regs.index_array.count;
  210. params.index_buffer_offset =
  211. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  212. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  213. } else {
  214. params.count = regs.vertex_buffer.count;
  215. params.vertex_first = regs.vertex_buffer.first;
  216. }
  217. return params;
  218. }
  219. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  220. MICROPROFILE_SCOPE(OpenGL_Shader);
  221. auto& gpu = system.GPU().Maxwell3D();
  222. BaseBindings base_bindings;
  223. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  224. // Prepare packed bindings
  225. bind_ubo_pushbuffer.Setup(base_bindings.cbuf);
  226. bind_ssbo_pushbuffer.Setup(base_bindings.gmem);
  227. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  228. const auto& shader_config = gpu.regs.shader_config[index];
  229. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  230. // Skip stages that are not enabled
  231. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  232. switch (program) {
  233. case Maxwell::ShaderProgram::Geometry:
  234. shader_program_manager->UseTrivialGeometryShader();
  235. break;
  236. default:
  237. break;
  238. }
  239. continue;
  240. }
  241. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  242. GLShader::MaxwellUniformData ubo{};
  243. ubo.SetFromRegs(gpu, stage);
  244. const GLintptr offset =
  245. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  246. // Bind the emulation info buffer
  247. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), offset,
  248. static_cast<GLsizeiptr>(sizeof(ubo)));
  249. Shader shader{shader_cache.GetStageProgram(program)};
  250. const auto [program_handle, next_bindings] =
  251. shader->GetProgramHandle(primitive_mode, base_bindings);
  252. switch (program) {
  253. case Maxwell::ShaderProgram::VertexA:
  254. case Maxwell::ShaderProgram::VertexB:
  255. shader_program_manager->UseProgrammableVertexShader(program_handle);
  256. break;
  257. case Maxwell::ShaderProgram::Geometry:
  258. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  259. break;
  260. case Maxwell::ShaderProgram::Fragment:
  261. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  262. break;
  263. default:
  264. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  265. shader_config.enable.Value(), shader_config.offset);
  266. }
  267. const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
  268. SetupConstBuffers(stage_enum, shader, program_handle, base_bindings);
  269. SetupGlobalRegions(stage_enum, shader, program_handle, base_bindings);
  270. SetupTextures(stage_enum, shader, program_handle, base_bindings);
  271. // Workaround for Intel drivers.
  272. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  273. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  274. // clip distances only when it's written by a shader stage.
  275. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  276. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  277. }
  278. // When VertexA is enabled, we have dual vertex shaders
  279. if (program == Maxwell::ShaderProgram::VertexA) {
  280. // VertexB was combined with VertexA, so we skip the VertexB iteration
  281. index++;
  282. }
  283. base_bindings = next_bindings;
  284. }
  285. bind_ubo_pushbuffer.Bind();
  286. bind_ssbo_pushbuffer.Bind();
  287. SyncClipEnabled(clip_distances);
  288. gpu.dirty_flags.shaders = false;
  289. }
  290. void RasterizerOpenGL::SetupCachedFramebuffer(const FramebufferCacheKey& fbkey,
  291. OpenGLState& current_state) {
  292. const auto [entry, is_cache_miss] = framebuffer_cache.try_emplace(fbkey);
  293. auto& framebuffer = entry->second;
  294. if (is_cache_miss)
  295. framebuffer.Create();
  296. current_state.draw.draw_framebuffer = framebuffer.handle;
  297. current_state.ApplyFramebufferState();
  298. if (!is_cache_miss)
  299. return;
  300. if (fbkey.is_single_buffer) {
  301. if (fbkey.color_attachments[0] != GL_NONE) {
  302. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, fbkey.color_attachments[0], fbkey.colors[0],
  303. 0);
  304. }
  305. glDrawBuffer(fbkey.color_attachments[0]);
  306. } else {
  307. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  308. if (fbkey.colors[index]) {
  309. glFramebufferTexture(GL_DRAW_FRAMEBUFFER,
  310. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  311. fbkey.colors[index], 0);
  312. }
  313. }
  314. glDrawBuffers(fbkey.colors_count, fbkey.color_attachments.data());
  315. }
  316. if (fbkey.zeta) {
  317. GLenum zeta_attachment =
  318. fbkey.stencil_enable ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT;
  319. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, zeta_attachment, fbkey.zeta, 0);
  320. }
  321. }
  322. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  323. const auto& regs = system.GPU().Maxwell3D().regs;
  324. std::size_t size = 0;
  325. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  326. if (!regs.vertex_array[index].IsEnabled())
  327. continue;
  328. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  329. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  330. ASSERT(end > start);
  331. size += end - start + 1;
  332. }
  333. return size;
  334. }
  335. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  336. const auto& regs = system.GPU().Maxwell3D().regs;
  337. return static_cast<std::size_t>(regs.index_array.count) *
  338. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  339. }
  340. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  341. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  342. DrawArrays();
  343. return true;
  344. }
  345. template <typename Map, typename Interval>
  346. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  347. return boost::make_iterator_range(map.equal_range(interval));
  348. }
  349. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  350. const u64 page_start{addr >> Memory::PAGE_BITS};
  351. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  352. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  353. // subtract after iterating
  354. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  355. if (delta > 0)
  356. cached_pages.add({pages_interval, delta});
  357. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  358. const auto interval = pair.first & pages_interval;
  359. const int count = pair.second;
  360. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  361. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  362. const u64 interval_size = interval_end_addr - interval_start_addr;
  363. if (delta > 0 && count == delta)
  364. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  365. else if (delta < 0 && count == -delta)
  366. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  367. else
  368. ASSERT(count >= 0);
  369. }
  370. if (delta < 0)
  371. cached_pages.add({pages_interval, delta});
  372. }
  373. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  374. const VideoCore::DiskResourceLoadCallback& callback) {
  375. shader_cache.LoadDiskCache(stop_loading, callback);
  376. }
  377. std::pair<bool, bool> RasterizerOpenGL::ConfigureFramebuffers(
  378. OpenGLState& current_state, bool using_color_fb, bool using_depth_fb, bool preserve_contents,
  379. std::optional<std::size_t> single_color_target) {
  380. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  381. auto& gpu = system.GPU().Maxwell3D();
  382. const auto& regs = gpu.regs;
  383. const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
  384. single_color_target};
  385. if (fb_config_state == current_framebuffer_config_state &&
  386. gpu.dirty_flags.color_buffer.none() && !gpu.dirty_flags.zeta_buffer) {
  387. // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
  388. // single color targets). This is done because the guest registers may not change but the
  389. // host framebuffer may contain different attachments
  390. return current_depth_stencil_usage;
  391. }
  392. current_framebuffer_config_state = fb_config_state;
  393. Surface depth_surface;
  394. if (using_depth_fb) {
  395. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  396. }
  397. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  398. // Bind the framebuffer surfaces
  399. current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  400. FramebufferCacheKey fbkey;
  401. if (using_color_fb) {
  402. if (single_color_target) {
  403. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  404. Surface color_surface =
  405. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  406. if (color_surface) {
  407. // Assume that a surface will be written to if it is used as a framebuffer, even if
  408. // the shader doesn't actually write to it.
  409. color_surface->MarkAsModified(true, res_cache);
  410. // Workaround for and issue in nvidia drivers
  411. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  412. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  413. }
  414. fbkey.is_single_buffer = true;
  415. fbkey.color_attachments[0] =
  416. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
  417. fbkey.colors[0] = color_surface != nullptr ? color_surface->Texture().handle : 0;
  418. } else {
  419. // Multiple color attachments are enabled
  420. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  421. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  422. if (color_surface) {
  423. // Assume that a surface will be written to if it is used as a framebuffer, even
  424. // if the shader doesn't actually write to it.
  425. color_surface->MarkAsModified(true, res_cache);
  426. // Enable sRGB only for supported formats
  427. // Workaround for and issue in nvidia drivers
  428. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  429. state.framebuffer_srgb.enabled |=
  430. color_surface->GetSurfaceParams().srgb_conversion;
  431. }
  432. fbkey.color_attachments[index] =
  433. GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  434. fbkey.colors[index] =
  435. color_surface != nullptr ? color_surface->Texture().handle : 0;
  436. }
  437. fbkey.is_single_buffer = false;
  438. fbkey.colors_count = regs.rt_control.count;
  439. }
  440. } else {
  441. // No color attachments are enabled - leave them as zero
  442. fbkey.is_single_buffer = true;
  443. }
  444. if (depth_surface) {
  445. // Assume that a surface will be written to if it is used as a framebuffer, even if
  446. // the shader doesn't actually write to it.
  447. depth_surface->MarkAsModified(true, res_cache);
  448. fbkey.zeta = depth_surface->Texture().handle;
  449. fbkey.stencil_enable = regs.stencil_enable &&
  450. depth_surface->GetSurfaceParams().type == SurfaceType::DepthStencil;
  451. }
  452. SetupCachedFramebuffer(fbkey, current_state);
  453. SyncViewport(current_state);
  454. return current_depth_stencil_usage = {static_cast<bool>(depth_surface), fbkey.stencil_enable};
  455. }
  456. void RasterizerOpenGL::Clear() {
  457. const auto& regs = system.GPU().Maxwell3D().regs;
  458. bool use_color{};
  459. bool use_depth{};
  460. bool use_stencil{};
  461. OpenGLState clear_state;
  462. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  463. regs.clear_buffers.A) {
  464. use_color = true;
  465. }
  466. if (use_color) {
  467. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  468. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  469. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  470. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  471. }
  472. if (regs.clear_buffers.Z) {
  473. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  474. use_depth = true;
  475. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  476. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  477. // true.
  478. clear_state.depth.test_enabled = true;
  479. clear_state.depth.test_func = GL_ALWAYS;
  480. }
  481. if (regs.clear_buffers.S) {
  482. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  483. use_stencil = true;
  484. clear_state.stencil.test_enabled = true;
  485. if (regs.clear_flags.stencil) {
  486. // Stencil affects the clear so fill it with the used masks
  487. clear_state.stencil.front.test_func = GL_ALWAYS;
  488. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  489. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  490. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  491. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  492. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  493. if (regs.stencil_two_side_enable) {
  494. clear_state.stencil.back.test_func = GL_ALWAYS;
  495. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  496. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  497. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  498. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  499. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  500. } else {
  501. clear_state.stencil.back.test_func = GL_ALWAYS;
  502. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  503. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  504. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  505. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  506. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  507. }
  508. }
  509. }
  510. if (!use_color && !use_depth && !use_stencil) {
  511. // No color surface nor depth/stencil surface are enabled
  512. return;
  513. }
  514. const auto [clear_depth, clear_stencil] = ConfigureFramebuffers(
  515. clear_state, use_color, use_depth || use_stencil, false, regs.clear_buffers.RT.Value());
  516. if (regs.clear_flags.scissor) {
  517. SyncScissorTest(clear_state);
  518. }
  519. if (regs.clear_flags.viewport) {
  520. clear_state.EmulateViewportWithScissor();
  521. }
  522. clear_state.ApplyColorMask();
  523. clear_state.ApplyDepth();
  524. clear_state.ApplyStencilTest();
  525. clear_state.ApplyViewport();
  526. if (use_color) {
  527. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  528. }
  529. if (clear_depth && clear_stencil) {
  530. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  531. } else if (clear_depth) {
  532. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  533. } else if (clear_stencil) {
  534. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  535. }
  536. }
  537. void RasterizerOpenGL::DrawArrays() {
  538. if (accelerate_draw == AccelDraw::Disabled)
  539. return;
  540. MICROPROFILE_SCOPE(OpenGL_Drawing);
  541. auto& gpu = system.GPU().Maxwell3D();
  542. const auto& regs = gpu.regs;
  543. ConfigureFramebuffers(state);
  544. SyncColorMask();
  545. SyncFragmentColorClampState();
  546. SyncMultiSampleState();
  547. SyncDepthTestState();
  548. SyncStencilTestState();
  549. SyncBlendState();
  550. SyncLogicOpState();
  551. SyncCullMode();
  552. SyncPrimitiveRestart();
  553. SyncScissorTest(state);
  554. // Alpha Testing is synced on shaders.
  555. SyncTransformFeedback();
  556. SyncPointState();
  557. CheckAlphaTests();
  558. SyncPolygonOffset();
  559. // TODO(bunnei): Sync framebuffer_scale uniform here
  560. // TODO(bunnei): Sync scissorbox uniform(s) here
  561. // Draw the vertex batch
  562. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  563. std::size_t buffer_size = CalculateVertexArraysSize();
  564. // Add space for index buffer
  565. if (is_indexed) {
  566. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  567. }
  568. // Uniform space for the 5 shader stages
  569. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  570. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  571. Maxwell::MaxShaderStage;
  572. // Add space for at least 18 constant buffers
  573. buffer_size +=
  574. Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  575. const bool invalidate = buffer_cache.Map(buffer_size);
  576. if (invalidate) {
  577. // As all cached buffers are invalidated, we need to recheck their state.
  578. gpu.dirty_flags.vertex_array.set();
  579. }
  580. const GLuint vao = SetupVertexFormat();
  581. SetupVertexBuffer(vao);
  582. DrawParameters params = SetupDraw();
  583. SetupShaders(params.primitive_mode);
  584. buffer_cache.Unmap();
  585. shader_program_manager->ApplyTo(state);
  586. state.Apply();
  587. res_cache.SignalPreDrawCall();
  588. params.DispatchDraw();
  589. res_cache.SignalPostDrawCall();
  590. accelerate_draw = AccelDraw::Disabled;
  591. }
  592. void RasterizerOpenGL::FlushAll() {}
  593. void RasterizerOpenGL::FlushRegion(CacheAddr addr, u64 size) {
  594. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  595. if (!addr || !size) {
  596. return;
  597. }
  598. res_cache.FlushRegion(addr, size);
  599. global_cache.FlushRegion(addr, size);
  600. }
  601. void RasterizerOpenGL::InvalidateRegion(CacheAddr addr, u64 size) {
  602. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  603. if (!addr || !size) {
  604. return;
  605. }
  606. res_cache.InvalidateRegion(addr, size);
  607. shader_cache.InvalidateRegion(addr, size);
  608. global_cache.InvalidateRegion(addr, size);
  609. buffer_cache.InvalidateRegion(addr, size);
  610. }
  611. void RasterizerOpenGL::FlushAndInvalidateRegion(CacheAddr addr, u64 size) {
  612. FlushRegion(addr, size);
  613. InvalidateRegion(addr, size);
  614. }
  615. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  616. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  617. const Common::Rectangle<u32>& src_rect,
  618. const Common::Rectangle<u32>& dst_rect) {
  619. MICROPROFILE_SCOPE(OpenGL_Blits);
  620. res_cache.FermiCopySurface(src, dst, src_rect, dst_rect);
  621. return true;
  622. }
  623. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  624. VAddr framebuffer_addr, u32 pixel_stride) {
  625. if (!framebuffer_addr) {
  626. return {};
  627. }
  628. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  629. const auto& surface{res_cache.TryFindFramebufferSurface(Memory::GetPointer(framebuffer_addr))};
  630. if (!surface) {
  631. return {};
  632. }
  633. // Verify that the cached surface is the same size and format as the requested framebuffer
  634. const auto& params{surface->GetSurfaceParams()};
  635. const auto& pixel_format{
  636. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  637. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  638. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  639. if (params.pixel_format != pixel_format) {
  640. LOG_WARNING(Render_OpenGL, "Framebuffer pixel_format is different");
  641. }
  642. screen_info.display_texture = surface->Texture().handle;
  643. return true;
  644. }
  645. void RasterizerOpenGL::SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  646. const Shader& shader, GLuint program_handle,
  647. BaseBindings base_bindings) {
  648. MICROPROFILE_SCOPE(OpenGL_UBO);
  649. const auto& gpu = system.GPU();
  650. const auto& maxwell3d = gpu.Maxwell3D();
  651. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  652. const auto& entries = shader->GetShaderEntries().const_buffers;
  653. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  654. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  655. const auto& used_buffer = entries[bindpoint];
  656. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  657. if (!buffer.enabled) {
  658. // Set values to zero to unbind buffers
  659. bind_ubo_pushbuffer.Push(0, 0, 0);
  660. continue;
  661. }
  662. std::size_t size = 0;
  663. if (used_buffer.IsIndirect()) {
  664. // Buffer is accessed indirectly, so upload the entire thing
  665. size = buffer.size;
  666. if (size > MaxConstbufferSize) {
  667. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", size,
  668. MaxConstbufferSize);
  669. size = MaxConstbufferSize;
  670. }
  671. } else {
  672. // Buffer is accessed directly, upload just what we use
  673. size = used_buffer.GetSize();
  674. }
  675. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  676. // UBO alignment requirements.
  677. size = Common::AlignUp(size, sizeof(GLvec4));
  678. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  679. const GLintptr const_buffer_offset =
  680. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  681. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), const_buffer_offset, size);
  682. }
  683. }
  684. void RasterizerOpenGL::SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  685. const Shader& shader, GLenum primitive_mode,
  686. BaseBindings base_bindings) {
  687. const auto& entries = shader->GetShaderEntries().global_memory_entries;
  688. for (std::size_t bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  689. const auto& entry{entries[bindpoint]};
  690. const auto& region{global_cache.GetGlobalRegion(entry, stage)};
  691. if (entry.IsWritten()) {
  692. region->MarkAsModified(true, global_cache);
  693. }
  694. bind_ssbo_pushbuffer.Push(region->GetBufferHandle(), 0,
  695. static_cast<GLsizeiptr>(region->GetSizeInBytes()));
  696. }
  697. }
  698. void RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, const Shader& shader,
  699. GLuint program_handle, BaseBindings base_bindings) {
  700. MICROPROFILE_SCOPE(OpenGL_Texture);
  701. const auto& gpu = system.GPU();
  702. const auto& maxwell3d = gpu.Maxwell3D();
  703. const auto& entries = shader->GetShaderEntries().samplers;
  704. ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
  705. "Exceeded the number of active textures.");
  706. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  707. const auto& entry = entries[bindpoint];
  708. Tegra::Texture::FullTextureInfo texture;
  709. if (entry.IsBindless()) {
  710. const auto cbuf = entry.GetBindlessCBuf();
  711. Tegra::Texture::TextureHandle tex_handle;
  712. tex_handle.raw = maxwell3d.AccessConstBuffer32(stage, cbuf.first, cbuf.second);
  713. texture = maxwell3d.GetTextureInfo(tex_handle, entry.GetOffset());
  714. } else {
  715. texture = maxwell3d.GetStageTexture(stage, entry.GetOffset());
  716. }
  717. const u32 current_bindpoint = base_bindings.sampler + bindpoint;
  718. state.texture_units[current_bindpoint].sampler = sampler_cache.GetSampler(texture.tsc);
  719. if (Surface surface = res_cache.GetTextureSurface(texture, entry); surface) {
  720. state.texture_units[current_bindpoint].texture =
  721. surface->Texture(entry.IsArray()).handle;
  722. surface->UpdateSwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  723. texture.tic.w_source);
  724. } else {
  725. // Can occur when texture addr is null or its memory is unmapped/invalid
  726. state.texture_units[current_bindpoint].texture = 0;
  727. }
  728. }
  729. }
  730. void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
  731. const auto& regs = system.GPU().Maxwell3D().regs;
  732. const bool geometry_shaders_enabled =
  733. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  734. const std::size_t viewport_count =
  735. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  736. for (std::size_t i = 0; i < viewport_count; i++) {
  737. auto& viewport = current_state.viewports[i];
  738. const auto& src = regs.viewports[i];
  739. const Common::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
  740. viewport.x = viewport_rect.left;
  741. viewport.y = viewport_rect.bottom;
  742. viewport.width = viewport_rect.GetWidth();
  743. viewport.height = viewport_rect.GetHeight();
  744. viewport.depth_range_far = src.depth_range_far;
  745. viewport.depth_range_near = src.depth_range_near;
  746. }
  747. state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
  748. state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
  749. }
  750. void RasterizerOpenGL::SyncClipEnabled(
  751. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  752. const auto& regs = system.GPU().Maxwell3D().regs;
  753. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  754. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  755. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  756. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  757. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  758. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  759. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  760. }
  761. }
  762. void RasterizerOpenGL::SyncClipCoef() {
  763. UNIMPLEMENTED();
  764. }
  765. void RasterizerOpenGL::SyncCullMode() {
  766. const auto& regs = system.GPU().Maxwell3D().regs;
  767. state.cull.enabled = regs.cull.enabled != 0;
  768. if (state.cull.enabled) {
  769. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  770. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  771. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  772. regs.viewport_transform[0].scale_y < 0.0f};
  773. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  774. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  775. // because OpenGL already does it for us.
  776. if (flip_triangles) {
  777. if (state.cull.front_face == GL_CCW)
  778. state.cull.front_face = GL_CW;
  779. else if (state.cull.front_face == GL_CW)
  780. state.cull.front_face = GL_CCW;
  781. }
  782. }
  783. }
  784. void RasterizerOpenGL::SyncPrimitiveRestart() {
  785. const auto& regs = system.GPU().Maxwell3D().regs;
  786. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  787. state.primitive_restart.index = regs.primitive_restart.index;
  788. }
  789. void RasterizerOpenGL::SyncDepthTestState() {
  790. const auto& regs = system.GPU().Maxwell3D().regs;
  791. state.depth.test_enabled = regs.depth_test_enable != 0;
  792. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  793. if (!state.depth.test_enabled)
  794. return;
  795. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  796. }
  797. void RasterizerOpenGL::SyncStencilTestState() {
  798. const auto& regs = system.GPU().Maxwell3D().regs;
  799. state.stencil.test_enabled = regs.stencil_enable != 0;
  800. if (!regs.stencil_enable) {
  801. return;
  802. }
  803. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  804. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  805. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  806. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  807. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  808. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  809. state.stencil.front.write_mask = regs.stencil_front_mask;
  810. if (regs.stencil_two_side_enable) {
  811. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  812. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  813. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  814. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  815. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  816. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  817. state.stencil.back.write_mask = regs.stencil_back_mask;
  818. } else {
  819. state.stencil.back.test_func = GL_ALWAYS;
  820. state.stencil.back.test_ref = 0;
  821. state.stencil.back.test_mask = 0xFFFFFFFF;
  822. state.stencil.back.write_mask = 0xFFFFFFFF;
  823. state.stencil.back.action_stencil_fail = GL_KEEP;
  824. state.stencil.back.action_depth_fail = GL_KEEP;
  825. state.stencil.back.action_depth_pass = GL_KEEP;
  826. }
  827. }
  828. void RasterizerOpenGL::SyncColorMask() {
  829. const auto& regs = system.GPU().Maxwell3D().regs;
  830. const std::size_t count =
  831. regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
  832. for (std::size_t i = 0; i < count; i++) {
  833. const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
  834. auto& dest = state.color_mask[i];
  835. dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
  836. dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
  837. dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
  838. dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
  839. }
  840. }
  841. void RasterizerOpenGL::SyncMultiSampleState() {
  842. const auto& regs = system.GPU().Maxwell3D().regs;
  843. state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
  844. state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
  845. }
  846. void RasterizerOpenGL::SyncFragmentColorClampState() {
  847. const auto& regs = system.GPU().Maxwell3D().regs;
  848. state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
  849. }
  850. void RasterizerOpenGL::SyncBlendState() {
  851. const auto& regs = system.GPU().Maxwell3D().regs;
  852. state.blend_color.red = regs.blend_color.r;
  853. state.blend_color.green = regs.blend_color.g;
  854. state.blend_color.blue = regs.blend_color.b;
  855. state.blend_color.alpha = regs.blend_color.a;
  856. state.independant_blend.enabled = regs.independent_blend_enable;
  857. if (!state.independant_blend.enabled) {
  858. auto& blend = state.blend[0];
  859. const auto& src = regs.blend;
  860. blend.enabled = src.enable[0] != 0;
  861. if (blend.enabled) {
  862. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  863. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  864. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  865. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  866. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  867. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  868. }
  869. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  870. state.blend[i].enabled = false;
  871. }
  872. return;
  873. }
  874. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  875. auto& blend = state.blend[i];
  876. const auto& src = regs.independent_blend[i];
  877. blend.enabled = regs.blend.enable[i] != 0;
  878. if (!blend.enabled)
  879. continue;
  880. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  881. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  882. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  883. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  884. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  885. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  886. }
  887. }
  888. void RasterizerOpenGL::SyncLogicOpState() {
  889. const auto& regs = system.GPU().Maxwell3D().regs;
  890. state.logic_op.enabled = regs.logic_op.enable != 0;
  891. if (!state.logic_op.enabled)
  892. return;
  893. ASSERT_MSG(regs.blend.enable[0] == 0,
  894. "Blending and logic op can't be enabled at the same time.");
  895. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  896. }
  897. void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
  898. const auto& regs = system.GPU().Maxwell3D().regs;
  899. const bool geometry_shaders_enabled =
  900. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  901. const std::size_t viewport_count =
  902. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  903. for (std::size_t i = 0; i < viewport_count; i++) {
  904. const auto& src = regs.scissor_test[i];
  905. auto& dst = current_state.viewports[i].scissor;
  906. dst.enabled = (src.enable != 0);
  907. if (dst.enabled == 0) {
  908. return;
  909. }
  910. const u32 width = src.max_x - src.min_x;
  911. const u32 height = src.max_y - src.min_y;
  912. dst.x = src.min_x;
  913. dst.y = src.min_y;
  914. dst.width = width;
  915. dst.height = height;
  916. }
  917. }
  918. void RasterizerOpenGL::SyncTransformFeedback() {
  919. const auto& regs = system.GPU().Maxwell3D().regs;
  920. UNIMPLEMENTED_IF_MSG(regs.tfb_enabled != 0, "Transform feedbacks are not implemented");
  921. }
  922. void RasterizerOpenGL::SyncPointState() {
  923. const auto& regs = system.GPU().Maxwell3D().regs;
  924. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  925. // in OpenGL).
  926. state.point.size = std::max(1.0f, regs.point_size);
  927. }
  928. void RasterizerOpenGL::SyncPolygonOffset() {
  929. const auto& regs = system.GPU().Maxwell3D().regs;
  930. state.polygon_offset.fill_enable = regs.polygon_offset_fill_enable != 0;
  931. state.polygon_offset.line_enable = regs.polygon_offset_line_enable != 0;
  932. state.polygon_offset.point_enable = regs.polygon_offset_point_enable != 0;
  933. state.polygon_offset.units = regs.polygon_offset_units;
  934. state.polygon_offset.factor = regs.polygon_offset_factor;
  935. state.polygon_offset.clamp = regs.polygon_offset_clamp;
  936. }
  937. void RasterizerOpenGL::CheckAlphaTests() {
  938. const auto& regs = system.GPU().Maxwell3D().regs;
  939. UNIMPLEMENTED_IF_MSG(regs.alpha_test_enabled != 0 && regs.rt_control.count > 1,
  940. "Alpha Testing is enabled with more than one rendertarget");
  941. }
  942. } // namespace OpenGL