gl_rasterizer.cpp 51 KB

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