gl_rasterizer.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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/memory.h"
  22. #include "core/settings.h"
  23. #include "video_core/engines/kepler_compute.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/engines/shader_type.h"
  26. #include "video_core/memory_manager.h"
  27. #include "video_core/renderer_opengl/gl_query_cache.h"
  28. #include "video_core/renderer_opengl/gl_rasterizer.h"
  29. #include "video_core/renderer_opengl/gl_shader_cache.h"
  30. #include "video_core/renderer_opengl/gl_shader_gen.h"
  31. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  32. #include "video_core/renderer_opengl/renderer_opengl.h"
  33. namespace OpenGL {
  34. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  35. using VideoCore::Surface::PixelFormat;
  36. using VideoCore::Surface::SurfaceTarget;
  37. using VideoCore::Surface::SurfaceType;
  38. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  43. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  45. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  46. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  47. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  48. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  49. namespace {
  50. template <typename Engine, typename Entry>
  51. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  52. Tegra::Engines::ShaderType shader_type,
  53. std::size_t index = 0) {
  54. if (entry.IsBindless()) {
  55. const Tegra::Texture::TextureHandle tex_handle =
  56. engine.AccessConstBuffer32(shader_type, entry.GetBuffer(), entry.GetOffset());
  57. return engine.GetTextureInfo(tex_handle);
  58. }
  59. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  60. const u32 offset =
  61. entry.GetOffset() + static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  62. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  63. return engine.GetStageTexture(shader_type, offset);
  64. } else {
  65. return engine.GetTexture(offset);
  66. }
  67. }
  68. std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
  69. const GLShader::ConstBufferEntry& entry) {
  70. if (!entry.IsIndirect()) {
  71. return entry.GetSize();
  72. }
  73. if (buffer.size > Maxwell::MaxConstBufferSize) {
  74. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", buffer.size,
  75. Maxwell::MaxConstBufferSize);
  76. return Maxwell::MaxConstBufferSize;
  77. }
  78. return buffer.size;
  79. }
  80. void oglEnable(GLenum cap, bool state) {
  81. (state ? glEnable : glDisable)(cap);
  82. }
  83. void oglEnablei(GLenum cap, bool state, GLuint index) {
  84. (state ? glEnablei : glDisablei)(cap, index);
  85. }
  86. } // Anonymous namespace
  87. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  88. ScreenInfo& info)
  89. : RasterizerAccelerated{system.Memory()}, texture_cache{system, *this, device},
  90. shader_cache{*this, system, emu_window, device}, query_cache{system, *this}, system{system},
  91. screen_info{info}, buffer_cache{*this, system, device, STREAM_BUFFER_SIZE} {
  92. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  93. state.draw.shader_program = 0;
  94. state.Apply();
  95. CheckExtensions();
  96. }
  97. RasterizerOpenGL::~RasterizerOpenGL() {}
  98. void RasterizerOpenGL::CheckExtensions() {
  99. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  100. LOG_WARNING(
  101. Render_OpenGL,
  102. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  103. }
  104. }
  105. void RasterizerOpenGL::SetupVertexFormat() {
  106. auto& gpu = system.GPU().Maxwell3D();
  107. const auto& regs = gpu.regs;
  108. MICROPROFILE_SCOPE(OpenGL_VAO);
  109. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  110. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  111. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  112. // avoid OpenGL errors.
  113. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  114. // assume every shader uses them all.
  115. for (u32 index = 0; index < 16; ++index) {
  116. const auto& attrib = regs.vertex_attrib_format[index];
  117. // Ignore invalid attributes.
  118. if (!attrib.IsValid()) {
  119. glDisableVertexAttribArray(index);
  120. continue;
  121. }
  122. glEnableVertexAttribArray(index);
  123. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  124. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  125. glVertexAttribIFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  126. attrib.offset);
  127. } else {
  128. glVertexAttribFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  129. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  130. }
  131. glVertexAttribBinding(index, attrib.buffer);
  132. }
  133. }
  134. void RasterizerOpenGL::SetupVertexBuffer() {
  135. auto& gpu = system.GPU().Maxwell3D();
  136. const auto& regs = gpu.regs;
  137. MICROPROFILE_SCOPE(OpenGL_VB);
  138. // Upload all guest vertex arrays sequentially to our buffer
  139. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  140. const auto& vertex_array = regs.vertex_array[index];
  141. if (!vertex_array.IsEnabled()) {
  142. continue;
  143. }
  144. const GPUVAddr start = vertex_array.StartAddress();
  145. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  146. ASSERT(end > start);
  147. const u64 size = end - start + 1;
  148. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  149. // Bind the vertex array to the buffer at the current offset.
  150. vertex_array_pushbuffer.SetVertexBuffer(index, vertex_buffer, vertex_buffer_offset,
  151. vertex_array.stride);
  152. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  153. // Enable vertex buffer instancing with the specified divisor.
  154. glVertexBindingDivisor(index, vertex_array.divisor);
  155. } else {
  156. // Disable the vertex buffer instancing.
  157. glVertexBindingDivisor(index, 0);
  158. }
  159. }
  160. }
  161. void RasterizerOpenGL::SetupVertexInstances() {
  162. auto& gpu = system.GPU().Maxwell3D();
  163. const auto& regs = gpu.regs;
  164. // Upload all guest vertex arrays sequentially to our buffer
  165. for (u32 index = 0; index < 16; ++index) {
  166. if (regs.instanced_arrays.IsInstancingEnabled(index) &&
  167. regs.vertex_array[index].divisor != 0) {
  168. // Enable vertex buffer instancing with the specified divisor.
  169. glVertexBindingDivisor(index, regs.vertex_array[index].divisor);
  170. } else {
  171. // Disable the vertex buffer instancing.
  172. glVertexBindingDivisor(index, 0);
  173. }
  174. }
  175. }
  176. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  177. MICROPROFILE_SCOPE(OpenGL_Index);
  178. const auto& regs = system.GPU().Maxwell3D().regs;
  179. const std::size_t size = CalculateIndexBufferSize();
  180. const auto [buffer, offset] = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  181. vertex_array_pushbuffer.SetIndexBuffer(buffer);
  182. return offset;
  183. }
  184. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  185. MICROPROFILE_SCOPE(OpenGL_Shader);
  186. auto& gpu = system.GPU().Maxwell3D();
  187. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  188. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  189. const auto& shader_config = gpu.regs.shader_config[index];
  190. const auto program{static_cast<Maxwell::ShaderProgram>(index)};
  191. // Skip stages that are not enabled
  192. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  193. switch (program) {
  194. case Maxwell::ShaderProgram::Geometry:
  195. shader_program_manager->UseTrivialGeometryShader();
  196. break;
  197. case Maxwell::ShaderProgram::Fragment:
  198. shader_program_manager->UseTrivialFragmentShader();
  199. break;
  200. default:
  201. break;
  202. }
  203. continue;
  204. }
  205. // Currently this stages are not supported in the OpenGL backend.
  206. // Todo(Blinkhawk): Port tesselation shaders from Vulkan to OpenGL
  207. if (program == Maxwell::ShaderProgram::TesselationControl) {
  208. continue;
  209. } else if (program == Maxwell::ShaderProgram::TesselationEval) {
  210. continue;
  211. }
  212. Shader shader{shader_cache.GetStageProgram(program)};
  213. // Stage indices are 0 - 5
  214. const std::size_t stage = index == 0 ? 0 : index - 1;
  215. SetupDrawConstBuffers(stage, shader);
  216. SetupDrawGlobalMemory(stage, shader);
  217. SetupDrawTextures(stage, shader);
  218. SetupDrawImages(stage, shader);
  219. const ProgramVariant variant(primitive_mode);
  220. const auto program_handle = shader->GetHandle(variant);
  221. switch (program) {
  222. case Maxwell::ShaderProgram::VertexA:
  223. case Maxwell::ShaderProgram::VertexB:
  224. shader_program_manager->UseProgrammableVertexShader(program_handle);
  225. break;
  226. case Maxwell::ShaderProgram::Geometry:
  227. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  228. break;
  229. case Maxwell::ShaderProgram::Fragment:
  230. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  231. break;
  232. default:
  233. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  234. shader_config.enable.Value(), shader_config.offset);
  235. }
  236. // Workaround for Intel drivers.
  237. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  238. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  239. // clip distances only when it's written by a shader stage.
  240. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  241. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  242. }
  243. // When VertexA is enabled, we have dual vertex shaders
  244. if (program == Maxwell::ShaderProgram::VertexA) {
  245. // VertexB was combined with VertexA, so we skip the VertexB iteration
  246. ++index;
  247. }
  248. }
  249. SyncClipEnabled(clip_distances);
  250. }
  251. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  252. const auto& regs = system.GPU().Maxwell3D().regs;
  253. std::size_t size = 0;
  254. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  255. if (!regs.vertex_array[index].IsEnabled())
  256. continue;
  257. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  258. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  259. ASSERT(end > start);
  260. size += end - start + 1;
  261. }
  262. return size;
  263. }
  264. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  265. const auto& regs = system.GPU().Maxwell3D().regs;
  266. return static_cast<std::size_t>(regs.index_array.count) *
  267. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  268. }
  269. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  270. const VideoCore::DiskResourceLoadCallback& callback) {
  271. shader_cache.LoadDiskCache(stop_loading, callback);
  272. }
  273. void RasterizerOpenGL::ConfigureFramebuffers() {
  274. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  275. auto& gpu = system.GPU().Maxwell3D();
  276. texture_cache.GuardRenderTargets(true);
  277. View depth_surface = texture_cache.GetDepthBufferSurface(true);
  278. const auto& regs = gpu.regs;
  279. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  280. // Bind the framebuffer surfaces
  281. FramebufferCacheKey key;
  282. const auto colors_count = static_cast<std::size_t>(regs.rt_control.count);
  283. for (std::size_t index = 0; index < colors_count; ++index) {
  284. View color_surface{texture_cache.GetColorBufferSurface(index, true)};
  285. if (!color_surface) {
  286. continue;
  287. }
  288. // Assume that a surface will be written to if it is used as a framebuffer, even
  289. // if the shader doesn't actually write to it.
  290. texture_cache.MarkColorBufferInUse(index);
  291. key.SetAttachment(index, regs.rt_control.GetMap(index));
  292. key.colors[index] = std::move(color_surface);
  293. }
  294. if (depth_surface) {
  295. // Assume that a surface will be written to if it is used as a framebuffer, even if
  296. // the shader doesn't actually write to it.
  297. texture_cache.MarkDepthBufferInUse();
  298. key.zeta = std::move(depth_surface);
  299. }
  300. texture_cache.GuardRenderTargets(false);
  301. state.draw.draw_framebuffer = framebuffer_cache.GetFramebuffer(key);
  302. }
  303. void RasterizerOpenGL::ConfigureClearFramebuffer(OpenGLState& current_state, bool using_color_fb,
  304. bool using_depth_fb, bool using_stencil_fb) {
  305. using VideoCore::Surface::SurfaceType;
  306. auto& gpu = system.GPU().Maxwell3D();
  307. const auto& regs = gpu.regs;
  308. texture_cache.GuardRenderTargets(true);
  309. View color_surface;
  310. if (using_color_fb) {
  311. color_surface = texture_cache.GetColorBufferSurface(regs.clear_buffers.RT, false);
  312. }
  313. View depth_surface;
  314. if (using_depth_fb || using_stencil_fb) {
  315. depth_surface = texture_cache.GetDepthBufferSurface(false);
  316. }
  317. texture_cache.GuardRenderTargets(false);
  318. FramebufferCacheKey key;
  319. key.colors[0] = color_surface;
  320. key.zeta = depth_surface;
  321. current_state.draw.draw_framebuffer = framebuffer_cache.GetFramebuffer(key);
  322. current_state.ApplyFramebufferState();
  323. }
  324. void RasterizerOpenGL::Clear() {
  325. const auto& maxwell3d = system.GPU().Maxwell3D();
  326. if (!maxwell3d.ShouldExecute()) {
  327. return;
  328. }
  329. const auto& regs = maxwell3d.regs;
  330. bool use_color{};
  331. bool use_depth{};
  332. bool use_stencil{};
  333. OpenGLState prev_state{OpenGLState::GetCurState()};
  334. SCOPE_EXIT({ prev_state.Apply(); });
  335. OpenGLState clear_state{OpenGLState::GetCurState()};
  336. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  337. regs.clear_buffers.A) {
  338. use_color = true;
  339. }
  340. if (use_color) {
  341. // TODO: Signal state tracker about these changes
  342. glColorMaski(0, regs.clear_buffers.R, regs.clear_buffers.G, regs.clear_buffers.B,
  343. regs.clear_buffers.A);
  344. SyncFramebufferSRGB();
  345. // TODO(Rodrigo): Determine if clamping is used on clears
  346. SyncFragmentColorClampState();
  347. }
  348. if (regs.clear_buffers.Z) {
  349. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  350. use_depth = true;
  351. // TODO: Signal state tracker about these changes
  352. glDepthMask(GL_TRUE);
  353. }
  354. if (regs.clear_buffers.S) {
  355. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  356. use_stencil = true;
  357. clear_state.stencil.test_enabled = true;
  358. if (regs.clear_flags.stencil) {
  359. // Stencil affects the clear so fill it with the used masks
  360. clear_state.stencil.front.test_func = GL_ALWAYS;
  361. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  362. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  363. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  364. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  365. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  366. if (regs.stencil_two_side_enable) {
  367. clear_state.stencil.back.test_func = GL_ALWAYS;
  368. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  369. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  370. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  371. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  372. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  373. } else {
  374. clear_state.stencil.back.test_func = GL_ALWAYS;
  375. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  376. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  377. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  378. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  379. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  380. }
  381. }
  382. }
  383. if (!use_color && !use_depth && !use_stencil) {
  384. // No color surface nor depth/stencil surface are enabled
  385. return;
  386. }
  387. ConfigureClearFramebuffer(clear_state, use_color, use_depth, use_stencil);
  388. SyncRasterizeEnable();
  389. if (regs.clear_flags.scissor) {
  390. SyncScissorTest();
  391. }
  392. UNIMPLEMENTED_IF(regs.clear_flags.viewport);
  393. clear_state.Apply();
  394. if (use_color) {
  395. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  396. }
  397. if (use_depth && use_stencil) {
  398. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  399. } else if (use_depth) {
  400. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  401. } else if (use_stencil) {
  402. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  403. }
  404. ++num_queued_commands;
  405. }
  406. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  407. MICROPROFILE_SCOPE(OpenGL_Drawing);
  408. auto& gpu = system.GPU().Maxwell3D();
  409. const auto& regs = gpu.regs;
  410. query_cache.UpdateCounters();
  411. SyncViewport();
  412. SyncRasterizeEnable();
  413. SyncColorMask();
  414. SyncFragmentColorClampState();
  415. SyncMultiSampleState();
  416. SyncDepthTestState();
  417. SyncStencilTestState();
  418. SyncBlendState();
  419. SyncLogicOpState();
  420. SyncCullMode();
  421. SyncPrimitiveRestart();
  422. SyncScissorTest();
  423. SyncTransformFeedback();
  424. SyncPointState();
  425. SyncPolygonOffset();
  426. SyncAlphaTest();
  427. SyncFramebufferSRGB();
  428. buffer_cache.Acquire();
  429. std::size_t buffer_size = CalculateVertexArraysSize();
  430. // Add space for index buffer
  431. if (is_indexed) {
  432. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  433. }
  434. // Uniform space for the 5 shader stages
  435. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  436. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  437. Maxwell::MaxShaderStage;
  438. // Add space for at least 18 constant buffers
  439. buffer_size += Maxwell::MaxConstBuffers *
  440. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  441. // Prepare the vertex array.
  442. buffer_cache.Map(buffer_size);
  443. // Prepare vertex array format.
  444. SetupVertexFormat();
  445. vertex_array_pushbuffer.Setup();
  446. // Upload vertex and index data.
  447. SetupVertexBuffer();
  448. SetupVertexInstances();
  449. GLintptr index_buffer_offset;
  450. if (is_indexed) {
  451. index_buffer_offset = SetupIndexBuffer();
  452. }
  453. // Prepare packed bindings.
  454. bind_ubo_pushbuffer.Setup();
  455. bind_ssbo_pushbuffer.Setup();
  456. // Setup emulation uniform buffer.
  457. GLShader::MaxwellUniformData ubo;
  458. ubo.SetFromRegs(gpu);
  459. const auto [buffer, offset] =
  460. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  461. bind_ubo_pushbuffer.Push(EmulationUniformBlockBinding, buffer, offset,
  462. static_cast<GLsizeiptr>(sizeof(ubo)));
  463. // Setup shaders and their used resources.
  464. texture_cache.GuardSamplers(true);
  465. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
  466. SetupShaders(primitive_mode);
  467. texture_cache.GuardSamplers(false);
  468. ConfigureFramebuffers();
  469. // Signal the buffer cache that we are not going to upload more things.
  470. const bool invalidate = buffer_cache.Unmap();
  471. // Now that we are no longer uploading data, we can safely bind the buffers to OpenGL.
  472. vertex_array_pushbuffer.Bind();
  473. bind_ubo_pushbuffer.Bind();
  474. bind_ssbo_pushbuffer.Bind();
  475. shader_program_manager->ApplyTo(state);
  476. state.Apply();
  477. if (texture_cache.TextureBarrier()) {
  478. glTextureBarrier();
  479. }
  480. ++num_queued_commands;
  481. const GLuint base_instance = static_cast<GLuint>(gpu.regs.vb_base_instance);
  482. const GLsizei num_instances =
  483. static_cast<GLsizei>(is_instanced ? gpu.mme_draw.instance_count : 1);
  484. if (is_indexed) {
  485. const GLint base_vertex = static_cast<GLint>(gpu.regs.vb_element_base);
  486. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.index_array.count);
  487. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  488. const GLenum format = MaxwellToGL::IndexFormat(gpu.regs.index_array.format);
  489. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  490. glDrawElements(primitive_mode, num_vertices, format, offset);
  491. } else if (num_instances == 1 && base_instance == 0) {
  492. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  493. } else if (base_vertex == 0 && base_instance == 0) {
  494. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  495. } else if (base_vertex == 0) {
  496. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  497. num_instances, base_instance);
  498. } else if (base_instance == 0) {
  499. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  500. num_instances, base_vertex);
  501. } else {
  502. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  503. offset, num_instances, base_vertex,
  504. base_instance);
  505. }
  506. } else {
  507. const GLint base_vertex = static_cast<GLint>(gpu.regs.vertex_buffer.first);
  508. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.vertex_buffer.count);
  509. if (num_instances == 1 && base_instance == 0) {
  510. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  511. } else if (base_instance == 0) {
  512. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  513. } else {
  514. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  515. num_instances, base_instance);
  516. }
  517. }
  518. }
  519. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  520. if (device.HasBrokenCompute()) {
  521. return;
  522. }
  523. buffer_cache.Acquire();
  524. auto kernel = shader_cache.GetComputeKernel(code_addr);
  525. SetupComputeTextures(kernel);
  526. SetupComputeImages(kernel);
  527. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  528. const ProgramVariant variant(launch_desc.block_dim_x, launch_desc.block_dim_y,
  529. launch_desc.block_dim_z, launch_desc.shared_alloc,
  530. launch_desc.local_pos_alloc);
  531. state.draw.shader_program = kernel->GetHandle(variant);
  532. state.draw.program_pipeline = 0;
  533. const std::size_t buffer_size =
  534. Tegra::Engines::KeplerCompute::NumConstBuffers *
  535. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  536. buffer_cache.Map(buffer_size);
  537. bind_ubo_pushbuffer.Setup();
  538. bind_ssbo_pushbuffer.Setup();
  539. SetupComputeConstBuffers(kernel);
  540. SetupComputeGlobalMemory(kernel);
  541. buffer_cache.Unmap();
  542. bind_ubo_pushbuffer.Bind();
  543. bind_ssbo_pushbuffer.Bind();
  544. state.ApplyTextures();
  545. state.ApplyImages();
  546. state.ApplyShaderProgram();
  547. state.ApplyProgramPipeline();
  548. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  549. ++num_queued_commands;
  550. }
  551. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  552. query_cache.ResetCounter(type);
  553. }
  554. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  555. std::optional<u64> timestamp) {
  556. query_cache.Query(gpu_addr, type, timestamp);
  557. }
  558. void RasterizerOpenGL::FlushAll() {}
  559. void RasterizerOpenGL::FlushRegion(CacheAddr addr, u64 size) {
  560. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  561. if (!addr || !size) {
  562. return;
  563. }
  564. texture_cache.FlushRegion(addr, size);
  565. buffer_cache.FlushRegion(addr, size);
  566. query_cache.FlushRegion(addr, size);
  567. }
  568. void RasterizerOpenGL::InvalidateRegion(CacheAddr addr, u64 size) {
  569. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  570. if (!addr || !size) {
  571. return;
  572. }
  573. texture_cache.InvalidateRegion(addr, size);
  574. shader_cache.InvalidateRegion(addr, size);
  575. buffer_cache.InvalidateRegion(addr, size);
  576. query_cache.InvalidateRegion(addr, size);
  577. }
  578. void RasterizerOpenGL::FlushAndInvalidateRegion(CacheAddr addr, u64 size) {
  579. if (Settings::values.use_accurate_gpu_emulation) {
  580. FlushRegion(addr, size);
  581. }
  582. InvalidateRegion(addr, size);
  583. }
  584. void RasterizerOpenGL::FlushCommands() {
  585. // Only flush when we have commands queued to OpenGL.
  586. if (num_queued_commands == 0) {
  587. return;
  588. }
  589. num_queued_commands = 0;
  590. glFlush();
  591. }
  592. void RasterizerOpenGL::TickFrame() {
  593. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  594. num_queued_commands = 0;
  595. buffer_cache.TickFrame();
  596. }
  597. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  598. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  599. const Tegra::Engines::Fermi2D::Config& copy_config) {
  600. MICROPROFILE_SCOPE(OpenGL_Blits);
  601. texture_cache.DoFermiCopy(src, dst, copy_config);
  602. return true;
  603. }
  604. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  605. VAddr framebuffer_addr, u32 pixel_stride) {
  606. if (!framebuffer_addr) {
  607. return {};
  608. }
  609. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  610. const auto surface{
  611. texture_cache.TryFindFramebufferSurface(system.Memory().GetPointer(framebuffer_addr))};
  612. if (!surface) {
  613. return {};
  614. }
  615. // Verify that the cached surface is the same size and format as the requested framebuffer
  616. const auto& params{surface->GetSurfaceParams()};
  617. const auto& pixel_format{
  618. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  619. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  620. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  621. if (params.pixel_format != pixel_format) {
  622. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  623. }
  624. screen_info.display_texture = surface->GetTexture();
  625. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  626. return true;
  627. }
  628. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, const Shader& shader) {
  629. MICROPROFILE_SCOPE(OpenGL_UBO);
  630. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  631. const auto& shader_stage = stages[stage_index];
  632. u32 binding = device.GetBaseBindings(stage_index).uniform_buffer;
  633. for (const auto& entry : shader->GetShaderEntries().const_buffers) {
  634. const auto& buffer = shader_stage.const_buffers[entry.GetIndex()];
  635. SetupConstBuffer(binding++, buffer, entry);
  636. }
  637. }
  638. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  639. MICROPROFILE_SCOPE(OpenGL_UBO);
  640. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  641. u32 binding = 0;
  642. for (const auto& entry : kernel->GetShaderEntries().const_buffers) {
  643. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  644. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  645. Tegra::Engines::ConstBufferInfo buffer;
  646. buffer.address = config.Address();
  647. buffer.size = config.size;
  648. buffer.enabled = mask[entry.GetIndex()];
  649. SetupConstBuffer(binding++, buffer, entry);
  650. }
  651. }
  652. void RasterizerOpenGL::SetupConstBuffer(u32 binding, const Tegra::Engines::ConstBufferInfo& buffer,
  653. const GLShader::ConstBufferEntry& entry) {
  654. if (!buffer.enabled) {
  655. // Set values to zero to unbind buffers
  656. bind_ubo_pushbuffer.Push(binding, buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  657. sizeof(float));
  658. return;
  659. }
  660. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  661. // UBO alignment requirements.
  662. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  663. const auto alignment = device.GetUniformBufferAlignment();
  664. const auto [cbuf, offset] = buffer_cache.UploadMemory(buffer.address, size, alignment, false,
  665. device.HasFastBufferSubData());
  666. bind_ubo_pushbuffer.Push(binding, cbuf, offset, size);
  667. }
  668. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, const Shader& shader) {
  669. auto& gpu{system.GPU()};
  670. auto& memory_manager{gpu.MemoryManager()};
  671. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage_index]};
  672. u32 binding = device.GetBaseBindings(stage_index).shader_storage_buffer;
  673. for (const auto& entry : shader->GetShaderEntries().global_memory_entries) {
  674. const auto addr{cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset()};
  675. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  676. const auto size{memory_manager.Read<u32>(addr + 8)};
  677. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  678. }
  679. }
  680. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  681. auto& gpu{system.GPU()};
  682. auto& memory_manager{gpu.MemoryManager()};
  683. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  684. u32 binding = 0;
  685. for (const auto& entry : kernel->GetShaderEntries().global_memory_entries) {
  686. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  687. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  688. const auto size{memory_manager.Read<u32>(addr + 8)};
  689. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  690. }
  691. }
  692. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GLShader::GlobalMemoryEntry& entry,
  693. GPUVAddr gpu_addr, std::size_t size) {
  694. const auto alignment{device.GetShaderStorageBufferAlignment()};
  695. const auto [ssbo, buffer_offset] =
  696. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.IsWritten());
  697. bind_ssbo_pushbuffer.Push(binding, ssbo, buffer_offset, static_cast<GLsizeiptr>(size));
  698. }
  699. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, const Shader& shader) {
  700. MICROPROFILE_SCOPE(OpenGL_Texture);
  701. const auto& maxwell3d = system.GPU().Maxwell3D();
  702. u32 binding = device.GetBaseBindings(stage_index).sampler;
  703. for (const auto& entry : shader->GetShaderEntries().samplers) {
  704. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  705. if (!entry.IsIndexed()) {
  706. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type);
  707. SetupTexture(binding++, texture, entry);
  708. } else {
  709. for (std::size_t i = 0; i < entry.Size(); ++i) {
  710. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  711. SetupTexture(binding++, texture, entry);
  712. }
  713. }
  714. }
  715. }
  716. void RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) {
  717. MICROPROFILE_SCOPE(OpenGL_Texture);
  718. const auto& compute = system.GPU().KeplerCompute();
  719. u32 binding = 0;
  720. for (const auto& entry : kernel->GetShaderEntries().samplers) {
  721. if (!entry.IsIndexed()) {
  722. const auto texture =
  723. GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute);
  724. SetupTexture(binding++, texture, entry);
  725. } else {
  726. for (std::size_t i = 0; i < entry.Size(); ++i) {
  727. const auto texture =
  728. GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute, i);
  729. SetupTexture(binding++, texture, entry);
  730. }
  731. }
  732. }
  733. }
  734. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  735. const GLShader::SamplerEntry& entry) {
  736. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  737. if (!view) {
  738. // Can occur when texture addr is null or its memory is unmapped/invalid
  739. state.samplers[binding] = 0;
  740. state.textures[binding] = 0;
  741. return;
  742. }
  743. state.textures[binding] = view->GetTexture();
  744. if (view->GetSurfaceParams().IsBuffer()) {
  745. return;
  746. }
  747. state.samplers[binding] = sampler_cache.GetSampler(texture.tsc);
  748. // Apply swizzle to textures that are not buffers.
  749. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  750. texture.tic.w_source);
  751. }
  752. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, const Shader& shader) {
  753. const auto& maxwell3d = system.GPU().Maxwell3D();
  754. u32 binding = device.GetBaseBindings(stage_index).image;
  755. for (const auto& entry : shader->GetShaderEntries().images) {
  756. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  757. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  758. SetupImage(binding++, tic, entry);
  759. }
  760. }
  761. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  762. const auto& compute = system.GPU().KeplerCompute();
  763. u32 binding = 0;
  764. for (const auto& entry : shader->GetShaderEntries().images) {
  765. const auto tic = GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute).tic;
  766. SetupImage(binding++, tic, entry);
  767. }
  768. }
  769. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  770. const GLShader::ImageEntry& entry) {
  771. const auto view = texture_cache.GetImageSurface(tic, entry);
  772. if (!view) {
  773. state.images[binding] = 0;
  774. return;
  775. }
  776. if (!tic.IsBuffer()) {
  777. view->ApplySwizzle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  778. }
  779. if (entry.IsWritten()) {
  780. view->MarkAsModified(texture_cache.Tick());
  781. }
  782. state.images[binding] = view->GetTexture();
  783. }
  784. void RasterizerOpenGL::SyncViewport() {
  785. const auto& regs = system.GPU().Maxwell3D().regs;
  786. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  787. const auto& src = regs.viewports[i];
  788. const Common::Rectangle<f32> rect{regs.viewport_transform[i].GetRect()};
  789. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  790. rect.GetHeight());
  791. glDepthRangef(src.depth_range_near, src.depth_range_far);
  792. }
  793. bool flip_y = false;
  794. if (regs.viewport_transform[0].scale_y < 0.0) {
  795. flip_y = !flip_y;
  796. }
  797. if (regs.screen_y_control.y_negate != 0) {
  798. flip_y = !flip_y;
  799. }
  800. state.clip_control.origin = flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT;
  801. state.clip_control.depth_mode =
  802. regs.depth_mode == Tegra::Engines::Maxwell3D::Regs::DepthMode::ZeroToOne
  803. ? GL_ZERO_TO_ONE
  804. : GL_NEGATIVE_ONE_TO_ONE;
  805. }
  806. void RasterizerOpenGL::SyncDepthClamp() {
  807. const auto& regs = system.GPU().Maxwell3D().regs;
  808. const auto& state = regs.view_volume_clip_control;
  809. UNIMPLEMENTED_IF_MSG(state.depth_clamp_far != state.depth_clamp_near,
  810. "Unimplemented Depth clamp separation!");
  811. oglEnable(GL_DEPTH_CLAMP, state.depth_clamp_far || state.depth_clamp_near);
  812. }
  813. void RasterizerOpenGL::SyncClipEnabled(
  814. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  815. const auto& regs = system.GPU().Maxwell3D().regs;
  816. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  817. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  818. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  819. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  820. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  821. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  822. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  823. }
  824. }
  825. void RasterizerOpenGL::SyncClipCoef() {
  826. UNIMPLEMENTED();
  827. }
  828. void RasterizerOpenGL::SyncCullMode() {
  829. const auto& regs = system.GPU().Maxwell3D().regs;
  830. oglEnable(GL_CULL_FACE, regs.cull.enabled);
  831. glCullFace(MaxwellToGL::CullFace(regs.cull.cull_face));
  832. glFrontFace(MaxwellToGL::FrontFace(regs.cull.front_face));
  833. }
  834. void RasterizerOpenGL::SyncPrimitiveRestart() {
  835. const auto& regs = system.GPU().Maxwell3D().regs;
  836. oglEnable(GL_PRIMITIVE_RESTART, regs.primitive_restart.enabled);
  837. glPrimitiveRestartIndex(regs.primitive_restart.index);
  838. }
  839. void RasterizerOpenGL::SyncDepthTestState() {
  840. const auto& regs = system.GPU().Maxwell3D().regs;
  841. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  842. oglEnable(GL_DEPTH_TEST, regs.depth_test_enable);
  843. if (regs.depth_test_enable) {
  844. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  845. }
  846. }
  847. void RasterizerOpenGL::SyncStencilTestState() {
  848. auto& maxwell3d = system.GPU().Maxwell3D();
  849. const auto& regs = maxwell3d.regs;
  850. state.stencil.test_enabled = regs.stencil_enable != 0;
  851. if (!regs.stencil_enable) {
  852. return;
  853. }
  854. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  855. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  856. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  857. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  858. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  859. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  860. state.stencil.front.write_mask = regs.stencil_front_mask;
  861. if (regs.stencil_two_side_enable) {
  862. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  863. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  864. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  865. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  866. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  867. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  868. state.stencil.back.write_mask = regs.stencil_back_mask;
  869. } else {
  870. state.stencil.back.test_func = GL_ALWAYS;
  871. state.stencil.back.test_ref = 0;
  872. state.stencil.back.test_mask = 0xFFFFFFFF;
  873. state.stencil.back.write_mask = 0xFFFFFFFF;
  874. state.stencil.back.action_stencil_fail = GL_KEEP;
  875. state.stencil.back.action_depth_fail = GL_KEEP;
  876. state.stencil.back.action_depth_pass = GL_KEEP;
  877. }
  878. }
  879. void RasterizerOpenGL::SyncRasterizeEnable() {
  880. const auto& regs = system.GPU().Maxwell3D().regs;
  881. oglEnable(GL_RASTERIZER_DISCARD, regs.rasterize_enable == 0);
  882. }
  883. void RasterizerOpenGL::SyncColorMask() {
  884. auto& maxwell3d = system.GPU().Maxwell3D();
  885. const auto& regs = maxwell3d.regs;
  886. if (regs.color_mask_common) {
  887. auto& mask = regs.color_mask[0];
  888. glColorMask(mask.R, mask.B, mask.G, mask.A);
  889. } else {
  890. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  891. const auto& mask = regs.color_mask[regs.color_mask_common ? 0 : i];
  892. glColorMaski(static_cast<GLuint>(i), mask.R, mask.G, mask.B, mask.A);
  893. }
  894. }
  895. }
  896. void RasterizerOpenGL::SyncMultiSampleState() {
  897. const auto& regs = system.GPU().Maxwell3D().regs;
  898. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  899. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  900. }
  901. void RasterizerOpenGL::SyncFragmentColorClampState() {
  902. const auto& regs = system.GPU().Maxwell3D().regs;
  903. glClampColor(GL_CLAMP_FRAGMENT_COLOR, regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  904. }
  905. void RasterizerOpenGL::SyncBlendState() {
  906. auto& maxwell3d = system.GPU().Maxwell3D();
  907. const auto& regs = maxwell3d.regs;
  908. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b, regs.blend_color.a);
  909. state.independant_blend.enabled = regs.independent_blend_enable;
  910. if (!state.independant_blend.enabled) {
  911. auto& blend = state.blend[0];
  912. const auto& src = regs.blend;
  913. blend.enabled = src.enable[0] != 0;
  914. if (blend.enabled) {
  915. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  916. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  917. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  918. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  919. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  920. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  921. }
  922. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  923. state.blend[i].enabled = false;
  924. }
  925. return;
  926. }
  927. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  928. auto& blend = state.blend[i];
  929. const auto& src = regs.independent_blend[i];
  930. blend.enabled = regs.blend.enable[i] != 0;
  931. if (!blend.enabled)
  932. continue;
  933. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  934. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  935. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  936. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  937. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  938. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  939. }
  940. }
  941. void RasterizerOpenGL::SyncLogicOpState() {
  942. const auto& regs = system.GPU().Maxwell3D().regs;
  943. oglEnable(GL_COLOR_LOGIC_OP, regs.logic_op.enable);
  944. if (regs.logic_op.enable) {
  945. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  946. }
  947. }
  948. void RasterizerOpenGL::SyncScissorTest() {
  949. const auto& regs = system.GPU().Maxwell3D().regs;
  950. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  951. const auto& src = regs.scissor_test[index];
  952. oglEnablei(GL_SCISSOR_TEST, src.enable, static_cast<GLuint>(index));
  953. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y, src.max_x - src.min_x,
  954. src.max_y - src.min_y);
  955. }
  956. }
  957. void RasterizerOpenGL::SyncTransformFeedback() {
  958. const auto& regs = system.GPU().Maxwell3D().regs;
  959. UNIMPLEMENTED_IF_MSG(regs.tfb_enabled != 0, "Transform feedbacks are not implemented");
  960. }
  961. void RasterizerOpenGL::SyncPointState() {
  962. const auto& regs = system.GPU().Maxwell3D().regs;
  963. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  964. // in OpenGL).
  965. oglEnable(GL_PROGRAM_POINT_SIZE, regs.vp_point_size.enable);
  966. oglEnable(GL_POINT_SPRITE, regs.point_sprite_enable);
  967. glPointSize(std::max(1.0f, regs.point_size));
  968. }
  969. void RasterizerOpenGL::SyncPolygonOffset() {
  970. auto& maxwell3d = system.GPU().Maxwell3D();
  971. const auto& regs = maxwell3d.regs;
  972. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  973. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  974. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  975. // Hardware divides polygon offset units by two
  976. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  977. regs.polygon_offset_clamp);
  978. }
  979. void RasterizerOpenGL::SyncAlphaTest() {
  980. const auto& regs = system.GPU().Maxwell3D().regs;
  981. UNIMPLEMENTED_IF_MSG(regs.alpha_test_enabled != 0 && regs.rt_control.count > 1,
  982. "Alpha Testing is enabled with more than one rendertarget");
  983. oglEnable(GL_ALPHA_TEST, regs.alpha_test_enabled);
  984. if (regs.alpha_test_enabled) {
  985. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  986. }
  987. }
  988. void RasterizerOpenGL::SyncFramebufferSRGB() {
  989. const auto& regs = system.GPU().Maxwell3D().regs;
  990. oglEnable(GL_FRAMEBUFFER_SRGB, regs.framebuffer_srgb);
  991. }
  992. } // namespace OpenGL