gl_rasterizer.cpp 50 KB

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