renderer_opengl.cpp 28 KB

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