gl_rasterizer.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. // SPDX-FileCopyrightText: 2015 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <bitset>
  6. #include <memory>
  7. #include <string_view>
  8. #include <utility>
  9. #include <glad/glad.h>
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "common/math_util.h"
  13. #include "common/microprofile.h"
  14. #include "common/scope_exit.h"
  15. #include "common/settings.h"
  16. #include "video_core/control/channel_state.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/memory_manager.h"
  20. #include "video_core/renderer_opengl/gl_device.h"
  21. #include "video_core/renderer_opengl/gl_query_cache.h"
  22. #include "video_core/renderer_opengl/gl_rasterizer.h"
  23. #include "video_core/renderer_opengl/gl_shader_cache.h"
  24. #include "video_core/renderer_opengl/gl_staging_buffer_pool.h"
  25. #include "video_core/renderer_opengl/gl_texture_cache.h"
  26. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  27. #include "video_core/renderer_opengl/renderer_opengl.h"
  28. #include "video_core/shader_cache.h"
  29. #include "video_core/texture_cache/texture_cache_base.h"
  30. namespace OpenGL {
  31. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  32. using GLvec4 = std::array<GLfloat, 4>;
  33. using VideoCore::Surface::PixelFormat;
  34. using VideoCore::Surface::SurfaceTarget;
  35. using VideoCore::Surface::SurfaceType;
  36. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Clears, "OpenGL", "Clears", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Management", MP_RGB(100, 255, 100));
  40. namespace {
  41. constexpr size_t NUM_SUPPORTED_VERTEX_ATTRIBUTES = 16;
  42. void oglEnable(GLenum cap, bool state) {
  43. (state ? glEnable : glDisable)(cap);
  44. }
  45. } // Anonymous namespace
  46. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
  47. Core::Memory::Memory& cpu_memory_, const Device& device_,
  48. ScreenInfo& screen_info_, ProgramManager& program_manager_,
  49. StateTracker& state_tracker_)
  50. : RasterizerAccelerated(cpu_memory_), gpu(gpu_), device(device_), screen_info(screen_info_),
  51. program_manager(program_manager_), state_tracker(state_tracker_),
  52. texture_cache_runtime(device, program_manager, state_tracker, staging_buffer_pool),
  53. texture_cache(texture_cache_runtime, *this),
  54. buffer_cache_runtime(device, staging_buffer_pool),
  55. buffer_cache(*this, cpu_memory_, buffer_cache_runtime),
  56. shader_cache(*this, emu_window_, device, texture_cache, buffer_cache, program_manager,
  57. state_tracker, gpu.ShaderNotify()),
  58. query_cache(*this, cpu_memory_), accelerate_dma(buffer_cache, texture_cache),
  59. fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache),
  60. blit_image(program_manager_) {}
  61. RasterizerOpenGL::~RasterizerOpenGL() = default;
  62. void RasterizerOpenGL::SyncVertexFormats() {
  63. auto& flags = maxwell3d->dirty.flags;
  64. if (!flags[Dirty::VertexFormats]) {
  65. return;
  66. }
  67. flags[Dirty::VertexFormats] = false;
  68. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  69. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  70. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  71. // avoid OpenGL errors.
  72. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  73. // assume every shader uses them all.
  74. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  75. if (!flags[Dirty::VertexFormat0 + index]) {
  76. continue;
  77. }
  78. flags[Dirty::VertexFormat0 + index] = false;
  79. const auto& attrib = maxwell3d->regs.vertex_attrib_format[index];
  80. const auto gl_index = static_cast<GLuint>(index);
  81. // Disable constant attributes.
  82. if (attrib.constant) {
  83. glDisableVertexAttribArray(gl_index);
  84. continue;
  85. }
  86. glEnableVertexAttribArray(gl_index);
  87. if (attrib.type == Maxwell::VertexAttribute::Type::SInt ||
  88. attrib.type == Maxwell::VertexAttribute::Type::UInt) {
  89. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  90. MaxwellToGL::VertexFormat(attrib), attrib.offset);
  91. } else {
  92. glVertexAttribFormat(gl_index, attrib.ComponentCount(),
  93. MaxwellToGL::VertexFormat(attrib),
  94. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  95. }
  96. glVertexAttribBinding(gl_index, attrib.buffer);
  97. }
  98. }
  99. void RasterizerOpenGL::SyncVertexInstances() {
  100. auto& flags = maxwell3d->dirty.flags;
  101. if (!flags[Dirty::VertexInstances]) {
  102. return;
  103. }
  104. flags[Dirty::VertexInstances] = false;
  105. const auto& regs = maxwell3d->regs;
  106. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  107. if (!flags[Dirty::VertexInstance0 + index]) {
  108. continue;
  109. }
  110. flags[Dirty::VertexInstance0 + index] = false;
  111. const auto gl_index = static_cast<GLuint>(index);
  112. const bool instancing_enabled = regs.vertex_stream_instances.IsInstancingEnabled(gl_index);
  113. const GLuint divisor = instancing_enabled ? regs.vertex_streams[index].frequency : 0;
  114. glVertexBindingDivisor(gl_index, divisor);
  115. }
  116. }
  117. void RasterizerOpenGL::LoadDiskResources(u64 title_id, std::stop_token stop_loading,
  118. const VideoCore::DiskResourceLoadCallback& callback) {
  119. shader_cache.LoadDiskResources(title_id, stop_loading, callback);
  120. }
  121. void RasterizerOpenGL::Clear(u32 layer_count) {
  122. MICROPROFILE_SCOPE(OpenGL_Clears);
  123. gpu_memory->FlushCaching();
  124. const auto& regs = maxwell3d->regs;
  125. bool use_color{};
  126. bool use_depth{};
  127. bool use_stencil{};
  128. if (regs.clear_surface.R || regs.clear_surface.G || regs.clear_surface.B ||
  129. regs.clear_surface.A) {
  130. use_color = true;
  131. const GLuint index = regs.clear_surface.RT;
  132. state_tracker.NotifyColorMask(index);
  133. glColorMaski(index, regs.clear_surface.R != 0, regs.clear_surface.G != 0,
  134. regs.clear_surface.B != 0, regs.clear_surface.A != 0);
  135. // TODO(Rodrigo): Determine if clamping is used on clears
  136. SyncFragmentColorClampState();
  137. SyncFramebufferSRGB();
  138. }
  139. if (regs.clear_surface.Z) {
  140. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  141. use_depth = true;
  142. state_tracker.NotifyDepthMask();
  143. glDepthMask(GL_TRUE);
  144. }
  145. if (regs.clear_surface.S) {
  146. ASSERT_MSG(regs.zeta_enable, "Tried to clear stencil but buffer is not enabled!");
  147. use_stencil = true;
  148. }
  149. if (!use_color && !use_depth && !use_stencil) {
  150. // No color surface nor depth/stencil surface are enabled
  151. return;
  152. }
  153. SyncRasterizeEnable();
  154. SyncStencilTestState();
  155. std::scoped_lock lock{texture_cache.mutex};
  156. texture_cache.UpdateRenderTargets(true);
  157. state_tracker.BindFramebuffer(texture_cache.GetFramebuffer()->Handle());
  158. SyncViewport();
  159. if (regs.clear_control.use_scissor) {
  160. SyncScissorTest();
  161. } else {
  162. state_tracker.NotifyScissor0();
  163. glDisablei(GL_SCISSOR_TEST, 0);
  164. }
  165. UNIMPLEMENTED_IF(regs.clear_control.use_viewport_clip0);
  166. if (use_color) {
  167. glClearBufferfv(GL_COLOR, regs.clear_surface.RT, regs.clear_color.data());
  168. }
  169. if (use_depth && use_stencil) {
  170. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  171. } else if (use_depth) {
  172. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  173. } else if (use_stencil) {
  174. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  175. }
  176. ++num_queued_commands;
  177. }
  178. template <typename Func>
  179. void RasterizerOpenGL::PrepareDraw(bool is_indexed, Func&& draw_func) {
  180. MICROPROFILE_SCOPE(OpenGL_Drawing);
  181. SCOPE_EXIT({ gpu.TickWork(); });
  182. gpu_memory->FlushCaching();
  183. query_cache.UpdateCounters();
  184. GraphicsPipeline* const pipeline{shader_cache.CurrentGraphicsPipeline()};
  185. if (!pipeline) {
  186. return;
  187. }
  188. gpu.TickWork();
  189. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  190. pipeline->SetEngine(maxwell3d, gpu_memory);
  191. pipeline->Configure(is_indexed);
  192. SyncState();
  193. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  194. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(draw_state.topology);
  195. BeginTransformFeedback(pipeline, primitive_mode);
  196. draw_func(primitive_mode);
  197. EndTransformFeedback();
  198. ++num_queued_commands;
  199. has_written_global_memory |= pipeline->WritesGlobalMemory();
  200. }
  201. void RasterizerOpenGL::Draw(bool is_indexed, u32 instance_count) {
  202. PrepareDraw(is_indexed, [this, is_indexed, instance_count](GLenum primitive_mode) {
  203. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  204. const GLuint base_instance = static_cast<GLuint>(draw_state.base_instance);
  205. const GLsizei num_instances = static_cast<GLsizei>(instance_count);
  206. if (is_indexed) {
  207. const GLint base_vertex = static_cast<GLint>(draw_state.base_index);
  208. const GLsizei num_vertices = static_cast<GLsizei>(draw_state.index_buffer.count);
  209. const GLvoid* const offset = buffer_cache_runtime.IndexOffset();
  210. const GLenum format = MaxwellToGL::IndexFormat(draw_state.index_buffer.format);
  211. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  212. glDrawElements(primitive_mode, num_vertices, format, offset);
  213. } else if (num_instances == 1 && base_instance == 0) {
  214. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  215. } else if (base_vertex == 0 && base_instance == 0) {
  216. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset,
  217. num_instances);
  218. } else if (base_vertex == 0) {
  219. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  220. num_instances, base_instance);
  221. } else if (base_instance == 0) {
  222. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  223. num_instances, base_vertex);
  224. } else {
  225. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  226. offset, num_instances, base_vertex,
  227. base_instance);
  228. }
  229. } else {
  230. const GLint base_vertex = static_cast<GLint>(draw_state.vertex_buffer.first);
  231. const GLsizei num_vertices = static_cast<GLsizei>(draw_state.vertex_buffer.count);
  232. if (num_instances == 1 && base_instance == 0) {
  233. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  234. } else if (base_instance == 0) {
  235. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  236. } else {
  237. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  238. num_instances, base_instance);
  239. }
  240. }
  241. });
  242. }
  243. void RasterizerOpenGL::DrawIndirect() {
  244. const auto& params = maxwell3d->draw_manager->GetIndirectParams();
  245. buffer_cache.SetDrawIndirect(&params);
  246. PrepareDraw(params.is_indexed, [this, &params](GLenum primitive_mode) {
  247. const auto [buffer, offset] = buffer_cache.GetDrawIndirectBuffer();
  248. const GLvoid* const gl_offset =
  249. reinterpret_cast<const GLvoid*>(static_cast<uintptr_t>(offset));
  250. glBindBuffer(GL_DRAW_INDIRECT_BUFFER, buffer->Handle());
  251. if (params.include_count) {
  252. const auto [draw_buffer, offset_base] = buffer_cache.GetDrawIndirectCount();
  253. glBindBuffer(GL_PARAMETER_BUFFER, draw_buffer->Handle());
  254. if (params.is_indexed) {
  255. const GLenum format = MaxwellToGL::IndexFormat(maxwell3d->regs.index_buffer.format);
  256. glMultiDrawElementsIndirectCount(primitive_mode, format, gl_offset,
  257. static_cast<GLintptr>(offset_base),
  258. static_cast<GLsizei>(params.max_draw_counts),
  259. static_cast<GLsizei>(params.stride));
  260. } else {
  261. glMultiDrawArraysIndirectCount(primitive_mode, gl_offset,
  262. static_cast<GLintptr>(offset_base),
  263. static_cast<GLsizei>(params.max_draw_counts),
  264. static_cast<GLsizei>(params.stride));
  265. }
  266. return;
  267. }
  268. if (params.is_indexed) {
  269. const GLenum format = MaxwellToGL::IndexFormat(maxwell3d->regs.index_buffer.format);
  270. glMultiDrawElementsIndirect(primitive_mode, format, gl_offset,
  271. static_cast<GLsizei>(params.max_draw_counts),
  272. static_cast<GLsizei>(params.stride));
  273. } else {
  274. glMultiDrawArraysIndirect(primitive_mode, gl_offset,
  275. static_cast<GLsizei>(params.max_draw_counts),
  276. static_cast<GLsizei>(params.stride));
  277. }
  278. });
  279. buffer_cache.SetDrawIndirect(nullptr);
  280. }
  281. void RasterizerOpenGL::DrawTexture() {
  282. MICROPROFILE_SCOPE(OpenGL_Drawing);
  283. SCOPE_EXIT({ gpu.TickWork(); });
  284. query_cache.UpdateCounters();
  285. texture_cache.SynchronizeGraphicsDescriptors();
  286. texture_cache.UpdateRenderTargets(false);
  287. SyncState();
  288. const auto& draw_texture_state = maxwell3d->draw_manager->GetDrawTextureState();
  289. const auto& sampler = texture_cache.GetGraphicsSampler(draw_texture_state.src_sampler);
  290. const auto& texture = texture_cache.GetImageView(draw_texture_state.src_texture);
  291. if (device.HasDrawTexture()) {
  292. state_tracker.BindFramebuffer(texture_cache.GetFramebuffer()->Handle());
  293. glDrawTextureNV(texture.DefaultHandle(), sampler->Handle(), draw_texture_state.dst_x0,
  294. draw_texture_state.dst_y0, draw_texture_state.dst_x1,
  295. draw_texture_state.dst_y1, 0,
  296. draw_texture_state.src_x0 / static_cast<float>(texture.size.width),
  297. draw_texture_state.src_y0 / static_cast<float>(texture.size.height),
  298. draw_texture_state.src_x1 / static_cast<float>(texture.size.width),
  299. draw_texture_state.src_y1 / static_cast<float>(texture.size.height));
  300. } else {
  301. Region2D dst_region = {Offset2D{.x = static_cast<s32>(draw_texture_state.dst_x0),
  302. .y = static_cast<s32>(draw_texture_state.dst_y0)},
  303. Offset2D{.x = static_cast<s32>(draw_texture_state.dst_x1),
  304. .y = static_cast<s32>(draw_texture_state.dst_y1)}};
  305. Region2D src_region = {Offset2D{.x = static_cast<s32>(draw_texture_state.src_x0),
  306. .y = static_cast<s32>(draw_texture_state.src_y0)},
  307. Offset2D{.x = static_cast<s32>(draw_texture_state.src_x1),
  308. .y = static_cast<s32>(draw_texture_state.src_y1)}};
  309. blit_image.BlitColor(texture_cache.GetFramebuffer()->Handle(), texture.DefaultHandle(),
  310. sampler->Handle(), dst_region, src_region, texture.size);
  311. state_tracker.InvalidateState();
  312. }
  313. ++num_queued_commands;
  314. }
  315. void RasterizerOpenGL::DispatchCompute() {
  316. gpu_memory->FlushCaching();
  317. ComputePipeline* const pipeline{shader_cache.CurrentComputePipeline()};
  318. if (!pipeline) {
  319. return;
  320. }
  321. pipeline->SetEngine(kepler_compute, gpu_memory);
  322. pipeline->Configure();
  323. const auto& qmd{kepler_compute->launch_description};
  324. glDispatchCompute(qmd.grid_dim_x, qmd.grid_dim_y, qmd.grid_dim_z);
  325. ++num_queued_commands;
  326. has_written_global_memory |= pipeline->WritesGlobalMemory();
  327. }
  328. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  329. query_cache.ResetCounter(type);
  330. }
  331. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  332. std::optional<u64> timestamp) {
  333. query_cache.Query(gpu_addr, type, timestamp);
  334. }
  335. void RasterizerOpenGL::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  336. u32 size) {
  337. std::scoped_lock lock{buffer_cache.mutex};
  338. buffer_cache.BindGraphicsUniformBuffer(stage, index, gpu_addr, size);
  339. }
  340. void RasterizerOpenGL::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  341. buffer_cache.DisableGraphicsUniformBuffer(stage, index);
  342. }
  343. void RasterizerOpenGL::FlushAll() {}
  344. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  345. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  346. if (addr == 0 || size == 0) {
  347. return;
  348. }
  349. if (True(which & VideoCommon::CacheType::TextureCache)) {
  350. std::scoped_lock lock{texture_cache.mutex};
  351. texture_cache.DownloadMemory(addr, size);
  352. }
  353. if ((True(which & VideoCommon::CacheType::BufferCache))) {
  354. std::scoped_lock lock{buffer_cache.mutex};
  355. buffer_cache.DownloadMemory(addr, size);
  356. }
  357. if ((True(which & VideoCommon::CacheType::QueryCache))) {
  358. query_cache.FlushRegion(addr, size);
  359. }
  360. }
  361. bool RasterizerOpenGL::MustFlushRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  362. if ((True(which & VideoCommon::CacheType::BufferCache))) {
  363. std::scoped_lock lock{buffer_cache.mutex};
  364. if (buffer_cache.IsRegionGpuModified(addr, size)) {
  365. return true;
  366. }
  367. }
  368. if (!Settings::IsGPULevelHigh()) {
  369. return false;
  370. }
  371. if (True(which & VideoCommon::CacheType::TextureCache)) {
  372. std::scoped_lock lock{texture_cache.mutex};
  373. return texture_cache.IsRegionGpuModified(addr, size);
  374. }
  375. return false;
  376. }
  377. VideoCore::RasterizerDownloadArea RasterizerOpenGL::GetFlushArea(VAddr addr, u64 size) {
  378. {
  379. std::scoped_lock lock{texture_cache.mutex};
  380. auto area = texture_cache.GetFlushArea(addr, size);
  381. if (area) {
  382. return *area;
  383. }
  384. }
  385. {
  386. std::scoped_lock lock{buffer_cache.mutex};
  387. auto area = buffer_cache.GetFlushArea(addr, size);
  388. if (area) {
  389. return *area;
  390. }
  391. }
  392. VideoCore::RasterizerDownloadArea new_area{
  393. .start_address = Common::AlignDown(addr, Core::Memory::YUZU_PAGESIZE),
  394. .end_address = Common::AlignUp(addr + size, Core::Memory::YUZU_PAGESIZE),
  395. .preemtive = true,
  396. };
  397. return new_area;
  398. }
  399. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  400. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  401. if (addr == 0 || size == 0) {
  402. return;
  403. }
  404. if (True(which & VideoCommon::CacheType::TextureCache)) {
  405. std::scoped_lock lock{texture_cache.mutex};
  406. texture_cache.WriteMemory(addr, size);
  407. }
  408. if (True(which & VideoCommon::CacheType::BufferCache)) {
  409. std::scoped_lock lock{buffer_cache.mutex};
  410. buffer_cache.WriteMemory(addr, size);
  411. }
  412. if (True(which & VideoCommon::CacheType::ShaderCache)) {
  413. shader_cache.InvalidateRegion(addr, size);
  414. }
  415. if (True(which & VideoCommon::CacheType::QueryCache)) {
  416. query_cache.InvalidateRegion(addr, size);
  417. }
  418. }
  419. void RasterizerOpenGL::OnCPUWrite(VAddr addr, u64 size) {
  420. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  421. if (addr == 0 || size == 0) {
  422. return;
  423. }
  424. shader_cache.OnCPUWrite(addr, size);
  425. {
  426. std::scoped_lock lock{texture_cache.mutex};
  427. texture_cache.WriteMemory(addr, size);
  428. }
  429. {
  430. std::scoped_lock lock{buffer_cache.mutex};
  431. buffer_cache.CachedWriteMemory(addr, size);
  432. }
  433. }
  434. void RasterizerOpenGL::InvalidateGPUCache() {
  435. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  436. shader_cache.SyncGuestHost();
  437. {
  438. std::scoped_lock lock{buffer_cache.mutex};
  439. buffer_cache.FlushCachedWrites();
  440. }
  441. }
  442. void RasterizerOpenGL::UnmapMemory(VAddr addr, u64 size) {
  443. {
  444. std::scoped_lock lock{texture_cache.mutex};
  445. texture_cache.UnmapMemory(addr, size);
  446. }
  447. {
  448. std::scoped_lock lock{buffer_cache.mutex};
  449. buffer_cache.WriteMemory(addr, size);
  450. }
  451. shader_cache.OnCPUWrite(addr, size);
  452. }
  453. void RasterizerOpenGL::ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) {
  454. {
  455. std::scoped_lock lock{texture_cache.mutex};
  456. texture_cache.UnmapGPUMemory(as_id, addr, size);
  457. }
  458. }
  459. void RasterizerOpenGL::SignalFence(std::function<void()>&& func) {
  460. fence_manager.SignalFence(std::move(func));
  461. }
  462. void RasterizerOpenGL::SyncOperation(std::function<void()>&& func) {
  463. fence_manager.SyncOperation(std::move(func));
  464. }
  465. void RasterizerOpenGL::SignalSyncPoint(u32 value) {
  466. fence_manager.SignalSyncPoint(value);
  467. }
  468. void RasterizerOpenGL::SignalReference() {
  469. fence_manager.SignalOrdering();
  470. }
  471. void RasterizerOpenGL::ReleaseFences() {
  472. fence_manager.WaitPendingFences();
  473. }
  474. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size,
  475. VideoCommon::CacheType which) {
  476. if (Settings::IsGPULevelExtreme()) {
  477. FlushRegion(addr, size, which);
  478. }
  479. InvalidateRegion(addr, size, which);
  480. }
  481. void RasterizerOpenGL::WaitForIdle() {
  482. glMemoryBarrier(GL_ALL_BARRIER_BITS);
  483. SignalReference();
  484. }
  485. void RasterizerOpenGL::FragmentBarrier() {
  486. glTextureBarrier();
  487. glMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT);
  488. }
  489. void RasterizerOpenGL::TiledCacheBarrier() {
  490. glTextureBarrier();
  491. }
  492. void RasterizerOpenGL::FlushCommands() {
  493. // Only flush when we have commands queued to OpenGL.
  494. if (num_queued_commands == 0) {
  495. return;
  496. }
  497. num_queued_commands = 0;
  498. // Make sure memory stored from the previous GL command stream is visible
  499. // This is only needed on assembly shaders where we write to GPU memory with raw pointers
  500. if (has_written_global_memory) {
  501. has_written_global_memory = false;
  502. glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
  503. }
  504. glFlush();
  505. }
  506. void RasterizerOpenGL::TickFrame() {
  507. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  508. num_queued_commands = 0;
  509. fence_manager.TickFrame();
  510. {
  511. std::scoped_lock lock{texture_cache.mutex};
  512. texture_cache.TickFrame();
  513. }
  514. {
  515. std::scoped_lock lock{buffer_cache.mutex};
  516. buffer_cache.TickFrame();
  517. }
  518. }
  519. bool RasterizerOpenGL::AccelerateConditionalRendering() {
  520. gpu_memory->FlushCaching();
  521. if (Settings::IsGPULevelHigh()) {
  522. // Reimplement Host conditional rendering.
  523. return false;
  524. }
  525. // Medium / Low Hack: stub any checks on queries written into the buffer cache.
  526. const GPUVAddr condition_address{maxwell3d->regs.render_enable.Address()};
  527. Maxwell::ReportSemaphore::Compare cmp;
  528. if (gpu_memory->IsMemoryDirty(condition_address, sizeof(cmp),
  529. VideoCommon::CacheType::BufferCache)) {
  530. return true;
  531. }
  532. return false;
  533. }
  534. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
  535. const Tegra::Engines::Fermi2D::Surface& dst,
  536. const Tegra::Engines::Fermi2D::Config& copy_config) {
  537. MICROPROFILE_SCOPE(OpenGL_Blits);
  538. std::scoped_lock lock{texture_cache.mutex};
  539. return texture_cache.BlitImage(dst, src, copy_config);
  540. }
  541. Tegra::Engines::AccelerateDMAInterface& RasterizerOpenGL::AccessAccelerateDMA() {
  542. return accelerate_dma;
  543. }
  544. void RasterizerOpenGL::AccelerateInlineToMemory(GPUVAddr address, size_t copy_size,
  545. std::span<const u8> memory) {
  546. auto cpu_addr = gpu_memory->GpuToCpuAddress(address);
  547. if (!cpu_addr) [[unlikely]] {
  548. gpu_memory->WriteBlock(address, memory.data(), copy_size);
  549. return;
  550. }
  551. gpu_memory->WriteBlockUnsafe(address, memory.data(), copy_size);
  552. {
  553. std::unique_lock<std::recursive_mutex> lock{buffer_cache.mutex};
  554. if (!buffer_cache.InlineMemory(*cpu_addr, copy_size, memory)) {
  555. buffer_cache.WriteMemory(*cpu_addr, copy_size);
  556. }
  557. }
  558. {
  559. std::scoped_lock lock_texture{texture_cache.mutex};
  560. texture_cache.WriteMemory(*cpu_addr, copy_size);
  561. }
  562. shader_cache.InvalidateRegion(*cpu_addr, copy_size);
  563. query_cache.InvalidateRegion(*cpu_addr, copy_size);
  564. }
  565. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  566. VAddr framebuffer_addr, u32 pixel_stride) {
  567. if (framebuffer_addr == 0) {
  568. return false;
  569. }
  570. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  571. std::scoped_lock lock{texture_cache.mutex};
  572. ImageView* const image_view{texture_cache.TryFindFramebufferImageView(framebuffer_addr)};
  573. if (!image_view) {
  574. return false;
  575. }
  576. // Verify that the cached surface is the same size and format as the requested framebuffer
  577. // ASSERT_MSG(image_view->size.width == config.width, "Framebuffer width is different");
  578. // ASSERT_MSG(image_view->size.height == config.height, "Framebuffer height is different");
  579. screen_info.texture.width = image_view->size.width;
  580. screen_info.texture.height = image_view->size.height;
  581. screen_info.display_texture = image_view->Handle(Shader::TextureType::Color2D);
  582. screen_info.display_srgb = VideoCore::Surface::IsPixelFormatSRGB(image_view->format);
  583. return true;
  584. }
  585. void RasterizerOpenGL::SyncState() {
  586. SyncViewport();
  587. SyncRasterizeEnable();
  588. SyncPolygonModes();
  589. SyncColorMask();
  590. SyncFragmentColorClampState();
  591. SyncMultiSampleState();
  592. SyncDepthTestState();
  593. SyncDepthClamp();
  594. SyncStencilTestState();
  595. SyncBlendState();
  596. SyncLogicOpState();
  597. SyncCullMode();
  598. SyncPrimitiveRestart();
  599. SyncScissorTest();
  600. SyncPointState();
  601. SyncLineState();
  602. SyncPolygonOffset();
  603. SyncAlphaTest();
  604. SyncFramebufferSRGB();
  605. SyncVertexFormats();
  606. SyncVertexInstances();
  607. }
  608. void RasterizerOpenGL::SyncViewport() {
  609. auto& flags = maxwell3d->dirty.flags;
  610. const auto& regs = maxwell3d->regs;
  611. const bool rescale_viewports = flags[VideoCommon::Dirty::RescaleViewports];
  612. const bool dirty_viewport = flags[Dirty::Viewports] || rescale_viewports;
  613. const bool dirty_clip_control = flags[Dirty::ClipControl];
  614. if (dirty_viewport || dirty_clip_control || flags[Dirty::FrontFace]) {
  615. flags[Dirty::FrontFace] = false;
  616. GLenum mode = MaxwellToGL::FrontFace(regs.gl_front_face);
  617. bool flip_faces = true;
  618. if (regs.window_origin.flip_y != 0) {
  619. flip_faces = !flip_faces;
  620. }
  621. if (regs.viewport_transform[0].scale_y < 0.0f) {
  622. flip_faces = !flip_faces;
  623. }
  624. if (flip_faces) {
  625. switch (mode) {
  626. case GL_CW:
  627. mode = GL_CCW;
  628. break;
  629. case GL_CCW:
  630. mode = GL_CW;
  631. break;
  632. }
  633. }
  634. glFrontFace(mode);
  635. }
  636. if (dirty_viewport || dirty_clip_control) {
  637. flags[Dirty::ClipControl] = false;
  638. bool flip_y = false;
  639. if (regs.viewport_transform[0].scale_y < 0.0f) {
  640. flip_y = !flip_y;
  641. }
  642. const bool lower_left{regs.window_origin.mode != Maxwell::WindowOrigin::Mode::UpperLeft};
  643. if (lower_left) {
  644. flip_y = !flip_y;
  645. }
  646. const bool is_zero_to_one = regs.depth_mode == Maxwell::DepthMode::ZeroToOne;
  647. const GLenum origin = flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT;
  648. const GLenum depth = is_zero_to_one ? GL_ZERO_TO_ONE : GL_NEGATIVE_ONE_TO_ONE;
  649. state_tracker.ClipControl(origin, depth);
  650. state_tracker.SetYNegate(lower_left);
  651. }
  652. const bool is_rescaling{texture_cache.IsRescaling()};
  653. const float scale = is_rescaling ? Settings::values.resolution_info.up_factor : 1.0f;
  654. const auto conv = [scale](float value) -> GLfloat {
  655. float new_value = value * scale;
  656. if (scale < 1.0f) {
  657. const bool sign = std::signbit(value);
  658. new_value = std::round(std::abs(new_value));
  659. new_value = sign ? -new_value : new_value;
  660. }
  661. return static_cast<GLfloat>(new_value);
  662. };
  663. if (dirty_viewport) {
  664. flags[Dirty::Viewports] = false;
  665. const bool force = flags[Dirty::ViewportTransform] || rescale_viewports;
  666. flags[Dirty::ViewportTransform] = false;
  667. flags[VideoCommon::Dirty::RescaleViewports] = false;
  668. for (size_t index = 0; index < Maxwell::NumViewports; ++index) {
  669. if (!force && !flags[Dirty::Viewport0 + index]) {
  670. continue;
  671. }
  672. flags[Dirty::Viewport0 + index] = false;
  673. if (!regs.viewport_scale_offset_enabled) {
  674. const auto x = static_cast<GLfloat>(regs.surface_clip.x);
  675. const auto y = static_cast<GLfloat>(regs.surface_clip.y);
  676. const auto width = static_cast<GLfloat>(regs.surface_clip.width);
  677. const auto height = static_cast<GLfloat>(regs.surface_clip.height);
  678. glViewportIndexedf(static_cast<GLuint>(index), x, y, width != 0.0f ? width : 1.0f,
  679. height != 0.0f ? height : 1.0f);
  680. continue;
  681. }
  682. const auto& src = regs.viewport_transform[index];
  683. GLfloat x = conv(src.translate_x - src.scale_x);
  684. GLfloat y = conv(src.translate_y - src.scale_y);
  685. GLfloat width = conv(src.scale_x * 2.0f);
  686. GLfloat height = conv(src.scale_y * 2.0f);
  687. if (height < 0) {
  688. y += height;
  689. height = -height;
  690. }
  691. glViewportIndexedf(static_cast<GLuint>(index), x, y, width != 0.0f ? width : 1.0f,
  692. height != 0.0f ? height : 1.0f);
  693. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  694. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  695. const GLdouble far_depth = src.translate_z + src.scale_z;
  696. if (device.HasDepthBufferFloat()) {
  697. glDepthRangeIndexeddNV(static_cast<GLuint>(index), near_depth, far_depth);
  698. } else {
  699. glDepthRangeIndexed(static_cast<GLuint>(index), near_depth, far_depth);
  700. }
  701. if (!GLAD_GL_NV_viewport_swizzle) {
  702. continue;
  703. }
  704. glViewportSwizzleNV(static_cast<GLuint>(index),
  705. MaxwellToGL::ViewportSwizzle(src.swizzle.x),
  706. MaxwellToGL::ViewportSwizzle(src.swizzle.y),
  707. MaxwellToGL::ViewportSwizzle(src.swizzle.z),
  708. MaxwellToGL::ViewportSwizzle(src.swizzle.w));
  709. }
  710. }
  711. }
  712. void RasterizerOpenGL::SyncDepthClamp() {
  713. auto& flags = maxwell3d->dirty.flags;
  714. if (!flags[Dirty::DepthClampEnabled]) {
  715. return;
  716. }
  717. flags[Dirty::DepthClampEnabled] = false;
  718. bool depth_clamp_disabled{maxwell3d->regs.viewport_clip_control.geometry_clip ==
  719. Maxwell::ViewportClipControl::GeometryClip::Passthrough ||
  720. maxwell3d->regs.viewport_clip_control.geometry_clip ==
  721. Maxwell::ViewportClipControl::GeometryClip::FrustumXYZ ||
  722. maxwell3d->regs.viewport_clip_control.geometry_clip ==
  723. Maxwell::ViewportClipControl::GeometryClip::FrustumZ};
  724. oglEnable(GL_DEPTH_CLAMP, !depth_clamp_disabled);
  725. }
  726. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  727. auto& flags = maxwell3d->dirty.flags;
  728. if (!flags[Dirty::ClipDistances] && !flags[VideoCommon::Dirty::Shaders]) {
  729. return;
  730. }
  731. flags[Dirty::ClipDistances] = false;
  732. clip_mask &= maxwell3d->regs.user_clip_enable.raw;
  733. if (clip_mask == last_clip_distance_mask) {
  734. return;
  735. }
  736. last_clip_distance_mask = clip_mask;
  737. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  738. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  739. }
  740. }
  741. void RasterizerOpenGL::SyncClipCoef() {
  742. UNIMPLEMENTED();
  743. }
  744. void RasterizerOpenGL::SyncCullMode() {
  745. auto& flags = maxwell3d->dirty.flags;
  746. const auto& regs = maxwell3d->regs;
  747. if (flags[Dirty::CullTest]) {
  748. flags[Dirty::CullTest] = false;
  749. if (regs.gl_cull_test_enabled) {
  750. glEnable(GL_CULL_FACE);
  751. glCullFace(MaxwellToGL::CullFace(regs.gl_cull_face));
  752. } else {
  753. glDisable(GL_CULL_FACE);
  754. }
  755. }
  756. }
  757. void RasterizerOpenGL::SyncPrimitiveRestart() {
  758. auto& flags = maxwell3d->dirty.flags;
  759. if (!flags[Dirty::PrimitiveRestart]) {
  760. return;
  761. }
  762. flags[Dirty::PrimitiveRestart] = false;
  763. if (maxwell3d->regs.primitive_restart.enabled) {
  764. glEnable(GL_PRIMITIVE_RESTART);
  765. glPrimitiveRestartIndex(maxwell3d->regs.primitive_restart.index);
  766. } else {
  767. glDisable(GL_PRIMITIVE_RESTART);
  768. }
  769. }
  770. void RasterizerOpenGL::SyncDepthTestState() {
  771. auto& flags = maxwell3d->dirty.flags;
  772. const auto& regs = maxwell3d->regs;
  773. if (flags[Dirty::DepthMask]) {
  774. flags[Dirty::DepthMask] = false;
  775. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  776. }
  777. if (flags[Dirty::DepthTest]) {
  778. flags[Dirty::DepthTest] = false;
  779. if (regs.depth_test_enable) {
  780. glEnable(GL_DEPTH_TEST);
  781. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  782. } else {
  783. glDisable(GL_DEPTH_TEST);
  784. }
  785. }
  786. }
  787. void RasterizerOpenGL::SyncStencilTestState() {
  788. auto& flags = maxwell3d->dirty.flags;
  789. if (!flags[Dirty::StencilTest]) {
  790. return;
  791. }
  792. flags[Dirty::StencilTest] = false;
  793. const auto& regs = maxwell3d->regs;
  794. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  795. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_op.func),
  796. regs.stencil_front_ref, regs.stencil_front_func_mask);
  797. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op.fail),
  798. MaxwellToGL::StencilOp(regs.stencil_front_op.zfail),
  799. MaxwellToGL::StencilOp(regs.stencil_front_op.zpass));
  800. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  801. if (regs.stencil_two_side_enable) {
  802. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_op.func),
  803. regs.stencil_back_ref, regs.stencil_back_func_mask);
  804. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op.fail),
  805. MaxwellToGL::StencilOp(regs.stencil_back_op.zfail),
  806. MaxwellToGL::StencilOp(regs.stencil_back_op.zpass));
  807. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  808. } else {
  809. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  810. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  811. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  812. }
  813. }
  814. void RasterizerOpenGL::SyncRasterizeEnable() {
  815. auto& flags = maxwell3d->dirty.flags;
  816. if (!flags[Dirty::RasterizeEnable]) {
  817. return;
  818. }
  819. flags[Dirty::RasterizeEnable] = false;
  820. oglEnable(GL_RASTERIZER_DISCARD, maxwell3d->regs.rasterize_enable == 0);
  821. }
  822. void RasterizerOpenGL::SyncPolygonModes() {
  823. auto& flags = maxwell3d->dirty.flags;
  824. if (!flags[Dirty::PolygonModes]) {
  825. return;
  826. }
  827. flags[Dirty::PolygonModes] = false;
  828. const auto& regs = maxwell3d->regs;
  829. if (regs.fill_via_triangle_mode != Maxwell::FillViaTriangleMode::Disabled) {
  830. if (!GLAD_GL_NV_fill_rectangle) {
  831. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  832. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  833. return;
  834. }
  835. flags[Dirty::PolygonModeFront] = true;
  836. flags[Dirty::PolygonModeBack] = true;
  837. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  838. return;
  839. }
  840. if (regs.polygon_mode_front == regs.polygon_mode_back) {
  841. flags[Dirty::PolygonModeFront] = false;
  842. flags[Dirty::PolygonModeBack] = false;
  843. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  844. return;
  845. }
  846. if (flags[Dirty::PolygonModeFront]) {
  847. flags[Dirty::PolygonModeFront] = false;
  848. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  849. }
  850. if (flags[Dirty::PolygonModeBack]) {
  851. flags[Dirty::PolygonModeBack] = false;
  852. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_back));
  853. }
  854. }
  855. void RasterizerOpenGL::SyncColorMask() {
  856. auto& flags = maxwell3d->dirty.flags;
  857. if (!flags[Dirty::ColorMasks]) {
  858. return;
  859. }
  860. flags[Dirty::ColorMasks] = false;
  861. const bool force = flags[Dirty::ColorMaskCommon];
  862. flags[Dirty::ColorMaskCommon] = false;
  863. const auto& regs = maxwell3d->regs;
  864. if (regs.color_mask_common) {
  865. if (!force && !flags[Dirty::ColorMask0]) {
  866. return;
  867. }
  868. flags[Dirty::ColorMask0] = false;
  869. auto& mask = regs.color_mask[0];
  870. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  871. return;
  872. }
  873. // Path without color_mask_common set
  874. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  875. if (!force && !flags[Dirty::ColorMask0 + i]) {
  876. continue;
  877. }
  878. flags[Dirty::ColorMask0 + i] = false;
  879. const auto& mask = regs.color_mask[i];
  880. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  881. }
  882. }
  883. void RasterizerOpenGL::SyncMultiSampleState() {
  884. auto& flags = maxwell3d->dirty.flags;
  885. if (!flags[Dirty::MultisampleControl]) {
  886. return;
  887. }
  888. flags[Dirty::MultisampleControl] = false;
  889. const auto& regs = maxwell3d->regs;
  890. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.anti_alias_alpha_control.alpha_to_coverage);
  891. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.anti_alias_alpha_control.alpha_to_one);
  892. }
  893. void RasterizerOpenGL::SyncFragmentColorClampState() {
  894. auto& flags = maxwell3d->dirty.flags;
  895. if (!flags[Dirty::FragmentClampColor]) {
  896. return;
  897. }
  898. flags[Dirty::FragmentClampColor] = false;
  899. glClampColor(GL_CLAMP_FRAGMENT_COLOR,
  900. maxwell3d->regs.frag_color_clamp.AnyEnabled() ? GL_TRUE : GL_FALSE);
  901. }
  902. void RasterizerOpenGL::SyncBlendState() {
  903. auto& flags = maxwell3d->dirty.flags;
  904. const auto& regs = maxwell3d->regs;
  905. if (flags[Dirty::BlendColor]) {
  906. flags[Dirty::BlendColor] = false;
  907. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  908. regs.blend_color.a);
  909. }
  910. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  911. if (!flags[Dirty::BlendStates]) {
  912. return;
  913. }
  914. flags[Dirty::BlendStates] = false;
  915. if (!regs.blend_per_target_enabled) {
  916. if (!regs.blend.enable[0]) {
  917. glDisable(GL_BLEND);
  918. return;
  919. }
  920. glEnable(GL_BLEND);
  921. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.color_source),
  922. MaxwellToGL::BlendFunc(regs.blend.color_dest),
  923. MaxwellToGL::BlendFunc(regs.blend.alpha_source),
  924. MaxwellToGL::BlendFunc(regs.blend.alpha_dest));
  925. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.color_op),
  926. MaxwellToGL::BlendEquation(regs.blend.alpha_op));
  927. return;
  928. }
  929. const bool force = flags[Dirty::BlendIndependentEnabled];
  930. flags[Dirty::BlendIndependentEnabled] = false;
  931. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  932. if (!force && !flags[Dirty::BlendState0 + i]) {
  933. continue;
  934. }
  935. flags[Dirty::BlendState0 + i] = false;
  936. if (!regs.blend.enable[i]) {
  937. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  938. continue;
  939. }
  940. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  941. const auto& src = regs.blend_per_target[i];
  942. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.color_source),
  943. MaxwellToGL::BlendFunc(src.color_dest),
  944. MaxwellToGL::BlendFunc(src.alpha_source),
  945. MaxwellToGL::BlendFunc(src.alpha_dest));
  946. glBlendEquationSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendEquation(src.color_op),
  947. MaxwellToGL::BlendEquation(src.alpha_op));
  948. }
  949. }
  950. void RasterizerOpenGL::SyncLogicOpState() {
  951. auto& flags = maxwell3d->dirty.flags;
  952. if (!flags[Dirty::LogicOp]) {
  953. return;
  954. }
  955. flags[Dirty::LogicOp] = false;
  956. const auto& regs = maxwell3d->regs;
  957. if (regs.logic_op.enable) {
  958. glEnable(GL_COLOR_LOGIC_OP);
  959. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.op));
  960. } else {
  961. glDisable(GL_COLOR_LOGIC_OP);
  962. }
  963. }
  964. void RasterizerOpenGL::SyncScissorTest() {
  965. auto& flags = maxwell3d->dirty.flags;
  966. if (!flags[Dirty::Scissors] && !flags[VideoCommon::Dirty::RescaleScissors]) {
  967. return;
  968. }
  969. flags[Dirty::Scissors] = false;
  970. const bool force = flags[VideoCommon::Dirty::RescaleScissors];
  971. flags[VideoCommon::Dirty::RescaleScissors] = false;
  972. const auto& regs = maxwell3d->regs;
  973. const auto& resolution = Settings::values.resolution_info;
  974. const bool is_rescaling{texture_cache.IsRescaling()};
  975. const u32 up_scale = is_rescaling ? resolution.up_scale : 1U;
  976. const u32 down_shift = is_rescaling ? resolution.down_shift : 0U;
  977. const auto scale_up = [up_scale, down_shift](u32 value) -> u32 {
  978. if (value == 0) {
  979. return 0U;
  980. }
  981. const u32 upset = value * up_scale;
  982. u32 acumm{};
  983. if ((up_scale >> down_shift) == 0) {
  984. acumm = upset % 2;
  985. }
  986. const u32 converted_value = upset >> down_shift;
  987. return std::max<u32>(converted_value + acumm, 1U);
  988. };
  989. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  990. if (!force && !flags[Dirty::Scissor0 + index]) {
  991. continue;
  992. }
  993. flags[Dirty::Scissor0 + index] = false;
  994. const auto& src = regs.scissor_test[index];
  995. if (src.enable) {
  996. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  997. glScissorIndexed(static_cast<GLuint>(index), scale_up(src.min_x), scale_up(src.min_y),
  998. scale_up(src.max_x - src.min_x), scale_up(src.max_y - src.min_y));
  999. } else {
  1000. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1001. }
  1002. }
  1003. }
  1004. void RasterizerOpenGL::SyncPointState() {
  1005. auto& flags = maxwell3d->dirty.flags;
  1006. if (!flags[Dirty::PointSize]) {
  1007. return;
  1008. }
  1009. flags[Dirty::PointSize] = false;
  1010. oglEnable(GL_POINT_SPRITE, maxwell3d->regs.point_sprite_enable);
  1011. oglEnable(GL_PROGRAM_POINT_SIZE, maxwell3d->regs.point_size_attribute.enabled);
  1012. const bool is_rescaling{texture_cache.IsRescaling()};
  1013. const float scale = is_rescaling ? Settings::values.resolution_info.up_factor : 1.0f;
  1014. glPointSize(std::max(1.0f, maxwell3d->regs.point_size * scale));
  1015. }
  1016. void RasterizerOpenGL::SyncLineState() {
  1017. auto& flags = maxwell3d->dirty.flags;
  1018. if (!flags[Dirty::LineWidth]) {
  1019. return;
  1020. }
  1021. flags[Dirty::LineWidth] = false;
  1022. const auto& regs = maxwell3d->regs;
  1023. oglEnable(GL_LINE_SMOOTH, regs.line_anti_alias_enable);
  1024. glLineWidth(regs.line_anti_alias_enable ? regs.line_width_smooth : regs.line_width_aliased);
  1025. }
  1026. void RasterizerOpenGL::SyncPolygonOffset() {
  1027. auto& flags = maxwell3d->dirty.flags;
  1028. if (!flags[Dirty::PolygonOffset]) {
  1029. return;
  1030. }
  1031. flags[Dirty::PolygonOffset] = false;
  1032. const auto& regs = maxwell3d->regs;
  1033. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  1034. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  1035. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  1036. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  1037. regs.polygon_offset_point_enable) {
  1038. // Hardware divides polygon offset units by two
  1039. glPolygonOffsetClamp(regs.slope_scale_depth_bias, regs.depth_bias / 2.0f,
  1040. regs.depth_bias_clamp);
  1041. }
  1042. }
  1043. void RasterizerOpenGL::SyncAlphaTest() {
  1044. auto& flags = maxwell3d->dirty.flags;
  1045. if (!flags[Dirty::AlphaTest]) {
  1046. return;
  1047. }
  1048. flags[Dirty::AlphaTest] = false;
  1049. const auto& regs = maxwell3d->regs;
  1050. if (regs.alpha_test_enabled) {
  1051. glEnable(GL_ALPHA_TEST);
  1052. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  1053. } else {
  1054. glDisable(GL_ALPHA_TEST);
  1055. }
  1056. }
  1057. void RasterizerOpenGL::SyncFramebufferSRGB() {
  1058. auto& flags = maxwell3d->dirty.flags;
  1059. if (!flags[Dirty::FramebufferSRGB]) {
  1060. return;
  1061. }
  1062. flags[Dirty::FramebufferSRGB] = false;
  1063. oglEnable(GL_FRAMEBUFFER_SRGB, maxwell3d->regs.framebuffer_srgb);
  1064. }
  1065. void RasterizerOpenGL::BeginTransformFeedback(GraphicsPipeline* program, GLenum primitive_mode) {
  1066. const auto& regs = maxwell3d->regs;
  1067. if (regs.transform_feedback_enabled == 0) {
  1068. return;
  1069. }
  1070. program->ConfigureTransformFeedback();
  1071. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderType::TessellationInit) ||
  1072. regs.IsShaderConfigEnabled(Maxwell::ShaderType::Tessellation) ||
  1073. regs.IsShaderConfigEnabled(Maxwell::ShaderType::Geometry));
  1074. UNIMPLEMENTED_IF(primitive_mode != GL_POINTS);
  1075. // We may have to call BeginTransformFeedbackNV here since they seem to call different
  1076. // implementations on Nvidia's driver (the pointer is different) but we are using
  1077. // ARB_transform_feedback3 features with NV_transform_feedback interactions and the ARB
  1078. // extension doesn't define BeginTransformFeedback (without NV) interactions. It just works.
  1079. glBeginTransformFeedback(GL_POINTS);
  1080. }
  1081. void RasterizerOpenGL::EndTransformFeedback() {
  1082. if (maxwell3d->regs.transform_feedback_enabled != 0) {
  1083. glEndTransformFeedback();
  1084. }
  1085. }
  1086. void RasterizerOpenGL::InitializeChannel(Tegra::Control::ChannelState& channel) {
  1087. CreateChannel(channel);
  1088. {
  1089. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1090. texture_cache.CreateChannel(channel);
  1091. buffer_cache.CreateChannel(channel);
  1092. }
  1093. shader_cache.CreateChannel(channel);
  1094. query_cache.CreateChannel(channel);
  1095. state_tracker.SetupTables(channel);
  1096. }
  1097. void RasterizerOpenGL::BindChannel(Tegra::Control::ChannelState& channel) {
  1098. const s32 channel_id = channel.bind_id;
  1099. BindToChannel(channel_id);
  1100. {
  1101. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1102. texture_cache.BindToChannel(channel_id);
  1103. buffer_cache.BindToChannel(channel_id);
  1104. }
  1105. shader_cache.BindToChannel(channel_id);
  1106. query_cache.BindToChannel(channel_id);
  1107. state_tracker.ChangeChannel(channel);
  1108. state_tracker.InvalidateState();
  1109. }
  1110. void RasterizerOpenGL::ReleaseChannel(s32 channel_id) {
  1111. EraseChannel(channel_id);
  1112. {
  1113. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1114. texture_cache.EraseChannel(channel_id);
  1115. buffer_cache.EraseChannel(channel_id);
  1116. }
  1117. shader_cache.EraseChannel(channel_id);
  1118. query_cache.EraseChannel(channel_id);
  1119. }
  1120. AccelerateDMA::AccelerateDMA(BufferCache& buffer_cache_, TextureCache& texture_cache_)
  1121. : buffer_cache{buffer_cache_}, texture_cache{texture_cache_} {}
  1122. bool AccelerateDMA::BufferCopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  1123. std::scoped_lock lock{buffer_cache.mutex};
  1124. return buffer_cache.DMACopy(src_address, dest_address, amount);
  1125. }
  1126. bool AccelerateDMA::BufferClear(GPUVAddr src_address, u64 amount, u32 value) {
  1127. std::scoped_lock lock{buffer_cache.mutex};
  1128. return buffer_cache.DMAClear(src_address, amount, value);
  1129. }
  1130. template <bool IS_IMAGE_UPLOAD>
  1131. bool AccelerateDMA::DmaBufferImageCopy(const Tegra::DMA::ImageCopy& copy_info,
  1132. const Tegra::DMA::BufferOperand& buffer_operand,
  1133. const Tegra::DMA::ImageOperand& image_operand) {
  1134. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1135. const auto image_id = texture_cache.DmaImageId(image_operand, IS_IMAGE_UPLOAD);
  1136. if (image_id == VideoCommon::NULL_IMAGE_ID) {
  1137. return false;
  1138. }
  1139. const u32 buffer_size = static_cast<u32>(buffer_operand.pitch * buffer_operand.height);
  1140. static constexpr auto sync_info = VideoCommon::ObtainBufferSynchronize::FullSynchronize;
  1141. const auto post_op = VideoCommon::ObtainBufferOperation::DoNothing;
  1142. const auto [buffer, offset] =
  1143. buffer_cache.ObtainBuffer(buffer_operand.address, buffer_size, sync_info, post_op);
  1144. const auto [image, copy] = texture_cache.DmaBufferImageCopy(
  1145. copy_info, buffer_operand, image_operand, image_id, IS_IMAGE_UPLOAD);
  1146. const std::span copy_span{&copy, 1};
  1147. if constexpr (IS_IMAGE_UPLOAD) {
  1148. image->UploadMemory(buffer->Handle(), offset, copy_span);
  1149. } else {
  1150. texture_cache.DownloadImageIntoBuffer(image, buffer->Handle(), offset, copy_span,
  1151. buffer_operand.address, buffer_size);
  1152. }
  1153. return true;
  1154. }
  1155. bool AccelerateDMA::ImageToBuffer(const Tegra::DMA::ImageCopy& copy_info,
  1156. const Tegra::DMA::ImageOperand& image_operand,
  1157. const Tegra::DMA::BufferOperand& buffer_operand) {
  1158. return DmaBufferImageCopy<false>(copy_info, buffer_operand, image_operand);
  1159. }
  1160. bool AccelerateDMA::BufferToImage(const Tegra::DMA::ImageCopy& copy_info,
  1161. const Tegra::DMA::BufferOperand& buffer_operand,
  1162. const Tegra::DMA::ImageOperand& image_operand) {
  1163. return DmaBufferImageCopy<true>(copy_info, buffer_operand, image_operand);
  1164. }
  1165. } // namespace OpenGL