renderer_opengl.cpp 17 KB

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