gl_rasterizer.cpp 48 KB

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