rasterizer.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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 <tuple>
  8. #include "common/assert.h"
  9. #include "common/bit_field.h"
  10. #include "common/color.h"
  11. #include "common/common_types.h"
  12. #include "common/logging/log.h"
  13. #include "common/math_util.h"
  14. #include "common/microprofile.h"
  15. #include "common/quaternion.h"
  16. #include "common/vector_math.h"
  17. #include "core/hw/gpu.h"
  18. #include "core/memory.h"
  19. #include "video_core/debug_utils/debug_utils.h"
  20. #include "video_core/pica_state.h"
  21. #include "video_core/pica_types.h"
  22. #include "video_core/regs_framebuffer.h"
  23. #include "video_core/regs_rasterizer.h"
  24. #include "video_core/regs_texturing.h"
  25. #include "video_core/shader/shader.h"
  26. #include "video_core/swrasterizer/framebuffer.h"
  27. #include "video_core/swrasterizer/proctex.h"
  28. #include "video_core/swrasterizer/rasterizer.h"
  29. #include "video_core/swrasterizer/texturing.h"
  30. #include "video_core/texture/texture_decode.h"
  31. #include "video_core/utils.h"
  32. namespace Pica {
  33. namespace Rasterizer {
  34. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  35. struct Fix12P4 {
  36. Fix12P4() {}
  37. Fix12P4(u16 val) : val(val) {}
  38. static u16 FracMask() {
  39. return 0xF;
  40. }
  41. static u16 IntMask() {
  42. return (u16)~0xF;
  43. }
  44. operator u16() const {
  45. return val;
  46. }
  47. bool operator<(const Fix12P4& oth) const {
  48. return (u16) * this < (u16)oth;
  49. }
  50. private:
  51. u16 val;
  52. };
  53. /**
  54. * Calculate signed area of the triangle spanned by the three argument vertices.
  55. * The sign denotes an orientation.
  56. *
  57. * @todo define orientation concretely.
  58. */
  59. static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
  60. const Math::Vec2<Fix12P4>& vtx3) {
  61. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  62. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  63. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  64. return Math::Cross(vec1, vec2).z;
  65. };
  66. /// Convert a 3D vector for cube map coordinates to 2D texture coordinates along with the face name
  67. static std::tuple<float24, float24, PAddr> ConvertCubeCoord(float24 u, float24 v, float24 w,
  68. const TexturingRegs& regs) {
  69. const float abs_u = std::abs(u.ToFloat32());
  70. const float abs_v = std::abs(v.ToFloat32());
  71. const float abs_w = std::abs(w.ToFloat32());
  72. float24 x, y, z;
  73. PAddr addr;
  74. if (abs_u > abs_v && abs_u > abs_w) {
  75. if (u > float24::FromFloat32(0)) {
  76. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveX);
  77. y = -v;
  78. } else {
  79. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeX);
  80. y = v;
  81. }
  82. x = -w;
  83. z = u;
  84. } else if (abs_v > abs_w) {
  85. if (v > float24::FromFloat32(0)) {
  86. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveY);
  87. x = u;
  88. } else {
  89. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeY);
  90. x = -u;
  91. }
  92. y = w;
  93. z = v;
  94. } else {
  95. if (w > float24::FromFloat32(0)) {
  96. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveZ);
  97. y = -v;
  98. } else {
  99. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeZ);
  100. y = v;
  101. }
  102. x = u;
  103. z = w;
  104. }
  105. const float24 half = float24::FromFloat32(0.5f);
  106. return std::make_tuple(x / z * half + half, y / z * half + half, addr);
  107. }
  108. float LookupLightingLut(size_t lut_index, u8 index, float delta) {
  109. ASSERT_MSG(lut_index < g_state.lighting.luts.size(), "Out of range lut");
  110. ASSERT_MSG(index < g_state.lighting.luts[0].size(), "Out of range index");
  111. float lut_value = g_state.lighting.luts[lut_index][index].ToFloat();
  112. float lut_diff = g_state.lighting.luts[lut_index][index].DiffToFloat();
  113. return lut_value + lut_diff * delta;
  114. }
  115. std::tuple<Math::Vec4<u8>, Math::Vec4<u8>> ComputeFragmentsColors(const Math::Quaternion<float>& normquat, const Math::Vec3<float>& view) {
  116. const auto& lighting = g_state.regs.lighting;
  117. if (lighting.disable)
  118. return {{}, {}};
  119. // TODO(Subv): Bump mapping
  120. Math::Vec3<float> surface_normal = {0.0f, 0.0f, 1.0f};
  121. if (lighting.config0.bump_mode != LightingRegs::LightingBumpMode::None) {
  122. LOG_CRITICAL(HW_GPU, "unimplemented bump mapping");
  123. UNIMPLEMENTED();
  124. }
  125. // Use the normalized the quaternion when performing the rotation
  126. auto normal = Math::QuaternionRotate(normquat.Normalized(), surface_normal);
  127. Math::Vec3<float> light_vector = {};
  128. Math::Vec4<float> diffuse_sum = {0.f, 0.f, 0.f, 1.f};
  129. Math::Vec4<float> specular_sum = {0.f, 0.f, 0.f, 1.f};
  130. Math::Vec3<float> refl_value = {};
  131. for (unsigned light_index = 0; light_index <= lighting.max_light_index; ++light_index) {
  132. unsigned num = lighting.light_enable.GetNum(light_index);
  133. const auto& light_config = g_state.regs.lighting.light[num];
  134. Math::Vec3<float> position = {float16::FromRaw(light_config.x).ToFloat32(), float16::FromRaw(light_config.y).ToFloat32(), float16::FromRaw(light_config.z).ToFloat32()};
  135. if (light_config.config.directional)
  136. light_vector = position;
  137. else
  138. light_vector = position + view;
  139. light_vector.Normalize();
  140. auto LV_N = Math::Dot(light_vector, normal);
  141. auto dot_product = LV_N;
  142. if (light_config.config.two_sided_diffuse)
  143. dot_product = std::abs(dot_product);
  144. else
  145. dot_product = std::max(dot_product, 0.0f);
  146. float dist_atten = 1.0f;
  147. if (!lighting.IsDistAttenDisabled(num)) {
  148. auto distance = (-view - position).Length();
  149. float scale = Pica::float20::FromRaw(light_config.dist_atten_scale).ToFloat32();
  150. float bias = Pica::float20::FromRaw(light_config.dist_atten_scale).ToFloat32();
  151. size_t lut = static_cast<size_t>(LightingRegs::LightingSampler::DistanceAttenuation) + num;
  152. float sample_loc = scale * distance + bias;
  153. u8 lutindex = MathUtil::Clamp(std::floor(sample_loc * 256.f), 0.0f, 255.0f);
  154. float delta = sample_loc * 256 - lutindex;
  155. dist_atten = LookupLightingLut(lut, lutindex, delta);
  156. }
  157. float clamp_highlights = 1.0f;
  158. if (lighting.config0.clamp_highlights) {
  159. if (LV_N <= 0.f)
  160. clamp_highlights = 0.f;
  161. else
  162. clamp_highlights = 1.f;
  163. }
  164. auto GetLutIndex = [&](unsigned num, LightingRegs::LightingLutInput input,
  165. bool abs) -> std::tuple<u8, float> {
  166. Math::Vec3<float> norm_view = view.Normalized();
  167. Math::Vec3<float> half_angle = (norm_view + light_vector).Normalized();
  168. float result = 0.0f;
  169. switch (input) {
  170. case LightingRegs::LightingLutInput::NH:
  171. result = Math::Dot(normal, half_angle);
  172. break;
  173. case LightingRegs::LightingLutInput::VH:
  174. result = Math::Dot(norm_view, half_angle);
  175. break;
  176. case LightingRegs::LightingLutInput::NV:
  177. result = Math::Dot(normal, norm_view);
  178. break;
  179. case LightingRegs::LightingLutInput::LN:
  180. result = Math::Dot(light_vector, normal);
  181. break;
  182. default:
  183. LOG_CRITICAL(HW_GPU, "Unknown lighting LUT input %d\n", (int)input);
  184. UNIMPLEMENTED();
  185. result = 0.f;
  186. }
  187. if (abs) {
  188. if (light_config.config.two_sided_diffuse)
  189. result = std::abs(result);
  190. else
  191. result = std::max(result, 0.0f);
  192. u8 lutindex = MathUtil::Clamp(std::floor(result * 256.f), 0.0f, 255.0f);
  193. float delta = result * 256 - lutindex;
  194. return { lutindex, delta };
  195. } else {
  196. float flr = std::floor(result * 128.f);
  197. s8 tmpi = MathUtil::Clamp(flr, -128.0f, 127.0f);
  198. float delta = result * 128.f - tmpi;
  199. return { tmpi & 0xFF, delta };
  200. }
  201. };
  202. // Specular 0 component
  203. float d0_lut_value = 1.0f;
  204. if (lighting.config1.disable_lut_d0 == 0 &&
  205. LightingRegs::IsLightingSamplerSupported(
  206. lighting.config0.config, LightingRegs::LightingSampler::Distribution0)) {
  207. // Lookup specular "distribution 0" LUT value
  208. u8 index;
  209. float delta;
  210. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.d0.Value(), lighting.abs_lut_input.disable_d0 == 0);
  211. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.d0);
  212. d0_lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Distribution0), index, delta);
  213. }
  214. Math::Vec3<float> specular_0 = d0_lut_value * light_config.specular_0.ToVec3f();
  215. // If enabled, lookup ReflectRed value, otherwise, 1.0 is used
  216. if (lighting.config1.disable_lut_rr == 0 &&
  217. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  218. LightingRegs::LightingSampler::ReflectRed)) {
  219. u8 index;
  220. float delta;
  221. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rr, lighting.abs_lut_input.disable_rr == 0);
  222. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rr);
  223. refl_value.x = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectRed), index, delta);
  224. } else {
  225. refl_value.x = 1.0f;
  226. }
  227. // If enabled, lookup ReflectGreen value, otherwise, ReflectRed value is used
  228. if (lighting.config1.disable_lut_rg == 0 &&
  229. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  230. LightingRegs::LightingSampler::ReflectGreen)) {
  231. u8 index;
  232. float delta;
  233. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rg, lighting.abs_lut_input.disable_rg == 0);
  234. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rg);
  235. refl_value.y = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectGreen), index, delta);
  236. } else {
  237. refl_value.y = refl_value.x;
  238. }
  239. // If enabled, lookup ReflectBlue value, otherwise, ReflectRed value is used
  240. if (lighting.config1.disable_lut_rb == 0 &&
  241. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  242. LightingRegs::LightingSampler::ReflectBlue)) {
  243. u8 index;
  244. float delta;
  245. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rb, lighting.abs_lut_input.disable_rb == 0);
  246. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rb);
  247. refl_value.z = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectBlue), index, delta);
  248. } else {
  249. refl_value.z = refl_value.x;
  250. }
  251. float d1_lut_value = 1.0f;
  252. if (lighting.config1.disable_lut_d1 == 0 &&
  253. LightingRegs::IsLightingSamplerSupported(
  254. lighting.config0.config, LightingRegs::LightingSampler::Distribution1)) {
  255. // Lookup specular "distribution 1" LUT value
  256. u8 index;
  257. float delta;
  258. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.d1.Value(), lighting.abs_lut_input.disable_d1 == 0);
  259. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.d1);
  260. d1_lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Distribution1), index, delta);
  261. }
  262. Math::Vec3<float> specular_1 = d1_lut_value * refl_value * light_config.specular_1.ToVec3f();
  263. if (lighting.config1.disable_lut_fr == 0 &&
  264. LightingRegs::IsLightingSamplerSupported(
  265. lighting.config0.config, LightingRegs::LightingSampler::Fresnel)) {
  266. // Lookup fresnel LUT value
  267. u8 index;
  268. float delta;
  269. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.fr.Value(), lighting.abs_lut_input.disable_fr == 0);
  270. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.fr);
  271. float lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Fresnel), index, delta);
  272. // Enabled for difffuse lighting alpha component
  273. if (lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::PrimaryAlpha ||
  274. lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
  275. diffuse_sum.a() *= lut_value;
  276. }
  277. // Enabled for the specular lighting alpha component
  278. if (lighting.config0.fresnel_selector ==
  279. LightingRegs::LightingFresnelSelector::SecondaryAlpha ||
  280. lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
  281. specular_sum.a() *= lut_value;
  282. }
  283. }
  284. auto diffuse = light_config.diffuse.ToVec3f() * dot_product + light_config.ambient.ToVec3f();
  285. diffuse_sum += Math::MakeVec(diffuse * dist_atten, 0.0f);
  286. specular_sum += Math::MakeVec((specular_0 + specular_1) * clamp_highlights * dist_atten, 0.f);
  287. }
  288. diffuse_sum += Math::MakeVec(lighting.global_ambient.ToVec3f(), 0.0f);
  289. return {
  290. Math::MakeVec<float>(MathUtil::Clamp(diffuse_sum.x, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.y, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.z, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.w, 0.0f, 1.0f) * 255).Cast<u8>(),
  291. Math::MakeVec<float>(MathUtil::Clamp(specular_sum.x, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.y, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.z, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.w, 0.0f, 1.0f) * 255).Cast<u8>()
  292. };
  293. }
  294. MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
  295. /**
  296. * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
  297. * culling via recursion.
  298. */
  299. static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
  300. bool reversed = false) {
  301. const auto& regs = g_state.regs;
  302. MICROPROFILE_SCOPE(GPU_Rasterization);
  303. // vertex positions in rasterizer coordinates
  304. static auto FloatToFix = [](float24 flt) {
  305. // TODO: Rounding here is necessary to prevent garbage pixels at
  306. // triangle borders. Is it that the correct solution, though?
  307. return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
  308. };
  309. static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
  310. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  311. };
  312. Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
  313. ScreenToRasterizerCoordinates(v1.screenpos),
  314. ScreenToRasterizerCoordinates(v2.screenpos)};
  315. if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
  316. // Make sure we always end up with a triangle wound counter-clockwise
  317. if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
  318. ProcessTriangleInternal(v0, v2, v1, true);
  319. return;
  320. }
  321. } else {
  322. if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
  323. // Reverse vertex order and use the CCW code path.
  324. ProcessTriangleInternal(v0, v2, v1, true);
  325. return;
  326. }
  327. // Cull away triangles which are wound clockwise.
  328. if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
  329. return;
  330. }
  331. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  332. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  333. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  334. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  335. // Convert the scissor box coordinates to 12.4 fixed point
  336. u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
  337. u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
  338. // x2,y2 have +1 added to cover the entire sub-pixel area
  339. u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
  340. u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
  341. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
  342. // Calculate the new bounds
  343. min_x = std::max(min_x, scissor_x1);
  344. min_y = std::max(min_y, scissor_y1);
  345. max_x = std::min(max_x, scissor_x2);
  346. max_y = std::min(max_y, scissor_y2);
  347. }
  348. min_x &= Fix12P4::IntMask();
  349. min_y &= Fix12P4::IntMask();
  350. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  351. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  352. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  353. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  354. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  355. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  356. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  357. const Math::Vec2<Fix12P4>& line1,
  358. const Math::Vec2<Fix12P4>& line2) {
  359. if (line1.y == line2.y) {
  360. // just check if vertex is above us => bottom line parallel to x-axis
  361. return vtx.y < line1.y;
  362. } else {
  363. // check if vertex is on our left => right side
  364. // TODO: Not sure how likely this is to overflow
  365. return (int)vtx.x < (int)line1.x +
  366. ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
  367. ((int)line2.y - (int)line1.y);
  368. }
  369. };
  370. int bias0 =
  371. IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  372. int bias1 =
  373. IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  374. int bias2 =
  375. IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  376. auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
  377. auto textures = regs.texturing.GetTextures();
  378. auto tev_stages = regs.texturing.GetTevStages();
  379. bool stencil_action_enable =
  380. g_state.regs.framebuffer.output_merger.stencil_test.enable &&
  381. g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
  382. const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
  383. // Enter rasterization loop, starting at the center of the topleft bounding box corner.
  384. // TODO: Not sure if looping through x first might be faster
  385. for (u16 y = min_y + 8; y < max_y; y += 0x10) {
  386. for (u16 x = min_x + 8; x < max_x; x += 0x10) {
  387. // Do not process the pixel if it's inside the scissor box and the scissor mode is set
  388. // to Exclude
  389. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
  390. if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
  391. continue;
  392. }
  393. // Calculate the barycentric coordinates w0, w1 and w2
  394. int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  395. int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  396. int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  397. int wsum = w0 + w1 + w2;
  398. // If current pixel is not covered by the current primitive
  399. if (w0 < 0 || w1 < 0 || w2 < 0)
  400. continue;
  401. auto baricentric_coordinates =
  402. Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  403. float24::FromFloat32(static_cast<float>(w1)),
  404. float24::FromFloat32(static_cast<float>(w2)));
  405. float24 interpolated_w_inverse =
  406. float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
  407. // interpolated_z = z / w
  408. float interpolated_z_over_w =
  409. (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
  410. v2.screenpos[2].ToFloat32() * w2) /
  411. wsum;
  412. // Not fully accurate. About 3 bits in precision are missing.
  413. // Z-Buffer (z / w * scale + offset)
  414. float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
  415. float depth_offset =
  416. float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
  417. float depth = interpolated_z_over_w * depth_scale + depth_offset;
  418. // Potentially switch to W-Buffer
  419. if (regs.rasterizer.depthmap_enable ==
  420. Pica::RasterizerRegs::DepthBuffering::WBuffering) {
  421. // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
  422. depth *= interpolated_w_inverse.ToFloat32() * wsum;
  423. }
  424. // Clamp the result
  425. depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
  426. // Perspective correct attribute interpolation:
  427. // Attribute values cannot be calculated by simple linear interpolation since
  428. // they are not linear in screen space. For example, when interpolating a
  429. // texture coordinate across two vertices, something simple like
  430. // u = (u0*w0 + u1*w1)/(w0+w1)
  431. // will not work. However, the attribute value divided by the
  432. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  433. // in screenspace. Hence, we can linearly interpolate these two independently and
  434. // calculate the interpolated attribute by dividing the results.
  435. // I.e.
  436. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  437. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  438. // u = u_over_w / one_over_w
  439. //
  440. // The generalization to three vertices is straightforward in baricentric coordinates.
  441. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  442. auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
  443. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  444. return interpolated_attr_over_w * interpolated_w_inverse;
  445. };
  446. Math::Vec4<u8> primary_color{
  447. (u8)(
  448. GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
  449. 255),
  450. (u8)(
  451. GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
  452. 255),
  453. (u8)(
  454. GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
  455. 255),
  456. (u8)(
  457. GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
  458. 255),
  459. };
  460. Math::Quaternion<float> normquat{
  461. {
  462. GetInterpolatedAttribute(v0.quat.x, v1.quat.x, v2.quat.x).ToFloat32(),
  463. GetInterpolatedAttribute(v0.quat.y, v1.quat.y, v2.quat.y).ToFloat32(),
  464. GetInterpolatedAttribute(v0.quat.z, v1.quat.z, v2.quat.z).ToFloat32()
  465. },
  466. GetInterpolatedAttribute(v0.quat.w, v1.quat.w, v2.quat.w).ToFloat32(),
  467. };
  468. Math::Vec3<float> fragment_position{
  469. GetInterpolatedAttribute(v0.view.x, v1.view.x, v2.view.x).ToFloat32(),
  470. GetInterpolatedAttribute(v0.view.y, v1.view.y, v2.view.y).ToFloat32(),
  471. GetInterpolatedAttribute(v0.view.z, v1.view.z, v2.view.z).ToFloat32()
  472. };
  473. Math::Vec2<float24> uv[3];
  474. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  475. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  476. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  477. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  478. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  479. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  480. Math::Vec4<u8> texture_color[4]{};
  481. for (int i = 0; i < 3; ++i) {
  482. const auto& texture = textures[i];
  483. if (!texture.enabled)
  484. continue;
  485. DEBUG_ASSERT(0 != texture.config.address);
  486. int coordinate_i =
  487. (i == 2 && regs.texturing.main_config.texture2_use_coord1) ? 1 : i;
  488. float24 u = uv[coordinate_i].u();
  489. float24 v = uv[coordinate_i].v();
  490. // Only unit 0 respects the texturing type (according to 3DBrew)
  491. // TODO: Refactor so cubemaps and shadowmaps can be handled
  492. PAddr texture_address = texture.config.GetPhysicalAddress();
  493. if (i == 0) {
  494. switch (texture.config.type) {
  495. case TexturingRegs::TextureConfig::Texture2D:
  496. break;
  497. case TexturingRegs::TextureConfig::TextureCube: {
  498. auto w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  499. std::tie(u, v, texture_address) = ConvertCubeCoord(u, v, w, regs.texturing);
  500. break;
  501. }
  502. case TexturingRegs::TextureConfig::Projection2D: {
  503. auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  504. u /= tc0_w;
  505. v /= tc0_w;
  506. break;
  507. }
  508. default:
  509. // TODO: Change to LOG_ERROR when more types are handled.
  510. LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
  511. UNIMPLEMENTED();
  512. break;
  513. }
  514. }
  515. int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
  516. .ToFloat32();
  517. int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
  518. .ToFloat32();
  519. bool use_border_s = false;
  520. bool use_border_t = false;
  521. if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder) {
  522. use_border_s = s < 0 || s >= static_cast<int>(texture.config.width);
  523. } else if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder2) {
  524. use_border_s = s >= static_cast<int>(texture.config.width);
  525. }
  526. if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder) {
  527. use_border_t = t < 0 || t >= static_cast<int>(texture.config.height);
  528. } else if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder2) {
  529. use_border_t = t >= static_cast<int>(texture.config.height);
  530. }
  531. if (use_border_s || use_border_t) {
  532. auto border_color = texture.config.border_color;
  533. texture_color[i] = {border_color.r, border_color.g, border_color.b,
  534. border_color.a};
  535. } else {
  536. // Textures are laid out from bottom to top, hence we invert the t coordinate.
  537. // NOTE: This may not be the right place for the inversion.
  538. // TODO: Check if this applies to ETC textures, too.
  539. s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
  540. t = texture.config.height - 1 -
  541. GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
  542. const u8* texture_data = Memory::GetPhysicalPointer(texture_address);
  543. auto info =
  544. Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
  545. // TODO: Apply the min and mag filters to the texture
  546. texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
  547. #if PICA_DUMP_TEXTURES
  548. DebugUtils::DumpTexture(texture.config, texture_data);
  549. #endif
  550. }
  551. }
  552. // sample procedural texture
  553. if (regs.texturing.main_config.texture3_enable) {
  554. const auto& proctex_uv = uv[regs.texturing.main_config.texture3_coordinates];
  555. texture_color[3] = ProcTex(proctex_uv.u().ToFloat32(), proctex_uv.v().ToFloat32(),
  556. g_state.regs.texturing, g_state.proctex);
  557. }
  558. // Texture environment - consists of 6 stages of color and alpha combining.
  559. //
  560. // Color combiners take three input color values from some source (e.g. interpolated
  561. // vertex color, texture color, previous stage, etc), perform some very simple
  562. // operations on each of them (e.g. inversion) and then calculate the output color
  563. // with some basic arithmetic. Alpha combiners can be configured separately but work
  564. // analogously.
  565. Math::Vec4<u8> combiner_output;
  566. Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
  567. Math::Vec4<u8> next_combiner_buffer = {
  568. regs.texturing.tev_combiner_buffer_color.r,
  569. regs.texturing.tev_combiner_buffer_color.g,
  570. regs.texturing.tev_combiner_buffer_color.b,
  571. regs.texturing.tev_combiner_buffer_color.a,
  572. };
  573. Math::Vec4<u8> primary_fragment_color;
  574. Math::Vec4<u8> secondary_fragment_color;
  575. std::tie(primary_fragment_color, secondary_fragment_color) = ComputeFragmentsColors(normquat, fragment_position);
  576. for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
  577. ++tev_stage_index) {
  578. const auto& tev_stage = tev_stages[tev_stage_index];
  579. using Source = TexturingRegs::TevStageConfig::Source;
  580. auto GetSource = [&](Source source) -> Math::Vec4<u8> {
  581. switch (source) {
  582. case Source::PrimaryColor:
  583. return primary_color;
  584. case Source::PrimaryFragmentColor:
  585. return primary_fragment_color;
  586. case Source::SecondaryFragmentColor:
  587. return secondary_fragment_color;
  588. case Source::Texture0:
  589. return texture_color[0];
  590. case Source::Texture1:
  591. return texture_color[1];
  592. case Source::Texture2:
  593. return texture_color[2];
  594. case Source::Texture3:
  595. return texture_color[3];
  596. case Source::PreviousBuffer:
  597. return combiner_buffer;
  598. case Source::Constant:
  599. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
  600. tev_stage.const_a};
  601. case Source::Previous:
  602. return combiner_output;
  603. default:
  604. LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
  605. UNIMPLEMENTED();
  606. return {0, 0, 0, 0};
  607. }
  608. };
  609. // color combiner
  610. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  611. // stage as input. Hence, we currently don't directly write the result to
  612. // combiner_output.rgb(), but instead store it in a temporary variable until
  613. // alpha combining has been done.
  614. Math::Vec3<u8> color_result[3] = {
  615. GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
  616. GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
  617. GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
  618. };
  619. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  620. u8 alpha_output;
  621. if (tev_stage.color_op == TexturingRegs::TevStageConfig::Operation::Dot3_RGBA) {
  622. // result of Dot3_RGBA operation is also placed to the alpha component
  623. alpha_output = color_output.x;
  624. } else {
  625. // alpha combiner
  626. std::array<u8, 3> alpha_result = {{
  627. GetAlphaModifier(tev_stage.alpha_modifier1,
  628. GetSource(tev_stage.alpha_source1)),
  629. GetAlphaModifier(tev_stage.alpha_modifier2,
  630. GetSource(tev_stage.alpha_source2)),
  631. GetAlphaModifier(tev_stage.alpha_modifier3,
  632. GetSource(tev_stage.alpha_source3)),
  633. }};
  634. alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  635. }
  636. combiner_output[0] =
  637. std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
  638. combiner_output[1] =
  639. std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
  640. combiner_output[2] =
  641. std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
  642. combiner_output[3] =
  643. std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
  644. combiner_buffer = next_combiner_buffer;
  645. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
  646. tev_stage_index)) {
  647. next_combiner_buffer.r() = combiner_output.r();
  648. next_combiner_buffer.g() = combiner_output.g();
  649. next_combiner_buffer.b() = combiner_output.b();
  650. }
  651. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
  652. tev_stage_index)) {
  653. next_combiner_buffer.a() = combiner_output.a();
  654. }
  655. }
  656. const auto& output_merger = regs.framebuffer.output_merger;
  657. // TODO: Does alpha testing happen before or after stencil?
  658. if (output_merger.alpha_test.enable) {
  659. bool pass = false;
  660. switch (output_merger.alpha_test.func) {
  661. case FramebufferRegs::CompareFunc::Never:
  662. pass = false;
  663. break;
  664. case FramebufferRegs::CompareFunc::Always:
  665. pass = true;
  666. break;
  667. case FramebufferRegs::CompareFunc::Equal:
  668. pass = combiner_output.a() == output_merger.alpha_test.ref;
  669. break;
  670. case FramebufferRegs::CompareFunc::NotEqual:
  671. pass = combiner_output.a() != output_merger.alpha_test.ref;
  672. break;
  673. case FramebufferRegs::CompareFunc::LessThan:
  674. pass = combiner_output.a() < output_merger.alpha_test.ref;
  675. break;
  676. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  677. pass = combiner_output.a() <= output_merger.alpha_test.ref;
  678. break;
  679. case FramebufferRegs::CompareFunc::GreaterThan:
  680. pass = combiner_output.a() > output_merger.alpha_test.ref;
  681. break;
  682. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  683. pass = combiner_output.a() >= output_merger.alpha_test.ref;
  684. break;
  685. }
  686. if (!pass)
  687. continue;
  688. }
  689. // Apply fog combiner
  690. // Not fully accurate. We'd have to know what data type is used to
  691. // store the depth etc. Using float for now until we know more
  692. // about Pica datatypes
  693. if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
  694. const Math::Vec3<u8> fog_color = {
  695. static_cast<u8>(regs.texturing.fog_color.r.Value()),
  696. static_cast<u8>(regs.texturing.fog_color.g.Value()),
  697. static_cast<u8>(regs.texturing.fog_color.b.Value()),
  698. };
  699. // Get index into fog LUT
  700. float fog_index;
  701. if (g_state.regs.texturing.fog_flip) {
  702. fog_index = (1.0f - depth) * 128.0f;
  703. } else {
  704. fog_index = depth * 128.0f;
  705. }
  706. // Generate clamped fog factor from LUT for given fog index
  707. float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
  708. float fog_f = fog_index - fog_i;
  709. const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
  710. float fog_factor = fog_lut_entry.ToFloat() + fog_lut_entry.DiffToFloat() * fog_f;
  711. fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
  712. // Blend the fog
  713. for (unsigned i = 0; i < 3; i++) {
  714. combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
  715. (1.0f - fog_factor) * fog_color[i]);
  716. }
  717. }
  718. u8 old_stencil = 0;
  719. auto UpdateStencil = [stencil_test, x, y,
  720. &old_stencil](Pica::FramebufferRegs::StencilAction action) {
  721. u8 new_stencil =
  722. PerformStencilAction(action, old_stencil, stencil_test.reference_value);
  723. if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
  724. SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
  725. (old_stencil & ~stencil_test.write_mask));
  726. };
  727. if (stencil_action_enable) {
  728. old_stencil = GetStencil(x >> 4, y >> 4);
  729. u8 dest = old_stencil & stencil_test.input_mask;
  730. u8 ref = stencil_test.reference_value & stencil_test.input_mask;
  731. bool pass = false;
  732. switch (stencil_test.func) {
  733. case FramebufferRegs::CompareFunc::Never:
  734. pass = false;
  735. break;
  736. case FramebufferRegs::CompareFunc::Always:
  737. pass = true;
  738. break;
  739. case FramebufferRegs::CompareFunc::Equal:
  740. pass = (ref == dest);
  741. break;
  742. case FramebufferRegs::CompareFunc::NotEqual:
  743. pass = (ref != dest);
  744. break;
  745. case FramebufferRegs::CompareFunc::LessThan:
  746. pass = (ref < dest);
  747. break;
  748. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  749. pass = (ref <= dest);
  750. break;
  751. case FramebufferRegs::CompareFunc::GreaterThan:
  752. pass = (ref > dest);
  753. break;
  754. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  755. pass = (ref >= dest);
  756. break;
  757. }
  758. if (!pass) {
  759. UpdateStencil(stencil_test.action_stencil_fail);
  760. continue;
  761. }
  762. }
  763. // Convert float to integer
  764. unsigned num_bits =
  765. FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
  766. u32 z = (u32)(depth * ((1 << num_bits) - 1));
  767. if (output_merger.depth_test_enable) {
  768. u32 ref_z = GetDepth(x >> 4, y >> 4);
  769. bool pass = false;
  770. switch (output_merger.depth_test_func) {
  771. case FramebufferRegs::CompareFunc::Never:
  772. pass = false;
  773. break;
  774. case FramebufferRegs::CompareFunc::Always:
  775. pass = true;
  776. break;
  777. case FramebufferRegs::CompareFunc::Equal:
  778. pass = z == ref_z;
  779. break;
  780. case FramebufferRegs::CompareFunc::NotEqual:
  781. pass = z != ref_z;
  782. break;
  783. case FramebufferRegs::CompareFunc::LessThan:
  784. pass = z < ref_z;
  785. break;
  786. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  787. pass = z <= ref_z;
  788. break;
  789. case FramebufferRegs::CompareFunc::GreaterThan:
  790. pass = z > ref_z;
  791. break;
  792. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  793. pass = z >= ref_z;
  794. break;
  795. }
  796. if (!pass) {
  797. if (stencil_action_enable)
  798. UpdateStencil(stencil_test.action_depth_fail);
  799. continue;
  800. }
  801. }
  802. if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
  803. output_merger.depth_write_enable) {
  804. SetDepth(x >> 4, y >> 4, z);
  805. }
  806. // The stencil depth_pass action is executed even if depth testing is disabled
  807. if (stencil_action_enable)
  808. UpdateStencil(stencil_test.action_depth_pass);
  809. auto dest = GetPixel(x >> 4, y >> 4);
  810. Math::Vec4<u8> blend_output = combiner_output;
  811. if (output_merger.alphablend_enable) {
  812. auto params = output_merger.alpha_blending;
  813. auto LookupFactor = [&](unsigned channel,
  814. FramebufferRegs::BlendFactor factor) -> u8 {
  815. DEBUG_ASSERT(channel < 4);
  816. const Math::Vec4<u8> blend_const = {
  817. static_cast<u8>(output_merger.blend_const.r),
  818. static_cast<u8>(output_merger.blend_const.g),
  819. static_cast<u8>(output_merger.blend_const.b),
  820. static_cast<u8>(output_merger.blend_const.a),
  821. };
  822. switch (factor) {
  823. case FramebufferRegs::BlendFactor::Zero:
  824. return 0;
  825. case FramebufferRegs::BlendFactor::One:
  826. return 255;
  827. case FramebufferRegs::BlendFactor::SourceColor:
  828. return combiner_output[channel];
  829. case FramebufferRegs::BlendFactor::OneMinusSourceColor:
  830. return 255 - combiner_output[channel];
  831. case FramebufferRegs::BlendFactor::DestColor:
  832. return dest[channel];
  833. case FramebufferRegs::BlendFactor::OneMinusDestColor:
  834. return 255 - dest[channel];
  835. case FramebufferRegs::BlendFactor::SourceAlpha:
  836. return combiner_output.a();
  837. case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
  838. return 255 - combiner_output.a();
  839. case FramebufferRegs::BlendFactor::DestAlpha:
  840. return dest.a();
  841. case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
  842. return 255 - dest.a();
  843. case FramebufferRegs::BlendFactor::ConstantColor:
  844. return blend_const[channel];
  845. case FramebufferRegs::BlendFactor::OneMinusConstantColor:
  846. return 255 - blend_const[channel];
  847. case FramebufferRegs::BlendFactor::ConstantAlpha:
  848. return blend_const.a();
  849. case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
  850. return 255 - blend_const.a();
  851. case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
  852. // Returns 1.0 for the alpha channel
  853. if (channel == 3)
  854. return 255;
  855. return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
  856. default:
  857. LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
  858. UNIMPLEMENTED();
  859. break;
  860. }
  861. return combiner_output[channel];
  862. };
  863. auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
  864. LookupFactor(1, params.factor_source_rgb),
  865. LookupFactor(2, params.factor_source_rgb),
  866. LookupFactor(3, params.factor_source_a));
  867. auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
  868. LookupFactor(1, params.factor_dest_rgb),
  869. LookupFactor(2, params.factor_dest_rgb),
  870. LookupFactor(3, params.factor_dest_a));
  871. blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
  872. params.blend_equation_rgb);
  873. blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
  874. dstfactor, params.blend_equation_a)
  875. .a();
  876. } else {
  877. blend_output =
  878. Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
  879. LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
  880. LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
  881. LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
  882. }
  883. const Math::Vec4<u8> result = {
  884. output_merger.red_enable ? blend_output.r() : dest.r(),
  885. output_merger.green_enable ? blend_output.g() : dest.g(),
  886. output_merger.blue_enable ? blend_output.b() : dest.b(),
  887. output_merger.alpha_enable ? blend_output.a() : dest.a(),
  888. };
  889. if (regs.framebuffer.framebuffer.allow_color_write != 0)
  890. DrawPixel(x >> 4, y >> 4, result);
  891. }
  892. }
  893. }
  894. void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
  895. ProcessTriangleInternal(v0, v1, v2);
  896. }
  897. } // namespace Rasterizer
  898. } // namespace Pica