renderer_opengl.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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/bit_field.h"
  11. #include "common/logging/log.h"
  12. #include "common/synchronized_wrapper.h"
  13. #include "core/core.h"
  14. #include "core/frontend/emu_window.h"
  15. #include "core/hw/gpu.h"
  16. #include "core/hw/hw.h"
  17. #include "core/hw/lcd.h"
  18. #include "core/memory.h"
  19. #include "core/settings.h"
  20. #include "core/tracer/recorder.h"
  21. #include "video_core/debug_utils/debug_utils.h"
  22. #include "video_core/rasterizer_interface.h"
  23. #include "video_core/renderer_opengl/renderer_opengl.h"
  24. #include "video_core/video_core.h"
  25. static const char vertex_shader[] = R"(
  26. #version 150 core
  27. in vec2 vert_position;
  28. in vec2 vert_tex_coord;
  29. out vec2 frag_tex_coord;
  30. // This is a truncated 3x3 matrix for 2D transformations:
  31. // The upper-left 2x2 submatrix performs scaling/rotation/mirroring.
  32. // The third column performs translation.
  33. // The third row could be used for projection, which we don't need in 2D. It hence is assumed to
  34. // implicitly be [0, 0, 1]
  35. uniform mat3x2 modelview_matrix;
  36. void main() {
  37. // Multiply input position by the rotscale part of the matrix and then manually translate by
  38. // the last column. This is equivalent to using a full 3x3 matrix and expanding the vector
  39. // to `vec3(vert_position.xy, 1.0)`
  40. gl_Position = vec4(mat2(modelview_matrix) * vert_position + modelview_matrix[2], 0.0, 1.0);
  41. frag_tex_coord = vert_tex_coord;
  42. }
  43. )";
  44. static const char fragment_shader[] = R"(
  45. #version 150 core
  46. in vec2 frag_tex_coord;
  47. out vec4 color;
  48. uniform sampler2D color_texture;
  49. void main() {
  50. color = texture(color_texture, frag_tex_coord);
  51. }
  52. )";
  53. /**
  54. * Vertex structure that the drawn screen rectangles are composed of.
  55. */
  56. struct ScreenRectVertex {
  57. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  58. position[0] = x;
  59. position[1] = y;
  60. tex_coord[0] = u;
  61. tex_coord[1] = v;
  62. }
  63. GLfloat position[2];
  64. GLfloat tex_coord[2];
  65. };
  66. /**
  67. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  68. * corner and (width, height) on the lower-bottom.
  69. *
  70. * The projection part of the matrix is trivial, hence these operations are represented
  71. * by a 3x2 matrix.
  72. */
  73. static std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(const float width, const float height) {
  74. std::array<GLfloat, 3 * 2> matrix; // Laid out in column-major order
  75. // clang-format off
  76. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  77. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  78. // Last matrix row is implicitly assumed to be [0, 0, 1].
  79. // clang-format on
  80. return matrix;
  81. }
  82. /// RendererOpenGL constructor
  83. RendererOpenGL::RendererOpenGL() {
  84. resolution_width = std::max(VideoCore::kScreenTopWidth, VideoCore::kScreenBottomWidth);
  85. resolution_height = VideoCore::kScreenTopHeight + VideoCore::kScreenBottomHeight;
  86. }
  87. /// RendererOpenGL destructor
  88. RendererOpenGL::~RendererOpenGL() {}
  89. /// Swap buffers (render frame)
  90. void RendererOpenGL::SwapBuffers() {
  91. // Maintain the rasterizer's state as a priority
  92. OpenGLState prev_state = OpenGLState::GetCurState();
  93. state.Apply();
  94. for (int i : {0, 1}) {
  95. const auto& framebuffer = GPU::g_regs.framebuffer_config[i];
  96. // Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04
  97. u32 lcd_color_addr =
  98. (i == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
  99. lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
  100. LCD::Regs::ColorFill color_fill = {0};
  101. LCD::Read(color_fill.raw, lcd_color_addr);
  102. if (color_fill.is_enabled) {
  103. LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b,
  104. screen_infos[i].texture);
  105. // Resize the texture in case the framebuffer size has changed
  106. screen_infos[i].texture.width = 1;
  107. screen_infos[i].texture.height = 1;
  108. } else {
  109. if (screen_infos[i].texture.width != (GLsizei)framebuffer.width ||
  110. screen_infos[i].texture.height != (GLsizei)framebuffer.height ||
  111. screen_infos[i].texture.format != framebuffer.color_format) {
  112. // Reallocate texture if the framebuffer size has changed.
  113. // This is expected to not happen very often and hence should not be a
  114. // performance problem.
  115. ConfigureFramebufferTexture(screen_infos[i].texture, framebuffer);
  116. }
  117. LoadFBToScreenInfo(framebuffer, screen_infos[i]);
  118. // Resize the texture in case the framebuffer size has changed
  119. screen_infos[i].texture.width = framebuffer.width;
  120. screen_infos[i].texture.height = framebuffer.height;
  121. }
  122. }
  123. DrawScreens();
  124. Core::System::GetInstance().perf_stats.EndSystemFrame();
  125. // Swap buffers
  126. render_window->PollEvents();
  127. render_window->SwapBuffers();
  128. prev_state.Apply();
  129. Core::System::GetInstance().perf_stats.BeginSystemFrame();
  130. RefreshRasterizerSetting();
  131. if (Pica::g_debug_context && Pica::g_debug_context->recorder) {
  132. Pica::g_debug_context->recorder->FrameFinished();
  133. }
  134. }
  135. /**
  136. * Loads framebuffer from emulated memory into the active OpenGL texture.
  137. */
  138. void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer,
  139. ScreenInfo& screen_info) {
  140. const PAddr framebuffer_addr =
  141. framebuffer.active_fb == 0 ? framebuffer.address_left1 : framebuffer.address_left2;
  142. LOG_TRACE(Render_OpenGL, "0x%08x bytes from 0x%08x(%dx%d), fmt %x",
  143. framebuffer.stride * framebuffer.height, framebuffer_addr, (int)framebuffer.width,
  144. (int)framebuffer.height, (int)framebuffer.format);
  145. int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
  146. size_t pixel_stride = framebuffer.stride / bpp;
  147. // OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
  148. ASSERT(pixel_stride * bpp == framebuffer.stride);
  149. // Ensure no bad interactions with GL_UNPACK_ALIGNMENT, which by default
  150. // only allows rows to have a memory alignement of 4.
  151. ASSERT(pixel_stride % 4 == 0);
  152. if (!Rasterizer()->AccelerateDisplay(framebuffer, framebuffer_addr,
  153. static_cast<u32>(pixel_stride), screen_info)) {
  154. // Reset the screen info's display texture to its own permanent texture
  155. screen_info.display_texture = screen_info.texture.resource.handle;
  156. screen_info.display_texcoords = MathUtil::Rectangle<float>(0.f, 0.f, 1.f, 1.f);
  157. Memory::RasterizerFlushRegion(framebuffer_addr, framebuffer.stride * framebuffer.height);
  158. const u8* framebuffer_data = Memory::GetPhysicalPointer(framebuffer_addr);
  159. state.texture_units[0].texture_2d = screen_info.texture.resource.handle;
  160. state.Apply();
  161. glActiveTexture(GL_TEXTURE0);
  162. glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride);
  163. // Update existing texture
  164. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that
  165. // they differ from the LCD resolution.
  166. // TODO: Applications could theoretically crash Citra here by specifying too large
  167. // framebuffer sizes. We should make sure that this cannot happen.
  168. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height,
  169. screen_info.texture.gl_format, screen_info.texture.gl_type,
  170. framebuffer_data);
  171. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  172. state.texture_units[0].texture_2d = 0;
  173. state.Apply();
  174. }
  175. }
  176. /**
  177. * Fills active OpenGL texture with the given RGB color. Since the color is solid, the texture can
  178. * be 1x1 but will stretch across whatever it's rendered on.
  179. */
  180. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b,
  181. const TextureInfo& texture) {
  182. state.texture_units[0].texture_2d = texture.resource.handle;
  183. state.Apply();
  184. glActiveTexture(GL_TEXTURE0);
  185. u8 framebuffer_data[3] = {color_r, color_g, color_b};
  186. // Update existing texture
  187. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer_data);
  188. state.texture_units[0].texture_2d = 0;
  189. state.Apply();
  190. }
  191. /**
  192. * Initializes the OpenGL state and creates persistent objects.
  193. */
  194. void RendererOpenGL::InitOpenGLObjects() {
  195. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  196. 0.0f);
  197. // Link shaders and get variable locations
  198. shader.Create(vertex_shader, fragment_shader);
  199. state.draw.shader_program = shader.handle;
  200. state.Apply();
  201. uniform_modelview_matrix = glGetUniformLocation(shader.handle, "modelview_matrix");
  202. uniform_color_texture = glGetUniformLocation(shader.handle, "color_texture");
  203. attrib_position = glGetAttribLocation(shader.handle, "vert_position");
  204. attrib_tex_coord = glGetAttribLocation(shader.handle, "vert_tex_coord");
  205. // Generate VBO handle for drawing
  206. vertex_buffer.Create();
  207. // Generate VAO
  208. vertex_array.Create();
  209. state.draw.vertex_array = vertex_array.handle;
  210. state.draw.vertex_buffer = vertex_buffer.handle;
  211. state.draw.uniform_buffer = 0;
  212. state.Apply();
  213. // Attach vertex data to VAO
  214. glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  215. glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex),
  216. (GLvoid*)offsetof(ScreenRectVertex, position));
  217. glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex),
  218. (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
  219. glEnableVertexAttribArray(attrib_position);
  220. glEnableVertexAttribArray(attrib_tex_coord);
  221. // Allocate textures for each screen
  222. for (auto& screen_info : screen_infos) {
  223. screen_info.texture.resource.Create();
  224. // Allocation of storage is deferred until the first frame, when we
  225. // know the framebuffer size.
  226. state.texture_units[0].texture_2d = screen_info.texture.resource.handle;
  227. state.Apply();
  228. glActiveTexture(GL_TEXTURE0);
  229. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  230. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  231. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  232. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  233. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  234. screen_info.display_texture = screen_info.texture.resource.handle;
  235. }
  236. state.texture_units[0].texture_2d = 0;
  237. state.Apply();
  238. }
  239. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  240. const GPU::Regs::FramebufferConfig& framebuffer) {
  241. GPU::Regs::PixelFormat format = framebuffer.color_format;
  242. GLint internal_format;
  243. texture.format = format;
  244. texture.width = framebuffer.width;
  245. texture.height = framebuffer.height;
  246. switch (format) {
  247. case GPU::Regs::PixelFormat::RGBA8:
  248. internal_format = GL_RGBA;
  249. texture.gl_format = GL_RGBA;
  250. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8;
  251. break;
  252. case GPU::Regs::PixelFormat::RGB8:
  253. // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
  254. // specific OpenGL type used in this function using native-endian (that is, little-endian
  255. // mostly everywhere) for words or half-words.
  256. // TODO: check how those behave on big-endian processors.
  257. internal_format = GL_RGB;
  258. texture.gl_format = GL_BGR;
  259. texture.gl_type = GL_UNSIGNED_BYTE;
  260. break;
  261. case GPU::Regs::PixelFormat::RGB565:
  262. internal_format = GL_RGB;
  263. texture.gl_format = GL_RGB;
  264. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  265. break;
  266. case GPU::Regs::PixelFormat::RGB5A1:
  267. internal_format = GL_RGBA;
  268. texture.gl_format = GL_RGBA;
  269. texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
  270. break;
  271. case GPU::Regs::PixelFormat::RGBA4:
  272. internal_format = GL_RGBA;
  273. texture.gl_format = GL_RGBA;
  274. texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
  275. break;
  276. default:
  277. UNIMPLEMENTED();
  278. }
  279. state.texture_units[0].texture_2d = texture.resource.handle;
  280. state.Apply();
  281. glActiveTexture(GL_TEXTURE0);
  282. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  283. texture.gl_format, texture.gl_type, nullptr);
  284. state.texture_units[0].texture_2d = 0;
  285. state.Apply();
  286. }
  287. /**
  288. * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD
  289. * rotation.
  290. */
  291. void RendererOpenGL::DrawSingleScreenRotated(const ScreenInfo& screen_info, float x, float y,
  292. float w, float h) {
  293. auto& texcoords = screen_info.display_texcoords;
  294. std::array<ScreenRectVertex, 4> vertices = {{
  295. ScreenRectVertex(x, y, texcoords.bottom, texcoords.left),
  296. ScreenRectVertex(x + w, y, texcoords.bottom, texcoords.right),
  297. ScreenRectVertex(x, y + h, texcoords.top, texcoords.left),
  298. ScreenRectVertex(x + w, y + h, texcoords.top, texcoords.right),
  299. }};
  300. state.texture_units[0].texture_2d = screen_info.display_texture;
  301. state.Apply();
  302. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
  303. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  304. state.texture_units[0].texture_2d = 0;
  305. state.Apply();
  306. }
  307. /**
  308. * Draws the emulated screens to the emulator window.
  309. */
  310. void RendererOpenGL::DrawScreens() {
  311. auto layout = render_window->GetFramebufferLayout();
  312. const auto& top_screen = layout.top_screen;
  313. const auto& bottom_screen = layout.bottom_screen;
  314. glViewport(0, 0, layout.width, layout.height);
  315. glClear(GL_COLOR_BUFFER_BIT);
  316. // Set projection matrix
  317. std::array<GLfloat, 3 * 2> ortho_matrix =
  318. MakeOrthographicMatrix((float)layout.width, (float)layout.height);
  319. glUniformMatrix3x2fv(uniform_modelview_matrix, 1, GL_FALSE, ortho_matrix.data());
  320. // Bind texture in Texture Unit 0
  321. glActiveTexture(GL_TEXTURE0);
  322. glUniform1i(uniform_color_texture, 0);
  323. if (layout.top_screen_enabled) {
  324. DrawSingleScreenRotated(screen_infos[0], (float)top_screen.left, (float)top_screen.top,
  325. (float)top_screen.GetWidth(), (float)top_screen.GetHeight());
  326. }
  327. if (layout.bottom_screen_enabled) {
  328. DrawSingleScreenRotated(screen_infos[1], (float)bottom_screen.left,
  329. (float)bottom_screen.top, (float)bottom_screen.GetWidth(),
  330. (float)bottom_screen.GetHeight());
  331. }
  332. m_current_frame++;
  333. }
  334. /// Updates the framerate
  335. void RendererOpenGL::UpdateFramerate() {}
  336. /**
  337. * Set the emulator window to use for renderer
  338. * @param window EmuWindow handle to emulator window to use for rendering
  339. */
  340. void RendererOpenGL::SetWindow(EmuWindow* window) {
  341. render_window = window;
  342. }
  343. static const char* GetSource(GLenum source) {
  344. #define RET(s) \
  345. case GL_DEBUG_SOURCE_##s: \
  346. return #s
  347. switch (source) {
  348. RET(API);
  349. RET(WINDOW_SYSTEM);
  350. RET(SHADER_COMPILER);
  351. RET(THIRD_PARTY);
  352. RET(APPLICATION);
  353. RET(OTHER);
  354. default:
  355. UNREACHABLE();
  356. }
  357. #undef RET
  358. }
  359. static const char* GetType(GLenum type) {
  360. #define RET(t) \
  361. case GL_DEBUG_TYPE_##t: \
  362. return #t
  363. switch (type) {
  364. RET(ERROR);
  365. RET(DEPRECATED_BEHAVIOR);
  366. RET(UNDEFINED_BEHAVIOR);
  367. RET(PORTABILITY);
  368. RET(PERFORMANCE);
  369. RET(OTHER);
  370. RET(MARKER);
  371. default:
  372. UNREACHABLE();
  373. }
  374. #undef RET
  375. }
  376. static void APIENTRY DebugHandler(GLenum source, GLenum type, GLuint id, GLenum severity,
  377. GLsizei length, const GLchar* message, const void* user_param) {
  378. Log::Level level;
  379. switch (severity) {
  380. case GL_DEBUG_SEVERITY_HIGH:
  381. level = Log::Level::Error;
  382. break;
  383. case GL_DEBUG_SEVERITY_MEDIUM:
  384. level = Log::Level::Warning;
  385. break;
  386. case GL_DEBUG_SEVERITY_NOTIFICATION:
  387. case GL_DEBUG_SEVERITY_LOW:
  388. level = Log::Level::Debug;
  389. break;
  390. }
  391. LOG_GENERIC(Log::Class::Render_OpenGL, level, "%s %s %d: %s", GetSource(source), GetType(type),
  392. id, message);
  393. }
  394. /// Initialize the renderer
  395. bool RendererOpenGL::Init() {
  396. render_window->MakeCurrent();
  397. if (GLAD_GL_KHR_debug) {
  398. glEnable(GL_DEBUG_OUTPUT);
  399. glDebugMessageCallback(DebugHandler, nullptr);
  400. }
  401. LOG_INFO(Render_OpenGL, "GL_VERSION: %s", glGetString(GL_VERSION));
  402. LOG_INFO(Render_OpenGL, "GL_VENDOR: %s", glGetString(GL_VENDOR));
  403. LOG_INFO(Render_OpenGL, "GL_RENDERER: %s", glGetString(GL_RENDERER));
  404. if (!GLAD_GL_VERSION_3_3) {
  405. return false;
  406. }
  407. InitOpenGLObjects();
  408. RefreshRasterizerSetting();
  409. return true;
  410. }
  411. /// Shutdown the renderer
  412. void RendererOpenGL::ShutDown() {}