renderer_opengl.cpp 29 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. : RendererBase{emu_window}, emu_window{emu_window}, system{system}, context{context},
  275. program_manager{device}, 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. pipeline.Create();
  398. glUseProgramStages(pipeline.handle, GL_VERTEX_SHADER_BIT, vertex_program.handle);
  399. glUseProgramStages(pipeline.handle, GL_FRAGMENT_SHADER_BIT, fragment_program.handle);
  400. // Generate VBO handle for drawing
  401. vertex_buffer.Create();
  402. // Attach vertex data to VAO
  403. glNamedBufferData(vertex_buffer.handle, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  404. // Allocate textures for the screen
  405. screen_info.texture.resource.Create(GL_TEXTURE_2D);
  406. const GLuint texture = screen_info.texture.resource.handle;
  407. glTextureStorage2D(texture, 1, GL_RGBA8, 1, 1);
  408. screen_info.display_texture = screen_info.texture.resource.handle;
  409. // Clear screen to black
  410. LoadColorToActiveGLTexture(0, 0, 0, 0, screen_info.texture);
  411. }
  412. void RendererOpenGL::AddTelemetryFields() {
  413. const char* const gl_version{reinterpret_cast<char const*>(glGetString(GL_VERSION))};
  414. const char* const gpu_vendor{reinterpret_cast<char const*>(glGetString(GL_VENDOR))};
  415. const char* const gpu_model{reinterpret_cast<char const*>(glGetString(GL_RENDERER))};
  416. LOG_INFO(Render_OpenGL, "GL_VERSION: {}", gl_version);
  417. LOG_INFO(Render_OpenGL, "GL_VENDOR: {}", gpu_vendor);
  418. LOG_INFO(Render_OpenGL, "GL_RENDERER: {}", gpu_model);
  419. auto& telemetry_session = system.TelemetrySession();
  420. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Vendor", gpu_vendor);
  421. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Model", gpu_model);
  422. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_OpenGL_Version", gl_version);
  423. }
  424. void RendererOpenGL::CreateRasterizer() {
  425. if (rasterizer) {
  426. return;
  427. }
  428. rasterizer = std::make_unique<RasterizerOpenGL>(system, emu_window, device, screen_info,
  429. program_manager, state_tracker);
  430. }
  431. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  432. const Tegra::FramebufferConfig& framebuffer) {
  433. texture.width = framebuffer.width;
  434. texture.height = framebuffer.height;
  435. texture.pixel_format = framebuffer.pixel_format;
  436. const auto pixel_format{
  437. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  438. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  439. gl_framebuffer_data.resize(texture.width * texture.height * bytes_per_pixel);
  440. GLint internal_format;
  441. switch (framebuffer.pixel_format) {
  442. case Tegra::FramebufferConfig::PixelFormat::ABGR8:
  443. internal_format = GL_RGBA8;
  444. texture.gl_format = GL_RGBA;
  445. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  446. break;
  447. case Tegra::FramebufferConfig::PixelFormat::RGB565:
  448. internal_format = GL_RGB565;
  449. texture.gl_format = GL_RGB;
  450. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  451. break;
  452. default:
  453. internal_format = GL_RGBA8;
  454. texture.gl_format = GL_RGBA;
  455. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  456. UNIMPLEMENTED_MSG("Unknown framebuffer pixel format: {}",
  457. static_cast<u32>(framebuffer.pixel_format));
  458. }
  459. texture.resource.Release();
  460. texture.resource.Create(GL_TEXTURE_2D);
  461. glTextureStorage2D(texture.resource.handle, 1, internal_format, texture.width, texture.height);
  462. }
  463. void RendererOpenGL::DrawScreen(const Layout::FramebufferLayout& layout) {
  464. if (renderer_settings.set_background_color) {
  465. // Update background color before drawing
  466. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  467. 0.0f);
  468. }
  469. // Set projection matrix
  470. const std::array ortho_matrix =
  471. MakeOrthographicMatrix(static_cast<float>(layout.width), static_cast<float>(layout.height));
  472. glProgramUniformMatrix3x2fv(vertex_program.handle, ModelViewMatrixLocation, 1, GL_FALSE,
  473. std::data(ortho_matrix));
  474. const auto& texcoords = screen_info.display_texcoords;
  475. auto left = texcoords.left;
  476. auto right = texcoords.right;
  477. if (framebuffer_transform_flags != Tegra::FramebufferConfig::TransformFlags::Unset) {
  478. if (framebuffer_transform_flags == Tegra::FramebufferConfig::TransformFlags::FlipV) {
  479. // Flip the framebuffer vertically
  480. left = texcoords.right;
  481. right = texcoords.left;
  482. } else {
  483. // Other transformations are unsupported
  484. LOG_CRITICAL(Render_OpenGL, "Unsupported framebuffer_transform_flags={}",
  485. static_cast<u32>(framebuffer_transform_flags));
  486. UNIMPLEMENTED();
  487. }
  488. }
  489. ASSERT_MSG(framebuffer_crop_rect.top == 0, "Unimplemented");
  490. ASSERT_MSG(framebuffer_crop_rect.left == 0, "Unimplemented");
  491. // Scale the output by the crop width/height. This is commonly used with 1280x720 rendering
  492. // (e.g. handheld mode) on a 1920x1080 framebuffer.
  493. f32 scale_u = 1.f, scale_v = 1.f;
  494. if (framebuffer_crop_rect.GetWidth() > 0) {
  495. scale_u = static_cast<f32>(framebuffer_crop_rect.GetWidth()) /
  496. static_cast<f32>(screen_info.texture.width);
  497. }
  498. if (framebuffer_crop_rect.GetHeight() > 0) {
  499. scale_v = static_cast<f32>(framebuffer_crop_rect.GetHeight()) /
  500. static_cast<f32>(screen_info.texture.height);
  501. }
  502. const auto& screen = layout.screen;
  503. const std::array vertices = {
  504. ScreenRectVertex(screen.left, screen.top, texcoords.top * scale_u, left * scale_v),
  505. ScreenRectVertex(screen.right, screen.top, texcoords.bottom * scale_u, left * scale_v),
  506. ScreenRectVertex(screen.left, screen.bottom, texcoords.top * scale_u, right * scale_v),
  507. ScreenRectVertex(screen.right, screen.bottom, texcoords.bottom * scale_u, right * scale_v),
  508. };
  509. glNamedBufferSubData(vertex_buffer.handle, 0, sizeof(vertices), std::data(vertices));
  510. // TODO: Signal state tracker about these changes
  511. state_tracker.NotifyScreenDrawVertexArray();
  512. state_tracker.NotifyPolygonModes();
  513. state_tracker.NotifyViewport0();
  514. state_tracker.NotifyScissor0();
  515. state_tracker.NotifyColorMask0();
  516. state_tracker.NotifyBlend0();
  517. state_tracker.NotifyFramebuffer();
  518. state_tracker.NotifyFrontFace();
  519. state_tracker.NotifyCullTest();
  520. state_tracker.NotifyDepthTest();
  521. state_tracker.NotifyStencilTest();
  522. state_tracker.NotifyPolygonOffset();
  523. state_tracker.NotifyRasterizeEnable();
  524. state_tracker.NotifyFramebufferSRGB();
  525. state_tracker.NotifyLogicOp();
  526. state_tracker.NotifyClipControl();
  527. state_tracker.NotifyAlphaTest();
  528. program_manager.BindHostPipeline(pipeline.handle);
  529. glEnable(GL_CULL_FACE);
  530. if (screen_info.display_srgb) {
  531. glEnable(GL_FRAMEBUFFER_SRGB);
  532. } else {
  533. glDisable(GL_FRAMEBUFFER_SRGB);
  534. }
  535. glDisable(GL_COLOR_LOGIC_OP);
  536. glDisable(GL_DEPTH_TEST);
  537. glDisable(GL_STENCIL_TEST);
  538. glDisable(GL_POLYGON_OFFSET_FILL);
  539. glDisable(GL_RASTERIZER_DISCARD);
  540. glDisable(GL_ALPHA_TEST);
  541. glDisablei(GL_BLEND, 0);
  542. glDisablei(GL_SCISSOR_TEST, 0);
  543. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  544. glCullFace(GL_BACK);
  545. glFrontFace(GL_CW);
  546. glColorMaski(0, GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  547. glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
  548. glViewportIndexedf(0, 0.0f, 0.0f, static_cast<GLfloat>(layout.width),
  549. static_cast<GLfloat>(layout.height));
  550. glDepthRangeIndexed(0, 0.0, 0.0);
  551. glEnableVertexAttribArray(PositionLocation);
  552. glEnableVertexAttribArray(TexCoordLocation);
  553. glVertexAttribDivisor(PositionLocation, 0);
  554. glVertexAttribDivisor(TexCoordLocation, 0);
  555. glVertexAttribFormat(PositionLocation, 2, GL_FLOAT, GL_FALSE,
  556. offsetof(ScreenRectVertex, position));
  557. glVertexAttribFormat(TexCoordLocation, 2, GL_FLOAT, GL_FALSE,
  558. offsetof(ScreenRectVertex, tex_coord));
  559. glVertexAttribBinding(PositionLocation, 0);
  560. glVertexAttribBinding(TexCoordLocation, 0);
  561. glBindVertexBuffer(0, vertex_buffer.handle, 0, sizeof(ScreenRectVertex));
  562. glBindTextureUnit(0, screen_info.display_texture);
  563. glBindSampler(0, 0);
  564. glClear(GL_COLOR_BUFFER_BIT);
  565. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  566. program_manager.RestoreGuestPipeline();
  567. }
  568. bool RendererOpenGL::TryPresent(int timeout_ms) {
  569. if (has_debug_tool) {
  570. LOG_DEBUG(Render_OpenGL,
  571. "Skipping presentation because we are presenting on the main context");
  572. return false;
  573. }
  574. return Present(timeout_ms);
  575. }
  576. bool RendererOpenGL::Present(int timeout_ms) {
  577. const auto& layout = render_window.GetFramebufferLayout();
  578. auto frame = frame_mailbox->TryGetPresentFrame(timeout_ms);
  579. if (!frame) {
  580. LOG_DEBUG(Render_OpenGL, "TryGetPresentFrame returned no frame to present");
  581. return false;
  582. }
  583. // Clearing before a full overwrite of a fbo can signal to drivers that they can avoid a
  584. // readback since we won't be doing any blending
  585. glClear(GL_COLOR_BUFFER_BIT);
  586. // Recreate the presentation FBO if the color attachment was changed
  587. if (frame->color_reloaded) {
  588. LOG_DEBUG(Render_OpenGL, "Reloading present frame");
  589. frame_mailbox->ReloadPresentFrame(frame, layout.width, layout.height);
  590. }
  591. glWaitSync(frame->render_fence, 0, GL_TIMEOUT_IGNORED);
  592. // INTEL workaround.
  593. // Normally we could just delete the draw fence here, but due to driver bugs, we can just delete
  594. // it on the emulation thread without too much penalty
  595. // glDeleteSync(frame.render_sync);
  596. // frame.render_sync = 0;
  597. glBindFramebuffer(GL_READ_FRAMEBUFFER, frame->present.handle);
  598. glBlitFramebuffer(0, 0, frame->width, frame->height, 0, 0, layout.width, layout.height,
  599. GL_COLOR_BUFFER_BIT, GL_LINEAR);
  600. // Insert fence for the main thread to block on
  601. frame->present_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  602. glFlush();
  603. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  604. return true;
  605. }
  606. void RendererOpenGL::RenderScreenshot() {
  607. if (!renderer_settings.screenshot_requested) {
  608. return;
  609. }
  610. GLint old_read_fb;
  611. GLint old_draw_fb;
  612. glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &old_read_fb);
  613. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &old_draw_fb);
  614. // Draw the current frame to the screenshot framebuffer
  615. screenshot_framebuffer.Create();
  616. glBindFramebuffer(GL_FRAMEBUFFER, screenshot_framebuffer.handle);
  617. Layout::FramebufferLayout layout{renderer_settings.screenshot_framebuffer_layout};
  618. GLuint renderbuffer;
  619. glGenRenderbuffers(1, &renderbuffer);
  620. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  621. glRenderbufferStorage(GL_RENDERBUFFER, screen_info.display_srgb ? GL_SRGB8 : GL_RGB8,
  622. layout.width, layout.height);
  623. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
  624. DrawScreen(layout);
  625. glReadPixels(0, 0, layout.width, layout.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  626. renderer_settings.screenshot_bits);
  627. screenshot_framebuffer.Release();
  628. glDeleteRenderbuffers(1, &renderbuffer);
  629. glBindFramebuffer(GL_READ_FRAMEBUFFER, old_read_fb);
  630. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, old_draw_fb);
  631. renderer_settings.screenshot_complete_callback();
  632. renderer_settings.screenshot_requested = false;
  633. }
  634. bool RendererOpenGL::Init() {
  635. if (GLAD_GL_KHR_debug) {
  636. glEnable(GL_DEBUG_OUTPUT);
  637. glDebugMessageCallback(DebugHandler, nullptr);
  638. }
  639. AddTelemetryFields();
  640. if (!GLAD_GL_VERSION_4_3) {
  641. return false;
  642. }
  643. InitOpenGLObjects();
  644. CreateRasterizer();
  645. return true;
  646. }
  647. void RendererOpenGL::ShutDown() {}
  648. } // namespace OpenGL