gl_rasterizer.cpp 35 KB

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