gl_rasterizer.cpp 48 KB

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