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