gl_rasterizer.cpp 52 KB

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