renderer_opengl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 "common/assert.h"
  8. #include "common/emu_window.h"
  9. #include "common/logging/log.h"
  10. #include "common/profiler_reporting.h"
  11. #include "core/memory.h"
  12. #include "core/settings.h"
  13. #include "core/hw/gpu.h"
  14. #include "core/hw/hw.h"
  15. #include "core/hw/lcd.h"
  16. #include "video_core/video_core.h"
  17. #include "video_core/debug_utils/debug_utils.h"
  18. #include "video_core/renderer_opengl/gl_rasterizer.h"
  19. #include "video_core/renderer_opengl/gl_shader_util.h"
  20. #include "video_core/renderer_opengl/gl_shaders.h"
  21. #include "video_core/renderer_opengl/renderer_opengl.h"
  22. /**
  23. * Vertex structure that the drawn screen rectangles are composed of.
  24. */
  25. struct ScreenRectVertex {
  26. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  27. position[0] = x;
  28. position[1] = y;
  29. tex_coord[0] = u;
  30. tex_coord[1] = v;
  31. }
  32. GLfloat position[2];
  33. GLfloat tex_coord[2];
  34. };
  35. /**
  36. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  37. * corner and (width, height) on the lower-bottom.
  38. *
  39. * The projection part of the matrix is trivial, hence these operations are represented
  40. * by a 3x2 matrix.
  41. */
  42. static std::array<GLfloat, 3*2> MakeOrthographicMatrix(const float width, const float height) {
  43. std::array<GLfloat, 3*2> matrix;
  44. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  45. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  46. // Last matrix row is implicitly assumed to be [0, 0, 1].
  47. return matrix;
  48. }
  49. /// RendererOpenGL constructor
  50. RendererOpenGL::RendererOpenGL() {
  51. hw_rasterizer.reset(new RasterizerOpenGL());
  52. resolution_width = std::max(VideoCore::kScreenTopWidth, VideoCore::kScreenBottomWidth);
  53. resolution_height = VideoCore::kScreenTopHeight + VideoCore::kScreenBottomHeight;
  54. }
  55. /// RendererOpenGL destructor
  56. RendererOpenGL::~RendererOpenGL() {
  57. }
  58. /// Swap buffers (render frame)
  59. void RendererOpenGL::SwapBuffers() {
  60. // Maintain the rasterizer's state as a priority
  61. OpenGLState prev_state = OpenGLState::GetCurState();
  62. state.Apply();
  63. for(int i : {0, 1}) {
  64. const auto& framebuffer = GPU::g_regs.framebuffer_config[i];
  65. // Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04
  66. u32 lcd_color_addr = (i == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
  67. lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
  68. LCD::Regs::ColorFill color_fill = {0};
  69. LCD::Read(color_fill.raw, lcd_color_addr);
  70. if (color_fill.is_enabled) {
  71. LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b, textures[i]);
  72. // Resize the texture in case the framebuffer size has changed
  73. textures[i].width = 1;
  74. textures[i].height = 1;
  75. } else {
  76. if (textures[i].width != (GLsizei)framebuffer.width ||
  77. textures[i].height != (GLsizei)framebuffer.height ||
  78. textures[i].format != framebuffer.color_format) {
  79. // Reallocate texture if the framebuffer size has changed.
  80. // This is expected to not happen very often and hence should not be a
  81. // performance problem.
  82. ConfigureFramebufferTexture(textures[i], framebuffer);
  83. }
  84. LoadFBToActiveGLTexture(framebuffer, textures[i]);
  85. // Resize the texture in case the framebuffer size has changed
  86. textures[i].width = framebuffer.width;
  87. textures[i].height = framebuffer.height;
  88. }
  89. }
  90. DrawScreens();
  91. auto& profiler = Common::Profiling::GetProfilingManager();
  92. profiler.FinishFrame();
  93. {
  94. auto aggregator = Common::Profiling::GetTimingResultsAggregator();
  95. aggregator->AddFrame(profiler.GetPreviousFrameResults());
  96. }
  97. // Swap buffers
  98. render_window->PollEvents();
  99. render_window->SwapBuffers();
  100. prev_state.Apply();
  101. profiler.BeginFrame();
  102. bool hw_renderer_enabled = VideoCore::g_hw_renderer_enabled;
  103. if (Settings::values.use_hw_renderer != hw_renderer_enabled) {
  104. // TODO: Save new setting value to config file for next startup
  105. Settings::values.use_hw_renderer = hw_renderer_enabled;
  106. if (Settings::values.use_hw_renderer) {
  107. hw_rasterizer->Reset();
  108. }
  109. }
  110. if (Pica::g_debug_context && Pica::g_debug_context->recorder) {
  111. Pica::g_debug_context->recorder->FrameFinished();
  112. }
  113. }
  114. /**
  115. * Loads framebuffer from emulated memory into the active OpenGL texture.
  116. */
  117. void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer,
  118. const TextureInfo& texture) {
  119. const PAddr framebuffer_addr = framebuffer.active_fb == 0 ?
  120. framebuffer.address_left1 : framebuffer.address_left2;
  121. LOG_TRACE(Render_OpenGL, "0x%08x bytes from 0x%08x(%dx%d), fmt %x",
  122. framebuffer.stride * framebuffer.height,
  123. framebuffer_addr, (int)framebuffer.width,
  124. (int)framebuffer.height, (int)framebuffer.format);
  125. const u8* framebuffer_data = Memory::GetPhysicalPointer(framebuffer_addr);
  126. int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
  127. size_t pixel_stride = framebuffer.stride / bpp;
  128. // OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
  129. ASSERT(pixel_stride * bpp == framebuffer.stride);
  130. // Ensure no bad interactions with GL_UNPACK_ALIGNMENT, which by default
  131. // only allows rows to have a memory alignement of 4.
  132. ASSERT(pixel_stride % 4 == 0);
  133. state.texture_units[0].texture_2d = texture.handle;
  134. state.Apply();
  135. glActiveTexture(GL_TEXTURE0);
  136. glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride);
  137. // Update existing texture
  138. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they
  139. // differ from the LCD resolution.
  140. // TODO: Applications could theoretically crash Citra here by specifying too large
  141. // framebuffer sizes. We should make sure that this cannot happen.
  142. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height,
  143. texture.gl_format, texture.gl_type, framebuffer_data);
  144. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  145. state.texture_units[0].texture_2d = 0;
  146. state.Apply();
  147. }
  148. /**
  149. * Fills active OpenGL texture with the given RGB color.
  150. * Since the color is solid, the texture can be 1x1 but will stretch across whatever it's rendered on.
  151. * This has the added benefit of being *really fast*.
  152. */
  153. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b,
  154. const TextureInfo& texture) {
  155. state.texture_units[0].texture_2d = texture.handle;
  156. state.Apply();
  157. glActiveTexture(GL_TEXTURE0);
  158. u8 framebuffer_data[3] = { color_r, color_g, color_b };
  159. // Update existing texture
  160. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer_data);
  161. }
  162. /**
  163. * Initializes the OpenGL state and creates persistent objects.
  164. */
  165. void RendererOpenGL::InitOpenGLObjects() {
  166. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue, 0.0f);
  167. // Link shaders and get variable locations
  168. program_id = ShaderUtil::LoadShaders(GLShaders::g_vertex_shader, GLShaders::g_fragment_shader);
  169. uniform_modelview_matrix = glGetUniformLocation(program_id, "modelview_matrix");
  170. uniform_color_texture = glGetUniformLocation(program_id, "color_texture");
  171. attrib_position = glGetAttribLocation(program_id, "vert_position");
  172. attrib_tex_coord = glGetAttribLocation(program_id, "vert_tex_coord");
  173. // Generate VBO handle for drawing
  174. glGenBuffers(1, &vertex_buffer_handle);
  175. // Generate VAO
  176. glGenVertexArrays(1, &vertex_array_handle);
  177. state.draw.vertex_array = vertex_array_handle;
  178. state.draw.vertex_buffer = vertex_buffer_handle;
  179. state.Apply();
  180. // Attach vertex data to VAO
  181. glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  182. glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, position));
  183. glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
  184. glEnableVertexAttribArray(attrib_position);
  185. glEnableVertexAttribArray(attrib_tex_coord);
  186. // Allocate textures for each screen
  187. for (auto& texture : textures) {
  188. glGenTextures(1, &texture.handle);
  189. // Allocation of storage is deferred until the first frame, when we
  190. // know the framebuffer size.
  191. state.texture_units[0].texture_2d = texture.handle;
  192. state.Apply();
  193. glActiveTexture(GL_TEXTURE0);
  194. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  195. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  196. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  197. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  198. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  199. }
  200. state.texture_units[0].texture_2d = 0;
  201. state.Apply();
  202. hw_rasterizer->InitObjects();
  203. }
  204. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  205. const GPU::Regs::FramebufferConfig& framebuffer) {
  206. GPU::Regs::PixelFormat format = framebuffer.color_format;
  207. GLint internal_format;
  208. texture.format = format;
  209. texture.width = framebuffer.width;
  210. texture.height = framebuffer.height;
  211. switch (format) {
  212. case GPU::Regs::PixelFormat::RGBA8:
  213. internal_format = GL_RGBA;
  214. texture.gl_format = GL_RGBA;
  215. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8;
  216. break;
  217. case GPU::Regs::PixelFormat::RGB8:
  218. // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
  219. // specific OpenGL type used in this function using native-endian (that is, little-endian
  220. // mostly everywhere) for words or half-words.
  221. // TODO: check how those behave on big-endian processors.
  222. internal_format = GL_RGB;
  223. texture.gl_format = GL_BGR;
  224. texture.gl_type = GL_UNSIGNED_BYTE;
  225. break;
  226. case GPU::Regs::PixelFormat::RGB565:
  227. internal_format = GL_RGB;
  228. texture.gl_format = GL_RGB;
  229. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  230. break;
  231. case GPU::Regs::PixelFormat::RGB5A1:
  232. internal_format = GL_RGBA;
  233. texture.gl_format = GL_RGBA;
  234. texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
  235. break;
  236. case GPU::Regs::PixelFormat::RGBA4:
  237. internal_format = GL_RGBA;
  238. texture.gl_format = GL_RGBA;
  239. texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
  240. break;
  241. default:
  242. UNIMPLEMENTED();
  243. }
  244. state.texture_units[0].texture_2d = texture.handle;
  245. state.Apply();
  246. glActiveTexture(GL_TEXTURE0);
  247. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  248. texture.gl_format, texture.gl_type, nullptr);
  249. }
  250. /**
  251. * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD rotation.
  252. */
  253. void RendererOpenGL::DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h) {
  254. std::array<ScreenRectVertex, 4> vertices = {{
  255. ScreenRectVertex(x, y, 1.f, 0.f),
  256. ScreenRectVertex(x+w, y, 1.f, 1.f),
  257. ScreenRectVertex(x, y+h, 0.f, 0.f),
  258. ScreenRectVertex(x+w, y+h, 0.f, 1.f),
  259. }};
  260. state.texture_units[0].texture_2d = texture.handle;
  261. state.Apply();
  262. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
  263. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  264. }
  265. /**
  266. * Draws the emulated screens to the emulator window.
  267. */
  268. void RendererOpenGL::DrawScreens() {
  269. auto layout = render_window->GetFramebufferLayout();
  270. glViewport(0, 0, layout.width, layout.height);
  271. glClear(GL_COLOR_BUFFER_BIT);
  272. state.draw.shader_program = program_id;
  273. state.Apply();
  274. // Set projection matrix
  275. std::array<GLfloat, 3 * 2> ortho_matrix = MakeOrthographicMatrix((float)layout.width,
  276. (float)layout.height);
  277. glUniformMatrix3x2fv(uniform_modelview_matrix, 1, GL_FALSE, ortho_matrix.data());
  278. // Bind texture in Texture Unit 0
  279. glActiveTexture(GL_TEXTURE0);
  280. glUniform1i(uniform_color_texture, 0);
  281. DrawSingleScreenRotated(textures[0], (float)layout.top_screen.left, (float)layout.top_screen.top,
  282. (float)layout.top_screen.GetWidth(), (float)layout.top_screen.GetHeight());
  283. DrawSingleScreenRotated(textures[1], (float)layout.bottom_screen.left,(float)layout.bottom_screen.top,
  284. (float)layout.bottom_screen.GetWidth(), (float)layout.bottom_screen.GetHeight());
  285. m_current_frame++;
  286. }
  287. /// Updates the framerate
  288. void RendererOpenGL::UpdateFramerate() {
  289. }
  290. /**
  291. * Set the emulator window to use for renderer
  292. * @param window EmuWindow handle to emulator window to use for rendering
  293. */
  294. void RendererOpenGL::SetWindow(EmuWindow* window) {
  295. render_window = window;
  296. }
  297. /// Initialize the renderer
  298. void RendererOpenGL::Init() {
  299. render_window->MakeCurrent();
  300. // TODO: Make frontends initialize this, so they can use gladLoadGLLoader with their own loaders
  301. if (!gladLoadGL()) {
  302. LOG_CRITICAL(Render_OpenGL, "Failed to initialize GL functions! Exiting...");
  303. exit(-1);
  304. }
  305. LOG_INFO(Render_OpenGL, "GL_VERSION: %s", glGetString(GL_VERSION));
  306. LOG_INFO(Render_OpenGL, "GL_VENDOR: %s", glGetString(GL_VENDOR));
  307. LOG_INFO(Render_OpenGL, "GL_RENDERER: %s", glGetString(GL_RENDERER));
  308. InitOpenGLObjects();
  309. }
  310. /// Shutdown the renderer
  311. void RendererOpenGL::ShutDown() {
  312. }