rasterizer.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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 <array>
  6. #include <cmath>
  7. #include "common/assert.h"
  8. #include "common/bit_field.h"
  9. #include "common/color.h"
  10. #include "common/common_types.h"
  11. #include "common/logging/log.h"
  12. #include "common/math_util.h"
  13. #include "common/microprofile.h"
  14. #include "common/vector_math.h"
  15. #include "core/hw/gpu.h"
  16. #include "core/memory.h"
  17. #include "video_core/debug_utils/debug_utils.h"
  18. #include "video_core/pica_state.h"
  19. #include "video_core/pica_types.h"
  20. #include "video_core/regs_framebuffer.h"
  21. #include "video_core/regs_rasterizer.h"
  22. #include "video_core/regs_texturing.h"
  23. #include "video_core/shader/shader.h"
  24. #include "video_core/swrasterizer/framebuffer.h"
  25. #include "video_core/swrasterizer/rasterizer.h"
  26. #include "video_core/swrasterizer/texturing.h"
  27. #include "video_core/texture/texture_decode.h"
  28. #include "video_core/utils.h"
  29. namespace Pica {
  30. namespace Rasterizer {
  31. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  32. struct Fix12P4 {
  33. Fix12P4() {}
  34. Fix12P4(u16 val) : val(val) {}
  35. static u16 FracMask() {
  36. return 0xF;
  37. }
  38. static u16 IntMask() {
  39. return (u16)~0xF;
  40. }
  41. operator u16() const {
  42. return val;
  43. }
  44. bool operator<(const Fix12P4& oth) const {
  45. return (u16) * this < (u16)oth;
  46. }
  47. private:
  48. u16 val;
  49. };
  50. /**
  51. * Calculate signed area of the triangle spanned by the three argument vertices.
  52. * The sign denotes an orientation.
  53. *
  54. * @todo define orientation concretely.
  55. */
  56. static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
  57. const Math::Vec2<Fix12P4>& vtx3) {
  58. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  59. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  60. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  61. return Math::Cross(vec1, vec2).z;
  62. };
  63. MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
  64. /**
  65. * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
  66. * culling via recursion.
  67. */
  68. static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
  69. bool reversed = false) {
  70. const auto& regs = g_state.regs;
  71. MICROPROFILE_SCOPE(GPU_Rasterization);
  72. // vertex positions in rasterizer coordinates
  73. static auto FloatToFix = [](float24 flt) {
  74. // TODO: Rounding here is necessary to prevent garbage pixels at
  75. // triangle borders. Is it that the correct solution, though?
  76. return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
  77. };
  78. static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
  79. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  80. };
  81. Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
  82. ScreenToRasterizerCoordinates(v1.screenpos),
  83. ScreenToRasterizerCoordinates(v2.screenpos)};
  84. if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
  85. // Make sure we always end up with a triangle wound counter-clockwise
  86. if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
  87. ProcessTriangleInternal(v0, v2, v1, true);
  88. return;
  89. }
  90. } else {
  91. if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
  92. // Reverse vertex order and use the CCW code path.
  93. ProcessTriangleInternal(v0, v2, v1, true);
  94. return;
  95. }
  96. // Cull away triangles which are wound clockwise.
  97. if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
  98. return;
  99. }
  100. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  101. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  102. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  103. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  104. // Convert the scissor box coordinates to 12.4 fixed point
  105. u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
  106. u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
  107. // x2,y2 have +1 added to cover the entire sub-pixel area
  108. u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
  109. u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
  110. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
  111. // Calculate the new bounds
  112. min_x = std::max(min_x, scissor_x1);
  113. min_y = std::max(min_y, scissor_y1);
  114. max_x = std::min(max_x, scissor_x2);
  115. max_y = std::min(max_y, scissor_y2);
  116. }
  117. min_x &= Fix12P4::IntMask();
  118. min_y &= Fix12P4::IntMask();
  119. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  120. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  121. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  122. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  123. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  124. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  125. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  126. const Math::Vec2<Fix12P4>& line1,
  127. const Math::Vec2<Fix12P4>& line2) {
  128. if (line1.y == line2.y) {
  129. // just check if vertex is above us => bottom line parallel to x-axis
  130. return vtx.y < line1.y;
  131. } else {
  132. // check if vertex is on our left => right side
  133. // TODO: Not sure how likely this is to overflow
  134. return (int)vtx.x < (int)line1.x +
  135. ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
  136. ((int)line2.y - (int)line1.y);
  137. }
  138. };
  139. int bias0 =
  140. IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  141. int bias1 =
  142. IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  143. int bias2 =
  144. IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  145. auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
  146. auto textures = regs.texturing.GetTextures();
  147. auto tev_stages = regs.texturing.GetTevStages();
  148. bool stencil_action_enable =
  149. g_state.regs.framebuffer.output_merger.stencil_test.enable &&
  150. g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
  151. const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
  152. // Enter rasterization loop, starting at the center of the topleft bounding box corner.
  153. // TODO: Not sure if looping through x first might be faster
  154. for (u16 y = min_y + 8; y < max_y; y += 0x10) {
  155. for (u16 x = min_x + 8; x < max_x; x += 0x10) {
  156. // Do not process the pixel if it's inside the scissor box and the scissor mode is set
  157. // to Exclude
  158. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
  159. if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
  160. continue;
  161. }
  162. // Calculate the barycentric coordinates w0, w1 and w2
  163. int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  164. int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  165. int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  166. int wsum = w0 + w1 + w2;
  167. // If current pixel is not covered by the current primitive
  168. if (w0 < 0 || w1 < 0 || w2 < 0)
  169. continue;
  170. auto baricentric_coordinates =
  171. Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  172. float24::FromFloat32(static_cast<float>(w1)),
  173. float24::FromFloat32(static_cast<float>(w2)));
  174. float24 interpolated_w_inverse =
  175. float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
  176. // interpolated_z = z / w
  177. float interpolated_z_over_w =
  178. (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
  179. v2.screenpos[2].ToFloat32() * w2) /
  180. wsum;
  181. // Not fully accurate. About 3 bits in precision are missing.
  182. // Z-Buffer (z / w * scale + offset)
  183. float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
  184. float depth_offset =
  185. float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
  186. float depth = interpolated_z_over_w * depth_scale + depth_offset;
  187. // Potentially switch to W-Buffer
  188. if (regs.rasterizer.depthmap_enable ==
  189. Pica::RasterizerRegs::DepthBuffering::WBuffering) {
  190. // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
  191. depth *= interpolated_w_inverse.ToFloat32() * wsum;
  192. }
  193. // Clamp the result
  194. depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
  195. // Perspective correct attribute interpolation:
  196. // Attribute values cannot be calculated by simple linear interpolation since
  197. // they are not linear in screen space. For example, when interpolating a
  198. // texture coordinate across two vertices, something simple like
  199. // u = (u0*w0 + u1*w1)/(w0+w1)
  200. // will not work. However, the attribute value divided by the
  201. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  202. // in screenspace. Hence, we can linearly interpolate these two independently and
  203. // calculate the interpolated attribute by dividing the results.
  204. // I.e.
  205. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  206. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  207. // u = u_over_w / one_over_w
  208. //
  209. // The generalization to three vertices is straightforward in baricentric coordinates.
  210. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  211. auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
  212. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  213. return interpolated_attr_over_w * interpolated_w_inverse;
  214. };
  215. Math::Vec4<u8> primary_color{
  216. (u8)(
  217. GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
  218. 255),
  219. (u8)(
  220. GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
  221. 255),
  222. (u8)(
  223. GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
  224. 255),
  225. (u8)(
  226. GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
  227. 255),
  228. };
  229. Math::Vec2<float24> uv[3];
  230. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  231. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  232. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  233. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  234. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  235. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  236. Math::Vec4<u8> texture_color[3]{};
  237. for (int i = 0; i < 3; ++i) {
  238. const auto& texture = textures[i];
  239. if (!texture.enabled)
  240. continue;
  241. DEBUG_ASSERT(0 != texture.config.address);
  242. float24 u = uv[i].u();
  243. float24 v = uv[i].v();
  244. // Only unit 0 respects the texturing type (according to 3DBrew)
  245. // TODO: Refactor so cubemaps and shadowmaps can be handled
  246. if (i == 0) {
  247. switch (texture.config.type) {
  248. case TexturingRegs::TextureConfig::Texture2D:
  249. break;
  250. case TexturingRegs::TextureConfig::Projection2D: {
  251. auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  252. u /= tc0_w;
  253. v /= tc0_w;
  254. break;
  255. }
  256. default:
  257. // TODO: Change to LOG_ERROR when more types are handled.
  258. LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
  259. UNIMPLEMENTED();
  260. break;
  261. }
  262. }
  263. int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
  264. .ToFloat32();
  265. int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
  266. .ToFloat32();
  267. if ((texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder &&
  268. (s < 0 || static_cast<u32>(s) >= texture.config.width)) ||
  269. (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder &&
  270. (t < 0 || static_cast<u32>(t) >= texture.config.height))) {
  271. auto border_color = texture.config.border_color;
  272. texture_color[i] = {border_color.r, border_color.g, border_color.b,
  273. border_color.a};
  274. } else {
  275. // Textures are laid out from bottom to top, hence we invert the t coordinate.
  276. // NOTE: This may not be the right place for the inversion.
  277. // TODO: Check if this applies to ETC textures, too.
  278. s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
  279. t = texture.config.height - 1 -
  280. GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
  281. u8* texture_data =
  282. Memory::GetPhysicalPointer(texture.config.GetPhysicalAddress());
  283. auto info =
  284. Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
  285. // TODO: Apply the min and mag filters to the texture
  286. texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
  287. #if PICA_DUMP_TEXTURES
  288. DebugUtils::DumpTexture(texture.config, texture_data);
  289. #endif
  290. }
  291. }
  292. // Texture environment - consists of 6 stages of color and alpha combining.
  293. //
  294. // Color combiners take three input color values from some source (e.g. interpolated
  295. // vertex color, texture color, previous stage, etc), perform some very simple
  296. // operations on each of them (e.g. inversion) and then calculate the output color
  297. // with some basic arithmetic. Alpha combiners can be configured separately but work
  298. // analogously.
  299. Math::Vec4<u8> combiner_output;
  300. Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
  301. Math::Vec4<u8> next_combiner_buffer = {
  302. regs.texturing.tev_combiner_buffer_color.r,
  303. regs.texturing.tev_combiner_buffer_color.g,
  304. regs.texturing.tev_combiner_buffer_color.b,
  305. regs.texturing.tev_combiner_buffer_color.a,
  306. };
  307. for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
  308. ++tev_stage_index) {
  309. const auto& tev_stage = tev_stages[tev_stage_index];
  310. using Source = TexturingRegs::TevStageConfig::Source;
  311. auto GetSource = [&](Source source) -> Math::Vec4<u8> {
  312. switch (source) {
  313. case Source::PrimaryColor:
  314. // HACK: Until we implement fragment lighting, use primary_color
  315. case Source::PrimaryFragmentColor:
  316. return primary_color;
  317. // HACK: Until we implement fragment lighting, use zero
  318. case Source::SecondaryFragmentColor:
  319. return {0, 0, 0, 0};
  320. case Source::Texture0:
  321. return texture_color[0];
  322. case Source::Texture1:
  323. return texture_color[1];
  324. case Source::Texture2:
  325. return texture_color[2];
  326. case Source::PreviousBuffer:
  327. return combiner_buffer;
  328. case Source::Constant:
  329. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
  330. tev_stage.const_a};
  331. case Source::Previous:
  332. return combiner_output;
  333. default:
  334. LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
  335. UNIMPLEMENTED();
  336. return {0, 0, 0, 0};
  337. }
  338. };
  339. // color combiner
  340. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  341. // stage as input. Hence, we currently don't directly write the result to
  342. // combiner_output.rgb(), but instead store it in a temporary variable until
  343. // alpha combining has been done.
  344. Math::Vec3<u8> color_result[3] = {
  345. GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
  346. GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
  347. GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
  348. };
  349. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  350. // alpha combiner
  351. std::array<u8, 3> alpha_result = {{
  352. GetAlphaModifier(tev_stage.alpha_modifier1, GetSource(tev_stage.alpha_source1)),
  353. GetAlphaModifier(tev_stage.alpha_modifier2, GetSource(tev_stage.alpha_source2)),
  354. GetAlphaModifier(tev_stage.alpha_modifier3, GetSource(tev_stage.alpha_source3)),
  355. }};
  356. auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  357. combiner_output[0] =
  358. std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
  359. combiner_output[1] =
  360. std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
  361. combiner_output[2] =
  362. std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
  363. combiner_output[3] =
  364. std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
  365. combiner_buffer = next_combiner_buffer;
  366. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
  367. tev_stage_index)) {
  368. next_combiner_buffer.r() = combiner_output.r();
  369. next_combiner_buffer.g() = combiner_output.g();
  370. next_combiner_buffer.b() = combiner_output.b();
  371. }
  372. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
  373. tev_stage_index)) {
  374. next_combiner_buffer.a() = combiner_output.a();
  375. }
  376. }
  377. const auto& output_merger = regs.framebuffer.output_merger;
  378. // TODO: Does alpha testing happen before or after stencil?
  379. if (output_merger.alpha_test.enable) {
  380. bool pass = false;
  381. switch (output_merger.alpha_test.func) {
  382. case FramebufferRegs::CompareFunc::Never:
  383. pass = false;
  384. break;
  385. case FramebufferRegs::CompareFunc::Always:
  386. pass = true;
  387. break;
  388. case FramebufferRegs::CompareFunc::Equal:
  389. pass = combiner_output.a() == output_merger.alpha_test.ref;
  390. break;
  391. case FramebufferRegs::CompareFunc::NotEqual:
  392. pass = combiner_output.a() != output_merger.alpha_test.ref;
  393. break;
  394. case FramebufferRegs::CompareFunc::LessThan:
  395. pass = combiner_output.a() < output_merger.alpha_test.ref;
  396. break;
  397. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  398. pass = combiner_output.a() <= output_merger.alpha_test.ref;
  399. break;
  400. case FramebufferRegs::CompareFunc::GreaterThan:
  401. pass = combiner_output.a() > output_merger.alpha_test.ref;
  402. break;
  403. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  404. pass = combiner_output.a() >= output_merger.alpha_test.ref;
  405. break;
  406. }
  407. if (!pass)
  408. continue;
  409. }
  410. // Apply fog combiner
  411. // Not fully accurate. We'd have to know what data type is used to
  412. // store the depth etc. Using float for now until we know more
  413. // about Pica datatypes
  414. if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
  415. const Math::Vec3<u8> fog_color = {
  416. static_cast<u8>(regs.texturing.fog_color.r.Value()),
  417. static_cast<u8>(regs.texturing.fog_color.g.Value()),
  418. static_cast<u8>(regs.texturing.fog_color.b.Value()),
  419. };
  420. // Get index into fog LUT
  421. float fog_index;
  422. if (g_state.regs.texturing.fog_flip) {
  423. fog_index = (1.0f - depth) * 128.0f;
  424. } else {
  425. fog_index = depth * 128.0f;
  426. }
  427. // Generate clamped fog factor from LUT for given fog index
  428. float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
  429. float fog_f = fog_index - fog_i;
  430. const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
  431. float fog_factor = (fog_lut_entry.value + fog_lut_entry.difference * fog_f) /
  432. 2047.0f; // This is signed fixed point 1.11
  433. fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
  434. // Blend the fog
  435. for (unsigned i = 0; i < 3; i++) {
  436. combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
  437. (1.0f - fog_factor) * fog_color[i]);
  438. }
  439. }
  440. u8 old_stencil = 0;
  441. auto UpdateStencil = [stencil_test, x, y,
  442. &old_stencil](Pica::FramebufferRegs::StencilAction action) {
  443. u8 new_stencil =
  444. PerformStencilAction(action, old_stencil, stencil_test.reference_value);
  445. if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
  446. SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
  447. (old_stencil & ~stencil_test.write_mask));
  448. };
  449. if (stencil_action_enable) {
  450. old_stencil = GetStencil(x >> 4, y >> 4);
  451. u8 dest = old_stencil & stencil_test.input_mask;
  452. u8 ref = stencil_test.reference_value & stencil_test.input_mask;
  453. bool pass = false;
  454. switch (stencil_test.func) {
  455. case FramebufferRegs::CompareFunc::Never:
  456. pass = false;
  457. break;
  458. case FramebufferRegs::CompareFunc::Always:
  459. pass = true;
  460. break;
  461. case FramebufferRegs::CompareFunc::Equal:
  462. pass = (ref == dest);
  463. break;
  464. case FramebufferRegs::CompareFunc::NotEqual:
  465. pass = (ref != dest);
  466. break;
  467. case FramebufferRegs::CompareFunc::LessThan:
  468. pass = (ref < dest);
  469. break;
  470. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  471. pass = (ref <= dest);
  472. break;
  473. case FramebufferRegs::CompareFunc::GreaterThan:
  474. pass = (ref > dest);
  475. break;
  476. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  477. pass = (ref >= dest);
  478. break;
  479. }
  480. if (!pass) {
  481. UpdateStencil(stencil_test.action_stencil_fail);
  482. continue;
  483. }
  484. }
  485. // Convert float to integer
  486. unsigned num_bits =
  487. FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
  488. u32 z = (u32)(depth * ((1 << num_bits) - 1));
  489. if (output_merger.depth_test_enable) {
  490. u32 ref_z = GetDepth(x >> 4, y >> 4);
  491. bool pass = false;
  492. switch (output_merger.depth_test_func) {
  493. case FramebufferRegs::CompareFunc::Never:
  494. pass = false;
  495. break;
  496. case FramebufferRegs::CompareFunc::Always:
  497. pass = true;
  498. break;
  499. case FramebufferRegs::CompareFunc::Equal:
  500. pass = z == ref_z;
  501. break;
  502. case FramebufferRegs::CompareFunc::NotEqual:
  503. pass = z != ref_z;
  504. break;
  505. case FramebufferRegs::CompareFunc::LessThan:
  506. pass = z < ref_z;
  507. break;
  508. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  509. pass = z <= ref_z;
  510. break;
  511. case FramebufferRegs::CompareFunc::GreaterThan:
  512. pass = z > ref_z;
  513. break;
  514. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  515. pass = z >= ref_z;
  516. break;
  517. }
  518. if (!pass) {
  519. if (stencil_action_enable)
  520. UpdateStencil(stencil_test.action_depth_fail);
  521. continue;
  522. }
  523. }
  524. if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
  525. output_merger.depth_write_enable) {
  526. SetDepth(x >> 4, y >> 4, z);
  527. }
  528. // The stencil depth_pass action is executed even if depth testing is disabled
  529. if (stencil_action_enable)
  530. UpdateStencil(stencil_test.action_depth_pass);
  531. auto dest = GetPixel(x >> 4, y >> 4);
  532. Math::Vec4<u8> blend_output = combiner_output;
  533. if (output_merger.alphablend_enable) {
  534. auto params = output_merger.alpha_blending;
  535. auto LookupFactor = [&](unsigned channel,
  536. FramebufferRegs::BlendFactor factor) -> u8 {
  537. DEBUG_ASSERT(channel < 4);
  538. const Math::Vec4<u8> blend_const = {
  539. static_cast<u8>(output_merger.blend_const.r),
  540. static_cast<u8>(output_merger.blend_const.g),
  541. static_cast<u8>(output_merger.blend_const.b),
  542. static_cast<u8>(output_merger.blend_const.a),
  543. };
  544. switch (factor) {
  545. case FramebufferRegs::BlendFactor::Zero:
  546. return 0;
  547. case FramebufferRegs::BlendFactor::One:
  548. return 255;
  549. case FramebufferRegs::BlendFactor::SourceColor:
  550. return combiner_output[channel];
  551. case FramebufferRegs::BlendFactor::OneMinusSourceColor:
  552. return 255 - combiner_output[channel];
  553. case FramebufferRegs::BlendFactor::DestColor:
  554. return dest[channel];
  555. case FramebufferRegs::BlendFactor::OneMinusDestColor:
  556. return 255 - dest[channel];
  557. case FramebufferRegs::BlendFactor::SourceAlpha:
  558. return combiner_output.a();
  559. case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
  560. return 255 - combiner_output.a();
  561. case FramebufferRegs::BlendFactor::DestAlpha:
  562. return dest.a();
  563. case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
  564. return 255 - dest.a();
  565. case FramebufferRegs::BlendFactor::ConstantColor:
  566. return blend_const[channel];
  567. case FramebufferRegs::BlendFactor::OneMinusConstantColor:
  568. return 255 - blend_const[channel];
  569. case FramebufferRegs::BlendFactor::ConstantAlpha:
  570. return blend_const.a();
  571. case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
  572. return 255 - blend_const.a();
  573. case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
  574. // Returns 1.0 for the alpha channel
  575. if (channel == 3)
  576. return 255;
  577. return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
  578. default:
  579. LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
  580. UNIMPLEMENTED();
  581. break;
  582. }
  583. return combiner_output[channel];
  584. };
  585. auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
  586. LookupFactor(1, params.factor_source_rgb),
  587. LookupFactor(2, params.factor_source_rgb),
  588. LookupFactor(3, params.factor_source_a));
  589. auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
  590. LookupFactor(1, params.factor_dest_rgb),
  591. LookupFactor(2, params.factor_dest_rgb),
  592. LookupFactor(3, params.factor_dest_a));
  593. blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
  594. params.blend_equation_rgb);
  595. blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
  596. dstfactor, params.blend_equation_a)
  597. .a();
  598. } else {
  599. blend_output =
  600. Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
  601. LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
  602. LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
  603. LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
  604. }
  605. const Math::Vec4<u8> result = {
  606. output_merger.red_enable ? blend_output.r() : dest.r(),
  607. output_merger.green_enable ? blend_output.g() : dest.g(),
  608. output_merger.blue_enable ? blend_output.b() : dest.b(),
  609. output_merger.alpha_enable ? blend_output.a() : dest.a(),
  610. };
  611. if (regs.framebuffer.framebuffer.allow_color_write != 0)
  612. DrawPixel(x >> 4, y >> 4, result);
  613. }
  614. }
  615. }
  616. void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
  617. ProcessTriangleInternal(v0, v1, v2);
  618. }
  619. } // namespace Rasterizer
  620. } // namespace Pica