gl_rasterizer.cpp 34 KB

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