gl_rasterizer.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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 <memory>
  6. #include <string>
  7. #include <string_view>
  8. #include <tuple>
  9. #include <utility>
  10. #include <glad/glad.h>
  11. #include "common/alignment.h"
  12. #include "common/assert.h"
  13. #include "common/logging/log.h"
  14. #include "common/math_util.h"
  15. #include "common/microprofile.h"
  16. #include "core/core.h"
  17. #include "core/frontend/emu_window.h"
  18. #include "core/hle/kernel/process.h"
  19. #include "core/settings.h"
  20. #include "video_core/engines/maxwell_3d.h"
  21. #include "video_core/renderer_opengl/gl_rasterizer.h"
  22. #include "video_core/renderer_opengl/gl_shader_gen.h"
  23. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  24. #include "video_core/renderer_opengl/renderer_opengl.h"
  25. #include "video_core/video_core.h"
  26. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  27. using PixelFormat = SurfaceParams::PixelFormat;
  28. using SurfaceType = SurfaceParams::SurfaceType;
  29. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array Setup", MP_RGB(128, 128, 192));
  30. MICROPROFILE_DEFINE(OpenGL_VS, "OpenGL", "Vertex Shader Setup", MP_RGB(128, 128, 192));
  31. MICROPROFILE_DEFINE(OpenGL_FS, "OpenGL", "Fragment Shader Setup", MP_RGB(128, 128, 192));
  32. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  33. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(100, 100, 255));
  34. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  35. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window)
  36. : emu_window{window}, stream_buffer(GL_ARRAY_BUFFER, STREAM_BUFFER_SIZE) {
  37. // Create sampler objects
  38. for (size_t i = 0; i < texture_samplers.size(); ++i) {
  39. texture_samplers[i].Create();
  40. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  41. }
  42. GLint ext_num;
  43. glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
  44. for (GLint i = 0; i < ext_num; i++) {
  45. const std::string_view extension{
  46. reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
  47. if (extension == "GL_ARB_direct_state_access") {
  48. has_ARB_direct_state_access = true;
  49. } else if (extension == "GL_ARB_separate_shader_objects") {
  50. has_ARB_separate_shader_objects = true;
  51. } else if (extension == "GL_ARB_vertex_attrib_binding") {
  52. has_ARB_vertex_attrib_binding = true;
  53. }
  54. }
  55. ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
  56. // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
  57. state.clip_distance[0] = true;
  58. // Generate VAO and UBO
  59. sw_vao.Create();
  60. uniform_buffer.Create();
  61. state.draw.vertex_array = sw_vao.handle;
  62. state.draw.uniform_buffer = uniform_buffer.handle;
  63. state.Apply();
  64. // Create render framebuffer
  65. framebuffer.Create();
  66. hw_vao.Create();
  67. state.draw.vertex_buffer = stream_buffer.GetHandle();
  68. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  69. state.draw.shader_program = 0;
  70. state.draw.vertex_array = hw_vao.handle;
  71. state.Apply();
  72. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, stream_buffer.GetHandle());
  73. glEnable(GL_BLEND);
  74. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  75. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  76. }
  77. RasterizerOpenGL::~RasterizerOpenGL() {}
  78. std::pair<u8*, GLintptr> RasterizerOpenGL::SetupVertexArrays(u8* array_ptr,
  79. GLintptr buffer_offset) {
  80. MICROPROFILE_SCOPE(OpenGL_VAO);
  81. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  82. state.draw.vertex_array = hw_vao.handle;
  83. state.draw.vertex_buffer = stream_buffer.GetHandle();
  84. state.Apply();
  85. // Upload all guest vertex arrays sequentially to our buffer
  86. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  87. const auto& vertex_array = regs.vertex_array[index];
  88. if (!vertex_array.IsEnabled())
  89. continue;
  90. const Tegra::GPUVAddr start = vertex_array.StartAddress();
  91. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  92. ASSERT(end > start);
  93. u64 size = end - start + 1;
  94. GLintptr vertex_buffer_offset;
  95. std::tie(array_ptr, buffer_offset, vertex_buffer_offset) =
  96. UploadMemory(array_ptr, buffer_offset, start, size);
  97. // Bind the vertex array to the buffer at the current offset.
  98. glBindVertexBuffer(index, stream_buffer.GetHandle(), vertex_buffer_offset,
  99. vertex_array.stride);
  100. ASSERT_MSG(vertex_array.divisor == 0, "Vertex buffer divisor unimplemented");
  101. }
  102. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  103. // Enables the first 16 vertex attributes always, as we don't know which ones are actually used
  104. // until shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now
  105. // to avoid OpenGL errors.
  106. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  107. // assume every shader uses them all.
  108. for (unsigned index = 0; index < 16; ++index) {
  109. auto& attrib = regs.vertex_attrib_format[index];
  110. // Ignore invalid attributes.
  111. if (!attrib.IsValid())
  112. continue;
  113. auto& buffer = regs.vertex_array[attrib.buffer];
  114. LOG_TRACE(HW_GPU, "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  115. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  116. attrib.offset.Value(), attrib.IsNormalized());
  117. ASSERT(buffer.IsEnabled());
  118. glEnableVertexAttribArray(index);
  119. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  120. attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  121. glVertexAttribIFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  122. attrib.offset);
  123. } else {
  124. glVertexAttribFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  125. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  126. }
  127. glVertexAttribBinding(index, attrib.buffer);
  128. }
  129. return {array_ptr, buffer_offset};
  130. }
  131. static GLShader::ProgramCode GetShaderProgramCode(Maxwell::ShaderProgram program) {
  132. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  133. // Fetch program code from memory
  134. GLShader::ProgramCode program_code;
  135. auto& shader_config = gpu.regs.shader_config[static_cast<size_t>(program)];
  136. const u64 gpu_address{gpu.regs.code_address.CodeAddress() + shader_config.offset};
  137. const boost::optional<VAddr> cpu_address{gpu.memory_manager.GpuToCpuAddress(gpu_address)};
  138. Memory::ReadBlock(*cpu_address, program_code.data(), program_code.size() * sizeof(u64));
  139. return program_code;
  140. }
  141. std::pair<u8*, GLintptr> RasterizerOpenGL::SetupShaders(u8* buffer_ptr, GLintptr buffer_offset) {
  142. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  143. // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
  144. // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
  145. u32 current_constbuffer_bindpoint = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
  146. u32 current_texture_bindpoint = 0;
  147. for (size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  148. auto& shader_config = gpu.regs.shader_config[index];
  149. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  150. // Skip stages that are not enabled
  151. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  152. continue;
  153. }
  154. std::tie(buffer_ptr, buffer_offset) =
  155. AlignBuffer(buffer_ptr, buffer_offset, static_cast<size_t>(uniform_buffer_alignment));
  156. const size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  157. GLShader::MaxwellUniformData ubo{};
  158. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  159. std::memcpy(buffer_ptr, &ubo, sizeof(ubo));
  160. // Bind the buffer
  161. glBindBufferRange(GL_UNIFORM_BUFFER, stage, stream_buffer.GetHandle(), buffer_offset,
  162. sizeof(ubo));
  163. buffer_ptr += sizeof(ubo);
  164. buffer_offset += sizeof(ubo);
  165. GLShader::ShaderSetup setup{GetShaderProgramCode(program)};
  166. GLShader::ShaderEntries shader_resources;
  167. switch (program) {
  168. case Maxwell::ShaderProgram::VertexA: {
  169. // VertexB is always enabled, so when VertexA is enabled, we have two vertex shaders.
  170. // Conventional HW does not support this, so we combine VertexA and VertexB into one
  171. // stage here.
  172. setup.SetProgramB(GetShaderProgramCode(Maxwell::ShaderProgram::VertexB));
  173. GLShader::MaxwellVSConfig vs_config{setup};
  174. shader_resources =
  175. shader_program_manager->UseProgrammableVertexShader(vs_config, setup);
  176. break;
  177. }
  178. case Maxwell::ShaderProgram::VertexB: {
  179. GLShader::MaxwellVSConfig vs_config{setup};
  180. shader_resources =
  181. shader_program_manager->UseProgrammableVertexShader(vs_config, setup);
  182. break;
  183. }
  184. case Maxwell::ShaderProgram::Fragment: {
  185. GLShader::MaxwellFSConfig fs_config{setup};
  186. shader_resources =
  187. shader_program_manager->UseProgrammableFragmentShader(fs_config, setup);
  188. break;
  189. }
  190. default:
  191. LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  192. shader_config.enable.Value(), shader_config.offset);
  193. UNREACHABLE();
  194. }
  195. GLuint gl_stage_program = shader_program_manager->GetCurrentProgramStage(
  196. static_cast<Maxwell::ShaderStage>(stage));
  197. // Configure the const buffers for this shader stage.
  198. std::tie(buffer_ptr, buffer_offset, current_constbuffer_bindpoint) = SetupConstBuffers(
  199. buffer_ptr, buffer_offset, static_cast<Maxwell::ShaderStage>(stage), gl_stage_program,
  200. current_constbuffer_bindpoint, shader_resources.const_buffer_entries);
  201. // Configure the textures for this shader stage.
  202. current_texture_bindpoint =
  203. SetupTextures(static_cast<Maxwell::ShaderStage>(stage), gl_stage_program,
  204. current_texture_bindpoint, shader_resources.texture_samplers);
  205. // When VertexA is enabled, we have dual vertex shaders
  206. if (program == Maxwell::ShaderProgram::VertexA) {
  207. // VertexB was combined with VertexA, so we skip the VertexB iteration
  208. index++;
  209. }
  210. }
  211. shader_program_manager->UseTrivialGeometryShader();
  212. return {buffer_ptr, buffer_offset};
  213. }
  214. size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  215. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  216. size_t size = 0;
  217. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  218. if (!regs.vertex_array[index].IsEnabled())
  219. continue;
  220. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  221. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  222. ASSERT(end > start);
  223. size += end - start + 1;
  224. }
  225. return size;
  226. }
  227. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  228. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  229. DrawArrays();
  230. return true;
  231. }
  232. std::pair<Surface, Surface> RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb,
  233. bool using_depth_fb) {
  234. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  235. if (regs.rt[0].format == Tegra::RenderTargetFormat::NONE) {
  236. LOG_ERROR(HW_GPU, "RenderTargetFormat is not configured");
  237. using_color_fb = false;
  238. }
  239. // TODO(bunnei): Implement this
  240. const bool has_stencil = false;
  241. const bool write_color_fb =
  242. state.color_mask.red_enabled == GL_TRUE || state.color_mask.green_enabled == GL_TRUE ||
  243. state.color_mask.blue_enabled == GL_TRUE || state.color_mask.alpha_enabled == GL_TRUE;
  244. const bool write_depth_fb =
  245. (state.depth.test_enabled && state.depth.write_mask == GL_TRUE) ||
  246. (has_stencil && state.stencil.test_enabled && state.stencil.write_mask != 0);
  247. Surface color_surface;
  248. Surface depth_surface;
  249. MathUtil::Rectangle<u32> surfaces_rect;
  250. std::tie(color_surface, depth_surface, surfaces_rect) =
  251. res_cache.GetFramebufferSurfaces(using_color_fb, using_depth_fb);
  252. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  253. const MathUtil::Rectangle<u32> draw_rect{
  254. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.left,
  255. surfaces_rect.left, surfaces_rect.right)), // Left
  256. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) + viewport_rect.top,
  257. surfaces_rect.bottom, surfaces_rect.top)), // Top
  258. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.right,
  259. surfaces_rect.left, surfaces_rect.right)), // Right
  260. static_cast<u32>(
  261. std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) + viewport_rect.bottom,
  262. surfaces_rect.bottom, surfaces_rect.top))}; // Bottom
  263. // Bind the framebuffer surfaces
  264. BindFramebufferSurfaces(color_surface, depth_surface, has_stencil);
  265. SyncViewport(surfaces_rect);
  266. // Viewport can have negative offsets or larger dimensions than our framebuffer sub-rect. Enable
  267. // scissor test to prevent drawing outside of the framebuffer region
  268. state.scissor.enabled = true;
  269. state.scissor.x = draw_rect.left;
  270. state.scissor.y = draw_rect.bottom;
  271. state.scissor.width = draw_rect.GetWidth();
  272. state.scissor.height = draw_rect.GetHeight();
  273. state.Apply();
  274. // Only return the surface to be marked as dirty if writing to it is enabled.
  275. return std::make_pair(write_color_fb ? color_surface : nullptr,
  276. write_depth_fb ? depth_surface : nullptr);
  277. }
  278. void RasterizerOpenGL::Clear() {
  279. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  280. bool use_color_fb = false;
  281. bool use_depth_fb = false;
  282. GLbitfield clear_mask = 0;
  283. if (regs.clear_buffers.R && regs.clear_buffers.G && regs.clear_buffers.B &&
  284. regs.clear_buffers.A) {
  285. clear_mask |= GL_COLOR_BUFFER_BIT;
  286. use_color_fb = true;
  287. }
  288. if (regs.clear_buffers.Z) {
  289. clear_mask |= GL_DEPTH_BUFFER_BIT;
  290. use_depth_fb = regs.zeta_enable != 0;
  291. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  292. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to true.
  293. state.depth.test_enabled = true;
  294. state.depth.write_mask = GL_TRUE;
  295. state.depth.test_func = GL_ALWAYS;
  296. state.Apply();
  297. }
  298. if (clear_mask == 0)
  299. return;
  300. ScopeAcquireGLContext acquire_context{emu_window};
  301. auto [dirty_color_surface, dirty_depth_surface] =
  302. ConfigureFramebuffers(use_color_fb, use_depth_fb);
  303. // TODO(Subv): Support clearing only partial colors.
  304. glClearColor(regs.clear_color[0], regs.clear_color[1], regs.clear_color[2],
  305. regs.clear_color[3]);
  306. glClearDepth(regs.clear_depth);
  307. glClear(clear_mask);
  308. // Mark framebuffer surfaces as dirty
  309. if (Settings::values.use_accurate_framebuffers) {
  310. if (dirty_color_surface != nullptr) {
  311. res_cache.FlushSurface(dirty_color_surface);
  312. }
  313. if (dirty_depth_surface != nullptr) {
  314. res_cache.FlushSurface(dirty_depth_surface);
  315. }
  316. }
  317. }
  318. std::pair<u8*, GLintptr> RasterizerOpenGL::AlignBuffer(u8* buffer_ptr, GLintptr buffer_offset,
  319. size_t alignment) {
  320. // Align the offset, not the mapped pointer
  321. GLintptr offset_aligned =
  322. static_cast<GLintptr>(Common::AlignUp(static_cast<size_t>(buffer_offset), alignment));
  323. return {buffer_ptr + (offset_aligned - buffer_offset), offset_aligned};
  324. }
  325. std::tuple<u8*, GLintptr, GLintptr> RasterizerOpenGL::UploadMemory(u8* buffer_ptr,
  326. GLintptr buffer_offset,
  327. Tegra::GPUVAddr gpu_addr,
  328. size_t size, size_t alignment) {
  329. std::tie(buffer_ptr, buffer_offset) = AlignBuffer(buffer_ptr, buffer_offset, alignment);
  330. GLintptr uploaded_offset = buffer_offset;
  331. const auto& memory_manager = Core::System::GetInstance().GPU().memory_manager;
  332. const boost::optional<VAddr> cpu_addr{memory_manager->GpuToCpuAddress(gpu_addr)};
  333. Memory::ReadBlock(*cpu_addr, buffer_ptr, size);
  334. buffer_ptr += size;
  335. buffer_offset += size;
  336. return {buffer_ptr, buffer_offset, uploaded_offset};
  337. }
  338. void RasterizerOpenGL::DrawArrays() {
  339. if (accelerate_draw == AccelDraw::Disabled)
  340. return;
  341. MICROPROFILE_SCOPE(OpenGL_Drawing);
  342. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  343. ScopeAcquireGLContext acquire_context{emu_window};
  344. auto [dirty_color_surface, dirty_depth_surface] =
  345. ConfigureFramebuffers(true, regs.zeta.Address() != 0 && regs.zeta_enable != 0);
  346. SyncDepthTestState();
  347. SyncBlendState();
  348. SyncCullMode();
  349. // TODO(bunnei): Sync framebuffer_scale uniform here
  350. // TODO(bunnei): Sync scissorbox uniform(s) here
  351. // Draw the vertex batch
  352. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  353. const u64 index_buffer_size{regs.index_array.count * regs.index_array.FormatSizeInBytes()};
  354. const unsigned vertex_num{is_indexed ? regs.index_array.count : regs.vertex_buffer.count};
  355. state.draw.vertex_buffer = stream_buffer.GetHandle();
  356. state.Apply();
  357. size_t buffer_size = CalculateVertexArraysSize();
  358. if (is_indexed) {
  359. buffer_size = Common::AlignUp<size_t>(buffer_size, 4) + index_buffer_size;
  360. }
  361. // Uniform space for the 5 shader stages
  362. buffer_size =
  363. Common::AlignUp<size_t>(buffer_size, 4) +
  364. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  365. // Add space for at least 18 constant buffers
  366. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  367. u8* buffer_ptr;
  368. GLintptr buffer_offset;
  369. std::tie(buffer_ptr, buffer_offset, std::ignore) =
  370. stream_buffer.Map(static_cast<GLsizeiptr>(buffer_size), 4);
  371. u8* buffer_ptr_base = buffer_ptr;
  372. std::tie(buffer_ptr, buffer_offset) = SetupVertexArrays(buffer_ptr, buffer_offset);
  373. // If indexed mode, copy the index buffer
  374. GLintptr index_buffer_offset = 0;
  375. if (is_indexed) {
  376. std::tie(buffer_ptr, buffer_offset, index_buffer_offset) = UploadMemory(
  377. buffer_ptr, buffer_offset, regs.index_array.StartAddress(), index_buffer_size);
  378. }
  379. std::tie(buffer_ptr, buffer_offset) = SetupShaders(buffer_ptr, buffer_offset);
  380. stream_buffer.Unmap(buffer_ptr - buffer_ptr_base);
  381. shader_program_manager->ApplyTo(state);
  382. state.Apply();
  383. const GLenum primitive_mode{MaxwellToGL::PrimitiveTopology(regs.draw.topology)};
  384. if (is_indexed) {
  385. const GLint base_vertex{static_cast<GLint>(regs.vb_element_base)};
  386. // Adjust the index buffer offset so it points to the first desired index.
  387. index_buffer_offset += regs.index_array.first * regs.index_array.FormatSizeInBytes();
  388. glDrawElementsBaseVertex(primitive_mode, regs.index_array.count,
  389. MaxwellToGL::IndexFormat(regs.index_array.format),
  390. reinterpret_cast<const void*>(index_buffer_offset), base_vertex);
  391. } else {
  392. glDrawArrays(primitive_mode, regs.vertex_buffer.first, regs.vertex_buffer.count);
  393. }
  394. // Disable scissor test
  395. state.scissor.enabled = false;
  396. accelerate_draw = AccelDraw::Disabled;
  397. // Unbind textures for potential future use as framebuffer attachments
  398. for (auto& texture_unit : state.texture_units) {
  399. texture_unit.Unbind();
  400. }
  401. state.Apply();
  402. // Mark framebuffer surfaces as dirty
  403. if (Settings::values.use_accurate_framebuffers) {
  404. if (dirty_color_surface != nullptr) {
  405. res_cache.FlushSurface(dirty_color_surface);
  406. }
  407. if (dirty_depth_surface != nullptr) {
  408. res_cache.FlushSurface(dirty_depth_surface);
  409. }
  410. }
  411. }
  412. void RasterizerOpenGL::NotifyMaxwellRegisterChanged(u32 method) {}
  413. void RasterizerOpenGL::FlushAll() {
  414. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  415. res_cache.FlushRegion(0, Kernel::VMManager::MAX_ADDRESS);
  416. }
  417. void RasterizerOpenGL::FlushRegion(Tegra::GPUVAddr addr, u64 size) {
  418. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  419. res_cache.FlushRegion(addr, size);
  420. }
  421. void RasterizerOpenGL::InvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  422. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  423. res_cache.InvalidateRegion(addr, size);
  424. }
  425. void RasterizerOpenGL::FlushAndInvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  426. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  427. res_cache.FlushRegion(addr, size);
  428. res_cache.InvalidateRegion(addr, size);
  429. }
  430. bool RasterizerOpenGL::AccelerateDisplayTransfer(const void* config) {
  431. MICROPROFILE_SCOPE(OpenGL_Blits);
  432. UNREACHABLE();
  433. return true;
  434. }
  435. bool RasterizerOpenGL::AccelerateTextureCopy(const void* config) {
  436. UNREACHABLE();
  437. return true;
  438. }
  439. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  440. UNREACHABLE();
  441. return true;
  442. }
  443. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  444. VAddr framebuffer_addr, u32 pixel_stride,
  445. ScreenInfo& screen_info) {
  446. if (!framebuffer_addr) {
  447. return {};
  448. }
  449. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  450. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  451. if (!surface) {
  452. return {};
  453. }
  454. // Verify that the cached surface is the same size and format as the requested framebuffer
  455. const auto& params{surface->GetSurfaceParams()};
  456. const auto& pixel_format{SurfaceParams::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  457. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  458. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  459. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  460. screen_info.display_texture = surface->Texture().handle;
  461. return true;
  462. }
  463. void RasterizerOpenGL::SamplerInfo::Create() {
  464. sampler.Create();
  465. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  466. wrap_u = wrap_v = Tegra::Texture::WrapMode::Wrap;
  467. // default is GL_LINEAR_MIPMAP_LINEAR
  468. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  469. // Other attributes have correct defaults
  470. }
  471. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  472. GLuint s = sampler.handle;
  473. if (mag_filter != config.mag_filter) {
  474. mag_filter = config.mag_filter;
  475. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter));
  476. }
  477. if (min_filter != config.min_filter) {
  478. min_filter = config.min_filter;
  479. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter));
  480. }
  481. if (wrap_u != config.wrap_u) {
  482. wrap_u = config.wrap_u;
  483. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  484. }
  485. if (wrap_v != config.wrap_v) {
  486. wrap_v = config.wrap_v;
  487. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  488. }
  489. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border) {
  490. const GLvec4 new_border_color = {{config.border_color_r, config.border_color_g,
  491. config.border_color_b, config.border_color_a}};
  492. if (border_color != new_border_color) {
  493. border_color = new_border_color;
  494. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
  495. }
  496. }
  497. }
  498. std::tuple<u8*, GLintptr, u32> RasterizerOpenGL::SetupConstBuffers(
  499. u8* buffer_ptr, GLintptr buffer_offset, Maxwell::ShaderStage stage, GLuint program,
  500. u32 current_bindpoint, const std::vector<GLShader::ConstBufferEntry>& entries) {
  501. const auto& gpu = Core::System::GetInstance().GPU();
  502. const auto& maxwell3d = gpu.Maxwell3D();
  503. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  504. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<size_t>(stage)];
  505. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  506. const auto& used_buffer = entries[bindpoint];
  507. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  508. if (!buffer.enabled) {
  509. continue;
  510. }
  511. size_t size = 0;
  512. if (used_buffer.IsIndirect()) {
  513. // Buffer is accessed indirectly, so upload the entire thing
  514. size = buffer.size;
  515. if (size > MaxConstbufferSize) {
  516. LOG_CRITICAL(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  517. MaxConstbufferSize);
  518. size = MaxConstbufferSize;
  519. }
  520. } else {
  521. // Buffer is accessed directly, upload just what we use
  522. size = used_buffer.GetSize() * sizeof(float);
  523. }
  524. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  525. // UBO alignment requirements.
  526. size = Common::AlignUp(size, sizeof(GLvec4));
  527. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  528. GLintptr const_buffer_offset;
  529. std::tie(buffer_ptr, buffer_offset, const_buffer_offset) =
  530. UploadMemory(buffer_ptr, buffer_offset, buffer.address, size,
  531. static_cast<size_t>(uniform_buffer_alignment));
  532. glBindBufferRange(GL_UNIFORM_BUFFER, current_bindpoint + bindpoint,
  533. stream_buffer.GetHandle(), const_buffer_offset, size);
  534. // Now configure the bindpoint of the buffer inside the shader
  535. const std::string buffer_name = used_buffer.GetName();
  536. const GLuint index =
  537. glGetProgramResourceIndex(program, GL_UNIFORM_BLOCK, buffer_name.c_str());
  538. if (index != GL_INVALID_INDEX) {
  539. glUniformBlockBinding(program, index, current_bindpoint + bindpoint);
  540. }
  541. }
  542. state.Apply();
  543. return {buffer_ptr, buffer_offset, current_bindpoint + static_cast<u32>(entries.size())};
  544. }
  545. u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, GLuint program, u32 current_unit,
  546. const std::vector<GLShader::SamplerEntry>& entries) {
  547. const auto& gpu = Core::System::GetInstance().GPU();
  548. const auto& maxwell3d = gpu.Maxwell3D();
  549. ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
  550. "Exceeded the number of active textures.");
  551. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  552. const auto& entry = entries[bindpoint];
  553. u32 current_bindpoint = current_unit + bindpoint;
  554. // Bind the uniform to the sampler.
  555. GLint uniform = glGetUniformLocation(program, entry.GetName().c_str());
  556. if (uniform == -1) {
  557. continue;
  558. }
  559. glProgramUniform1i(program, uniform, current_bindpoint);
  560. const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
  561. if (!texture.enabled) {
  562. state.texture_units[current_bindpoint].texture_2d = 0;
  563. continue;
  564. }
  565. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  566. Surface surface = res_cache.GetTextureSurface(texture);
  567. if (surface != nullptr) {
  568. state.texture_units[current_bindpoint].texture_2d = surface->Texture().handle;
  569. state.texture_units[current_bindpoint].swizzle.r =
  570. MaxwellToGL::SwizzleSource(texture.tic.x_source);
  571. state.texture_units[current_bindpoint].swizzle.g =
  572. MaxwellToGL::SwizzleSource(texture.tic.y_source);
  573. state.texture_units[current_bindpoint].swizzle.b =
  574. MaxwellToGL::SwizzleSource(texture.tic.z_source);
  575. state.texture_units[current_bindpoint].swizzle.a =
  576. MaxwellToGL::SwizzleSource(texture.tic.w_source);
  577. } else {
  578. // Can occur when texture addr is null or its memory is unmapped/invalid
  579. state.texture_units[current_bindpoint].texture_2d = 0;
  580. }
  581. }
  582. state.Apply();
  583. return current_unit + static_cast<u32>(entries.size());
  584. }
  585. void RasterizerOpenGL::BindFramebufferSurfaces(const Surface& color_surface,
  586. const Surface& depth_surface, bool has_stencil) {
  587. state.draw.draw_framebuffer = framebuffer.handle;
  588. state.Apply();
  589. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
  590. color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
  591. if (depth_surface != nullptr) {
  592. if (has_stencil) {
  593. // attach both depth and stencil
  594. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  595. depth_surface->Texture().handle, 0);
  596. } else {
  597. // attach depth
  598. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  599. depth_surface->Texture().handle, 0);
  600. // clear stencil attachment
  601. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  602. }
  603. } else {
  604. // clear both depth and stencil attachment
  605. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  606. 0);
  607. }
  608. }
  609. void RasterizerOpenGL::SyncViewport(const MathUtil::Rectangle<u32>& surfaces_rect) {
  610. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  611. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  612. state.viewport.x = static_cast<GLint>(surfaces_rect.left) + viewport_rect.left;
  613. state.viewport.y = static_cast<GLint>(surfaces_rect.bottom) + viewport_rect.bottom;
  614. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
  615. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
  616. }
  617. void RasterizerOpenGL::SyncClipEnabled() {
  618. UNREACHABLE();
  619. }
  620. void RasterizerOpenGL::SyncClipCoef() {
  621. UNREACHABLE();
  622. }
  623. void RasterizerOpenGL::SyncCullMode() {
  624. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  625. state.cull.enabled = regs.cull.enabled != 0;
  626. if (state.cull.enabled) {
  627. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  628. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  629. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  630. regs.viewport_transform[0].scale_y < 0.0f};
  631. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  632. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  633. // because OpenGL already does it for us.
  634. if (flip_triangles) {
  635. if (state.cull.front_face == GL_CCW)
  636. state.cull.front_face = GL_CW;
  637. else if (state.cull.front_face == GL_CW)
  638. state.cull.front_face = GL_CCW;
  639. }
  640. }
  641. }
  642. void RasterizerOpenGL::SyncDepthScale() {
  643. UNREACHABLE();
  644. }
  645. void RasterizerOpenGL::SyncDepthOffset() {
  646. UNREACHABLE();
  647. }
  648. void RasterizerOpenGL::SyncDepthTestState() {
  649. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  650. state.depth.test_enabled = regs.depth_test_enable != 0;
  651. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  652. if (!state.depth.test_enabled)
  653. return;
  654. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  655. }
  656. void RasterizerOpenGL::SyncBlendState() {
  657. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  658. // TODO(Subv): Support more than just render target 0.
  659. state.blend.enabled = regs.blend.enable[0] != 0;
  660. if (!state.blend.enabled)
  661. return;
  662. ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
  663. ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
  664. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
  665. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
  666. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
  667. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
  668. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
  669. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
  670. }