renderer_opengl.cpp 26 KB

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