renderer_opengl.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "core/hw/gpu.h"
  5. #include "core/mem_map.h"
  6. #include "common/emu_window.h"
  7. #include "video_core/video_core.h"
  8. #include "video_core/renderer_opengl/renderer_opengl.h"
  9. #include "video_core/renderer_opengl/gl_shader_util.h"
  10. #include "video_core/renderer_opengl/gl_shaders.h"
  11. #include <algorithm>
  12. /**
  13. * Vertex structure that the drawn screen rectangles are composed of.
  14. */
  15. struct ScreenRectVertex {
  16. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  17. position[0] = x;
  18. position[1] = y;
  19. tex_coord[0] = u;
  20. tex_coord[1] = v;
  21. }
  22. GLfloat position[2];
  23. GLfloat tex_coord[2];
  24. };
  25. /**
  26. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  27. * corner and (width, height) on the lower-bottom.
  28. *
  29. * The projection part of the matrix is trivial, hence these operations are represented
  30. * by a 3x2 matrix.
  31. */
  32. static std::array<GLfloat, 3*2> MakeOrthographicMatrix(const float width, const float height) {
  33. std::array<GLfloat, 3*2> matrix;
  34. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  35. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  36. // Last matrix row is implicitly assumed to be [0, 0, 1].
  37. return matrix;
  38. }
  39. /// RendererOpenGL constructor
  40. RendererOpenGL::RendererOpenGL() {
  41. resolution_width = std::max(VideoCore::kScreenTopWidth, VideoCore::kScreenBottomWidth);
  42. resolution_height = VideoCore::kScreenTopHeight + VideoCore::kScreenBottomHeight;
  43. }
  44. /// RendererOpenGL destructor
  45. RendererOpenGL::~RendererOpenGL() {
  46. }
  47. /// Swap buffers (render frame)
  48. void RendererOpenGL::SwapBuffers() {
  49. render_window->MakeCurrent();
  50. for(int i : {0, 1}) {
  51. const auto& framebuffer = GPU::g_regs.framebuffer_config[i];
  52. if (textures[i].width != (GLsizei)framebuffer.width ||
  53. textures[i].height != (GLsizei)framebuffer.height ||
  54. textures[i].format != framebuffer.color_format) {
  55. // Reallocate texture if the framebuffer size has changed.
  56. // This is expected to not happen very often and hence should not be a
  57. // performance problem.
  58. ConfigureFramebufferTexture(textures[i], framebuffer);
  59. }
  60. LoadFBToActiveGLTexture(GPU::g_regs.framebuffer_config[i], textures[i]);
  61. }
  62. DrawScreens();
  63. // Swap buffers
  64. render_window->PollEvents();
  65. render_window->SwapBuffers();
  66. }
  67. /**
  68. * Loads framebuffer from emulated memory into the active OpenGL texture.
  69. */
  70. void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer,
  71. const TextureInfo& texture) {
  72. const VAddr framebuffer_vaddr = Memory::PhysicalToVirtualAddress(
  73. framebuffer.active_fb == 0 ? framebuffer.address_left1 : framebuffer.address_left2);
  74. LOG_TRACE(Render_OpenGL, "0x%08x bytes from 0x%08x(%dx%d), fmt %x",
  75. framebuffer.stride * framebuffer.height,
  76. framebuffer_vaddr, (int)framebuffer.width,
  77. (int)framebuffer.height, (int)framebuffer.format);
  78. const u8* framebuffer_data = Memory::GetPointer(framebuffer_vaddr);
  79. int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
  80. size_t pixel_stride = framebuffer.stride / bpp;
  81. // OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
  82. ASSERT(pixel_stride * bpp == framebuffer.stride);
  83. // Ensure no bad interactions with GL_UNPACK_ALIGNMENT, which by default
  84. // only allows rows to have a memory alignement of 4.
  85. ASSERT(pixel_stride % 4 == 0);
  86. glBindTexture(GL_TEXTURE_2D, texture.handle);
  87. glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride);
  88. // Update existing texture
  89. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they
  90. // differ from the LCD resolution.
  91. // TODO: Applications could theoretically crash Citra here by specifying too large
  92. // framebuffer sizes. We should make sure that this cannot happen.
  93. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height,
  94. texture.gl_format, texture.gl_type, framebuffer_data);
  95. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  96. glBindTexture(GL_TEXTURE_2D, 0);
  97. }
  98. /**
  99. * Initializes the OpenGL state and creates persistent objects.
  100. */
  101. void RendererOpenGL::InitOpenGLObjects() {
  102. glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
  103. glDisable(GL_DEPTH_TEST);
  104. // Link shaders and get variable locations
  105. program_id = ShaderUtil::LoadShaders(GLShaders::g_vertex_shader, GLShaders::g_fragment_shader);
  106. uniform_modelview_matrix = glGetUniformLocation(program_id, "modelview_matrix");
  107. uniform_color_texture = glGetUniformLocation(program_id, "color_texture");
  108. attrib_position = glGetAttribLocation(program_id, "vert_position");
  109. attrib_tex_coord = glGetAttribLocation(program_id, "vert_tex_coord");
  110. // Generate VBO handle for drawing
  111. glGenBuffers(1, &vertex_buffer_handle);
  112. // Generate VAO
  113. glGenVertexArrays(1, &vertex_array_handle);
  114. glBindVertexArray(vertex_array_handle);
  115. // Attach vertex data to VAO
  116. glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_handle);
  117. glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  118. glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, position));
  119. glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
  120. glEnableVertexAttribArray(attrib_position);
  121. glEnableVertexAttribArray(attrib_tex_coord);
  122. // Allocate textures for each screen
  123. for (auto& texture : textures) {
  124. glGenTextures(1, &texture.handle);
  125. // Allocation of storage is deferred until the first frame, when we
  126. // know the framebuffer size.
  127. glBindTexture(GL_TEXTURE_2D, texture.handle);
  128. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  129. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  130. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  131. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  132. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  133. }
  134. glBindTexture(GL_TEXTURE_2D, 0);
  135. }
  136. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  137. const GPU::Regs::FramebufferConfig& framebuffer) {
  138. GPU::Regs::PixelFormat format = framebuffer.color_format;
  139. GLint internal_format;
  140. texture.format = format;
  141. texture.width = framebuffer.width;
  142. texture.height = framebuffer.height;
  143. switch (format) {
  144. case GPU::Regs::PixelFormat::RGBA8:
  145. internal_format = GL_RGBA;
  146. texture.gl_format = GL_RGBA;
  147. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8;
  148. break;
  149. case GPU::Regs::PixelFormat::RGB8:
  150. // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
  151. // specific OpenGL type used in this function using native-endian (that is, little-endian
  152. // mostly everywhere) for words or half-words.
  153. // TODO: check how those behave on big-endian processors.
  154. internal_format = GL_RGB;
  155. texture.gl_format = GL_BGR;
  156. texture.gl_type = GL_UNSIGNED_BYTE;
  157. break;
  158. case GPU::Regs::PixelFormat::RGB565:
  159. internal_format = GL_RGB;
  160. texture.gl_format = GL_RGB;
  161. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  162. break;
  163. case GPU::Regs::PixelFormat::RGB5A1:
  164. internal_format = GL_RGBA;
  165. texture.gl_format = GL_RGBA;
  166. texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
  167. break;
  168. case GPU::Regs::PixelFormat::RGBA4:
  169. internal_format = GL_RGBA;
  170. texture.gl_format = GL_RGBA;
  171. texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
  172. break;
  173. default:
  174. UNIMPLEMENTED();
  175. }
  176. glBindTexture(GL_TEXTURE_2D, texture.handle);
  177. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  178. texture.gl_format, texture.gl_type, nullptr);
  179. }
  180. /**
  181. * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD rotation.
  182. */
  183. void RendererOpenGL::DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h) {
  184. std::array<ScreenRectVertex, 4> vertices = {
  185. ScreenRectVertex(x, y, 1.f, 0.f),
  186. ScreenRectVertex(x+w, y, 1.f, 1.f),
  187. ScreenRectVertex(x, y+h, 0.f, 0.f),
  188. ScreenRectVertex(x+w, y+h, 0.f, 1.f),
  189. };
  190. glBindTexture(GL_TEXTURE_2D, texture.handle);
  191. glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_handle);
  192. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
  193. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  194. }
  195. /**
  196. * Draws the emulated screens to the emulator window.
  197. */
  198. void RendererOpenGL::DrawScreens() {
  199. auto viewport_extent = GetViewportExtent();
  200. glViewport(viewport_extent.left, viewport_extent.top, viewport_extent.GetWidth(), viewport_extent.GetHeight()); // TODO: Or bottom?
  201. glClear(GL_COLOR_BUFFER_BIT);
  202. glUseProgram(program_id);
  203. // Set projection matrix
  204. std::array<GLfloat, 3*2> ortho_matrix = MakeOrthographicMatrix((float)resolution_width, (float)resolution_height);
  205. glUniformMatrix3x2fv(uniform_modelview_matrix, 1, GL_FALSE, ortho_matrix.data());
  206. // Bind texture in Texture Unit 0
  207. glActiveTexture(GL_TEXTURE0);
  208. glUniform1i(uniform_color_texture, 0);
  209. const float max_width = std::max((float)VideoCore::kScreenTopWidth, (float)VideoCore::kScreenBottomWidth);
  210. const float top_x = 0.5f * (max_width - VideoCore::kScreenTopWidth);
  211. const float bottom_x = 0.5f * (max_width - VideoCore::kScreenBottomWidth);
  212. DrawSingleScreenRotated(textures[0], top_x, 0,
  213. (float)VideoCore::kScreenTopWidth, (float)VideoCore::kScreenTopHeight);
  214. DrawSingleScreenRotated(textures[1], bottom_x, (float)VideoCore::kScreenTopHeight,
  215. (float)VideoCore::kScreenBottomWidth, (float)VideoCore::kScreenBottomHeight);
  216. m_current_frame++;
  217. }
  218. /// Updates the framerate
  219. void RendererOpenGL::UpdateFramerate() {
  220. }
  221. /**
  222. * Set the emulator window to use for renderer
  223. * @param window EmuWindow handle to emulator window to use for rendering
  224. */
  225. void RendererOpenGL::SetWindow(EmuWindow* window) {
  226. render_window = window;
  227. }
  228. MathUtil::Rectangle<unsigned> RendererOpenGL::GetViewportExtent() {
  229. unsigned framebuffer_width;
  230. unsigned framebuffer_height;
  231. std::tie(framebuffer_width, framebuffer_height) = render_window->GetFramebufferSize();
  232. float window_aspect_ratio = static_cast<float>(framebuffer_height) / framebuffer_width;
  233. float emulation_aspect_ratio = static_cast<float>(resolution_height) / resolution_width;
  234. MathUtil::Rectangle<unsigned> viewport_extent;
  235. if (window_aspect_ratio > emulation_aspect_ratio) {
  236. // Window is narrower than the emulation content => apply borders to the top and bottom
  237. unsigned viewport_height = static_cast<unsigned>(std::round(emulation_aspect_ratio * framebuffer_width));
  238. viewport_extent.left = 0;
  239. viewport_extent.top = (framebuffer_height - viewport_height) / 2;
  240. viewport_extent.right = viewport_extent.left + framebuffer_width;
  241. viewport_extent.bottom = viewport_extent.top + viewport_height;
  242. } else {
  243. // Otherwise, apply borders to the left and right sides of the window.
  244. unsigned viewport_width = static_cast<unsigned>(std::round(framebuffer_height / emulation_aspect_ratio));
  245. viewport_extent.left = (framebuffer_width - viewport_width) / 2;
  246. viewport_extent.top = 0;
  247. viewport_extent.right = viewport_extent.left + viewport_width;
  248. viewport_extent.bottom = viewport_extent.top + framebuffer_height;
  249. }
  250. return viewport_extent;
  251. }
  252. /// Initialize the renderer
  253. void RendererOpenGL::Init() {
  254. render_window->MakeCurrent();
  255. int err = ogl_LoadFunctions();
  256. if (ogl_LOAD_SUCCEEDED != err) {
  257. LOG_CRITICAL(Render_OpenGL, "Failed to initialize GL functions! Exiting...");
  258. exit(-1);
  259. }
  260. LOG_INFO(Render_OpenGL, "GL_VERSION: %s", glGetString(GL_VERSION));
  261. InitOpenGLObjects();
  262. }
  263. /// Shutdown the renderer
  264. void RendererOpenGL::ShutDown() {
  265. }