gl_rasterizer.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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<View, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> colors{};
  77. u32 colors_count = 0;
  78. View zeta = nullptr;
  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. : texture_cache{system, *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::InitMemoryMananger(Tegra::MemoryManager& memory_manager) {
  101. texture_cache.InitMemoryMananger(memory_manager);
  102. }
  103. void RasterizerOpenGL::CheckExtensions() {
  104. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  105. LOG_WARNING(
  106. Render_OpenGL,
  107. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  108. }
  109. if (!GLAD_GL_ARB_buffer_storage) {
  110. LOG_WARNING(
  111. Render_OpenGL,
  112. "Buffer storage control is not supported! This can cause performance degradation.");
  113. }
  114. }
  115. GLuint RasterizerOpenGL::SetupVertexFormat() {
  116. auto& gpu = system.GPU().Maxwell3D();
  117. const auto& regs = gpu.regs;
  118. if (!gpu.dirty_flags.vertex_attrib_format) {
  119. return state.draw.vertex_array;
  120. }
  121. gpu.dirty_flags.vertex_attrib_format = false;
  122. MICROPROFILE_SCOPE(OpenGL_VAO);
  123. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  124. auto& vao_entry = iter->second;
  125. if (is_cache_miss) {
  126. vao_entry.Create();
  127. const GLuint vao = vao_entry.handle;
  128. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  129. // that fails to properly create the vertex array if it's not bound even after creating it
  130. // with glCreateVertexArrays
  131. state.draw.vertex_array = vao;
  132. state.ApplyVertexArrayState();
  133. glVertexArrayElementBuffer(vao, buffer_cache.GetHandle());
  134. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  135. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  136. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  137. // for now to avoid OpenGL errors.
  138. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  139. // assume every shader uses them all.
  140. for (u32 index = 0; index < 16; ++index) {
  141. const auto& attrib = regs.vertex_attrib_format[index];
  142. // Ignore invalid attributes.
  143. if (!attrib.IsValid())
  144. continue;
  145. const auto& buffer = regs.vertex_array[attrib.buffer];
  146. LOG_TRACE(Render_OpenGL,
  147. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  148. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  149. attrib.offset.Value(), attrib.IsNormalized());
  150. ASSERT(buffer.IsEnabled());
  151. glEnableVertexArrayAttrib(vao, index);
  152. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  153. attrib.type ==
  154. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  155. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  156. MaxwellToGL::VertexType(attrib), attrib.offset);
  157. } else {
  158. glVertexArrayAttribFormat(
  159. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  160. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  161. }
  162. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  163. }
  164. }
  165. // Rebinding the VAO invalidates the vertex buffer bindings.
  166. gpu.dirty_flags.vertex_array.set();
  167. state.draw.vertex_array = vao_entry.handle;
  168. return vao_entry.handle;
  169. }
  170. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  171. auto& gpu = system.GPU().Maxwell3D();
  172. const auto& regs = gpu.regs;
  173. if (gpu.dirty_flags.vertex_array.none())
  174. return;
  175. MICROPROFILE_SCOPE(OpenGL_VB);
  176. // Upload all guest vertex arrays sequentially to our buffer
  177. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  178. if (!gpu.dirty_flags.vertex_array[index])
  179. continue;
  180. const auto& vertex_array = regs.vertex_array[index];
  181. if (!vertex_array.IsEnabled())
  182. continue;
  183. const GPUVAddr start = vertex_array.StartAddress();
  184. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  185. ASSERT(end > start);
  186. const u64 size = end - start + 1;
  187. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  188. // Bind the vertex array to the buffer at the current offset.
  189. glVertexArrayVertexBuffer(vao, index, buffer_cache.GetHandle(), vertex_buffer_offset,
  190. vertex_array.stride);
  191. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  192. // Enable vertex buffer instancing with the specified divisor.
  193. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  194. } else {
  195. // Disable the vertex buffer instancing.
  196. glVertexArrayBindingDivisor(vao, index, 0);
  197. }
  198. }
  199. gpu.dirty_flags.vertex_array.reset();
  200. }
  201. DrawParameters RasterizerOpenGL::SetupDraw() {
  202. const auto& gpu = system.GPU().Maxwell3D();
  203. const auto& regs = gpu.regs;
  204. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  205. DrawParameters params{};
  206. params.current_instance = gpu.state.current_instance;
  207. params.use_indexed = is_indexed;
  208. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  209. if (is_indexed) {
  210. MICROPROFILE_SCOPE(OpenGL_Index);
  211. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  212. params.count = regs.index_array.count;
  213. params.index_buffer_offset =
  214. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  215. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  216. } else {
  217. params.count = regs.vertex_buffer.count;
  218. params.vertex_first = regs.vertex_buffer.first;
  219. }
  220. return params;
  221. }
  222. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  223. MICROPROFILE_SCOPE(OpenGL_Shader);
  224. auto& gpu = system.GPU().Maxwell3D();
  225. BaseBindings base_bindings;
  226. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  227. // Prepare packed bindings
  228. bind_ubo_pushbuffer.Setup(base_bindings.cbuf);
  229. bind_ssbo_pushbuffer.Setup(base_bindings.gmem);
  230. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  231. const auto& shader_config = gpu.regs.shader_config[index];
  232. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  233. // Skip stages that are not enabled
  234. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  235. switch (program) {
  236. case Maxwell::ShaderProgram::Geometry:
  237. shader_program_manager->UseTrivialGeometryShader();
  238. break;
  239. default:
  240. break;
  241. }
  242. continue;
  243. }
  244. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  245. GLShader::MaxwellUniformData ubo{};
  246. ubo.SetFromRegs(gpu, stage);
  247. const GLintptr offset =
  248. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  249. // Bind the emulation info buffer
  250. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), offset,
  251. static_cast<GLsizeiptr>(sizeof(ubo)));
  252. Shader shader{shader_cache.GetStageProgram(program)};
  253. const auto [program_handle, next_bindings] =
  254. shader->GetProgramHandle(primitive_mode, base_bindings);
  255. switch (program) {
  256. case Maxwell::ShaderProgram::VertexA:
  257. case Maxwell::ShaderProgram::VertexB:
  258. shader_program_manager->UseProgrammableVertexShader(program_handle);
  259. break;
  260. case Maxwell::ShaderProgram::Geometry:
  261. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  262. break;
  263. case Maxwell::ShaderProgram::Fragment:
  264. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  265. break;
  266. default:
  267. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  268. shader_config.enable.Value(), shader_config.offset);
  269. }
  270. const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
  271. SetupDrawConstBuffers(stage_enum, shader);
  272. SetupGlobalRegions(stage_enum, shader);
  273. SetupTextures(stage_enum, shader, base_bindings);
  274. // Workaround for Intel drivers.
  275. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  276. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  277. // clip distances only when it's written by a shader stage.
  278. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  279. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  280. }
  281. // When VertexA is enabled, we have dual vertex shaders
  282. if (program == Maxwell::ShaderProgram::VertexA) {
  283. // VertexB was combined with VertexA, so we skip the VertexB iteration
  284. index++;
  285. }
  286. base_bindings = next_bindings;
  287. }
  288. bind_ubo_pushbuffer.Bind();
  289. bind_ssbo_pushbuffer.Bind();
  290. SyncClipEnabled(clip_distances);
  291. gpu.dirty_flags.shaders = false;
  292. }
  293. void RasterizerOpenGL::SetupCachedFramebuffer(const FramebufferCacheKey& fbkey,
  294. OpenGLState& current_state) {
  295. const auto [entry, is_cache_miss] = framebuffer_cache.try_emplace(fbkey);
  296. auto& framebuffer = entry->second;
  297. if (is_cache_miss)
  298. framebuffer.Create();
  299. current_state.draw.draw_framebuffer = framebuffer.handle;
  300. current_state.ApplyFramebufferState();
  301. if (!is_cache_miss)
  302. return;
  303. if (fbkey.is_single_buffer) {
  304. if (fbkey.color_attachments[0] != GL_NONE) {
  305. fbkey.colors[0]->Attach(fbkey.color_attachments[0]);
  306. }
  307. glDrawBuffer(fbkey.color_attachments[0]);
  308. } else {
  309. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  310. if (fbkey.colors[index]) {
  311. fbkey.colors[index]->Attach(GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index));
  312. }
  313. }
  314. glDrawBuffers(fbkey.colors_count, fbkey.color_attachments.data());
  315. }
  316. if (fbkey.zeta) {
  317. fbkey.zeta->Attach(fbkey.stencil_enable ? GL_DEPTH_STENCIL_ATTACHMENT
  318. : GL_DEPTH_ATTACHMENT);
  319. }
  320. }
  321. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  322. const auto& regs = system.GPU().Maxwell3D().regs;
  323. std::size_t size = 0;
  324. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  325. if (!regs.vertex_array[index].IsEnabled())
  326. continue;
  327. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  328. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  329. ASSERT(end > start);
  330. size += end - start + 1;
  331. }
  332. return size;
  333. }
  334. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  335. const auto& regs = system.GPU().Maxwell3D().regs;
  336. return static_cast<std::size_t>(regs.index_array.count) *
  337. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  338. }
  339. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  340. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  341. DrawArrays();
  342. return true;
  343. }
  344. template <typename Map, typename Interval>
  345. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  346. return boost::make_iterator_range(map.equal_range(interval));
  347. }
  348. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  349. const u64 page_start{addr >> Memory::PAGE_BITS};
  350. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  351. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  352. // subtract after iterating
  353. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  354. if (delta > 0)
  355. cached_pages.add({pages_interval, delta});
  356. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  357. const auto interval = pair.first & pages_interval;
  358. const int count = pair.second;
  359. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  360. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  361. const u64 interval_size = interval_end_addr - interval_start_addr;
  362. if (delta > 0 && count == delta)
  363. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  364. else if (delta < 0 && count == -delta)
  365. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  366. else
  367. ASSERT(count >= 0);
  368. }
  369. if (delta < 0)
  370. cached_pages.add({pages_interval, delta});
  371. }
  372. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  373. const VideoCore::DiskResourceLoadCallback& callback) {
  374. shader_cache.LoadDiskCache(stop_loading, callback);
  375. }
  376. std::pair<bool, bool> RasterizerOpenGL::ConfigureFramebuffers(
  377. OpenGLState& current_state, bool using_color_fb, bool using_depth_fb, bool preserve_contents,
  378. std::optional<std::size_t> single_color_target) {
  379. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  380. auto& gpu = system.GPU().Maxwell3D();
  381. const auto& regs = gpu.regs;
  382. const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
  383. single_color_target};
  384. if (fb_config_state == current_framebuffer_config_state &&
  385. gpu.dirty_flags.color_buffer.none() && !gpu.dirty_flags.zeta_buffer) {
  386. // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
  387. // single color targets). This is done because the guest registers may not change but the
  388. // host framebuffer may contain different attachments
  389. return current_depth_stencil_usage;
  390. }
  391. current_framebuffer_config_state = fb_config_state;
  392. View depth_surface{};
  393. if (using_depth_fb) {
  394. depth_surface = texture_cache.GetDepthBufferSurface(preserve_contents);
  395. } else {
  396. texture_cache.SetEmptyDepthBuffer();
  397. }
  398. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  399. // Bind the framebuffer surfaces
  400. current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  401. FramebufferCacheKey fbkey;
  402. if (using_color_fb) {
  403. if (single_color_target) {
  404. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  405. View color_surface{
  406. texture_cache.GetColorBufferSurface(*single_color_target, preserve_contents)};
  407. if (color_surface) {
  408. // Assume that a surface will be written to if it is used as a framebuffer, even if
  409. // the shader doesn't actually write to it.
  410. texture_cache.MarkColorBufferInUse(*single_color_target);
  411. // Workaround for and issue in nvidia drivers
  412. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  413. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  414. }
  415. fbkey.is_single_buffer = true;
  416. fbkey.color_attachments[0] =
  417. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
  418. fbkey.colors[0] = color_surface;
  419. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  420. if (index != *single_color_target) {
  421. texture_cache.SetEmptyColorBuffer(index);
  422. }
  423. }
  424. } else {
  425. // Multiple color attachments are enabled
  426. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  427. View color_surface{texture_cache.GetColorBufferSurface(index, preserve_contents)};
  428. if (color_surface) {
  429. // Assume that a surface will be written to if it is used as a framebuffer, even
  430. // if the shader doesn't actually write to it.
  431. texture_cache.MarkColorBufferInUse(index);
  432. // Enable sRGB only for supported formats
  433. // Workaround for and issue in nvidia drivers
  434. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  435. state.framebuffer_srgb.enabled |=
  436. color_surface->GetSurfaceParams().srgb_conversion;
  437. }
  438. fbkey.color_attachments[index] =
  439. GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  440. fbkey.colors[index] = color_surface;
  441. }
  442. fbkey.is_single_buffer = false;
  443. fbkey.colors_count = regs.rt_control.count;
  444. }
  445. } else {
  446. // No color attachments are enabled - leave them as zero
  447. fbkey.is_single_buffer = true;
  448. }
  449. if (depth_surface) {
  450. // Assume that a surface will be written to if it is used as a framebuffer, even if
  451. // the shader doesn't actually write to it.
  452. texture_cache.MarkDepthBufferInUse();
  453. fbkey.zeta = depth_surface;
  454. fbkey.stencil_enable = regs.stencil_enable &&
  455. depth_surface->GetSurfaceParams().type == SurfaceType::DepthStencil;
  456. }
  457. SetupCachedFramebuffer(fbkey, current_state);
  458. SyncViewport(current_state);
  459. return current_depth_stencil_usage = {static_cast<bool>(depth_surface), fbkey.stencil_enable};
  460. }
  461. void RasterizerOpenGL::Clear() {
  462. const auto& regs = system.GPU().Maxwell3D().regs;
  463. bool use_color{};
  464. bool use_depth{};
  465. bool use_stencil{};
  466. OpenGLState clear_state;
  467. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  468. regs.clear_buffers.A) {
  469. use_color = true;
  470. }
  471. if (use_color) {
  472. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  473. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  474. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  475. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  476. }
  477. if (regs.clear_buffers.Z) {
  478. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  479. use_depth = true;
  480. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  481. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  482. // true.
  483. clear_state.depth.test_enabled = true;
  484. clear_state.depth.test_func = GL_ALWAYS;
  485. }
  486. if (regs.clear_buffers.S) {
  487. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  488. use_stencil = true;
  489. clear_state.stencil.test_enabled = true;
  490. if (regs.clear_flags.stencil) {
  491. // Stencil affects the clear so fill it with the used masks
  492. clear_state.stencil.front.test_func = GL_ALWAYS;
  493. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  494. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  495. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  496. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  497. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  498. if (regs.stencil_two_side_enable) {
  499. clear_state.stencil.back.test_func = GL_ALWAYS;
  500. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  501. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  502. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  503. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  504. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  505. } else {
  506. clear_state.stencil.back.test_func = GL_ALWAYS;
  507. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  508. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  509. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  510. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  511. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  512. }
  513. }
  514. }
  515. if (!use_color && !use_depth && !use_stencil) {
  516. // No color surface nor depth/stencil surface are enabled
  517. return;
  518. }
  519. const auto [clear_depth, clear_stencil] = ConfigureFramebuffers(
  520. clear_state, use_color, use_depth || use_stencil, false, regs.clear_buffers.RT.Value());
  521. if (regs.clear_flags.scissor) {
  522. SyncScissorTest(clear_state);
  523. }
  524. if (regs.clear_flags.viewport) {
  525. clear_state.EmulateViewportWithScissor();
  526. }
  527. clear_state.ApplyColorMask();
  528. clear_state.ApplyDepth();
  529. clear_state.ApplyStencilTest();
  530. clear_state.ApplyViewport();
  531. if (use_color) {
  532. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  533. }
  534. if (clear_depth && clear_stencil) {
  535. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  536. } else if (clear_depth) {
  537. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  538. } else if (clear_stencil) {
  539. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  540. }
  541. }
  542. void RasterizerOpenGL::DrawArrays() {
  543. if (accelerate_draw == AccelDraw::Disabled)
  544. return;
  545. MICROPROFILE_SCOPE(OpenGL_Drawing);
  546. auto& gpu = system.GPU().Maxwell3D();
  547. const auto& regs = gpu.regs;
  548. ConfigureFramebuffers(state);
  549. SyncColorMask();
  550. SyncFragmentColorClampState();
  551. SyncMultiSampleState();
  552. SyncDepthTestState();
  553. SyncStencilTestState();
  554. SyncBlendState();
  555. SyncLogicOpState();
  556. SyncCullMode();
  557. SyncPrimitiveRestart();
  558. SyncScissorTest(state);
  559. SyncTransformFeedback();
  560. SyncPointState();
  561. SyncPolygonOffset();
  562. SyncAlphaTest();
  563. // Draw the vertex batch
  564. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  565. std::size_t buffer_size = CalculateVertexArraysSize();
  566. // Add space for index buffer
  567. if (is_indexed) {
  568. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  569. }
  570. // Uniform space for the 5 shader stages
  571. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  572. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  573. Maxwell::MaxShaderStage;
  574. // Add space for at least 18 constant buffers
  575. buffer_size +=
  576. Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  577. const bool invalidate = buffer_cache.Map(buffer_size);
  578. if (invalidate) {
  579. // As all cached buffers are invalidated, we need to recheck their state.
  580. gpu.dirty_flags.vertex_array.set();
  581. }
  582. const GLuint vao = SetupVertexFormat();
  583. SetupVertexBuffer(vao);
  584. DrawParameters params = SetupDraw();
  585. SetupShaders(params.primitive_mode);
  586. buffer_cache.Unmap();
  587. shader_program_manager->ApplyTo(state);
  588. state.Apply();
  589. params.DispatchDraw();
  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. // texture_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. texture_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. texture_cache.DoFermiCopy(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{
  630. texture_cache.TryFindFramebufferSurface(Memory::GetPointer(framebuffer_addr))};
  631. if (!surface) {
  632. return {};
  633. }
  634. // Verify that the cached surface is the same size and format as the requested framebuffer
  635. const auto& params{surface->GetSurfaceParams()};
  636. const auto& pixel_format{
  637. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  638. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  639. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  640. if (params.pixel_format != pixel_format) {
  641. LOG_WARNING(Render_OpenGL, "Framebuffer pixel_format is different");
  642. }
  643. screen_info.display_texture = surface->GetTexture();
  644. return true;
  645. }
  646. void RasterizerOpenGL::SetupDrawConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  647. const Shader& shader) {
  648. MICROPROFILE_SCOPE(OpenGL_UBO);
  649. const auto stage_index = static_cast<std::size_t>(stage);
  650. const auto& shader_stage = system.GPU().Maxwell3D().state.shader_stages[stage_index];
  651. const auto& entries = shader->GetShaderEntries().const_buffers;
  652. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  653. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  654. const auto& entry = entries[bindpoint];
  655. SetupConstBuffer(shader_stage.const_buffers[entry.GetIndex()], entry);
  656. }
  657. }
  658. void RasterizerOpenGL::SetupConstBuffer(const Tegra::Engines::ConstBufferInfo& buffer,
  659. const GLShader::ConstBufferEntry& entry) {
  660. if (!buffer.enabled) {
  661. // Set values to zero to unbind buffers
  662. bind_ubo_pushbuffer.Push(0, 0, 0);
  663. return;
  664. }
  665. std::size_t size;
  666. if (entry.IsIndirect()) {
  667. // Buffer is accessed indirectly, so upload the entire thing
  668. size = buffer.size;
  669. if (size > MaxConstbufferSize) {
  670. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", size,
  671. MaxConstbufferSize);
  672. size = MaxConstbufferSize;
  673. }
  674. } else {
  675. // Buffer is accessed directly, upload just what we use
  676. size = entry.GetSize();
  677. }
  678. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  679. // UBO alignment requirements.
  680. size = Common::AlignUp(size, sizeof(GLvec4));
  681. ASSERT_MSG(size <= MaxConstbufferSize, "Constant buffer is too big");
  682. const std::size_t alignment = device.GetUniformBufferAlignment();
  683. const GLintptr offset = buffer_cache.UploadMemory(buffer.address, size, alignment);
  684. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), offset, size);
  685. }
  686. void RasterizerOpenGL::SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  687. const Shader& shader) {
  688. const auto& entries = shader->GetShaderEntries().global_memory_entries;
  689. for (std::size_t bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  690. const auto& entry{entries[bindpoint]};
  691. const auto& region{global_cache.GetGlobalRegion(entry, stage)};
  692. if (entry.IsWritten()) {
  693. region->MarkAsModified(true, global_cache);
  694. }
  695. bind_ssbo_pushbuffer.Push(region->GetBufferHandle(), 0,
  696. static_cast<GLsizeiptr>(region->GetSizeInBytes()));
  697. }
  698. }
  699. void RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, const Shader& shader,
  700. BaseBindings base_bindings) {
  701. MICROPROFILE_SCOPE(OpenGL_Texture);
  702. const auto& gpu = system.GPU();
  703. const auto& maxwell3d = gpu.Maxwell3D();
  704. const auto& entries = shader->GetShaderEntries().samplers;
  705. ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
  706. "Exceeded the number of active textures.");
  707. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  708. const auto& entry = entries[bindpoint];
  709. Tegra::Texture::FullTextureInfo texture;
  710. if (entry.IsBindless()) {
  711. const auto cbuf = entry.GetBindlessCBuf();
  712. Tegra::Texture::TextureHandle tex_handle;
  713. tex_handle.raw = maxwell3d.AccessConstBuffer32(stage, cbuf.first, cbuf.second);
  714. texture = maxwell3d.GetTextureInfo(tex_handle, entry.GetOffset());
  715. } else {
  716. texture = maxwell3d.GetStageTexture(stage, entry.GetOffset());
  717. }
  718. const u32 current_bindpoint = base_bindings.sampler + bindpoint;
  719. state.texture_units[current_bindpoint].sampler = sampler_cache.GetSampler(texture.tsc);
  720. if (const auto view{texture_cache.GetTextureSurface(texture, entry)}; view) {
  721. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  722. texture.tic.w_source);
  723. state.texture_units[current_bindpoint].texture = view->GetTexture();
  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::SyncAlphaTest() {
  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. state.alpha_test.enabled = regs.alpha_test_enabled;
  942. if (!state.alpha_test.enabled) {
  943. return;
  944. }
  945. state.alpha_test.func = MaxwellToGL::ComparisonOp(regs.alpha_test_func);
  946. state.alpha_test.ref = regs.alpha_test_ref;
  947. }
  948. } // namespace OpenGL