gl_rasterizer.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstring>
  5. #include <memory>
  6. #include <glad/glad.h>
  7. #include "common/color.h"
  8. #include "common/file_util.h"
  9. #include "common/make_unique.h"
  10. #include "common/math_util.h"
  11. #include "common/microprofile.h"
  12. #include "common/profiler.h"
  13. #include "core/memory.h"
  14. #include "core/settings.h"
  15. #include "core/hw/gpu.h"
  16. #include "video_core/pica.h"
  17. #include "video_core/utils.h"
  18. #include "video_core/renderer_opengl/gl_rasterizer.h"
  19. #include "video_core/renderer_opengl/gl_shader_gen.h"
  20. #include "video_core/renderer_opengl/gl_shader_util.h"
  21. #include "video_core/renderer_opengl/pica_to_gl.h"
  22. static bool IsPassThroughTevStage(const Pica::Regs::TevStageConfig& stage) {
  23. return (stage.color_op == Pica::Regs::TevStageConfig::Operation::Replace &&
  24. stage.alpha_op == Pica::Regs::TevStageConfig::Operation::Replace &&
  25. stage.color_source1 == Pica::Regs::TevStageConfig::Source::Previous &&
  26. stage.alpha_source1 == Pica::Regs::TevStageConfig::Source::Previous &&
  27. stage.color_modifier1 == Pica::Regs::TevStageConfig::ColorModifier::SourceColor &&
  28. stage.alpha_modifier1 == Pica::Regs::TevStageConfig::AlphaModifier::SourceAlpha &&
  29. stage.GetColorMultiplier() == 1 &&
  30. stage.GetAlphaMultiplier() == 1);
  31. }
  32. RasterizerOpenGL::RasterizerOpenGL() : cached_fb_color_addr(0), cached_fb_depth_addr(0) { }
  33. RasterizerOpenGL::~RasterizerOpenGL() { }
  34. void RasterizerOpenGL::InitObjects() {
  35. // Create sampler objects
  36. for (size_t i = 0; i < texture_samplers.size(); ++i) {
  37. texture_samplers[i].Create();
  38. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  39. }
  40. // Generate VBO, VAO and UBO
  41. vertex_buffer.Create();
  42. vertex_array.Create();
  43. uniform_buffer.Create();
  44. state.draw.vertex_array = vertex_array.handle;
  45. state.draw.vertex_buffer = vertex_buffer.handle;
  46. state.draw.uniform_buffer = uniform_buffer.handle;
  47. state.Apply();
  48. // Bind the UBO to binding point 0
  49. glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniform_buffer.handle);
  50. uniform_block_data.dirty = true;
  51. // Set vertex attributes
  52. glVertexAttribPointer(GLShader::ATTRIBUTE_POSITION, 4, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, position));
  53. glEnableVertexAttribArray(GLShader::ATTRIBUTE_POSITION);
  54. glVertexAttribPointer(GLShader::ATTRIBUTE_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, color));
  55. glEnableVertexAttribArray(GLShader::ATTRIBUTE_COLOR);
  56. glVertexAttribPointer(GLShader::ATTRIBUTE_TEXCOORD0, 2, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, tex_coord0));
  57. glVertexAttribPointer(GLShader::ATTRIBUTE_TEXCOORD1, 2, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, tex_coord1));
  58. glVertexAttribPointer(GLShader::ATTRIBUTE_TEXCOORD2, 2, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, tex_coord2));
  59. glEnableVertexAttribArray(GLShader::ATTRIBUTE_TEXCOORD0);
  60. glEnableVertexAttribArray(GLShader::ATTRIBUTE_TEXCOORD1);
  61. glEnableVertexAttribArray(GLShader::ATTRIBUTE_TEXCOORD2);
  62. SetShader();
  63. // Create textures for OGL framebuffer that will be rendered to, initially 1x1 to succeed in framebuffer creation
  64. fb_color_texture.texture.Create();
  65. ReconfigureColorTexture(fb_color_texture, Pica::Regs::ColorFormat::RGBA8, 1, 1);
  66. state.texture_units[0].texture_2d = fb_color_texture.texture.handle;
  67. state.Apply();
  68. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  69. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  70. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  71. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  72. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  73. state.texture_units[0].texture_2d = 0;
  74. state.Apply();
  75. fb_depth_texture.texture.Create();
  76. ReconfigureDepthTexture(fb_depth_texture, Pica::Regs::DepthFormat::D16, 1, 1);
  77. state.texture_units[0].texture_2d = fb_depth_texture.texture.handle;
  78. state.Apply();
  79. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  80. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  81. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  82. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  83. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  84. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
  85. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  86. state.texture_units[0].texture_2d = 0;
  87. state.Apply();
  88. // Configure OpenGL framebuffer
  89. framebuffer.Create();
  90. state.draw.framebuffer = framebuffer.handle;
  91. state.Apply();
  92. glActiveTexture(GL_TEXTURE0);
  93. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_color_texture.texture.handle, 0);
  94. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fb_depth_texture.texture.handle, 0);
  95. ASSERT_MSG(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE,
  96. "OpenGL rasterizer framebuffer setup failed, status %X", glCheckFramebufferStatus(GL_FRAMEBUFFER));
  97. }
  98. void RasterizerOpenGL::Reset() {
  99. SyncCullMode();
  100. SyncDepthModifiers();
  101. SyncBlendEnabled();
  102. SyncBlendFuncs();
  103. SyncBlendColor();
  104. SyncLogicOp();
  105. SyncStencilTest();
  106. SyncDepthTest();
  107. SetShader();
  108. res_cache.InvalidateAll();
  109. }
  110. void RasterizerOpenGL::AddTriangle(const Pica::Shader::OutputVertex& v0,
  111. const Pica::Shader::OutputVertex& v1,
  112. const Pica::Shader::OutputVertex& v2) {
  113. vertex_batch.emplace_back(v0);
  114. vertex_batch.emplace_back(v1);
  115. vertex_batch.emplace_back(v2);
  116. }
  117. void RasterizerOpenGL::DrawTriangles() {
  118. SyncFramebuffer();
  119. SyncDrawState();
  120. if (state.draw.shader_dirty) {
  121. SetShader();
  122. state.draw.shader_dirty = false;
  123. }
  124. if (uniform_block_data.dirty) {
  125. glBufferData(GL_UNIFORM_BUFFER, sizeof(UniformData), &uniform_block_data.data, GL_STATIC_DRAW);
  126. uniform_block_data.dirty = false;
  127. }
  128. glBufferData(GL_ARRAY_BUFFER, vertex_batch.size() * sizeof(HardwareVertex), vertex_batch.data(), GL_STREAM_DRAW);
  129. glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertex_batch.size());
  130. vertex_batch.clear();
  131. // Flush the resource cache at the current depth and color framebuffer addresses for render-to-texture
  132. const auto& regs = Pica::g_state.regs;
  133. u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format)
  134. * fb_color_texture.width * fb_color_texture.height;
  135. u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format)
  136. * fb_depth_texture.width * fb_depth_texture.height;
  137. res_cache.InvalidateInRange(cached_fb_color_addr, cached_fb_color_size, true);
  138. res_cache.InvalidateInRange(cached_fb_depth_addr, cached_fb_depth_size, true);
  139. }
  140. void RasterizerOpenGL::FlushFramebuffer() {
  141. CommitColorBuffer();
  142. CommitDepthBuffer();
  143. }
  144. void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) {
  145. const auto& regs = Pica::g_state.regs;
  146. switch(id) {
  147. // Culling
  148. case PICA_REG_INDEX(cull_mode):
  149. SyncCullMode();
  150. break;
  151. // Depth modifiers
  152. case PICA_REG_INDEX(viewport_depth_range):
  153. case PICA_REG_INDEX(viewport_depth_far_plane):
  154. SyncDepthModifiers();
  155. break;
  156. // Blending
  157. case PICA_REG_INDEX(output_merger.alphablend_enable):
  158. SyncBlendEnabled();
  159. break;
  160. case PICA_REG_INDEX(output_merger.alpha_blending):
  161. SyncBlendFuncs();
  162. break;
  163. case PICA_REG_INDEX(output_merger.blend_const):
  164. SyncBlendColor();
  165. break;
  166. // Alpha test
  167. case PICA_REG_INDEX(output_merger.alpha_test):
  168. SyncAlphaTest();
  169. state.draw.shader_dirty = true;
  170. break;
  171. // Stencil test
  172. case PICA_REG_INDEX(output_merger.stencil_test.raw_func):
  173. case PICA_REG_INDEX(output_merger.stencil_test.raw_op):
  174. SyncStencilTest();
  175. break;
  176. // Depth test
  177. case PICA_REG_INDEX(output_merger.depth_test_enable):
  178. SyncDepthTest();
  179. break;
  180. // Logic op
  181. case PICA_REG_INDEX(output_merger.logic_op):
  182. SyncLogicOp();
  183. break;
  184. // TEV stages
  185. case PICA_REG_INDEX(tev_stage0.color_source1):
  186. case PICA_REG_INDEX(tev_stage0.color_modifier1):
  187. case PICA_REG_INDEX(tev_stage0.color_op):
  188. case PICA_REG_INDEX(tev_stage0.color_scale):
  189. case PICA_REG_INDEX(tev_stage1.color_source1):
  190. case PICA_REG_INDEX(tev_stage1.color_modifier1):
  191. case PICA_REG_INDEX(tev_stage1.color_op):
  192. case PICA_REG_INDEX(tev_stage1.color_scale):
  193. case PICA_REG_INDEX(tev_stage2.color_source1):
  194. case PICA_REG_INDEX(tev_stage2.color_modifier1):
  195. case PICA_REG_INDEX(tev_stage2.color_op):
  196. case PICA_REG_INDEX(tev_stage2.color_scale):
  197. case PICA_REG_INDEX(tev_stage3.color_source1):
  198. case PICA_REG_INDEX(tev_stage3.color_modifier1):
  199. case PICA_REG_INDEX(tev_stage3.color_op):
  200. case PICA_REG_INDEX(tev_stage3.color_scale):
  201. case PICA_REG_INDEX(tev_stage4.color_source1):
  202. case PICA_REG_INDEX(tev_stage4.color_modifier1):
  203. case PICA_REG_INDEX(tev_stage4.color_op):
  204. case PICA_REG_INDEX(tev_stage4.color_scale):
  205. case PICA_REG_INDEX(tev_stage5.color_source1):
  206. case PICA_REG_INDEX(tev_stage5.color_modifier1):
  207. case PICA_REG_INDEX(tev_stage5.color_op):
  208. case PICA_REG_INDEX(tev_stage5.color_scale):
  209. case PICA_REG_INDEX(tev_combiner_buffer_input):
  210. state.draw.shader_dirty = true;
  211. break;
  212. case PICA_REG_INDEX(tev_stage0.const_r):
  213. SyncTevConstColor(0, regs.tev_stage0);
  214. break;
  215. case PICA_REG_INDEX(tev_stage1.const_r):
  216. SyncTevConstColor(1, regs.tev_stage1);
  217. break;
  218. case PICA_REG_INDEX(tev_stage2.const_r):
  219. SyncTevConstColor(2, regs.tev_stage2);
  220. break;
  221. case PICA_REG_INDEX(tev_stage3.const_r):
  222. SyncTevConstColor(3, regs.tev_stage3);
  223. break;
  224. case PICA_REG_INDEX(tev_stage4.const_r):
  225. SyncTevConstColor(4, regs.tev_stage4);
  226. break;
  227. case PICA_REG_INDEX(tev_stage5.const_r):
  228. SyncTevConstColor(5, regs.tev_stage5);
  229. break;
  230. // TEV combiner buffer color
  231. case PICA_REG_INDEX(tev_combiner_buffer_color):
  232. SyncCombinerColor();
  233. break;
  234. }
  235. }
  236. void RasterizerOpenGL::FlushRegion(PAddr addr, u32 size) {
  237. const auto& regs = Pica::g_state.regs;
  238. u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format)
  239. * fb_color_texture.width * fb_color_texture.height;
  240. u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format)
  241. * fb_depth_texture.width * fb_depth_texture.height;
  242. // If source memory region overlaps 3DS framebuffers, commit them before the copy happens
  243. if (MathUtil::IntervalsIntersect(addr, size, cached_fb_color_addr, cached_fb_color_size))
  244. CommitColorBuffer();
  245. if (MathUtil::IntervalsIntersect(addr, size, cached_fb_depth_addr, cached_fb_depth_size))
  246. CommitDepthBuffer();
  247. }
  248. void RasterizerOpenGL::InvalidateRegion(PAddr addr, u32 size) {
  249. const auto& regs = Pica::g_state.regs;
  250. u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format)
  251. * fb_color_texture.width * fb_color_texture.height;
  252. u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format)
  253. * fb_depth_texture.width * fb_depth_texture.height;
  254. // If modified memory region overlaps 3DS framebuffers, reload their contents into OpenGL
  255. if (MathUtil::IntervalsIntersect(addr, size, cached_fb_color_addr, cached_fb_color_size))
  256. ReloadColorBuffer();
  257. if (MathUtil::IntervalsIntersect(addr, size, cached_fb_depth_addr, cached_fb_depth_size))
  258. ReloadDepthBuffer();
  259. // Notify cache of flush in case the region touches a cached resource
  260. res_cache.InvalidateInRange(addr, size);
  261. }
  262. void RasterizerOpenGL::SamplerInfo::Create() {
  263. sampler.Create();
  264. mag_filter = min_filter = TextureConfig::Linear;
  265. wrap_s = wrap_t = TextureConfig::Repeat;
  266. border_color = 0;
  267. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // default is GL_LINEAR_MIPMAP_LINEAR
  268. // Other attributes have correct defaults
  269. }
  270. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Pica::Regs::TextureConfig& config) {
  271. GLuint s = sampler.handle;
  272. if (mag_filter != config.mag_filter) {
  273. mag_filter = config.mag_filter;
  274. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, PicaToGL::TextureFilterMode(mag_filter));
  275. }
  276. if (min_filter != config.min_filter) {
  277. min_filter = config.min_filter;
  278. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, PicaToGL::TextureFilterMode(min_filter));
  279. }
  280. if (wrap_s != config.wrap_s) {
  281. wrap_s = config.wrap_s;
  282. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, PicaToGL::WrapMode(wrap_s));
  283. }
  284. if (wrap_t != config.wrap_t) {
  285. wrap_t = config.wrap_t;
  286. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, PicaToGL::WrapMode(wrap_t));
  287. }
  288. if (wrap_s == TextureConfig::ClampToBorder || wrap_t == TextureConfig::ClampToBorder) {
  289. if (border_color != config.border_color.raw) {
  290. auto gl_color = PicaToGL::ColorRGBA8(border_color);
  291. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, gl_color.data());
  292. }
  293. }
  294. }
  295. void RasterizerOpenGL::ReconfigureColorTexture(TextureInfo& texture, Pica::Regs::ColorFormat format, u32 width, u32 height) {
  296. GLint internal_format;
  297. texture.format = format;
  298. texture.width = width;
  299. texture.height = height;
  300. switch (format) {
  301. case Pica::Regs::ColorFormat::RGBA8:
  302. internal_format = GL_RGBA;
  303. texture.gl_format = GL_RGBA;
  304. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8;
  305. break;
  306. case Pica::Regs::ColorFormat::RGB8:
  307. // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
  308. // specific OpenGL type used in this function using native-endian (that is, little-endian
  309. // mostly everywhere) for words or half-words.
  310. // TODO: check how those behave on big-endian processors.
  311. internal_format = GL_RGB;
  312. texture.gl_format = GL_BGR;
  313. texture.gl_type = GL_UNSIGNED_BYTE;
  314. break;
  315. case Pica::Regs::ColorFormat::RGB5A1:
  316. internal_format = GL_RGBA;
  317. texture.gl_format = GL_RGBA;
  318. texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
  319. break;
  320. case Pica::Regs::ColorFormat::RGB565:
  321. internal_format = GL_RGB;
  322. texture.gl_format = GL_RGB;
  323. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  324. break;
  325. case Pica::Regs::ColorFormat::RGBA4:
  326. internal_format = GL_RGBA;
  327. texture.gl_format = GL_RGBA;
  328. texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
  329. break;
  330. default:
  331. LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer texture color format %x", format);
  332. UNIMPLEMENTED();
  333. break;
  334. }
  335. state.texture_units[0].texture_2d = texture.texture.handle;
  336. state.Apply();
  337. glActiveTexture(GL_TEXTURE0);
  338. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  339. texture.gl_format, texture.gl_type, nullptr);
  340. state.texture_units[0].texture_2d = 0;
  341. state.Apply();
  342. }
  343. void RasterizerOpenGL::ReconfigureDepthTexture(DepthTextureInfo& texture, Pica::Regs::DepthFormat format, u32 width, u32 height) {
  344. GLint internal_format;
  345. texture.format = format;
  346. texture.width = width;
  347. texture.height = height;
  348. switch (format) {
  349. case Pica::Regs::DepthFormat::D16:
  350. internal_format = GL_DEPTH_COMPONENT16;
  351. texture.gl_format = GL_DEPTH_COMPONENT;
  352. texture.gl_type = GL_UNSIGNED_SHORT;
  353. break;
  354. case Pica::Regs::DepthFormat::D24:
  355. internal_format = GL_DEPTH_COMPONENT24;
  356. texture.gl_format = GL_DEPTH_COMPONENT;
  357. texture.gl_type = GL_UNSIGNED_INT;
  358. break;
  359. case Pica::Regs::DepthFormat::D24S8:
  360. internal_format = GL_DEPTH24_STENCIL8;
  361. texture.gl_format = GL_DEPTH_STENCIL;
  362. texture.gl_type = GL_UNSIGNED_INT_24_8;
  363. break;
  364. default:
  365. LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer texture depth format %x", format);
  366. UNIMPLEMENTED();
  367. break;
  368. }
  369. state.texture_units[0].texture_2d = texture.texture.handle;
  370. state.Apply();
  371. glActiveTexture(GL_TEXTURE0);
  372. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  373. texture.gl_format, texture.gl_type, nullptr);
  374. state.texture_units[0].texture_2d = 0;
  375. state.Apply();
  376. }
  377. void RasterizerOpenGL::SetShader() {
  378. PicaShaderConfig config = PicaShaderConfig::CurrentConfig();
  379. std::unique_ptr<PicaShader> shader = Common::make_unique<PicaShader>();
  380. // Find (or generate) the GLSL shader for the current TEV state
  381. auto cached_shader = shader_cache.find(config);
  382. if (cached_shader != shader_cache.end()) {
  383. current_shader = cached_shader->second.get();
  384. state.draw.shader_program = current_shader->shader.handle;
  385. state.Apply();
  386. } else {
  387. LOG_DEBUG(Render_OpenGL, "Creating new shader");
  388. shader->shader.Create(GLShader::GenerateVertexShader().c_str(), GLShader::GenerateFragmentShader(config).c_str());
  389. state.draw.shader_program = shader->shader.handle;
  390. state.Apply();
  391. // Set the texture samplers to correspond to different texture units
  392. GLuint uniform_tex = glGetUniformLocation(shader->shader.handle, "tex[0]");
  393. if (uniform_tex != -1) { glUniform1i(uniform_tex, 0); }
  394. uniform_tex = glGetUniformLocation(shader->shader.handle, "tex[1]");
  395. if (uniform_tex != -1) { glUniform1i(uniform_tex, 1); }
  396. uniform_tex = glGetUniformLocation(shader->shader.handle, "tex[2]");
  397. if (uniform_tex != -1) { glUniform1i(uniform_tex, 2); }
  398. current_shader = shader_cache.emplace(config, std::move(shader)).first->second.get();
  399. unsigned int block_index = glGetUniformBlockIndex(current_shader->shader.handle, "shader_data");
  400. glUniformBlockBinding(current_shader->shader.handle, block_index, 0);
  401. }
  402. // Update uniforms
  403. SyncAlphaTest();
  404. SyncCombinerColor();
  405. auto& tev_stages = Pica::g_state.regs.GetTevStages();
  406. for (int index = 0; index < tev_stages.size(); ++index)
  407. SyncTevConstColor(index, tev_stages[index]);
  408. }
  409. void RasterizerOpenGL::SyncFramebuffer() {
  410. const auto& regs = Pica::g_state.regs;
  411. PAddr new_fb_color_addr = regs.framebuffer.GetColorBufferPhysicalAddress();
  412. Pica::Regs::ColorFormat new_fb_color_format = regs.framebuffer.color_format;
  413. PAddr new_fb_depth_addr = regs.framebuffer.GetDepthBufferPhysicalAddress();
  414. Pica::Regs::DepthFormat new_fb_depth_format = regs.framebuffer.depth_format;
  415. bool fb_size_changed = fb_color_texture.width != static_cast<GLsizei>(regs.framebuffer.GetWidth()) ||
  416. fb_color_texture.height != static_cast<GLsizei>(regs.framebuffer.GetHeight());
  417. bool color_fb_prop_changed = fb_color_texture.format != new_fb_color_format ||
  418. fb_size_changed;
  419. bool depth_fb_prop_changed = fb_depth_texture.format != new_fb_depth_format ||
  420. fb_size_changed;
  421. bool color_fb_modified = cached_fb_color_addr != new_fb_color_addr ||
  422. color_fb_prop_changed;
  423. bool depth_fb_modified = cached_fb_depth_addr != new_fb_depth_addr ||
  424. depth_fb_prop_changed;
  425. // Commit if framebuffer modified in any way
  426. if (color_fb_modified)
  427. CommitColorBuffer();
  428. if (depth_fb_modified)
  429. CommitDepthBuffer();
  430. // Reconfigure framebuffer textures if any property has changed
  431. if (color_fb_prop_changed) {
  432. ReconfigureColorTexture(fb_color_texture, new_fb_color_format,
  433. regs.framebuffer.GetWidth(), regs.framebuffer.GetHeight());
  434. }
  435. if (depth_fb_prop_changed) {
  436. ReconfigureDepthTexture(fb_depth_texture, new_fb_depth_format,
  437. regs.framebuffer.GetWidth(), regs.framebuffer.GetHeight());
  438. // Only attach depth buffer as stencil if it supports stencil
  439. switch (new_fb_depth_format) {
  440. case Pica::Regs::DepthFormat::D16:
  441. case Pica::Regs::DepthFormat::D24:
  442. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  443. break;
  444. case Pica::Regs::DepthFormat::D24S8:
  445. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, fb_depth_texture.texture.handle, 0);
  446. break;
  447. default:
  448. LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer depth format %x", new_fb_depth_format);
  449. UNIMPLEMENTED();
  450. break;
  451. }
  452. }
  453. // Load buffer data again if fb modified in any way
  454. if (color_fb_modified) {
  455. cached_fb_color_addr = new_fb_color_addr;
  456. ReloadColorBuffer();
  457. }
  458. if (depth_fb_modified) {
  459. cached_fb_depth_addr = new_fb_depth_addr;
  460. ReloadDepthBuffer();
  461. }
  462. }
  463. void RasterizerOpenGL::SyncCullMode() {
  464. const auto& regs = Pica::g_state.regs;
  465. switch (regs.cull_mode) {
  466. case Pica::Regs::CullMode::KeepAll:
  467. state.cull.enabled = false;
  468. break;
  469. case Pica::Regs::CullMode::KeepClockWise:
  470. state.cull.enabled = true;
  471. state.cull.front_face = GL_CW;
  472. break;
  473. case Pica::Regs::CullMode::KeepCounterClockWise:
  474. state.cull.enabled = true;
  475. state.cull.front_face = GL_CCW;
  476. break;
  477. default:
  478. LOG_CRITICAL(Render_OpenGL, "Unknown cull mode %d", regs.cull_mode.Value());
  479. UNIMPLEMENTED();
  480. break;
  481. }
  482. }
  483. void RasterizerOpenGL::SyncDepthModifiers() {
  484. float depth_scale = -Pica::float24::FromRawFloat24(Pica::g_state.regs.viewport_depth_range).ToFloat32();
  485. float depth_offset = Pica::float24::FromRawFloat24(Pica::g_state.regs.viewport_depth_far_plane).ToFloat32() / 2.0f;
  486. // TODO: Implement scale modifier
  487. uniform_block_data.data.depth_offset = depth_offset;
  488. uniform_block_data.dirty = true;
  489. }
  490. void RasterizerOpenGL::SyncBlendEnabled() {
  491. state.blend.enabled = (Pica::g_state.regs.output_merger.alphablend_enable == 1);
  492. }
  493. void RasterizerOpenGL::SyncBlendFuncs() {
  494. const auto& regs = Pica::g_state.regs;
  495. state.blend.src_rgb_func = PicaToGL::BlendFunc(regs.output_merger.alpha_blending.factor_source_rgb);
  496. state.blend.dst_rgb_func = PicaToGL::BlendFunc(regs.output_merger.alpha_blending.factor_dest_rgb);
  497. state.blend.src_a_func = PicaToGL::BlendFunc(regs.output_merger.alpha_blending.factor_source_a);
  498. state.blend.dst_a_func = PicaToGL::BlendFunc(regs.output_merger.alpha_blending.factor_dest_a);
  499. }
  500. void RasterizerOpenGL::SyncBlendColor() {
  501. auto blend_color = PicaToGL::ColorRGBA8(Pica::g_state.regs.output_merger.blend_const.raw);
  502. state.blend.color.red = blend_color[0];
  503. state.blend.color.green = blend_color[1];
  504. state.blend.color.blue = blend_color[2];
  505. state.blend.color.alpha = blend_color[3];
  506. }
  507. void RasterizerOpenGL::SyncAlphaTest() {
  508. const auto& regs = Pica::g_state.regs;
  509. if (regs.output_merger.alpha_test.ref != uniform_block_data.data.alphatest_ref) {
  510. uniform_block_data.data.alphatest_ref = regs.output_merger.alpha_test.ref;
  511. uniform_block_data.dirty = true;
  512. }
  513. }
  514. void RasterizerOpenGL::SyncLogicOp() {
  515. state.logic_op = PicaToGL::LogicOp(Pica::g_state.regs.output_merger.logic_op);
  516. }
  517. void RasterizerOpenGL::SyncStencilTest() {
  518. const auto& regs = Pica::g_state.regs;
  519. state.stencil.test_enabled = regs.output_merger.stencil_test.enable && regs.framebuffer.depth_format == Pica::Regs::DepthFormat::D24S8;
  520. state.stencil.test_func = PicaToGL::CompareFunc(regs.output_merger.stencil_test.func);
  521. state.stencil.test_ref = regs.output_merger.stencil_test.reference_value;
  522. state.stencil.test_mask = regs.output_merger.stencil_test.input_mask;
  523. state.stencil.write_mask = regs.output_merger.stencil_test.write_mask;
  524. state.stencil.action_stencil_fail = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_stencil_fail);
  525. state.stencil.action_depth_fail = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_depth_fail);
  526. state.stencil.action_depth_pass = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_depth_pass);
  527. }
  528. void RasterizerOpenGL::SyncDepthTest() {
  529. const auto& regs = Pica::g_state.regs;
  530. state.depth.test_enabled = (regs.output_merger.depth_test_enable == 1);
  531. state.depth.test_func = PicaToGL::CompareFunc(regs.output_merger.depth_test_func);
  532. state.color_mask.red_enabled = regs.output_merger.red_enable;
  533. state.color_mask.green_enabled = regs.output_merger.green_enable;
  534. state.color_mask.blue_enabled = regs.output_merger.blue_enable;
  535. state.color_mask.alpha_enabled = regs.output_merger.alpha_enable;
  536. state.depth.write_mask = regs.output_merger.depth_write_enable ? GL_TRUE : GL_FALSE;
  537. }
  538. void RasterizerOpenGL::SyncCombinerColor() {
  539. auto combiner_color = PicaToGL::ColorRGBA8(Pica::g_state.regs.tev_combiner_buffer_color.raw);
  540. if (combiner_color != uniform_block_data.data.tev_combiner_buffer_color) {
  541. uniform_block_data.data.tev_combiner_buffer_color = combiner_color;
  542. uniform_block_data.dirty = true;
  543. }
  544. }
  545. void RasterizerOpenGL::SyncTevConstColor(int stage_index, const Pica::Regs::TevStageConfig& tev_stage) {
  546. auto const_color = PicaToGL::ColorRGBA8(tev_stage.const_color);
  547. if (const_color != uniform_block_data.data.const_color[stage_index]) {
  548. uniform_block_data.data.const_color[stage_index] = const_color;
  549. uniform_block_data.dirty = true;
  550. }
  551. }
  552. void RasterizerOpenGL::SyncDrawState() {
  553. const auto& regs = Pica::g_state.regs;
  554. // Sync the viewport
  555. GLsizei viewport_width = (GLsizei)Pica::float24::FromRawFloat24(regs.viewport_size_x).ToFloat32() * 2;
  556. GLsizei viewport_height = (GLsizei)Pica::float24::FromRawFloat24(regs.viewport_size_y).ToFloat32() * 2;
  557. // OpenGL uses different y coordinates, so negate corner offset and flip origin
  558. // TODO: Ensure viewport_corner.x should not be negated or origin flipped
  559. // TODO: Use floating-point viewports for accuracy if supported
  560. glViewport((GLsizei)regs.viewport_corner.x,
  561. (GLsizei)regs.viewport_corner.y,
  562. viewport_width, viewport_height);
  563. // Sync bound texture(s), upload if not cached
  564. const auto pica_textures = regs.GetTextures();
  565. for (unsigned texture_index = 0; texture_index < pica_textures.size(); ++texture_index) {
  566. const auto& texture = pica_textures[texture_index];
  567. if (texture.enabled) {
  568. texture_samplers[texture_index].SyncWithConfig(texture.config);
  569. res_cache.LoadAndBindTexture(state, texture_index, texture);
  570. } else {
  571. state.texture_units[texture_index].texture_2d = 0;
  572. }
  573. }
  574. state.draw.uniform_buffer = uniform_buffer.handle;
  575. state.Apply();
  576. }
  577. MICROPROFILE_DEFINE(OpenGL_FramebufferReload, "OpenGL", "FB Reload", MP_RGB(70, 70, 200));
  578. void RasterizerOpenGL::ReloadColorBuffer() {
  579. u8* color_buffer = Memory::GetPhysicalPointer(cached_fb_color_addr);
  580. if (color_buffer == nullptr)
  581. return;
  582. MICROPROFILE_SCOPE(OpenGL_FramebufferReload);
  583. u32 bytes_per_pixel = Pica::Regs::BytesPerColorPixel(fb_color_texture.format);
  584. std::unique_ptr<u8[]> temp_fb_color_buffer(new u8[fb_color_texture.width * fb_color_texture.height * bytes_per_pixel]);
  585. // Directly copy pixels. Internal OpenGL color formats are consistent so no conversion is necessary.
  586. for (int y = 0; y < fb_color_texture.height; ++y) {
  587. for (int x = 0; x < fb_color_texture.width; ++x) {
  588. const u32 coarse_y = y & ~7;
  589. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_color_texture.width * bytes_per_pixel;
  590. u32 gl_pixel_index = (x + (fb_color_texture.height - 1 - y) * fb_color_texture.width) * bytes_per_pixel;
  591. u8* pixel = color_buffer + dst_offset;
  592. memcpy(&temp_fb_color_buffer[gl_pixel_index], pixel, bytes_per_pixel);
  593. }
  594. }
  595. state.texture_units[0].texture_2d = fb_color_texture.texture.handle;
  596. state.Apply();
  597. glActiveTexture(GL_TEXTURE0);
  598. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, fb_color_texture.width, fb_color_texture.height,
  599. fb_color_texture.gl_format, fb_color_texture.gl_type, temp_fb_color_buffer.get());
  600. state.texture_units[0].texture_2d = 0;
  601. state.Apply();
  602. }
  603. void RasterizerOpenGL::ReloadDepthBuffer() {
  604. if (cached_fb_depth_addr == 0)
  605. return;
  606. // TODO: Appears to work, but double-check endianness of depth values and order of depth-stencil
  607. u8* depth_buffer = Memory::GetPhysicalPointer(cached_fb_depth_addr);
  608. if (depth_buffer == nullptr)
  609. return;
  610. MICROPROFILE_SCOPE(OpenGL_FramebufferReload);
  611. u32 bytes_per_pixel = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format);
  612. // OpenGL needs 4 bpp alignment for D24
  613. u32 gl_bpp = bytes_per_pixel == 3 ? 4 : bytes_per_pixel;
  614. std::unique_ptr<u8[]> temp_fb_depth_buffer(new u8[fb_depth_texture.width * fb_depth_texture.height * gl_bpp]);
  615. u8* temp_fb_depth_data = bytes_per_pixel == 3 ? (temp_fb_depth_buffer.get() + 1) : temp_fb_depth_buffer.get();
  616. if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) {
  617. for (int y = 0; y < fb_depth_texture.height; ++y) {
  618. for (int x = 0; x < fb_depth_texture.width; ++x) {
  619. const u32 coarse_y = y & ~7;
  620. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel;
  621. u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width);
  622. u8* pixel = depth_buffer + dst_offset;
  623. u32 depth_stencil = *(u32*)pixel;
  624. ((u32*)temp_fb_depth_data)[gl_pixel_index] = (depth_stencil << 8) | (depth_stencil >> 24);
  625. }
  626. }
  627. } else {
  628. for (int y = 0; y < fb_depth_texture.height; ++y) {
  629. for (int x = 0; x < fb_depth_texture.width; ++x) {
  630. const u32 coarse_y = y & ~7;
  631. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel;
  632. u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width) * gl_bpp;
  633. u8* pixel = depth_buffer + dst_offset;
  634. memcpy(&temp_fb_depth_data[gl_pixel_index], pixel, bytes_per_pixel);
  635. }
  636. }
  637. }
  638. state.texture_units[0].texture_2d = fb_depth_texture.texture.handle;
  639. state.Apply();
  640. glActiveTexture(GL_TEXTURE0);
  641. if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) {
  642. // TODO(Subv): There is a bug with Intel Windows drivers that makes glTexSubImage2D not change the stencil buffer.
  643. // The bug has been reported to Intel (https://communities.intel.com/message/324464)
  644. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, fb_depth_texture.width, fb_depth_texture.height, 0,
  645. GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, temp_fb_depth_buffer.get());
  646. } else {
  647. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, fb_depth_texture.width, fb_depth_texture.height,
  648. fb_depth_texture.gl_format, fb_depth_texture.gl_type, temp_fb_depth_buffer.get());
  649. }
  650. state.texture_units[0].texture_2d = 0;
  651. state.Apply();
  652. }
  653. Common::Profiling::TimingCategory buffer_commit_category("Framebuffer Commit");
  654. MICROPROFILE_DEFINE(OpenGL_FramebufferCommit, "OpenGL", "FB Commit", MP_RGB(70, 70, 200));
  655. void RasterizerOpenGL::CommitColorBuffer() {
  656. if (cached_fb_color_addr != 0) {
  657. u8* color_buffer = Memory::GetPhysicalPointer(cached_fb_color_addr);
  658. if (color_buffer != nullptr) {
  659. Common::Profiling::ScopeTimer timer(buffer_commit_category);
  660. MICROPROFILE_SCOPE(OpenGL_FramebufferCommit);
  661. u32 bytes_per_pixel = Pica::Regs::BytesPerColorPixel(fb_color_texture.format);
  662. std::unique_ptr<u8[]> temp_gl_color_buffer(new u8[fb_color_texture.width * fb_color_texture.height * bytes_per_pixel]);
  663. state.texture_units[0].texture_2d = fb_color_texture.texture.handle;
  664. state.Apply();
  665. glActiveTexture(GL_TEXTURE0);
  666. glGetTexImage(GL_TEXTURE_2D, 0, fb_color_texture.gl_format, fb_color_texture.gl_type, temp_gl_color_buffer.get());
  667. state.texture_units[0].texture_2d = 0;
  668. state.Apply();
  669. // Directly copy pixels. Internal OpenGL color formats are consistent so no conversion is necessary.
  670. for (int y = 0; y < fb_color_texture.height; ++y) {
  671. for (int x = 0; x < fb_color_texture.width; ++x) {
  672. const u32 coarse_y = y & ~7;
  673. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_color_texture.width * bytes_per_pixel;
  674. u32 gl_pixel_index = x * bytes_per_pixel + (fb_color_texture.height - 1 - y) * fb_color_texture.width * bytes_per_pixel;
  675. u8* pixel = color_buffer + dst_offset;
  676. memcpy(pixel, &temp_gl_color_buffer[gl_pixel_index], bytes_per_pixel);
  677. }
  678. }
  679. }
  680. }
  681. }
  682. void RasterizerOpenGL::CommitDepthBuffer() {
  683. if (cached_fb_depth_addr != 0) {
  684. // TODO: Output seems correct visually, but doesn't quite match sw renderer output. One of them is wrong.
  685. u8* depth_buffer = Memory::GetPhysicalPointer(cached_fb_depth_addr);
  686. if (depth_buffer != nullptr) {
  687. Common::Profiling::ScopeTimer timer(buffer_commit_category);
  688. MICROPROFILE_SCOPE(OpenGL_FramebufferCommit);
  689. u32 bytes_per_pixel = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format);
  690. // OpenGL needs 4 bpp alignment for D24
  691. u32 gl_bpp = bytes_per_pixel == 3 ? 4 : bytes_per_pixel;
  692. std::unique_ptr<u8[]> temp_gl_depth_buffer(new u8[fb_depth_texture.width * fb_depth_texture.height * gl_bpp]);
  693. state.texture_units[0].texture_2d = fb_depth_texture.texture.handle;
  694. state.Apply();
  695. glActiveTexture(GL_TEXTURE0);
  696. glGetTexImage(GL_TEXTURE_2D, 0, fb_depth_texture.gl_format, fb_depth_texture.gl_type, temp_gl_depth_buffer.get());
  697. state.texture_units[0].texture_2d = 0;
  698. state.Apply();
  699. u8* temp_gl_depth_data = bytes_per_pixel == 3 ? (temp_gl_depth_buffer.get() + 1) : temp_gl_depth_buffer.get();
  700. if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) {
  701. for (int y = 0; y < fb_depth_texture.height; ++y) {
  702. for (int x = 0; x < fb_depth_texture.width; ++x) {
  703. const u32 coarse_y = y & ~7;
  704. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel;
  705. u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width);
  706. u8* pixel = depth_buffer + dst_offset;
  707. u32 depth_stencil = ((u32*)temp_gl_depth_data)[gl_pixel_index];
  708. *(u32*)pixel = (depth_stencil >> 8) | (depth_stencil << 24);
  709. }
  710. }
  711. } else {
  712. for (int y = 0; y < fb_depth_texture.height; ++y) {
  713. for (int x = 0; x < fb_depth_texture.width; ++x) {
  714. const u32 coarse_y = y & ~7;
  715. u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel;
  716. u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width) * gl_bpp;
  717. u8* pixel = depth_buffer + dst_offset;
  718. memcpy(pixel, &temp_gl_depth_data[gl_pixel_index], bytes_per_pixel);
  719. }
  720. }
  721. }
  722. }
  723. }
  724. }