gl_rasterizer.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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/frontend/emu_window.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/settings.h"
  22. #include "video_core/engines/maxwell_3d.h"
  23. #include "video_core/renderer_opengl/gl_rasterizer.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. #include "video_core/video_core.h"
  28. namespace OpenGL {
  29. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  30. using PixelFormat = SurfaceParams::PixelFormat;
  31. using SurfaceType = SurfaceParams::SurfaceType;
  32. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array 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. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
  73. : emu_window{window}, screen_info{info}, buffer_cache(STREAM_BUFFER_SIZE) {
  74. // Create sampler objects
  75. for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
  76. texture_samplers[i].Create();
  77. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  78. }
  79. GLint ext_num;
  80. glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
  81. for (GLint i = 0; i < ext_num; i++) {
  82. const std::string_view extension{
  83. reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
  84. if (extension == "GL_ARB_direct_state_access") {
  85. has_ARB_direct_state_access = true;
  86. } else if (extension == "GL_ARB_multi_bind") {
  87. has_ARB_multi_bind = true;
  88. } else if (extension == "GL_ARB_separate_shader_objects") {
  89. has_ARB_separate_shader_objects = true;
  90. } else if (extension == "GL_ARB_vertex_attrib_binding") {
  91. has_ARB_vertex_attrib_binding = true;
  92. }
  93. }
  94. ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
  95. // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
  96. state.clip_distance[0] = true;
  97. // Create render framebuffer
  98. framebuffer.Create();
  99. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  100. state.draw.shader_program = 0;
  101. state.Apply();
  102. glEnable(GL_BLEND);
  103. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  104. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  105. }
  106. RasterizerOpenGL::~RasterizerOpenGL() {}
  107. void RasterizerOpenGL::SetupVertexArrays() {
  108. MICROPROFILE_SCOPE(OpenGL_VAO);
  109. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  110. const auto& regs = gpu.regs;
  111. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  112. auto& VAO = iter->second;
  113. if (is_cache_miss) {
  114. VAO.Create();
  115. state.draw.vertex_array = VAO.handle;
  116. state.Apply();
  117. // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
  118. // around.
  119. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_cache.GetHandle());
  120. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  121. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  122. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  123. // for now to avoid OpenGL errors.
  124. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  125. // assume every shader uses them all.
  126. for (unsigned index = 0; index < 16; ++index) {
  127. const auto& attrib = regs.vertex_attrib_format[index];
  128. // Ignore invalid attributes.
  129. if (!attrib.IsValid())
  130. continue;
  131. const auto& buffer = regs.vertex_array[attrib.buffer];
  132. LOG_TRACE(HW_GPU,
  133. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  134. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  135. attrib.offset.Value(), attrib.IsNormalized());
  136. ASSERT(buffer.IsEnabled());
  137. glEnableVertexAttribArray(index);
  138. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  139. attrib.type ==
  140. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  141. glVertexAttribIFormat(index, attrib.ComponentCount(),
  142. MaxwellToGL::VertexType(attrib), attrib.offset);
  143. } else {
  144. glVertexAttribFormat(index, attrib.ComponentCount(),
  145. MaxwellToGL::VertexType(attrib),
  146. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  147. }
  148. glVertexAttribBinding(index, attrib.buffer);
  149. }
  150. }
  151. state.draw.vertex_array = VAO.handle;
  152. state.draw.vertex_buffer = buffer_cache.GetHandle();
  153. state.Apply();
  154. // Upload all guest vertex arrays sequentially to our buffer
  155. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  156. const auto& vertex_array = regs.vertex_array[index];
  157. if (!vertex_array.IsEnabled())
  158. continue;
  159. Tegra::GPUVAddr start = vertex_array.StartAddress();
  160. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  161. ASSERT(end > start);
  162. const u64 size = end - start + 1;
  163. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  164. // Bind the vertex array to the buffer at the current offset.
  165. glBindVertexBuffer(index, buffer_cache.GetHandle(), vertex_buffer_offset,
  166. vertex_array.stride);
  167. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  168. // Enable vertex buffer instancing with the specified divisor.
  169. glVertexBindingDivisor(index, vertex_array.divisor);
  170. } else {
  171. // Disable the vertex buffer instancing.
  172. glVertexBindingDivisor(index, 0);
  173. }
  174. }
  175. }
  176. DrawParameters RasterizerOpenGL::SetupDraw() {
  177. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  178. const auto& regs = gpu.regs;
  179. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  180. DrawParameters params{};
  181. params.current_instance = gpu.state.current_instance;
  182. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  183. MICROPROFILE_SCOPE(OpenGL_PrimitiveAssembly);
  184. params.use_indexed = true;
  185. params.primitive_mode = GL_TRIANGLES;
  186. if (is_indexed) {
  187. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  188. params.count = (regs.index_array.count / 4) * 6;
  189. params.index_buffer_offset = primitive_assembler.MakeQuadIndexed(
  190. regs.index_array.IndexStart(), regs.index_array.FormatSizeInBytes(),
  191. regs.index_array.count);
  192. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  193. } else {
  194. // MakeQuadArray always generates u32 indexes
  195. params.index_format = GL_UNSIGNED_INT;
  196. params.count = (regs.vertex_buffer.count / 4) * 6;
  197. params.index_buffer_offset =
  198. primitive_assembler.MakeQuadArray(regs.vertex_buffer.first, params.count);
  199. }
  200. return params;
  201. }
  202. params.use_indexed = is_indexed;
  203. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  204. if (is_indexed) {
  205. MICROPROFILE_SCOPE(OpenGL_Index);
  206. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  207. params.count = regs.index_array.count;
  208. params.index_buffer_offset =
  209. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  210. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  211. } else {
  212. params.count = regs.vertex_buffer.count;
  213. params.vertex_first = regs.vertex_buffer.first;
  214. }
  215. return params;
  216. }
  217. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  218. MICROPROFILE_SCOPE(OpenGL_Shader);
  219. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  220. // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
  221. // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
  222. u32 current_constbuffer_bindpoint = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
  223. u32 current_texture_bindpoint = 0;
  224. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  225. const auto& shader_config = gpu.regs.shader_config[index];
  226. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  227. // Skip stages that are not enabled
  228. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  229. switch (program) {
  230. case Maxwell::ShaderProgram::Geometry:
  231. shader_program_manager->UseTrivialGeometryShader();
  232. break;
  233. }
  234. continue;
  235. }
  236. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  237. GLShader::MaxwellUniformData ubo{};
  238. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  239. const GLintptr offset = buffer_cache.UploadHostMemory(
  240. &ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
  241. // Bind the buffer
  242. glBindBufferRange(GL_UNIFORM_BUFFER, static_cast<GLuint>(stage), buffer_cache.GetHandle(),
  243. offset, static_cast<GLsizeiptr>(sizeof(ubo)));
  244. Shader shader{shader_cache.GetStageProgram(program)};
  245. switch (program) {
  246. case Maxwell::ShaderProgram::VertexA:
  247. case Maxwell::ShaderProgram::VertexB: {
  248. shader_program_manager->UseProgrammableVertexShader(
  249. shader->GetProgramHandle(primitive_mode));
  250. break;
  251. }
  252. case Maxwell::ShaderProgram::Geometry: {
  253. shader_program_manager->UseProgrammableGeometryShader(
  254. shader->GetProgramHandle(primitive_mode));
  255. break;
  256. }
  257. case Maxwell::ShaderProgram::Fragment: {
  258. shader_program_manager->UseProgrammableFragmentShader(
  259. shader->GetProgramHandle(primitive_mode));
  260. break;
  261. }
  262. default:
  263. LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  264. shader_config.enable.Value(), shader_config.offset);
  265. UNREACHABLE();
  266. }
  267. // Configure the const buffers for this shader stage.
  268. current_constbuffer_bindpoint =
  269. SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), shader, primitive_mode,
  270. current_constbuffer_bindpoint);
  271. // Configure the textures for this shader stage.
  272. current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader,
  273. primitive_mode, current_texture_bindpoint);
  274. // When VertexA is enabled, we have dual vertex shaders
  275. if (program == Maxwell::ShaderProgram::VertexA) {
  276. // VertexB was combined with VertexA, so we skip the VertexB iteration
  277. index++;
  278. }
  279. }
  280. state.Apply();
  281. }
  282. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  283. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  284. std::size_t size = 0;
  285. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  286. if (!regs.vertex_array[index].IsEnabled())
  287. continue;
  288. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  289. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  290. ASSERT(end > start);
  291. size += end - start + 1;
  292. }
  293. return size;
  294. }
  295. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  296. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  297. return static_cast<std::size_t>(regs.index_array.count) *
  298. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  299. }
  300. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  301. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  302. DrawArrays();
  303. return true;
  304. }
  305. template <typename Map, typename Interval>
  306. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  307. return boost::make_iterator_range(map.equal_range(interval));
  308. }
  309. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  310. const u64 page_start{addr >> Memory::PAGE_BITS};
  311. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  312. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  313. // subtract after iterating
  314. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  315. if (delta > 0)
  316. cached_pages.add({pages_interval, delta});
  317. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  318. const auto interval = pair.first & pages_interval;
  319. const int count = pair.second;
  320. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  321. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  322. const u64 interval_size = interval_end_addr - interval_start_addr;
  323. if (delta > 0 && count == delta)
  324. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  325. else if (delta < 0 && count == -delta)
  326. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  327. else
  328. ASSERT(count >= 0);
  329. }
  330. if (delta < 0)
  331. cached_pages.add({pages_interval, delta});
  332. }
  333. void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_depth_fb,
  334. bool preserve_contents,
  335. boost::optional<std::size_t> single_color_target) {
  336. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  337. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  338. Surface depth_surface;
  339. if (using_depth_fb) {
  340. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  341. }
  342. // TODO(bunnei): Figure out how the below register works. According to envytools, this should be
  343. // used to enable multiple render targets. However, it is left unset on all games that I have
  344. // tested.
  345. ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
  346. // Bind the framebuffer surfaces
  347. state.draw.draw_framebuffer = framebuffer.handle;
  348. state.Apply();
  349. if (using_color_fb) {
  350. if (single_color_target) {
  351. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  352. Surface color_surface =
  353. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  354. if (color_surface) {
  355. // Assume that a surface will be written to if it is used as a framebuffer, even if
  356. // the shader doesn't actually write to it.
  357. color_surface->MarkAsModified(true, res_cache);
  358. }
  359. glFramebufferTexture2D(
  360. GL_DRAW_FRAMEBUFFER,
  361. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target), GL_TEXTURE_2D,
  362. color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
  363. glDrawBuffer(GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target));
  364. } else {
  365. // Multiple color attachments are enabled
  366. std::array<GLenum, Maxwell::NumRenderTargets> buffers;
  367. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  368. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  369. if (color_surface) {
  370. // Assume that a surface will be written to if it is used as a framebuffer, even
  371. // if the shader doesn't actually write to it.
  372. color_surface->MarkAsModified(true, res_cache);
  373. }
  374. buffers[index] = GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  375. glFramebufferTexture2D(
  376. GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  377. GL_TEXTURE_2D, color_surface != nullptr ? color_surface->Texture().handle : 0,
  378. 0);
  379. }
  380. glDrawBuffers(regs.rt_control.count, buffers.data());
  381. }
  382. } else {
  383. // No color attachments are enabled - zero out all of them
  384. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  385. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
  386. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index), GL_TEXTURE_2D,
  387. 0, 0);
  388. }
  389. glDrawBuffer(GL_NONE);
  390. }
  391. if (depth_surface) {
  392. // Assume that a surface will be written to if it is used as a framebuffer, even if
  393. // the shader doesn't actually write to it.
  394. depth_surface->MarkAsModified(true, res_cache);
  395. if (regs.stencil_enable) {
  396. // Attach both depth and stencil
  397. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  398. depth_surface->Texture().handle, 0);
  399. } else {
  400. // Attach depth
  401. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  402. depth_surface->Texture().handle, 0);
  403. // Clear stencil attachment
  404. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  405. }
  406. } else {
  407. // Clear both depth and stencil attachment
  408. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  409. 0);
  410. }
  411. SyncViewport();
  412. state.Apply();
  413. }
  414. void RasterizerOpenGL::Clear() {
  415. const auto prev_state{state};
  416. SCOPE_EXIT({ prev_state.Apply(); });
  417. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  418. bool use_color{};
  419. bool use_depth{};
  420. bool use_stencil{};
  421. OpenGLState clear_state;
  422. clear_state.draw.draw_framebuffer = framebuffer.handle;
  423. clear_state.color_mask.red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  424. clear_state.color_mask.green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  425. clear_state.color_mask.blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  426. clear_state.color_mask.alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  427. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  428. regs.clear_buffers.A) {
  429. use_color = true;
  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 true.
  436. clear_state.depth.test_enabled = true;
  437. clear_state.depth.test_func = GL_ALWAYS;
  438. }
  439. if (regs.clear_buffers.S) {
  440. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  441. use_stencil = true;
  442. clear_state.stencil.test_enabled = true;
  443. }
  444. if (!use_color && !use_depth && !use_stencil) {
  445. // No color surface nor depth/stencil surface are enabled
  446. return;
  447. }
  448. ScopeAcquireGLContext acquire_context{emu_window};
  449. ConfigureFramebuffers(use_color, use_depth || use_stencil, false,
  450. regs.clear_buffers.RT.Value());
  451. clear_state.Apply();
  452. if (use_color) {
  453. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  454. }
  455. if (use_depth && use_stencil) {
  456. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  457. } else if (use_depth) {
  458. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  459. } else if (use_stencil) {
  460. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  461. }
  462. }
  463. void RasterizerOpenGL::DrawArrays() {
  464. if (accelerate_draw == AccelDraw::Disabled)
  465. return;
  466. MICROPROFILE_SCOPE(OpenGL_Drawing);
  467. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  468. const auto& regs = gpu.regs;
  469. ScopeAcquireGLContext acquire_context{emu_window};
  470. ConfigureFramebuffers();
  471. SyncDepthTestState();
  472. SyncStencilTestState();
  473. SyncBlendState();
  474. SyncLogicOpState();
  475. SyncCullMode();
  476. SyncPrimitiveRestart();
  477. SyncDepthRange();
  478. SyncScissorTest();
  479. // Alpha Testing is synced on shaders.
  480. SyncTransformFeedback();
  481. SyncPointState();
  482. CheckAlphaTests();
  483. // TODO(bunnei): Sync framebuffer_scale uniform here
  484. // TODO(bunnei): Sync scissorbox uniform(s) here
  485. // Draw the vertex batch
  486. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  487. state.draw.vertex_buffer = buffer_cache.GetHandle();
  488. state.Apply();
  489. std::size_t buffer_size = CalculateVertexArraysSize();
  490. // Add space for index buffer (keeping in mind non-core primitives)
  491. switch (regs.draw.topology) {
  492. case Maxwell::PrimitiveTopology::Quads:
  493. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  494. primitive_assembler.CalculateQuadSize(regs.vertex_buffer.count);
  495. break;
  496. default:
  497. if (is_indexed) {
  498. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) + CalculateIndexBufferSize();
  499. }
  500. break;
  501. }
  502. // Uniform space for the 5 shader stages
  503. buffer_size =
  504. Common::AlignUp<std::size_t>(buffer_size, 4) +
  505. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  506. // Add space for at least 18 constant buffers
  507. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  508. buffer_cache.Map(buffer_size);
  509. SetupVertexArrays();
  510. DrawParameters params = SetupDraw();
  511. SetupShaders(params.primitive_mode);
  512. buffer_cache.Unmap();
  513. shader_program_manager->ApplyTo(state);
  514. state.Apply();
  515. // Execute draw call
  516. params.DispatchDraw();
  517. // Disable scissor test
  518. state.scissor.enabled = false;
  519. accelerate_draw = AccelDraw::Disabled;
  520. // Unbind textures for potential future use as framebuffer attachments
  521. for (auto& texture_unit : state.texture_units) {
  522. texture_unit.Unbind();
  523. }
  524. state.Apply();
  525. }
  526. void RasterizerOpenGL::FlushAll() {}
  527. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  528. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  529. if (Settings::values.use_accurate_gpu_emulation) {
  530. // Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit
  531. res_cache.FlushRegion(addr, size);
  532. }
  533. }
  534. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  535. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  536. res_cache.InvalidateRegion(addr, size);
  537. shader_cache.InvalidateRegion(addr, size);
  538. buffer_cache.InvalidateRegion(addr, size);
  539. }
  540. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  541. FlushRegion(addr, size);
  542. InvalidateRegion(addr, size);
  543. }
  544. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  545. const Tegra::Engines::Fermi2D::Regs::Surface& dst) {
  546. MICROPROFILE_SCOPE(OpenGL_Blits);
  547. if (Settings::values.use_accurate_gpu_emulation) {
  548. // Skip the accelerated copy and perform a slow but more accurate copy
  549. return false;
  550. }
  551. res_cache.FermiCopySurface(src, dst);
  552. return true;
  553. }
  554. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  555. UNREACHABLE();
  556. return true;
  557. }
  558. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  559. VAddr framebuffer_addr, u32 pixel_stride) {
  560. if (!framebuffer_addr) {
  561. return {};
  562. }
  563. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  564. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  565. if (!surface) {
  566. return {};
  567. }
  568. // Verify that the cached surface is the same size and format as the requested framebuffer
  569. const auto& params{surface->GetSurfaceParams()};
  570. const auto& pixel_format{SurfaceParams::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  571. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  572. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  573. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  574. screen_info.display_texture = surface->Texture().handle;
  575. return true;
  576. }
  577. void RasterizerOpenGL::SamplerInfo::Create() {
  578. sampler.Create();
  579. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  580. wrap_u = wrap_v = wrap_p = Tegra::Texture::WrapMode::Wrap;
  581. uses_depth_compare = false;
  582. depth_compare_func = Tegra::Texture::DepthCompareFunc::Never;
  583. // default is GL_LINEAR_MIPMAP_LINEAR
  584. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  585. // Other attributes have correct defaults
  586. glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER);
  587. }
  588. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  589. const GLuint s = sampler.handle;
  590. if (mag_filter != config.mag_filter) {
  591. mag_filter = config.mag_filter;
  592. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter));
  593. }
  594. if (min_filter != config.min_filter) {
  595. min_filter = config.min_filter;
  596. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter));
  597. }
  598. if (wrap_u != config.wrap_u) {
  599. wrap_u = config.wrap_u;
  600. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  601. }
  602. if (wrap_v != config.wrap_v) {
  603. wrap_v = config.wrap_v;
  604. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  605. }
  606. if (wrap_p != config.wrap_p) {
  607. wrap_p = config.wrap_p;
  608. glSamplerParameteri(s, GL_TEXTURE_WRAP_R, MaxwellToGL::WrapMode(wrap_p));
  609. }
  610. if (uses_depth_compare != (config.depth_compare_enabled == 1)) {
  611. uses_depth_compare = (config.depth_compare_enabled == 1);
  612. if (uses_depth_compare) {
  613. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  614. } else {
  615. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  616. }
  617. }
  618. if (depth_compare_func != config.depth_compare_func) {
  619. depth_compare_func = config.depth_compare_func;
  620. glSamplerParameteri(s, GL_TEXTURE_COMPARE_FUNC,
  621. MaxwellToGL::DepthCompareFunc(depth_compare_func));
  622. }
  623. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border ||
  624. wrap_p == Tegra::Texture::WrapMode::Border) {
  625. const GLvec4 new_border_color = {{config.border_color_r, config.border_color_g,
  626. config.border_color_b, config.border_color_a}};
  627. if (border_color != new_border_color) {
  628. border_color = new_border_color;
  629. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
  630. }
  631. }
  632. }
  633. u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
  634. GLenum primitive_mode, u32 current_bindpoint) {
  635. MICROPROFILE_SCOPE(OpenGL_UBO);
  636. const auto& gpu = Core::System::GetInstance().GPU();
  637. const auto& maxwell3d = gpu.Maxwell3D();
  638. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  639. const auto& entries = shader->GetShaderEntries().const_buffer_entries;
  640. constexpr u64 max_binds = Tegra::Engines::Maxwell3D::Regs::MaxConstBuffers;
  641. std::array<GLuint, max_binds> bind_buffers;
  642. std::array<GLintptr, max_binds> bind_offsets;
  643. std::array<GLsizeiptr, max_binds> bind_sizes;
  644. ASSERT_MSG(entries.size() <= max_binds, "Exceeded expected number of binding points.");
  645. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  646. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  647. const auto& used_buffer = entries[bindpoint];
  648. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  649. if (!buffer.enabled) {
  650. // With disabled buffers set values as zero to unbind them
  651. bind_buffers[bindpoint] = 0;
  652. bind_offsets[bindpoint] = 0;
  653. bind_sizes[bindpoint] = 0;
  654. continue;
  655. }
  656. std::size_t size = 0;
  657. if (used_buffer.IsIndirect()) {
  658. // Buffer is accessed indirectly, so upload the entire thing
  659. size = buffer.size;
  660. if (size > MaxConstbufferSize) {
  661. LOG_CRITICAL(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  662. MaxConstbufferSize);
  663. size = MaxConstbufferSize;
  664. }
  665. } else {
  666. // Buffer is accessed directly, upload just what we use
  667. size = used_buffer.GetSize() * sizeof(float);
  668. }
  669. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  670. // UBO alignment requirements.
  671. size = Common::AlignUp(size, sizeof(GLvec4));
  672. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  673. GLintptr const_buffer_offset = buffer_cache.UploadMemory(
  674. buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
  675. // Now configure the bindpoint of the buffer inside the shader
  676. glUniformBlockBinding(shader->GetProgramHandle(primitive_mode),
  677. shader->GetProgramResourceIndex(used_buffer),
  678. current_bindpoint + bindpoint);
  679. // Prepare values for multibind
  680. bind_buffers[bindpoint] = buffer_cache.GetHandle();
  681. bind_offsets[bindpoint] = const_buffer_offset;
  682. bind_sizes[bindpoint] = size;
  683. }
  684. glBindBuffersRange(GL_UNIFORM_BUFFER, current_bindpoint, static_cast<GLsizei>(entries.size()),
  685. bind_buffers.data(), bind_offsets.data(), bind_sizes.data());
  686. return current_bindpoint + static_cast<u32>(entries.size());
  687. }
  688. u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
  689. GLenum primitive_mode, u32 current_unit) {
  690. MICROPROFILE_SCOPE(OpenGL_Texture);
  691. const auto& gpu = Core::System::GetInstance().GPU();
  692. const auto& maxwell3d = gpu.Maxwell3D();
  693. const auto& entries = shader->GetShaderEntries().texture_samplers;
  694. ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
  695. "Exceeded the number of active textures.");
  696. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  697. const auto& entry = entries[bindpoint];
  698. const u32 current_bindpoint = current_unit + bindpoint;
  699. // Bind the uniform to the sampler.
  700. glProgramUniform1i(shader->GetProgramHandle(primitive_mode),
  701. shader->GetUniformLocation(entry), current_bindpoint);
  702. const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
  703. if (!texture.enabled) {
  704. state.texture_units[current_bindpoint].texture = 0;
  705. continue;
  706. }
  707. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  708. Surface surface = res_cache.GetTextureSurface(texture, entry);
  709. if (surface != nullptr) {
  710. state.texture_units[current_bindpoint].texture = surface->Texture().handle;
  711. state.texture_units[current_bindpoint].target = surface->Target();
  712. state.texture_units[current_bindpoint].swizzle.r =
  713. MaxwellToGL::SwizzleSource(texture.tic.x_source);
  714. state.texture_units[current_bindpoint].swizzle.g =
  715. MaxwellToGL::SwizzleSource(texture.tic.y_source);
  716. state.texture_units[current_bindpoint].swizzle.b =
  717. MaxwellToGL::SwizzleSource(texture.tic.z_source);
  718. state.texture_units[current_bindpoint].swizzle.a =
  719. MaxwellToGL::SwizzleSource(texture.tic.w_source);
  720. } else {
  721. // Can occur when texture addr is null or its memory is unmapped/invalid
  722. state.texture_units[current_bindpoint].texture = 0;
  723. }
  724. }
  725. return current_unit + static_cast<u32>(entries.size());
  726. }
  727. void RasterizerOpenGL::SyncViewport() {
  728. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  729. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  730. state.viewport.x = viewport_rect.left;
  731. state.viewport.y = viewport_rect.bottom;
  732. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
  733. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
  734. }
  735. void RasterizerOpenGL::SyncClipEnabled() {
  736. UNREACHABLE();
  737. }
  738. void RasterizerOpenGL::SyncClipCoef() {
  739. UNREACHABLE();
  740. }
  741. void RasterizerOpenGL::SyncCullMode() {
  742. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  743. state.cull.enabled = regs.cull.enabled != 0;
  744. if (state.cull.enabled) {
  745. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  746. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  747. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  748. regs.viewport_transform[0].scale_y < 0.0f};
  749. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  750. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  751. // because OpenGL already does it for us.
  752. if (flip_triangles) {
  753. if (state.cull.front_face == GL_CCW)
  754. state.cull.front_face = GL_CW;
  755. else if (state.cull.front_face == GL_CW)
  756. state.cull.front_face = GL_CCW;
  757. }
  758. }
  759. }
  760. void RasterizerOpenGL::SyncPrimitiveRestart() {
  761. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  762. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  763. state.primitive_restart.index = regs.primitive_restart.index;
  764. }
  765. void RasterizerOpenGL::SyncDepthRange() {
  766. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  767. state.depth.depth_range_near = regs.viewport->depth_range_near;
  768. state.depth.depth_range_far = regs.viewport->depth_range_far;
  769. }
  770. void RasterizerOpenGL::SyncDepthTestState() {
  771. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  772. state.depth.test_enabled = regs.depth_test_enable != 0;
  773. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  774. if (!state.depth.test_enabled)
  775. return;
  776. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  777. }
  778. void RasterizerOpenGL::SyncStencilTestState() {
  779. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  780. state.stencil.test_enabled = regs.stencil_enable != 0;
  781. if (!regs.stencil_enable) {
  782. return;
  783. }
  784. // TODO(bunnei): Verify behavior when this is not set
  785. ASSERT(regs.stencil_two_side_enable);
  786. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  787. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  788. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  789. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  790. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  791. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  792. state.stencil.front.write_mask = regs.stencil_front_mask;
  793. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  794. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  795. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  796. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  797. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  798. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  799. state.stencil.back.write_mask = regs.stencil_back_mask;
  800. }
  801. void RasterizerOpenGL::SyncBlendState() {
  802. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  803. // TODO(Subv): Support more than just render target 0.
  804. state.blend.enabled = regs.blend.enable[0] != 0;
  805. if (!state.blend.enabled)
  806. return;
  807. ASSERT_MSG(regs.logic_op.enable == 0,
  808. "Blending and logic op can't be enabled at the same time.");
  809. ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
  810. ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
  811. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
  812. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
  813. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
  814. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
  815. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
  816. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
  817. }
  818. void RasterizerOpenGL::SyncLogicOpState() {
  819. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  820. // TODO(Subv): Support more than just render target 0.
  821. state.logic_op.enabled = regs.logic_op.enable != 0;
  822. if (!state.logic_op.enabled)
  823. return;
  824. ASSERT_MSG(regs.blend.enable[0] == 0,
  825. "Blending and logic op can't be enabled at the same time.");
  826. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  827. }
  828. void RasterizerOpenGL::SyncScissorTest() {
  829. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  830. state.scissor.enabled = (regs.scissor_test.enable != 0);
  831. // TODO(Blinkhawk): Figure if the hardware supports scissor testing per viewport and how it's
  832. // implemented.
  833. if (regs.scissor_test.enable != 0) {
  834. const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
  835. const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
  836. state.scissor.x = regs.scissor_test.min_x;
  837. state.scissor.y = regs.scissor_test.min_y;
  838. state.scissor.width = width;
  839. state.scissor.height = height;
  840. }
  841. }
  842. void RasterizerOpenGL::SyncTransformFeedback() {
  843. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  844. if (regs.tfb_enabled != 0) {
  845. LOG_CRITICAL(Render_OpenGL, "Transform feedbacks are not implemented");
  846. UNREACHABLE();
  847. }
  848. }
  849. void RasterizerOpenGL::SyncPointState() {
  850. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  851. // TODO(Rodrigo): Most games do not set a point size. I think this is a case of a
  852. // register carrying a default value. For now, if the point size is zero, assume it's
  853. // OpenGL's default (1).
  854. state.point.size = regs.point_size == 0 ? 1 : regs.point_size;
  855. }
  856. void RasterizerOpenGL::CheckAlphaTests() {
  857. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  858. if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) {
  859. LOG_CRITICAL(
  860. Render_OpenGL,
  861. "Alpha Testing is enabled with Multiple Render Targets, this behavior is undefined.");
  862. UNREACHABLE();
  863. }
  864. }
  865. } // namespace OpenGL