renderer_opengl.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <cstdlib>
  7. #include <memory>
  8. #include <glad/glad.h>
  9. #include "common/assert.h"
  10. #include "common/logging/log.h"
  11. #include "common/microprofile.h"
  12. #include "common/telemetry.h"
  13. #include "core/core.h"
  14. #include "core/core_timing.h"
  15. #include "core/frontend/emu_window.h"
  16. #include "core/memory.h"
  17. #include "core/perf_stats.h"
  18. #include "core/settings.h"
  19. #include "core/telemetry_session.h"
  20. #include "video_core/morton.h"
  21. #include "video_core/renderer_opengl/gl_rasterizer.h"
  22. #include "video_core/renderer_opengl/gl_shader_manager.h"
  23. #include "video_core/renderer_opengl/renderer_opengl.h"
  24. namespace OpenGL {
  25. // If the size of this is too small, it ends up creating a soft cap on FPS as the renderer will have
  26. // to wait on available presentation frames.
  27. constexpr std::size_t SWAP_CHAIN_SIZE = 3;
  28. struct Frame {
  29. u32 width{}; /// Width of the frame (to detect resize)
  30. u32 height{}; /// Height of the frame
  31. bool color_reloaded{}; /// Texture attachment was recreated (ie: resized)
  32. OpenGL::OGLRenderbuffer color{}; /// Buffer shared between the render/present FBO
  33. OpenGL::OGLFramebuffer render{}; /// FBO created on the render thread
  34. OpenGL::OGLFramebuffer present{}; /// FBO created on the present thread
  35. GLsync render_fence{}; /// Fence created on the render thread
  36. GLsync present_fence{}; /// Fence created on the presentation thread
  37. bool is_srgb{}; /// Framebuffer is sRGB or RGB
  38. };
  39. /**
  40. * For smooth Vsync rendering, we want to always present the latest frame that the core generates,
  41. * but also make sure that rendering happens at the pace that the frontend dictates. This is a
  42. * helper class that the renderer uses to sync frames between the render thread and the presentation
  43. * thread
  44. */
  45. class FrameMailbox {
  46. public:
  47. std::mutex swap_chain_lock;
  48. std::condition_variable present_cv;
  49. std::array<Frame, SWAP_CHAIN_SIZE> swap_chain{};
  50. std::queue<Frame*> free_queue;
  51. std::deque<Frame*> present_queue;
  52. Frame* previous_frame{};
  53. FrameMailbox() {
  54. for (auto& frame : swap_chain) {
  55. free_queue.push(&frame);
  56. }
  57. }
  58. ~FrameMailbox() {
  59. // lock the mutex and clear out the present and free_queues and notify any people who are
  60. // blocked to prevent deadlock on shutdown
  61. std::scoped_lock lock{swap_chain_lock};
  62. std::queue<Frame*>().swap(free_queue);
  63. present_queue.clear();
  64. present_cv.notify_all();
  65. }
  66. void ReloadPresentFrame(Frame* frame, u32 height, u32 width) {
  67. frame->present.Release();
  68. frame->present.Create();
  69. GLint previous_draw_fbo{};
  70. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous_draw_fbo);
  71. glBindFramebuffer(GL_FRAMEBUFFER, frame->present.handle);
  72. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
  73. frame->color.handle);
  74. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
  75. LOG_CRITICAL(Render_OpenGL, "Failed to recreate present FBO!");
  76. }
  77. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previous_draw_fbo);
  78. frame->color_reloaded = false;
  79. }
  80. void ReloadRenderFrame(Frame* frame, u32 width, u32 height) {
  81. // Recreate the color texture attachment
  82. frame->color.Release();
  83. frame->color.Create();
  84. const GLenum internal_format = frame->is_srgb ? GL_SRGB8 : GL_RGB8;
  85. glNamedRenderbufferStorage(frame->color.handle, internal_format, width, height);
  86. // Recreate the FBO for the render target
  87. frame->render.Release();
  88. frame->render.Create();
  89. glBindFramebuffer(GL_FRAMEBUFFER, frame->render.handle);
  90. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
  91. frame->color.handle);
  92. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
  93. LOG_CRITICAL(Render_OpenGL, "Failed to recreate render FBO!");
  94. }
  95. frame->width = width;
  96. frame->height = height;
  97. frame->color_reloaded = true;
  98. }
  99. Frame* GetRenderFrame() {
  100. std::unique_lock lock{swap_chain_lock};
  101. // If theres no free frames, we will reuse the oldest render frame
  102. if (free_queue.empty()) {
  103. auto frame = present_queue.back();
  104. present_queue.pop_back();
  105. return frame;
  106. }
  107. Frame* frame = free_queue.front();
  108. free_queue.pop();
  109. return frame;
  110. }
  111. void ReleaseRenderFrame(Frame* frame) {
  112. std::unique_lock lock{swap_chain_lock};
  113. present_queue.push_front(frame);
  114. present_cv.notify_one();
  115. }
  116. Frame* TryGetPresentFrame(int timeout_ms) {
  117. std::unique_lock lock{swap_chain_lock};
  118. // wait for new entries in the present_queue
  119. present_cv.wait_for(lock, std::chrono::milliseconds(timeout_ms),
  120. [&] { return !present_queue.empty(); });
  121. if (present_queue.empty()) {
  122. // timed out waiting for a frame to draw so return the previous frame
  123. return previous_frame;
  124. }
  125. // free the previous frame and add it back to the free queue
  126. if (previous_frame) {
  127. free_queue.push(previous_frame);
  128. }
  129. // the newest entries are pushed to the front of the queue
  130. Frame* frame = present_queue.front();
  131. present_queue.pop_front();
  132. // remove all old entries from the present queue and move them back to the free_queue
  133. for (auto f : present_queue) {
  134. free_queue.push(f);
  135. }
  136. present_queue.clear();
  137. previous_frame = frame;
  138. return frame;
  139. }
  140. };
  141. namespace {
  142. constexpr char VERTEX_SHADER[] = R"(
  143. #version 430 core
  144. out gl_PerVertex {
  145. vec4 gl_Position;
  146. };
  147. layout (location = 0) in vec2 vert_position;
  148. layout (location = 1) in vec2 vert_tex_coord;
  149. layout (location = 0) out vec2 frag_tex_coord;
  150. // This is a truncated 3x3 matrix for 2D transformations:
  151. // The upper-left 2x2 submatrix performs scaling/rotation/mirroring.
  152. // The third column performs translation.
  153. // The third row could be used for projection, which we don't need in 2D. It hence is assumed to
  154. // implicitly be [0, 0, 1]
  155. layout (location = 0) uniform mat3x2 modelview_matrix;
  156. void main() {
  157. // Multiply input position by the rotscale part of the matrix and then manually translate by
  158. // the last column. This is equivalent to using a full 3x3 matrix and expanding the vector
  159. // to `vec3(vert_position.xy, 1.0)`
  160. gl_Position = vec4(mat2(modelview_matrix) * vert_position + modelview_matrix[2], 0.0, 1.0);
  161. frag_tex_coord = vert_tex_coord;
  162. }
  163. )";
  164. constexpr char FRAGMENT_SHADER[] = R"(
  165. #version 430 core
  166. layout (location = 0) in vec2 frag_tex_coord;
  167. layout (location = 0) out vec4 color;
  168. layout (binding = 0) uniform sampler2D color_texture;
  169. void main() {
  170. color = vec4(texture(color_texture, frag_tex_coord).rgb, 1.0f);
  171. }
  172. )";
  173. constexpr GLint PositionLocation = 0;
  174. constexpr GLint TexCoordLocation = 1;
  175. constexpr GLint ModelViewMatrixLocation = 0;
  176. struct ScreenRectVertex {
  177. constexpr ScreenRectVertex(u32 x, u32 y, GLfloat u, GLfloat v)
  178. : position{{static_cast<GLfloat>(x), static_cast<GLfloat>(y)}}, tex_coord{{u, v}} {}
  179. std::array<GLfloat, 2> position;
  180. std::array<GLfloat, 2> tex_coord;
  181. };
  182. /**
  183. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  184. * corner and (width, height) on the lower-bottom.
  185. *
  186. * The projection part of the matrix is trivial, hence these operations are represented
  187. * by a 3x2 matrix.
  188. */
  189. std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(float width, float height) {
  190. std::array<GLfloat, 3 * 2> matrix; // Laid out in column-major order
  191. // clang-format off
  192. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  193. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  194. // Last matrix row is implicitly assumed to be [0, 0, 1].
  195. // clang-format on
  196. return matrix;
  197. }
  198. const char* GetSource(GLenum source) {
  199. switch (source) {
  200. case GL_DEBUG_SOURCE_API:
  201. return "API";
  202. case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
  203. return "WINDOW_SYSTEM";
  204. case GL_DEBUG_SOURCE_SHADER_COMPILER:
  205. return "SHADER_COMPILER";
  206. case GL_DEBUG_SOURCE_THIRD_PARTY:
  207. return "THIRD_PARTY";
  208. case GL_DEBUG_SOURCE_APPLICATION:
  209. return "APPLICATION";
  210. case GL_DEBUG_SOURCE_OTHER:
  211. return "OTHER";
  212. default:
  213. UNREACHABLE();
  214. return "Unknown source";
  215. }
  216. }
  217. const char* GetType(GLenum type) {
  218. switch (type) {
  219. case GL_DEBUG_TYPE_ERROR:
  220. return "ERROR";
  221. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
  222. return "DEPRECATED_BEHAVIOR";
  223. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
  224. return "UNDEFINED_BEHAVIOR";
  225. case GL_DEBUG_TYPE_PORTABILITY:
  226. return "PORTABILITY";
  227. case GL_DEBUG_TYPE_PERFORMANCE:
  228. return "PERFORMANCE";
  229. case GL_DEBUG_TYPE_OTHER:
  230. return "OTHER";
  231. case GL_DEBUG_TYPE_MARKER:
  232. return "MARKER";
  233. default:
  234. UNREACHABLE();
  235. return "Unknown type";
  236. }
  237. }
  238. void APIENTRY DebugHandler(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  239. const GLchar* message, const void* user_param) {
  240. const char format[] = "{} {} {}: {}";
  241. const char* const str_source = GetSource(source);
  242. const char* const str_type = GetType(type);
  243. switch (severity) {
  244. case GL_DEBUG_SEVERITY_HIGH:
  245. LOG_CRITICAL(Render_OpenGL, format, str_source, str_type, id, message);
  246. break;
  247. case GL_DEBUG_SEVERITY_MEDIUM:
  248. LOG_WARNING(Render_OpenGL, format, str_source, str_type, id, message);
  249. break;
  250. case GL_DEBUG_SEVERITY_NOTIFICATION:
  251. case GL_DEBUG_SEVERITY_LOW:
  252. LOG_DEBUG(Render_OpenGL, format, str_source, str_type, id, message);
  253. break;
  254. }
  255. }
  256. } // Anonymous namespace
  257. RendererOpenGL::RendererOpenGL(Core::Frontend::EmuWindow& emu_window, Core::System& system)
  258. : VideoCore::RendererBase{emu_window}, emu_window{emu_window}, system{system},
  259. frame_mailbox{std::make_unique<FrameMailbox>()} {}
  260. RendererOpenGL::~RendererOpenGL() = default;
  261. MICROPROFILE_DEFINE(OpenGL_RenderFrame, "OpenGL", "Render Frame", MP_RGB(128, 128, 64));
  262. MICROPROFILE_DEFINE(OpenGL_WaitPresent, "OpenGL", "Wait For Present", MP_RGB(128, 128, 128));
  263. void RendererOpenGL::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  264. render_window.PollEvents();
  265. if (!framebuffer) {
  266. return;
  267. }
  268. PrepareRendertarget(framebuffer);
  269. RenderScreenshot();
  270. Frame* frame;
  271. {
  272. MICROPROFILE_SCOPE(OpenGL_WaitPresent);
  273. frame = frame_mailbox->GetRenderFrame();
  274. // Clean up sync objects before drawing
  275. // INTEL driver workaround. We can't delete the previous render sync object until we are
  276. // sure that the presentation is done
  277. if (frame->present_fence) {
  278. glClientWaitSync(frame->present_fence, 0, GL_TIMEOUT_IGNORED);
  279. }
  280. // delete the draw fence if the frame wasn't presented
  281. if (frame->render_fence) {
  282. glDeleteSync(frame->render_fence);
  283. frame->render_fence = 0;
  284. }
  285. // wait for the presentation to be done
  286. if (frame->present_fence) {
  287. glWaitSync(frame->present_fence, 0, GL_TIMEOUT_IGNORED);
  288. glDeleteSync(frame->present_fence);
  289. frame->present_fence = 0;
  290. }
  291. }
  292. {
  293. MICROPROFILE_SCOPE(OpenGL_RenderFrame);
  294. const auto& layout = render_window.GetFramebufferLayout();
  295. // Recreate the frame if the size of the window has changed
  296. if (layout.width != frame->width || layout.height != frame->height ||
  297. screen_info.display_srgb != frame->is_srgb) {
  298. LOG_DEBUG(Render_OpenGL, "Reloading render frame");
  299. frame->is_srgb = screen_info.display_srgb;
  300. frame_mailbox->ReloadRenderFrame(frame, layout.width, layout.height);
  301. }
  302. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame->render.handle);
  303. DrawScreen(layout);
  304. // Create a fence for the frontend to wait on and swap this frame to OffTex
  305. frame->render_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  306. glFlush();
  307. frame_mailbox->ReleaseRenderFrame(frame);
  308. m_current_frame++;
  309. rasterizer->TickFrame();
  310. }
  311. }
  312. void RendererOpenGL::PrepareRendertarget(const Tegra::FramebufferConfig* framebuffer) {
  313. if (framebuffer) {
  314. // If framebuffer is provided, reload it from memory to a texture
  315. if (screen_info.texture.width != static_cast<GLsizei>(framebuffer->width) ||
  316. screen_info.texture.height != static_cast<GLsizei>(framebuffer->height) ||
  317. screen_info.texture.pixel_format != framebuffer->pixel_format ||
  318. gl_framebuffer_data.empty()) {
  319. // Reallocate texture if the framebuffer size has changed.
  320. // This is expected to not happen very often and hence should not be a
  321. // performance problem.
  322. ConfigureFramebufferTexture(screen_info.texture, *framebuffer);
  323. }
  324. // Load the framebuffer from memory, draw it to the screen, and swap buffers
  325. LoadFBToScreenInfo(*framebuffer);
  326. }
  327. }
  328. void RendererOpenGL::LoadFBToScreenInfo(const Tegra::FramebufferConfig& framebuffer) {
  329. // Framebuffer orientation handling
  330. framebuffer_transform_flags = framebuffer.transform_flags;
  331. framebuffer_crop_rect = framebuffer.crop_rect;
  332. const VAddr framebuffer_addr{framebuffer.address + framebuffer.offset};
  333. if (rasterizer->AccelerateDisplay(framebuffer, framebuffer_addr, framebuffer.stride)) {
  334. return;
  335. }
  336. // Reset the screen info's display texture to its own permanent texture
  337. screen_info.display_texture = screen_info.texture.resource.handle;
  338. const auto pixel_format{
  339. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  340. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  341. const u64 size_in_bytes{framebuffer.stride * framebuffer.height * bytes_per_pixel};
  342. u8* const host_ptr{system.Memory().GetPointer(framebuffer_addr)};
  343. rasterizer->FlushRegion(ToCacheAddr(host_ptr), size_in_bytes);
  344. // TODO(Rodrigo): Read this from HLE
  345. constexpr u32 block_height_log2 = 4;
  346. VideoCore::MortonSwizzle(VideoCore::MortonSwizzleMode::MortonToLinear, pixel_format,
  347. framebuffer.stride, block_height_log2, framebuffer.height, 0, 1, 1,
  348. gl_framebuffer_data.data(), host_ptr);
  349. glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(framebuffer.stride));
  350. // Update existing texture
  351. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that
  352. // they differ from the LCD resolution.
  353. // TODO: Applications could theoretically crash yuzu here by specifying too large
  354. // framebuffer sizes. We should make sure that this cannot happen.
  355. glTextureSubImage2D(screen_info.texture.resource.handle, 0, 0, 0, framebuffer.width,
  356. framebuffer.height, screen_info.texture.gl_format,
  357. screen_info.texture.gl_type, gl_framebuffer_data.data());
  358. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  359. }
  360. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, u8 color_a,
  361. const TextureInfo& texture) {
  362. const u8 framebuffer_data[4] = {color_a, color_b, color_g, color_r};
  363. glClearTexImage(texture.resource.handle, 0, GL_RGBA, GL_UNSIGNED_BYTE, framebuffer_data);
  364. }
  365. void RendererOpenGL::InitOpenGLObjects() {
  366. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  367. 0.0f);
  368. // Create shader programs
  369. OGLShader vertex_shader;
  370. vertex_shader.Create(VERTEX_SHADER, GL_VERTEX_SHADER);
  371. OGLShader fragment_shader;
  372. fragment_shader.Create(FRAGMENT_SHADER, GL_FRAGMENT_SHADER);
  373. vertex_program.Create(true, false, vertex_shader.handle);
  374. fragment_program.Create(true, false, fragment_shader.handle);
  375. // Create program pipeline
  376. program_manager.Create();
  377. // Generate VBO handle for drawing
  378. vertex_buffer.Create();
  379. // Attach vertex data to VAO
  380. glNamedBufferData(vertex_buffer.handle, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  381. // Allocate textures for the screen
  382. screen_info.texture.resource.Create(GL_TEXTURE_2D);
  383. const GLuint texture = screen_info.texture.resource.handle;
  384. glTextureStorage2D(texture, 1, GL_RGBA8, 1, 1);
  385. screen_info.display_texture = screen_info.texture.resource.handle;
  386. // Clear screen to black
  387. LoadColorToActiveGLTexture(0, 0, 0, 0, screen_info.texture);
  388. }
  389. void RendererOpenGL::AddTelemetryFields() {
  390. const char* const gl_version{reinterpret_cast<char const*>(glGetString(GL_VERSION))};
  391. const char* const gpu_vendor{reinterpret_cast<char const*>(glGetString(GL_VENDOR))};
  392. const char* const gpu_model{reinterpret_cast<char const*>(glGetString(GL_RENDERER))};
  393. LOG_INFO(Render_OpenGL, "GL_VERSION: {}", gl_version);
  394. LOG_INFO(Render_OpenGL, "GL_VENDOR: {}", gpu_vendor);
  395. LOG_INFO(Render_OpenGL, "GL_RENDERER: {}", gpu_model);
  396. auto& telemetry_session = system.TelemetrySession();
  397. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Vendor", gpu_vendor);
  398. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Model", gpu_model);
  399. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_OpenGL_Version", gl_version);
  400. }
  401. void RendererOpenGL::CreateRasterizer() {
  402. if (rasterizer) {
  403. return;
  404. }
  405. rasterizer = std::make_unique<RasterizerOpenGL>(system, emu_window, screen_info,
  406. program_manager, state_tracker);
  407. }
  408. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  409. const Tegra::FramebufferConfig& framebuffer) {
  410. texture.width = framebuffer.width;
  411. texture.height = framebuffer.height;
  412. texture.pixel_format = framebuffer.pixel_format;
  413. const auto pixel_format{
  414. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  415. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  416. gl_framebuffer_data.resize(texture.width * texture.height * bytes_per_pixel);
  417. GLint internal_format;
  418. switch (framebuffer.pixel_format) {
  419. case Tegra::FramebufferConfig::PixelFormat::ABGR8:
  420. internal_format = GL_RGBA8;
  421. texture.gl_format = GL_RGBA;
  422. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  423. break;
  424. case Tegra::FramebufferConfig::PixelFormat::RGB565:
  425. internal_format = GL_RGB565;
  426. texture.gl_format = GL_RGB;
  427. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  428. break;
  429. default:
  430. internal_format = GL_RGBA8;
  431. texture.gl_format = GL_RGBA;
  432. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  433. UNIMPLEMENTED_MSG("Unknown framebuffer pixel format: {}",
  434. static_cast<u32>(framebuffer.pixel_format));
  435. }
  436. texture.resource.Release();
  437. texture.resource.Create(GL_TEXTURE_2D);
  438. glTextureStorage2D(texture.resource.handle, 1, internal_format, texture.width, texture.height);
  439. }
  440. void RendererOpenGL::DrawScreen(const Layout::FramebufferLayout& layout) {
  441. if (renderer_settings.set_background_color) {
  442. // Update background color before drawing
  443. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  444. 0.0f);
  445. }
  446. // Set projection matrix
  447. const std::array ortho_matrix =
  448. MakeOrthographicMatrix(static_cast<float>(layout.width), static_cast<float>(layout.height));
  449. glProgramUniformMatrix3x2fv(vertex_program.handle, ModelViewMatrixLocation, 1, GL_FALSE,
  450. std::data(ortho_matrix));
  451. const auto& texcoords = screen_info.display_texcoords;
  452. auto left = texcoords.left;
  453. auto right = texcoords.right;
  454. if (framebuffer_transform_flags != Tegra::FramebufferConfig::TransformFlags::Unset) {
  455. if (framebuffer_transform_flags == Tegra::FramebufferConfig::TransformFlags::FlipV) {
  456. // Flip the framebuffer vertically
  457. left = texcoords.right;
  458. right = texcoords.left;
  459. } else {
  460. // Other transformations are unsupported
  461. LOG_CRITICAL(Render_OpenGL, "Unsupported framebuffer_transform_flags={}",
  462. static_cast<u32>(framebuffer_transform_flags));
  463. UNIMPLEMENTED();
  464. }
  465. }
  466. ASSERT_MSG(framebuffer_crop_rect.top == 0, "Unimplemented");
  467. ASSERT_MSG(framebuffer_crop_rect.left == 0, "Unimplemented");
  468. // Scale the output by the crop width/height. This is commonly used with 1280x720 rendering
  469. // (e.g. handheld mode) on a 1920x1080 framebuffer.
  470. f32 scale_u = 1.f, scale_v = 1.f;
  471. if (framebuffer_crop_rect.GetWidth() > 0) {
  472. scale_u = static_cast<f32>(framebuffer_crop_rect.GetWidth()) /
  473. static_cast<f32>(screen_info.texture.width);
  474. }
  475. if (framebuffer_crop_rect.GetHeight() > 0) {
  476. scale_v = static_cast<f32>(framebuffer_crop_rect.GetHeight()) /
  477. static_cast<f32>(screen_info.texture.height);
  478. }
  479. const auto& screen = layout.screen;
  480. const std::array vertices = {
  481. ScreenRectVertex(screen.left, screen.top, texcoords.top * scale_u, left * scale_v),
  482. ScreenRectVertex(screen.right, screen.top, texcoords.bottom * scale_u, left * scale_v),
  483. ScreenRectVertex(screen.left, screen.bottom, texcoords.top * scale_u, right * scale_v),
  484. ScreenRectVertex(screen.right, screen.bottom, texcoords.bottom * scale_u, right * scale_v),
  485. };
  486. glNamedBufferSubData(vertex_buffer.handle, 0, sizeof(vertices), std::data(vertices));
  487. // TODO: Signal state tracker about these changes
  488. state_tracker.NotifyScreenDrawVertexArray();
  489. state_tracker.NotifyViewport0();
  490. state_tracker.NotifyScissor0();
  491. state_tracker.NotifyColorMask0();
  492. state_tracker.NotifyBlend0();
  493. state_tracker.NotifyFramebuffer();
  494. state_tracker.NotifyFrontFace();
  495. state_tracker.NotifyCullTest();
  496. state_tracker.NotifyDepthTest();
  497. state_tracker.NotifyStencilTest();
  498. state_tracker.NotifyPolygonOffset();
  499. state_tracker.NotifyRasterizeEnable();
  500. state_tracker.NotifyFramebufferSRGB();
  501. state_tracker.NotifyLogicOp();
  502. state_tracker.NotifyClipControl();
  503. state_tracker.NotifyAlphaTest();
  504. program_manager.UseVertexShader(vertex_program.handle);
  505. program_manager.UseGeometryShader(0);
  506. program_manager.UseFragmentShader(fragment_program.handle);
  507. program_manager.BindGraphicsPipeline();
  508. glEnable(GL_CULL_FACE);
  509. if (screen_info.display_srgb) {
  510. glEnable(GL_FRAMEBUFFER_SRGB);
  511. } else {
  512. glDisable(GL_FRAMEBUFFER_SRGB);
  513. }
  514. glDisable(GL_COLOR_LOGIC_OP);
  515. glDisable(GL_DEPTH_TEST);
  516. glDisable(GL_STENCIL_TEST);
  517. glDisable(GL_POLYGON_OFFSET_FILL);
  518. glDisable(GL_RASTERIZER_DISCARD);
  519. glDisable(GL_ALPHA_TEST);
  520. glDisablei(GL_BLEND, 0);
  521. glDisablei(GL_SCISSOR_TEST, 0);
  522. glCullFace(GL_BACK);
  523. glFrontFace(GL_CW);
  524. glColorMaski(0, GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  525. glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
  526. glViewportIndexedf(0, 0.0f, 0.0f, static_cast<GLfloat>(layout.width),
  527. static_cast<GLfloat>(layout.height));
  528. glDepthRangeIndexed(0, 0.0, 0.0);
  529. glEnableVertexAttribArray(PositionLocation);
  530. glEnableVertexAttribArray(TexCoordLocation);
  531. glVertexAttribDivisor(PositionLocation, 0);
  532. glVertexAttribDivisor(TexCoordLocation, 0);
  533. glVertexAttribFormat(PositionLocation, 2, GL_FLOAT, GL_FALSE,
  534. offsetof(ScreenRectVertex, position));
  535. glVertexAttribFormat(TexCoordLocation, 2, GL_FLOAT, GL_FALSE,
  536. offsetof(ScreenRectVertex, tex_coord));
  537. glVertexAttribBinding(PositionLocation, 0);
  538. glVertexAttribBinding(TexCoordLocation, 0);
  539. glBindVertexBuffer(0, vertex_buffer.handle, 0, sizeof(ScreenRectVertex));
  540. glBindTextureUnit(0, screen_info.display_texture);
  541. glBindSampler(0, 0);
  542. glClear(GL_COLOR_BUFFER_BIT);
  543. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  544. }
  545. void RendererOpenGL::TryPresent(int timeout_ms) {
  546. const auto& layout = render_window.GetFramebufferLayout();
  547. auto frame = frame_mailbox->TryGetPresentFrame(timeout_ms);
  548. if (!frame) {
  549. LOG_DEBUG(Render_OpenGL, "TryGetPresentFrame returned no frame to present");
  550. return;
  551. }
  552. // Clearing before a full overwrite of a fbo can signal to drivers that they can avoid a
  553. // readback since we won't be doing any blending
  554. glClear(GL_COLOR_BUFFER_BIT);
  555. // Recreate the presentation FBO if the color attachment was changed
  556. if (frame->color_reloaded) {
  557. LOG_DEBUG(Render_OpenGL, "Reloading present frame");
  558. frame_mailbox->ReloadPresentFrame(frame, layout.width, layout.height);
  559. }
  560. glWaitSync(frame->render_fence, 0, GL_TIMEOUT_IGNORED);
  561. // INTEL workaround.
  562. // Normally we could just delete the draw fence here, but due to driver bugs, we can just delete
  563. // it on the emulation thread without too much penalty
  564. // glDeleteSync(frame.render_sync);
  565. // frame.render_sync = 0;
  566. glBindFramebuffer(GL_READ_FRAMEBUFFER, frame->present.handle);
  567. glBlitFramebuffer(0, 0, frame->width, frame->height, 0, 0, layout.width, layout.height,
  568. GL_COLOR_BUFFER_BIT, GL_LINEAR);
  569. // Insert fence for the main thread to block on
  570. frame->present_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  571. glFlush();
  572. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  573. }
  574. void RendererOpenGL::RenderScreenshot() {
  575. if (!renderer_settings.screenshot_requested) {
  576. return;
  577. }
  578. GLint old_read_fb;
  579. GLint old_draw_fb;
  580. glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &old_read_fb);
  581. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &old_draw_fb);
  582. // Draw the current frame to the screenshot framebuffer
  583. screenshot_framebuffer.Create();
  584. glBindFramebuffer(GL_FRAMEBUFFER, screenshot_framebuffer.handle);
  585. Layout::FramebufferLayout layout{renderer_settings.screenshot_framebuffer_layout};
  586. GLuint renderbuffer;
  587. glGenRenderbuffers(1, &renderbuffer);
  588. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  589. glRenderbufferStorage(GL_RENDERBUFFER, screen_info.display_srgb ? GL_SRGB8 : GL_RGB8,
  590. layout.width, layout.height);
  591. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
  592. DrawScreen(layout);
  593. glReadPixels(0, 0, layout.width, layout.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  594. renderer_settings.screenshot_bits);
  595. screenshot_framebuffer.Release();
  596. glDeleteRenderbuffers(1, &renderbuffer);
  597. glBindFramebuffer(GL_READ_FRAMEBUFFER, old_read_fb);
  598. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, old_draw_fb);
  599. renderer_settings.screenshot_complete_callback();
  600. renderer_settings.screenshot_requested = false;
  601. }
  602. bool RendererOpenGL::Init() {
  603. if (GLAD_GL_KHR_debug) {
  604. glEnable(GL_DEBUG_OUTPUT);
  605. glDebugMessageCallback(DebugHandler, nullptr);
  606. }
  607. AddTelemetryFields();
  608. if (!GLAD_GL_VERSION_4_3) {
  609. return false;
  610. }
  611. InitOpenGLObjects();
  612. CreateRasterizer();
  613. return true;
  614. }
  615. void RendererOpenGL::ShutDown() {}
  616. } // namespace OpenGL