gl_rasterizer.cpp 54 KB

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