rasterizer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 "common/common_types.h"
  6. #include "math.h"
  7. #include "pica.h"
  8. #include "rasterizer.h"
  9. #include "vertex_shader.h"
  10. #include "debug_utils/debug_utils.h"
  11. namespace Pica {
  12. namespace Rasterizer {
  13. static void DrawPixel(int x, int y, const Math::Vec4<u8>& color) {
  14. u32* color_buffer = reinterpret_cast<u32*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetColorBufferPhysicalAddress())));
  15. u32 value = (color.a() << 24) | (color.r() << 16) | (color.g() << 8) | color.b();
  16. // Assuming RGBA8 format until actual framebuffer format handling is implemented
  17. *(color_buffer + x + y * registers.framebuffer.GetWidth()) = value;
  18. }
  19. static u32 GetDepth(int x, int y) {
  20. u16* depth_buffer = reinterpret_cast<u16*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetDepthBufferPhysicalAddress())));
  21. // Assuming 16-bit depth buffer format until actual format handling is implemented
  22. return *(depth_buffer + x + y * registers.framebuffer.GetWidth());
  23. }
  24. static void SetDepth(int x, int y, u16 value) {
  25. u16* depth_buffer = reinterpret_cast<u16*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetDepthBufferPhysicalAddress())));
  26. // Assuming 16-bit depth buffer format until actual format handling is implemented
  27. *(depth_buffer + x + y * registers.framebuffer.GetWidth()) = value;
  28. }
  29. void ProcessTriangle(const VertexShader::OutputVertex& v0,
  30. const VertexShader::OutputVertex& v1,
  31. const VertexShader::OutputVertex& v2)
  32. {
  33. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  34. struct Fix12P4 {
  35. Fix12P4() {}
  36. Fix12P4(u16 val) : val(val) {}
  37. static u16 FracMask() { return 0xF; }
  38. static u16 IntMask() { return (u16)~0xF; }
  39. operator u16() const {
  40. return val;
  41. }
  42. bool operator < (const Fix12P4& oth) const {
  43. return (u16)*this < (u16)oth;
  44. }
  45. private:
  46. u16 val;
  47. };
  48. // vertex positions in rasterizer coordinates
  49. auto FloatToFix = [](float24 flt) {
  50. return Fix12P4(static_cast<unsigned short>(flt.ToFloat32() * 16.0f));
  51. };
  52. auto ScreenToRasterizerCoordinates = [FloatToFix](const Math::Vec3<float24> vec) {
  53. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  54. };
  55. Math::Vec3<Fix12P4> vtxpos[3]{ ScreenToRasterizerCoordinates(v0.screenpos),
  56. ScreenToRasterizerCoordinates(v1.screenpos),
  57. ScreenToRasterizerCoordinates(v2.screenpos) };
  58. // TODO: Proper scissor rect test!
  59. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  60. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  61. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  62. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  63. min_x &= Fix12P4::IntMask();
  64. min_y &= Fix12P4::IntMask();
  65. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  66. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  67. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  68. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  69. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  70. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  71. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  72. const Math::Vec2<Fix12P4>& line1,
  73. const Math::Vec2<Fix12P4>& line2)
  74. {
  75. if (line1.y == line2.y) {
  76. // just check if vertex is above us => bottom line parallel to x-axis
  77. return vtx.y < line1.y;
  78. } else {
  79. // check if vertex is on our left => right side
  80. // TODO: Not sure how likely this is to overflow
  81. return (int)vtx.x < (int)line1.x + ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) / ((int)line2.y - (int)line1.y);
  82. }
  83. };
  84. int bias0 = IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  85. int bias1 = IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  86. int bias2 = IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  87. // TODO: Not sure if looping through x first might be faster
  88. for (u16 y = min_y; y < max_y; y += 0x10) {
  89. for (u16 x = min_x; x < max_x; x += 0x10) {
  90. // Calculate the barycentric coordinates w0, w1 and w2
  91. auto orient2d = [](const Math::Vec2<Fix12P4>& vtx1,
  92. const Math::Vec2<Fix12P4>& vtx2,
  93. const Math::Vec2<Fix12P4>& vtx3) {
  94. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  95. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  96. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  97. return Math::Cross(vec1, vec2).z;
  98. };
  99. int w0 = bias0 + orient2d(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  100. int w1 = bias1 + orient2d(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  101. int w2 = bias2 + orient2d(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  102. int wsum = w0 + w1 + w2;
  103. // If current pixel is not covered by the current primitive
  104. if (w0 < 0 || w1 < 0 || w2 < 0)
  105. continue;
  106. // Perspective correct attribute interpolation:
  107. // Attribute values cannot be calculated by simple linear interpolation since
  108. // they are not linear in screen space. For example, when interpolating a
  109. // texture coordinate across two vertices, something simple like
  110. // u = (u0*w0 + u1*w1)/(w0+w1)
  111. // will not work. However, the attribute value divided by the
  112. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  113. // in screenspace. Hence, we can linearly interpolate these two independently and
  114. // calculate the interpolated attribute by dividing the results.
  115. // I.e.
  116. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  117. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  118. // u = u_over_w / one_over_w
  119. //
  120. // The generalization to three vertices is straightforward in baricentric coordinates.
  121. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  122. auto attr_over_w = Math::MakeVec(attr0 / v0.pos.w,
  123. attr1 / v1.pos.w,
  124. attr2 / v2.pos.w);
  125. auto w_inverse = Math::MakeVec(float24::FromFloat32(1.f) / v0.pos.w,
  126. float24::FromFloat32(1.f) / v1.pos.w,
  127. float24::FromFloat32(1.f) / v2.pos.w);
  128. auto baricentric_coordinates = Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  129. float24::FromFloat32(static_cast<float>(w1)),
  130. float24::FromFloat32(static_cast<float>(w2)));
  131. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  132. float24 interpolated_w_inverse = Math::Dot(w_inverse, baricentric_coordinates);
  133. return interpolated_attr_over_w / interpolated_w_inverse;
  134. };
  135. Math::Vec4<u8> primary_color{
  136. (u8)(GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() * 255),
  137. (u8)(GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() * 255),
  138. (u8)(GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() * 255),
  139. (u8)(GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() * 255)
  140. };
  141. Math::Vec2<float24> uv[3];
  142. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  143. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  144. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  145. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  146. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  147. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  148. Math::Vec4<u8> texture_color[3]{};
  149. for (int i = 0; i < 3; ++i) {
  150. auto texture = registers.GetTextures()[i];
  151. if (!texture.enabled)
  152. continue;
  153. _dbg_assert_(HW_GPU, 0 != texture.config.address);
  154. int s = (int)(uv[i].u() * float24::FromFloat32(static_cast<float>(texture.config.width))).ToFloat32();
  155. int t = (int)(uv[i].v() * float24::FromFloat32(static_cast<float>(texture.config.height))).ToFloat32();
  156. auto GetWrappedTexCoord = [](Regs::TextureConfig::WrapMode mode, int val, unsigned size) {
  157. switch (mode) {
  158. case Regs::TextureConfig::ClampToEdge:
  159. val = std::max(val, 0);
  160. val = std::min(val, (int)size - 1);
  161. return val;
  162. case Regs::TextureConfig::Repeat:
  163. return (int)(((unsigned)val) % size);
  164. default:
  165. LOG_ERROR(HW_GPU, "Unknown texture coordinate wrapping mode %x\n", (int)mode);
  166. _dbg_assert_(HW_GPU, 0);
  167. return 0;
  168. }
  169. };
  170. s = GetWrappedTexCoord(registers.texture0.wrap_s, s, registers.texture0.width);
  171. t = GetWrappedTexCoord(registers.texture0.wrap_t, t, registers.texture0.height);
  172. u8* texture_data = Memory::GetPointer(PAddrToVAddr(texture.config.GetPhysicalAddress()));
  173. auto info = DebugUtils::TextureInfo::FromPicaRegister(texture.config, texture.format);
  174. texture_color[i] = DebugUtils::LookupTexture(texture_data, s, t, info);
  175. DebugUtils::DumpTexture(texture.config, texture_data);
  176. }
  177. // Texture environment - consists of 6 stages of color and alpha combining.
  178. //
  179. // Color combiners take three input color values from some source (e.g. interpolated
  180. // vertex color, texture color, previous stage, etc), perform some very simple
  181. // operations on each of them (e.g. inversion) and then calculate the output color
  182. // with some basic arithmetic. Alpha combiners can be configured separately but work
  183. // analogously.
  184. Math::Vec4<u8> combiner_output;
  185. for (auto tev_stage : registers.GetTevStages()) {
  186. using Source = Regs::TevStageConfig::Source;
  187. using ColorModifier = Regs::TevStageConfig::ColorModifier;
  188. using AlphaModifier = Regs::TevStageConfig::AlphaModifier;
  189. using Operation = Regs::TevStageConfig::Operation;
  190. auto GetColorSource = [&](Source source) -> Math::Vec4<u8> {
  191. switch (source) {
  192. case Source::PrimaryColor:
  193. return primary_color;
  194. case Source::Texture0:
  195. return texture_color[0];
  196. case Source::Texture1:
  197. return texture_color[1];
  198. case Source::Texture2:
  199. return texture_color[2];
  200. case Source::Constant:
  201. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b, tev_stage.const_a};
  202. case Source::Previous:
  203. return combiner_output;
  204. default:
  205. LOG_ERROR(HW_GPU, "Unknown color combiner source %d\n", (int)source);
  206. _dbg_assert_(HW_GPU, 0);
  207. return {};
  208. }
  209. };
  210. auto GetAlphaSource = [&](Source source) -> u8 {
  211. switch (source) {
  212. case Source::PrimaryColor:
  213. return primary_color.a();
  214. case Source::Texture0:
  215. return texture_color[0].a();
  216. case Source::Texture1:
  217. return texture_color[1].a();
  218. case Source::Texture2:
  219. return texture_color[2].a();
  220. case Source::Constant:
  221. return tev_stage.const_a;
  222. case Source::Previous:
  223. return combiner_output.a();
  224. default:
  225. LOG_ERROR(HW_GPU, "Unknown alpha combiner source %d\n", (int)source);
  226. _dbg_assert_(HW_GPU, 0);
  227. return 0;
  228. }
  229. };
  230. auto GetColorModifier = [](ColorModifier factor, const Math::Vec4<u8>& values) -> Math::Vec3<u8> {
  231. switch (factor)
  232. {
  233. case ColorModifier::SourceColor:
  234. return values.rgb();
  235. case ColorModifier::SourceAlpha:
  236. return { values.a(), values.a(), values.a() };
  237. default:
  238. LOG_ERROR(HW_GPU, "Unknown color factor %d\n", (int)factor);
  239. _dbg_assert_(HW_GPU, 0);
  240. return {};
  241. }
  242. };
  243. auto GetAlphaModifier = [](AlphaModifier factor, u8 value) -> u8 {
  244. switch (factor) {
  245. case AlphaModifier::SourceAlpha:
  246. return value;
  247. case AlphaModifier::OneMinusSourceAlpha:
  248. return 255 - value;
  249. default:
  250. LOG_ERROR(HW_GPU, "Unknown alpha factor %d\n", (int)factor);
  251. _dbg_assert_(HW_GPU, 0);
  252. return 0;
  253. }
  254. };
  255. auto ColorCombine = [](Operation op, const Math::Vec3<u8> input[3]) -> Math::Vec3<u8> {
  256. switch (op) {
  257. case Operation::Replace:
  258. return input[0];
  259. case Operation::Modulate:
  260. return ((input[0] * input[1]) / 255).Cast<u8>();
  261. case Operation::Add:
  262. {
  263. auto result = input[0] + input[1];
  264. result.r() = std::min(255, result.r());
  265. result.g() = std::min(255, result.g());
  266. result.b() = std::min(255, result.b());
  267. return result.Cast<u8>();
  268. }
  269. case Operation::Lerp:
  270. return ((input[0] * input[2] + input[1] * (Math::MakeVec<u8>(255, 255, 255) - input[2]).Cast<u8>()) / 255).Cast<u8>();
  271. default:
  272. LOG_ERROR(HW_GPU, "Unknown color combiner operation %d\n", (int)op);
  273. _dbg_assert_(HW_GPU, 0);
  274. return {};
  275. }
  276. };
  277. auto AlphaCombine = [](Operation op, const std::array<u8,3>& input) -> u8 {
  278. switch (op) {
  279. case Operation::Replace:
  280. return input[0];
  281. case Operation::Modulate:
  282. return input[0] * input[1] / 255;
  283. case Operation::Add:
  284. return std::min(255, input[0] + input[1]);
  285. case Operation::Lerp:
  286. return (input[0] * input[2] + input[1] * (255 - input[2])) / 255;
  287. default:
  288. LOG_ERROR(HW_GPU, "Unknown alpha combiner operation %d\n", (int)op);
  289. _dbg_assert_(HW_GPU, 0);
  290. return 0;
  291. }
  292. };
  293. // color combiner
  294. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  295. // stage as input. Hence, we currently don't directly write the result to
  296. // combiner_output.rgb(), but instead store it in a temporary variable until
  297. // alpha combining has been done.
  298. Math::Vec3<u8> color_result[3] = {
  299. GetColorModifier(tev_stage.color_modifier1, GetColorSource(tev_stage.color_source1)),
  300. GetColorModifier(tev_stage.color_modifier2, GetColorSource(tev_stage.color_source2)),
  301. GetColorModifier(tev_stage.color_modifier3, GetColorSource(tev_stage.color_source3))
  302. };
  303. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  304. // alpha combiner
  305. std::array<u8,3> alpha_result = {
  306. GetAlphaModifier(tev_stage.alpha_modifier1, GetAlphaSource(tev_stage.alpha_source1)),
  307. GetAlphaModifier(tev_stage.alpha_modifier2, GetAlphaSource(tev_stage.alpha_source2)),
  308. GetAlphaModifier(tev_stage.alpha_modifier3, GetAlphaSource(tev_stage.alpha_source3))
  309. };
  310. auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  311. combiner_output = Math::MakeVec(color_output, alpha_output);
  312. }
  313. // TODO: Not sure if the multiplication by 65535 has already been taken care
  314. // of when transforming to screen coordinates or not.
  315. u16 z = (u16)(((float)v0.screenpos[2].ToFloat32() * w0 +
  316. (float)v1.screenpos[2].ToFloat32() * w1 +
  317. (float)v2.screenpos[2].ToFloat32() * w2) * 65535.f / wsum);
  318. SetDepth(x >> 4, y >> 4, z);
  319. DrawPixel(x >> 4, y >> 4, combiner_output);
  320. }
  321. }
  322. }
  323. } // namespace Rasterizer
  324. } // namespace Pica