Device.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  4. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Math.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/SIMDExtras.h>
  11. #include <AK/SIMDMath.h>
  12. #include <LibCore/ElapsedTimer.h>
  13. #include <LibGfx/Painter.h>
  14. #include <LibGfx/Vector2.h>
  15. #include <LibGfx/Vector3.h>
  16. #include <LibSoftGPU/Config.h>
  17. #include <LibSoftGPU/Device.h>
  18. #include <LibSoftGPU/PixelQuad.h>
  19. #include <LibSoftGPU/SIMD.h>
  20. namespace SoftGPU {
  21. static long long g_num_rasterized_triangles;
  22. static long long g_num_pixels;
  23. static long long g_num_pixels_shaded;
  24. static long long g_num_pixels_blended;
  25. static long long g_num_sampler_calls;
  26. static long long g_num_stencil_writes;
  27. static long long g_num_quads;
  28. using IntVector2 = Gfx::Vector2<int>;
  29. using IntVector3 = Gfx::Vector3<int>;
  30. using AK::SIMD::any;
  31. using AK::SIMD::exp;
  32. using AK::SIMD::expand4;
  33. using AK::SIMD::f32x4;
  34. using AK::SIMD::i32x4;
  35. using AK::SIMD::load4_masked;
  36. using AK::SIMD::maskbits;
  37. using AK::SIMD::maskcount;
  38. using AK::SIMD::none;
  39. using AK::SIMD::store4_masked;
  40. using AK::SIMD::to_f32x4;
  41. using AK::SIMD::to_u32x4;
  42. using AK::SIMD::u32x4;
  43. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  44. {
  45. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  46. }
  47. constexpr static i32x4 edge_function4(const IntVector2& a, const IntVector2& b, const Vector2<i32x4>& c)
  48. {
  49. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  50. }
  51. template<typename T, typename U>
  52. constexpr static auto interpolate(const T& v0, const T& v1, const T& v2, const Vector3<U>& barycentric_coords)
  53. {
  54. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  55. }
  56. static ColorType to_bgra32(FloatVector4 const& color)
  57. {
  58. auto clamped = color.clamped(0.0f, 1.0f);
  59. auto r = static_cast<u8>(clamped.x() * 255);
  60. auto g = static_cast<u8>(clamped.y() * 255);
  61. auto b = static_cast<u8>(clamped.z() * 255);
  62. auto a = static_cast<u8>(clamped.w() * 255);
  63. return a << 24 | r << 16 | g << 8 | b;
  64. }
  65. ALWAYS_INLINE static u32x4 to_bgra32(Vector4<f32x4> const& v)
  66. {
  67. auto clamped = v.clamped(expand4(0.0f), expand4(1.0f));
  68. auto r = to_u32x4(clamped.x() * 255);
  69. auto g = to_u32x4(clamped.y() * 255);
  70. auto b = to_u32x4(clamped.z() * 255);
  71. auto a = to_u32x4(clamped.w() * 255);
  72. return a << 24 | r << 16 | g << 8 | b;
  73. }
  74. static Vector4<f32x4> to_vec4(u32x4 rgba)
  75. {
  76. auto constexpr one_over_255 = expand4(1.0f / 255);
  77. return {
  78. to_f32x4((rgba >> 16) & 0xff) * one_over_255,
  79. to_f32x4((rgba >> 8) & 0xff) * one_over_255,
  80. to_f32x4(rgba & 0xff) * one_over_255,
  81. to_f32x4((rgba >> 24) & 0xff) * one_over_255,
  82. };
  83. }
  84. Gfx::IntRect Device::window_coordinates_to_target_coordinates(Gfx::IntRect const& window_rect)
  85. {
  86. return {
  87. window_rect.x(),
  88. m_frame_buffer->rect().height() - window_rect.height() - window_rect.y(),
  89. window_rect.width(),
  90. window_rect.height(),
  91. };
  92. }
  93. void Device::setup_blend_factors()
  94. {
  95. m_alpha_blend_factors = {};
  96. switch (m_options.blend_source_factor) {
  97. case BlendFactor::Zero:
  98. break;
  99. case BlendFactor::One:
  100. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  101. break;
  102. case BlendFactor::SrcColor:
  103. m_alpha_blend_factors.src_factor_src_color = 1;
  104. break;
  105. case BlendFactor::OneMinusSrcColor:
  106. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  107. m_alpha_blend_factors.src_factor_src_color = -1;
  108. break;
  109. case BlendFactor::SrcAlpha:
  110. m_alpha_blend_factors.src_factor_src_alpha = 1;
  111. break;
  112. case BlendFactor::OneMinusSrcAlpha:
  113. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  114. m_alpha_blend_factors.src_factor_src_alpha = -1;
  115. break;
  116. case BlendFactor::DstAlpha:
  117. m_alpha_blend_factors.src_factor_dst_alpha = 1;
  118. break;
  119. case BlendFactor::OneMinusDstAlpha:
  120. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  121. m_alpha_blend_factors.src_factor_dst_alpha = -1;
  122. break;
  123. case BlendFactor::DstColor:
  124. m_alpha_blend_factors.src_factor_dst_color = 1;
  125. break;
  126. case BlendFactor::OneMinusDstColor:
  127. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  128. m_alpha_blend_factors.src_factor_dst_color = -1;
  129. break;
  130. case BlendFactor::SrcAlphaSaturate:
  131. default:
  132. VERIFY_NOT_REACHED();
  133. }
  134. switch (m_options.blend_destination_factor) {
  135. case BlendFactor::Zero:
  136. break;
  137. case BlendFactor::One:
  138. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  139. break;
  140. case BlendFactor::SrcColor:
  141. m_alpha_blend_factors.dst_factor_src_color = 1;
  142. break;
  143. case BlendFactor::OneMinusSrcColor:
  144. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  145. m_alpha_blend_factors.dst_factor_src_color = -1;
  146. break;
  147. case BlendFactor::SrcAlpha:
  148. m_alpha_blend_factors.dst_factor_src_alpha = 1;
  149. break;
  150. case BlendFactor::OneMinusSrcAlpha:
  151. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  152. m_alpha_blend_factors.dst_factor_src_alpha = -1;
  153. break;
  154. case BlendFactor::DstAlpha:
  155. m_alpha_blend_factors.dst_factor_dst_alpha = 1;
  156. break;
  157. case BlendFactor::OneMinusDstAlpha:
  158. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  159. m_alpha_blend_factors.dst_factor_dst_alpha = -1;
  160. break;
  161. case BlendFactor::DstColor:
  162. m_alpha_blend_factors.dst_factor_dst_color = 1;
  163. break;
  164. case BlendFactor::OneMinusDstColor:
  165. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  166. m_alpha_blend_factors.dst_factor_dst_color = -1;
  167. break;
  168. case BlendFactor::SrcAlphaSaturate:
  169. default:
  170. VERIFY_NOT_REACHED();
  171. }
  172. }
  173. void Device::rasterize_triangle(const Triangle& triangle)
  174. {
  175. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  176. // Return if alpha testing is a no-op
  177. if (m_options.enable_alpha_test && m_options.alpha_test_func == AlphaTestFunction::Never)
  178. return;
  179. // Vertices
  180. Vertex const vertex0 = triangle.vertices[0];
  181. Vertex const vertex1 = triangle.vertices[1];
  182. Vertex const vertex2 = triangle.vertices[2];
  183. constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  184. // Calculate area of the triangle for later tests
  185. IntVector2 const v0 { static_cast<int>(vertex0.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex0.window_coordinates.y() * subpixel_factor) };
  186. IntVector2 const v1 { static_cast<int>(vertex1.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex1.window_coordinates.y() * subpixel_factor) };
  187. IntVector2 const v2 { static_cast<int>(vertex2.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex2.window_coordinates.y() * subpixel_factor) };
  188. int area = edge_function(v0, v1, v2);
  189. if (area == 0)
  190. return;
  191. auto const one_over_area = 1.0f / area;
  192. auto render_bounds = m_frame_buffer->rect();
  193. if (m_options.scissor_enabled)
  194. render_bounds.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  195. // Obey top-left rule:
  196. // This sets up "zero" for later pixel coverage tests.
  197. // Depending on where on the triangle the edge is located
  198. // it is either tested against 0 or 1, effectively
  199. // turning "< 0" into "<= 0"
  200. IntVector3 zero { 1, 1, 1 };
  201. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  202. zero.set_z(0);
  203. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  204. zero.set_x(0);
  205. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  206. zero.set_y(0);
  207. // This function calculates the 3 edge values for the pixel relative to the triangle.
  208. auto calculate_edge_values4 = [v0, v1, v2](Vector2<i32x4> const& p) -> Vector3<i32x4> {
  209. return {
  210. edge_function4(v1, v2, p),
  211. edge_function4(v2, v0, p),
  212. edge_function4(v0, v1, p),
  213. };
  214. };
  215. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  216. auto test_point4 = [zero](Vector3<i32x4> const& edges) -> i32x4 {
  217. return edges.x() >= zero.x()
  218. && edges.y() >= zero.y()
  219. && edges.z() >= zero.z();
  220. };
  221. // Calculate block-based bounds
  222. // clang-format off
  223. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1;
  224. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1) + 2;
  225. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1;
  226. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1) + 2;
  227. // clang-format on
  228. // Fog depths
  229. float const vertex0_eye_absz = fabsf(vertex0.eye_coordinates.z());
  230. float const vertex1_eye_absz = fabsf(vertex1.eye_coordinates.z());
  231. float const vertex2_eye_absz = fabsf(vertex2.eye_coordinates.z());
  232. int const render_bounds_left = render_bounds.x();
  233. int const render_bounds_right = render_bounds.x() + render_bounds.width();
  234. int const render_bounds_top = render_bounds.y();
  235. int const render_bounds_bottom = render_bounds.y() + render_bounds.height();
  236. auto const half_pixel_offset = Vector2<i32x4> {
  237. expand4(subpixel_factor / 2),
  238. expand4(subpixel_factor / 2),
  239. };
  240. auto color_buffer = m_frame_buffer->color_buffer();
  241. auto depth_buffer = m_frame_buffer->depth_buffer();
  242. auto stencil_buffer = m_frame_buffer->stencil_buffer();
  243. // Stencil configuration and writing
  244. auto const stencil_configuration = m_stencil_configuration[Face::Front];
  245. auto const stencil_reference_value = stencil_configuration.reference_value & stencil_configuration.test_mask;
  246. auto write_to_stencil = [](StencilType* stencil_ptrs[4], i32x4 stencil_value, StencilOperation op, StencilType reference_value, StencilType write_mask, i32x4 pixel_mask) {
  247. if (write_mask == 0 || op == StencilOperation::Keep)
  248. return;
  249. switch (op) {
  250. case StencilOperation::Decrement:
  251. stencil_value = (stencil_value & ~write_mask) | (max(stencil_value - 1, expand4(0)) & write_mask);
  252. break;
  253. case StencilOperation::DecrementWrap:
  254. stencil_value = (stencil_value & ~write_mask) | (((stencil_value - 1) & 0xFF) & write_mask);
  255. break;
  256. case StencilOperation::Increment:
  257. stencil_value = (stencil_value & ~write_mask) | (min(stencil_value + 1, expand4(0xFF)) & write_mask);
  258. break;
  259. case StencilOperation::IncrementWrap:
  260. stencil_value = (stencil_value & ~write_mask) | (((stencil_value + 1) & 0xFF) & write_mask);
  261. break;
  262. case StencilOperation::Invert:
  263. stencil_value ^= write_mask;
  264. break;
  265. case StencilOperation::Replace:
  266. stencil_value = (stencil_value & ~write_mask) | (reference_value & write_mask);
  267. break;
  268. case StencilOperation::Zero:
  269. stencil_value &= ~write_mask;
  270. break;
  271. default:
  272. VERIFY_NOT_REACHED();
  273. }
  274. INCREASE_STATISTICS_COUNTER(g_num_stencil_writes, maskcount(pixel_mask));
  275. store4_masked(stencil_value, stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], pixel_mask);
  276. };
  277. // Iterate over all blocks within the bounds of the triangle
  278. for (int by = by0; by < by1; by += 2) {
  279. for (int bx = bx0; bx < bx1; bx += 2) {
  280. PixelQuad quad;
  281. quad.screen_coordinates = {
  282. i32x4 { bx, bx + 1, bx, bx + 1 },
  283. i32x4 { by, by, by + 1, by + 1 },
  284. };
  285. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor + half_pixel_offset);
  286. // Generate triangle coverage mask
  287. quad.mask = test_point4(edge_values);
  288. // Test quad against intersection of render target size and scissor rect
  289. quad.mask &= quad.screen_coordinates.x() >= render_bounds_left
  290. && quad.screen_coordinates.x() < render_bounds_right
  291. && quad.screen_coordinates.y() >= render_bounds_top
  292. && quad.screen_coordinates.y() < render_bounds_bottom;
  293. if (none(quad.mask))
  294. continue;
  295. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  296. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  297. // Calculate barycentric coordinates from previously calculated edge values
  298. quad.barycentrics = Vector3<f32x4> {
  299. to_f32x4(edge_values.x()),
  300. to_f32x4(edge_values.y()),
  301. to_f32x4(edge_values.z()),
  302. } * one_over_area;
  303. int coverage_bits = maskbits(quad.mask);
  304. // Stencil testing
  305. StencilType* stencil_ptrs[4];
  306. i32x4 stencil_value;
  307. if (m_options.enable_stencil_test) {
  308. stencil_ptrs[0] = coverage_bits & 1 ? &stencil_buffer->scanline(by)[bx] : nullptr;
  309. stencil_ptrs[1] = coverage_bits & 2 ? &stencil_buffer->scanline(by)[bx + 1] : nullptr;
  310. stencil_ptrs[2] = coverage_bits & 4 ? &stencil_buffer->scanline(by + 1)[bx] : nullptr;
  311. stencil_ptrs[3] = coverage_bits & 8 ? &stencil_buffer->scanline(by + 1)[bx + 1] : nullptr;
  312. stencil_value = load4_masked(stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], quad.mask);
  313. stencil_value &= stencil_configuration.test_mask;
  314. i32x4 stencil_test_passed;
  315. switch (stencil_configuration.test_function) {
  316. case StencilTestFunction::Always:
  317. stencil_test_passed = expand4(~0);
  318. break;
  319. case StencilTestFunction::Equal:
  320. stencil_test_passed = stencil_value == stencil_reference_value;
  321. break;
  322. case StencilTestFunction::Greater:
  323. stencil_test_passed = stencil_value > stencil_reference_value;
  324. break;
  325. case StencilTestFunction::GreaterOrEqual:
  326. stencil_test_passed = stencil_value >= stencil_reference_value;
  327. break;
  328. case StencilTestFunction::Less:
  329. stencil_test_passed = stencil_value < stencil_reference_value;
  330. break;
  331. case StencilTestFunction::LessOrEqual:
  332. stencil_test_passed = stencil_value <= stencil_reference_value;
  333. break;
  334. case StencilTestFunction::Never:
  335. stencil_test_passed = expand4(0);
  336. break;
  337. case StencilTestFunction::NotEqual:
  338. stencil_test_passed = stencil_value != stencil_reference_value;
  339. break;
  340. default:
  341. VERIFY_NOT_REACHED();
  342. }
  343. // Update stencil buffer for pixels that failed the stencil test
  344. write_to_stencil(
  345. stencil_ptrs,
  346. stencil_value,
  347. stencil_configuration.on_stencil_test_fail,
  348. stencil_reference_value,
  349. stencil_configuration.write_mask,
  350. quad.mask & ~stencil_test_passed);
  351. // Update coverage mask + early quad rejection
  352. quad.mask &= stencil_test_passed;
  353. if (none(quad.mask))
  354. continue;
  355. }
  356. // Depth testing
  357. DepthType* depth_ptrs[4] = {
  358. coverage_bits & 1 ? &depth_buffer->scanline(by)[bx] : nullptr,
  359. coverage_bits & 2 ? &depth_buffer->scanline(by)[bx + 1] : nullptr,
  360. coverage_bits & 4 ? &depth_buffer->scanline(by + 1)[bx] : nullptr,
  361. coverage_bits & 8 ? &depth_buffer->scanline(by + 1)[bx + 1] : nullptr,
  362. };
  363. if (m_options.enable_depth_test) {
  364. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  365. quad.depth = interpolate(vertex0.window_coordinates.z(), vertex1.window_coordinates.z(), vertex2.window_coordinates.z(), quad.barycentrics);
  366. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  367. if (m_options.depth_offset_enabled)
  368. quad.depth += m_options.depth_offset_constant * NumericLimits<float>::epsilon();
  369. i32x4 depth_test_passed;
  370. switch (m_options.depth_func) {
  371. case DepthTestFunction::Always:
  372. depth_test_passed = expand4(~0);
  373. break;
  374. case DepthTestFunction::Never:
  375. depth_test_passed = expand4(0);
  376. break;
  377. case DepthTestFunction::Greater:
  378. depth_test_passed = quad.depth > depth;
  379. break;
  380. case DepthTestFunction::GreaterOrEqual:
  381. depth_test_passed = quad.depth >= depth;
  382. break;
  383. case DepthTestFunction::NotEqual:
  384. #ifdef __SSE__
  385. depth_test_passed = quad.depth != depth;
  386. #else
  387. depth_test_passed = i32x4 {
  388. bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0,
  389. bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0,
  390. bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0,
  391. bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0,
  392. };
  393. #endif
  394. break;
  395. case DepthTestFunction::Equal:
  396. #ifdef __SSE__
  397. depth_test_passed = quad.depth == depth;
  398. #else
  399. //
  400. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  401. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  402. // it is an 80-bit x87 floating point number, however, when stored into the depth buffer, this is
  403. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  404. // used here the comparison fails.
  405. // This could be solved by using a `long double` for the depth buffer, however this would take
  406. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  407. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  408. // equal, we can pretty much guarantee that it's actually equal.
  409. //
  410. depth_test_passed = i32x4 {
  411. bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0,
  412. bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0,
  413. bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0,
  414. bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0,
  415. };
  416. #endif
  417. break;
  418. case DepthTestFunction::LessOrEqual:
  419. depth_test_passed = quad.depth <= depth;
  420. break;
  421. case DepthTestFunction::Less:
  422. depth_test_passed = quad.depth < depth;
  423. break;
  424. default:
  425. VERIFY_NOT_REACHED();
  426. }
  427. // Update stencil buffer for pixels that failed the depth test
  428. if (m_options.enable_stencil_test) {
  429. write_to_stencil(
  430. stencil_ptrs,
  431. stencil_value,
  432. stencil_configuration.on_depth_test_fail,
  433. stencil_reference_value,
  434. stencil_configuration.write_mask,
  435. quad.mask & ~depth_test_passed);
  436. }
  437. // Update coverage mask + early quad rejection
  438. quad.mask &= depth_test_passed;
  439. if (none(quad.mask))
  440. continue;
  441. }
  442. // Update stencil buffer for passed pixels
  443. if (m_options.enable_stencil_test) {
  444. write_to_stencil(
  445. stencil_ptrs,
  446. stencil_value,
  447. stencil_configuration.on_pass,
  448. stencil_reference_value,
  449. stencil_configuration.write_mask,
  450. quad.mask);
  451. }
  452. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  453. // Draw the pixels according to the previously generated mask
  454. auto const w_coordinates = Vector3<f32x4> {
  455. expand4(vertex0.window_coordinates.w()),
  456. expand4(vertex1.window_coordinates.w()),
  457. expand4(vertex2.window_coordinates.w()),
  458. };
  459. auto const interpolated_reciprocal_w = interpolate(w_coordinates.x(), w_coordinates.y(), w_coordinates.z(), quad.barycentrics);
  460. auto const interpolated_w = 1.0f / interpolated_reciprocal_w;
  461. quad.barycentrics = quad.barycentrics * w_coordinates * interpolated_w;
  462. // FIXME: make this more generic. We want to interpolate more than just color and uv
  463. if (m_options.shade_smooth) {
  464. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  465. } else {
  466. quad.vertex_color = expand4(vertex0.color);
  467. }
  468. for (size_t i = 0; i < NUM_SAMPLERS; ++i)
  469. quad.texture_coordinates[i] = interpolate(expand4(vertex0.tex_coords[i]), expand4(vertex1.tex_coords[i]), expand4(vertex2.tex_coords[i]), quad.barycentrics);
  470. if (m_options.fog_enabled) {
  471. // Calculate depth of fragment for fog
  472. //
  473. // OpenGL 1.5 spec chapter 3.10: "An implementation may choose to approximate the
  474. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  475. quad.fog_depth = interpolate(expand4(vertex0_eye_absz), expand4(vertex1_eye_absz), expand4(vertex2_eye_absz), quad.barycentrics);
  476. }
  477. shade_fragments(quad);
  478. if (m_options.enable_alpha_test && m_options.alpha_test_func != AlphaTestFunction::Always && !test_alpha(quad)) {
  479. continue;
  480. }
  481. // Write to depth buffer
  482. if (m_options.enable_depth_test && m_options.enable_depth_write)
  483. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  484. // We will not update the color buffer at all
  485. if (!m_options.color_mask || !m_options.enable_color_write)
  486. continue;
  487. ColorType* color_ptrs[4] = {
  488. coverage_bits & 1 ? &color_buffer->scanline(by)[bx] : nullptr,
  489. coverage_bits & 2 ? &color_buffer->scanline(by)[bx + 1] : nullptr,
  490. coverage_bits & 4 ? &color_buffer->scanline(by + 1)[bx] : nullptr,
  491. coverage_bits & 8 ? &color_buffer->scanline(by + 1)[bx + 1] : nullptr,
  492. };
  493. u32x4 dst_u32;
  494. if (m_options.enable_blending || m_options.color_mask != 0xffffffff)
  495. dst_u32 = load4_masked(color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  496. if (m_options.enable_blending) {
  497. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  498. // Blend color values from pixel_staging into color_buffer
  499. Vector4<f32x4> const& src = quad.out_color;
  500. auto dst = to_vec4(dst_u32);
  501. auto src_factor = expand4(m_alpha_blend_factors.src_constant)
  502. + src * m_alpha_blend_factors.src_factor_src_color
  503. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.src_factor_src_alpha
  504. + dst * m_alpha_blend_factors.src_factor_dst_color
  505. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.src_factor_dst_alpha;
  506. auto dst_factor = expand4(m_alpha_blend_factors.dst_constant)
  507. + src * m_alpha_blend_factors.dst_factor_src_color
  508. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.dst_factor_src_alpha
  509. + dst * m_alpha_blend_factors.dst_factor_dst_color
  510. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.dst_factor_dst_alpha;
  511. quad.out_color = src * src_factor + dst * dst_factor;
  512. }
  513. if (m_options.color_mask == 0xffffffff)
  514. store4_masked(to_bgra32(quad.out_color), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  515. else
  516. store4_masked((to_bgra32(quad.out_color) & m_options.color_mask) | (dst_u32 & ~m_options.color_mask), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  517. }
  518. }
  519. }
  520. Device::Device(Gfx::IntSize const& size)
  521. : m_frame_buffer(FrameBuffer<ColorType, DepthType, StencilType>::try_create(size).release_value_but_fixme_should_propagate_errors())
  522. {
  523. m_options.scissor_box = m_frame_buffer->rect();
  524. m_options.viewport = m_frame_buffer->rect();
  525. }
  526. DeviceInfo Device::info() const
  527. {
  528. return {
  529. .vendor_name = "SerenityOS",
  530. .device_name = "SoftGPU",
  531. .num_texture_units = NUM_SAMPLERS,
  532. .num_lights = NUM_LIGHTS,
  533. .stencil_bits = sizeof(StencilType) * 8,
  534. .supports_npot_textures = true,
  535. };
  536. }
  537. static void generate_texture_coordinates(Vertex& vertex, RasterizerOptions const& options)
  538. {
  539. auto generate_coordinate = [&](size_t texcoord_index, size_t config_index) -> float {
  540. auto mode = options.texcoord_generation_config[texcoord_index][config_index].mode;
  541. switch (mode) {
  542. case TexCoordGenerationMode::ObjectLinear: {
  543. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  544. return coefficients.dot(vertex.position);
  545. }
  546. case TexCoordGenerationMode::EyeLinear: {
  547. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  548. return coefficients.dot(vertex.eye_coordinates);
  549. }
  550. case TexCoordGenerationMode::SphereMap: {
  551. auto const eye_unit = vertex.eye_coordinates.normalized();
  552. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  553. auto const normal = vertex.normal;
  554. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  555. reflection.set_z(reflection.z() + 1);
  556. auto const reflection_value = (config_index == 0) ? reflection.x() : reflection.y();
  557. return reflection_value / (2 * reflection.length()) + 0.5f;
  558. }
  559. case TexCoordGenerationMode::ReflectionMap: {
  560. auto const eye_unit = vertex.eye_coordinates.normalized();
  561. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  562. auto const normal = vertex.normal;
  563. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  564. switch (config_index) {
  565. case 0:
  566. return reflection.x();
  567. case 1:
  568. return reflection.y();
  569. case 2:
  570. return reflection.z();
  571. default:
  572. VERIFY_NOT_REACHED();
  573. }
  574. }
  575. case TexCoordGenerationMode::NormalMap: {
  576. auto const normal = vertex.normal;
  577. switch (config_index) {
  578. case 0:
  579. return normal.x();
  580. case 1:
  581. return normal.y();
  582. case 2:
  583. return normal.z();
  584. default:
  585. VERIFY_NOT_REACHED();
  586. }
  587. }
  588. default:
  589. VERIFY_NOT_REACHED();
  590. }
  591. };
  592. for (size_t i = 0; i < vertex.tex_coords.size(); ++i) {
  593. auto& tex_coord = vertex.tex_coords[i];
  594. auto const enabled_coords = options.texcoord_generation_enabled_coordinates[i];
  595. tex_coord = {
  596. ((enabled_coords & TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(i, 0) : tex_coord.x(),
  597. ((enabled_coords & TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(i, 1) : tex_coord.y(),
  598. ((enabled_coords & TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(i, 2) : tex_coord.z(),
  599. ((enabled_coords & TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(i, 3) : tex_coord.w(),
  600. };
  601. }
  602. }
  603. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix3x3 const& normal_transform,
  604. FloatMatrix4x4 const& projection_transform, FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices,
  605. Vector<size_t> const& enabled_texture_units)
  606. {
  607. // At this point, the user has effectively specified that they are done with defining the geometry
  608. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  609. //
  610. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  611. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  612. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  613. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  614. // 5. The vertices are sorted (for the rasterizer, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  615. // 6. The vertices are then sent off to the rasterizer and drawn to the screen
  616. m_enabled_texture_units = enabled_texture_units;
  617. m_triangle_list.clear_with_capacity();
  618. m_processed_triangles.clear_with_capacity();
  619. // Let's construct some triangles
  620. if (primitive_type == PrimitiveType::Triangles) {
  621. Triangle triangle;
  622. if (vertices.size() < 3)
  623. return;
  624. for (size_t i = 0; i < vertices.size() - 2; i += 3) {
  625. triangle.vertices[0] = vertices.at(i);
  626. triangle.vertices[1] = vertices.at(i + 1);
  627. triangle.vertices[2] = vertices.at(i + 2);
  628. m_triangle_list.append(triangle);
  629. }
  630. } else if (primitive_type == PrimitiveType::Quads) {
  631. // We need to construct two triangles to form the quad
  632. Triangle triangle;
  633. if (vertices.size() < 4)
  634. return;
  635. for (size_t i = 0; i < vertices.size() - 3; i += 4) {
  636. // Triangle 1
  637. triangle.vertices[0] = vertices.at(i);
  638. triangle.vertices[1] = vertices.at(i + 1);
  639. triangle.vertices[2] = vertices.at(i + 2);
  640. m_triangle_list.append(triangle);
  641. // Triangle 2
  642. triangle.vertices[0] = vertices.at(i + 2);
  643. triangle.vertices[1] = vertices.at(i + 3);
  644. triangle.vertices[2] = vertices.at(i);
  645. m_triangle_list.append(triangle);
  646. }
  647. } else if (primitive_type == PrimitiveType::TriangleFan) {
  648. Triangle triangle;
  649. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  650. // This is technically `n-2` triangles. We start at index 1
  651. for (size_t i = 1; i < vertices.size() - 1; i++) {
  652. triangle.vertices[1] = vertices.at(i);
  653. triangle.vertices[2] = vertices.at(i + 1);
  654. m_triangle_list.append(triangle);
  655. }
  656. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  657. Triangle triangle;
  658. if (vertices.size() < 3)
  659. return;
  660. for (size_t i = 0; i < vertices.size() - 2; i++) {
  661. if (i % 2 == 0) {
  662. triangle.vertices[0] = vertices.at(i);
  663. triangle.vertices[1] = vertices.at(i + 1);
  664. triangle.vertices[2] = vertices.at(i + 2);
  665. } else {
  666. triangle.vertices[0] = vertices.at(i + 1);
  667. triangle.vertices[1] = vertices.at(i);
  668. triangle.vertices[2] = vertices.at(i + 2);
  669. }
  670. m_triangle_list.append(triangle);
  671. }
  672. }
  673. // Now let's transform each triangle and send that to the GPU
  674. auto const viewport = window_coordinates_to_target_coordinates(m_options.viewport);
  675. auto const viewport_half_width = viewport.width() / 2.0f;
  676. auto const viewport_half_height = viewport.height() / 2.0f;
  677. auto const viewport_center_x = viewport.x() + viewport_half_width;
  678. auto const viewport_center_y = viewport.y() + viewport_half_height;
  679. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  680. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  681. for (auto& triangle : m_triangle_list) {
  682. // Transform vertices into eye coordinates using the model-view transform
  683. triangle.vertices[0].eye_coordinates = model_view_transform * triangle.vertices[0].position;
  684. triangle.vertices[1].eye_coordinates = model_view_transform * triangle.vertices[1].position;
  685. triangle.vertices[2].eye_coordinates = model_view_transform * triangle.vertices[2].position;
  686. // Transform the vertex normals into eye-space
  687. triangle.vertices[0].normal = transform_direction(model_view_transform, triangle.vertices[0].normal);
  688. triangle.vertices[1].normal = transform_direction(model_view_transform, triangle.vertices[1].normal);
  689. triangle.vertices[2].normal = transform_direction(model_view_transform, triangle.vertices[2].normal);
  690. // Calculate per-vertex lighting
  691. if (m_options.lighting_enabled) {
  692. auto const& material = m_materials.at(0);
  693. for (auto& vertex : triangle.vertices) {
  694. auto ambient = material.ambient;
  695. auto diffuse = material.diffuse;
  696. auto emissive = material.emissive;
  697. auto specular = material.specular;
  698. if (m_options.color_material_enabled
  699. && (m_options.color_material_face == ColorMaterialFace::Front || m_options.color_material_face == ColorMaterialFace::FrontAndBack)) {
  700. switch (m_options.color_material_mode) {
  701. case ColorMaterialMode::Ambient:
  702. ambient = vertex.color;
  703. break;
  704. case ColorMaterialMode::AmbientAndDiffuse:
  705. ambient = vertex.color;
  706. diffuse = vertex.color;
  707. break;
  708. case ColorMaterialMode::Diffuse:
  709. diffuse = vertex.color;
  710. break;
  711. case ColorMaterialMode::Emissive:
  712. emissive = vertex.color;
  713. break;
  714. case ColorMaterialMode::Specular:
  715. specular = vertex.color;
  716. break;
  717. }
  718. }
  719. FloatVector4 result_color = emissive + (ambient * m_lighting_model.scene_ambient_color);
  720. for (auto const& light : m_lights) {
  721. if (!light.is_enabled)
  722. continue;
  723. // We need to save the length here because the attenuation factor requires a non
  724. // normalized vector!
  725. auto sgi_arrow_operator = [](FloatVector4 const& p1, FloatVector4 const& p2, float& saved_length) {
  726. if ((p1.w() != 0.0f) && (p2.w() == 0.0f)) {
  727. saved_length = p2.length();
  728. return (p2 / saved_length).xyz();
  729. } else if ((p1.w() == 0.0f) && (p2.w() != 0.0f)) {
  730. saved_length = p2.length();
  731. return -(p1 / saved_length).xyz();
  732. } else {
  733. // FIXME: The OpenGL 1.5 spec says nothing about the case where P1 and P2 BOTH have a w value of 1, which would
  734. // then mean the light position has an implicit value of (0, 0, 0, 0). This doesn't make any logical sense, and it most likely
  735. // a typographical error. Most other GL implementations seem to just fix it to the distance from the vertex to the light, which
  736. // seems to work just fine.
  737. // If somebody with more insight about this could clarify this eventually, that'd be great.
  738. auto distance = (p2 - p1);
  739. saved_length = distance.length();
  740. return (distance / saved_length).xyz();
  741. }
  742. };
  743. auto sgi_dot_operator = [](FloatVector3 const& d1, FloatVector3 const& d2) {
  744. return AK::max(d1.dot(d2), 0.0f);
  745. };
  746. float vector_length = 0.0f;
  747. FloatVector3 vertex_to_light = sgi_arrow_operator(vertex.eye_coordinates, light.position, vector_length);
  748. // Light attenuation value.
  749. float light_attenuation_factor = 1.0f;
  750. if (light.position.w() != 0.0f) {
  751. auto const vertex_to_light_length = vertex_to_light.length();
  752. auto const vertex_to_light_length_squared = vertex_to_light_length * vertex_to_light_length;
  753. light_attenuation_factor = 1.0f / (light.constant_attenuation + (light.linear_attenuation * vertex_to_light_length) + (light.quadratic_attenuation * vertex_to_light_length_squared));
  754. }
  755. // Spotlight factor
  756. float spotlight_factor = 1.0f;
  757. if (light.spotlight_cutoff_angle != 180.0f) {
  758. auto const vertex_to_light_dot_spotlight_direction = sgi_dot_operator(vertex_to_light, light.spotlight_direction.normalized());
  759. auto const cos_spotlight_cutoff = AK::cos<float>(light.spotlight_cutoff_angle * AK::Pi<float> / 180.f);
  760. if (vertex_to_light_dot_spotlight_direction >= cos_spotlight_cutoff)
  761. spotlight_factor = AK::pow<float>(vertex_to_light_dot_spotlight_direction, light.spotlight_exponent);
  762. else
  763. spotlight_factor = 0.0f;
  764. }
  765. // FIXME: The spec allows for splitting the colors calculated here into multiple different colors (primary/secondary color). Investigate what this means.
  766. (void)m_lighting_model.single_color;
  767. // FIXME: Two sided lighting should be implemented eventually (I believe this is where the normals are -ve and then lighting is calculated with the BACK material)
  768. (void)m_lighting_model.two_sided_lighting;
  769. // Ambient
  770. auto const ambient_component = ambient * light.ambient_intensity;
  771. // Diffuse
  772. auto const normal_dot_vertex_to_light = sgi_dot_operator(vertex.normal, vertex_to_light);
  773. auto const diffuse_component = ((diffuse * light.diffuse_intensity) * normal_dot_vertex_to_light);
  774. // Specular
  775. FloatVector4 specular_component = { 0.0f, 0.0f, 0.0f, 0.0f };
  776. if (normal_dot_vertex_to_light > 0.0f) {
  777. FloatVector3 half_vector_normalized;
  778. if (!m_lighting_model.viewer_at_infinity) {
  779. half_vector_normalized = (vertex_to_light + FloatVector3(0.0f, 0.0f, 1.0f)).normalized();
  780. } else {
  781. auto const vertex_to_eye_point = sgi_arrow_operator(vertex.eye_coordinates.normalized(), FloatVector4(0.0f, 0.0f, 0.0f, 1.0f), vector_length);
  782. half_vector_normalized = vertex_to_light + vertex_to_eye_point;
  783. }
  784. auto const normal_dot_half_vector = sgi_dot_operator(vertex.normal.normalized(), half_vector_normalized);
  785. auto const specular_coefficient = AK::pow(normal_dot_half_vector, material.shininess);
  786. specular_component = (specular * light.specular_intensity) * specular_coefficient;
  787. }
  788. FloatVector4 color = ambient_component;
  789. color += diffuse_component;
  790. color += specular_component;
  791. color = color * light_attenuation_factor * spotlight_factor;
  792. result_color += color;
  793. }
  794. vertex.color = result_color;
  795. vertex.color.set_w(diffuse.w()); // OpenGL 1.5 spec, page 59: "The A produced by lighting is the alpha value associated with diffuse color material"
  796. vertex.color.clamp(0.0f, 1.0f);
  797. }
  798. }
  799. // Transform eye coordinates into clip coordinates using the projection transform
  800. triangle.vertices[0].clip_coordinates = projection_transform * triangle.vertices[0].eye_coordinates;
  801. triangle.vertices[1].clip_coordinates = projection_transform * triangle.vertices[1].eye_coordinates;
  802. triangle.vertices[2].clip_coordinates = projection_transform * triangle.vertices[2].eye_coordinates;
  803. // At this point, we're in clip space
  804. // Here's where we do the clipping. This is a really crude implementation of the
  805. // https://learnopengl.com/Getting-started/Coordinate-Systems
  806. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  807. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  808. //
  809. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  810. // Okay, let's do some face culling first
  811. m_clipped_vertices.clear_with_capacity();
  812. m_clipped_vertices.append(triangle.vertices[0]);
  813. m_clipped_vertices.append(triangle.vertices[1]);
  814. m_clipped_vertices.append(triangle.vertices[2]);
  815. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  816. if (m_clipped_vertices.size() < 3)
  817. continue;
  818. for (auto& vec : m_clipped_vertices) {
  819. // To normalized device coordinates (NDC)
  820. auto const one_over_w = 1 / vec.clip_coordinates.w();
  821. auto const ndc_coordinates = FloatVector4 {
  822. vec.clip_coordinates.x() * one_over_w,
  823. vec.clip_coordinates.y() * one_over_w,
  824. vec.clip_coordinates.z() * one_over_w,
  825. one_over_w,
  826. };
  827. // To window coordinates - note that we flip the Y coordinate into target space
  828. vec.window_coordinates = {
  829. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  830. viewport_center_y - ndc_coordinates.y() * viewport_half_height,
  831. depth_halfway + ndc_coordinates.z() * depth_half_range,
  832. ndc_coordinates.w(),
  833. };
  834. }
  835. Triangle tri;
  836. tri.vertices[0] = m_clipped_vertices[0];
  837. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  838. tri.vertices[1] = m_clipped_vertices[i];
  839. tri.vertices[2] = m_clipped_vertices[i + 1];
  840. m_processed_triangles.append(tri);
  841. }
  842. }
  843. // Generate texture coordinates if at least one coordinate is enabled
  844. bool texture_coordinate_generation_enabled = false;
  845. for (auto const coordinates_enabled : m_options.texcoord_generation_enabled_coordinates) {
  846. if (coordinates_enabled != TexCoordGenerationCoordinate::None) {
  847. texture_coordinate_generation_enabled = true;
  848. break;
  849. }
  850. }
  851. for (auto& triangle : m_processed_triangles) {
  852. // Let's calculate the (signed) area of the triangle
  853. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  854. float dxAB = triangle.vertices[0].window_coordinates.x() - triangle.vertices[1].window_coordinates.x(); // A.x - B.x
  855. float dxBC = triangle.vertices[1].window_coordinates.x() - triangle.vertices[2].window_coordinates.x(); // B.X - C.x
  856. float dyAB = triangle.vertices[0].window_coordinates.y() - triangle.vertices[1].window_coordinates.y();
  857. float dyBC = triangle.vertices[1].window_coordinates.y() - triangle.vertices[2].window_coordinates.y();
  858. float area = (dxAB * dyBC) - (dxBC * dyAB);
  859. if (area == 0.0f)
  860. continue;
  861. if (m_options.enable_culling) {
  862. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area < 0 : area > 0);
  863. if (!is_front && m_options.cull_back)
  864. continue;
  865. if (is_front && m_options.cull_front)
  866. continue;
  867. }
  868. if (area > 0)
  869. swap(triangle.vertices[0], triangle.vertices[1]);
  870. // Transform normals
  871. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  872. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  873. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  874. if (m_options.normalization_enabled) {
  875. triangle.vertices[0].normal.normalize();
  876. triangle.vertices[1].normal.normalize();
  877. triangle.vertices[2].normal.normalize();
  878. }
  879. if (texture_coordinate_generation_enabled) {
  880. generate_texture_coordinates(triangle.vertices[0], m_options);
  881. generate_texture_coordinates(triangle.vertices[1], m_options);
  882. generate_texture_coordinates(triangle.vertices[2], m_options);
  883. }
  884. // Apply texture transformation
  885. for (size_t i = 0; i < NUM_SAMPLERS; ++i) {
  886. triangle.vertices[0].tex_coords[i] = texture_transform * triangle.vertices[0].tex_coords[i];
  887. triangle.vertices[1].tex_coords[i] = texture_transform * triangle.vertices[1].tex_coords[i];
  888. triangle.vertices[2].tex_coords[i] = texture_transform * triangle.vertices[2].tex_coords[i];
  889. }
  890. rasterize_triangle(triangle);
  891. }
  892. }
  893. ALWAYS_INLINE void Device::shade_fragments(PixelQuad& quad)
  894. {
  895. quad.out_color = quad.vertex_color;
  896. for (size_t i : m_enabled_texture_units) {
  897. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  898. auto const& sampler = m_samplers[i];
  899. auto texel = sampler.sample_2d({ quad.texture_coordinates[i].x(), quad.texture_coordinates[i].y() });
  900. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  901. // FIXME: Implement more blend modes
  902. switch (sampler.config().fixed_function_texture_env_mode) {
  903. case TextureEnvMode::Modulate:
  904. quad.out_color = quad.out_color * texel;
  905. break;
  906. case TextureEnvMode::Replace:
  907. quad.out_color = texel;
  908. break;
  909. case TextureEnvMode::Decal: {
  910. auto src_alpha = quad.out_color.w();
  911. quad.out_color.set_x(mix(quad.out_color.x(), texel.x(), src_alpha));
  912. quad.out_color.set_y(mix(quad.out_color.y(), texel.y(), src_alpha));
  913. quad.out_color.set_z(mix(quad.out_color.z(), texel.z(), src_alpha));
  914. break;
  915. }
  916. default:
  917. VERIFY_NOT_REACHED();
  918. }
  919. }
  920. // Calculate fog
  921. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  922. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  923. if (m_options.fog_enabled) {
  924. auto factor = expand4(0.0f);
  925. switch (m_options.fog_mode) {
  926. case FogMode::Linear:
  927. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  928. break;
  929. case FogMode::Exp: {
  930. auto argument = -m_options.fog_density * quad.fog_depth;
  931. factor = exp(argument);
  932. } break;
  933. case FogMode::Exp2: {
  934. auto argument = m_options.fog_density * quad.fog_depth;
  935. argument *= -argument;
  936. factor = exp(argument);
  937. } break;
  938. default:
  939. VERIFY_NOT_REACHED();
  940. }
  941. // Mix texel's RGB with fog's RBG - leave alpha alone
  942. auto fog_color = expand4(m_options.fog_color);
  943. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  944. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  945. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  946. }
  947. }
  948. ALWAYS_INLINE bool Device::test_alpha(PixelQuad& quad)
  949. {
  950. auto const alpha = quad.out_color.w();
  951. auto const ref_value = expand4(m_options.alpha_test_ref_value);
  952. switch (m_options.alpha_test_func) {
  953. case AlphaTestFunction::Less:
  954. quad.mask &= alpha < ref_value;
  955. break;
  956. case AlphaTestFunction::Equal:
  957. quad.mask &= alpha == ref_value;
  958. break;
  959. case AlphaTestFunction::LessOrEqual:
  960. quad.mask &= alpha <= ref_value;
  961. break;
  962. case AlphaTestFunction::Greater:
  963. quad.mask &= alpha > ref_value;
  964. break;
  965. case AlphaTestFunction::NotEqual:
  966. quad.mask &= alpha != ref_value;
  967. break;
  968. case AlphaTestFunction::GreaterOrEqual:
  969. quad.mask &= alpha >= ref_value;
  970. break;
  971. case AlphaTestFunction::Never:
  972. case AlphaTestFunction::Always:
  973. default:
  974. VERIFY_NOT_REACHED();
  975. }
  976. return any(quad.mask);
  977. }
  978. void Device::resize(Gfx::IntSize const& size)
  979. {
  980. auto frame_buffer_or_error = FrameBuffer<ColorType, DepthType, StencilType>::try_create(size);
  981. m_frame_buffer = MUST(frame_buffer_or_error);
  982. }
  983. void Device::clear_color(FloatVector4 const& color)
  984. {
  985. auto const fill_color = to_bgra32(color);
  986. auto fill_rect = m_frame_buffer->rect();
  987. if (m_options.scissor_enabled)
  988. fill_rect.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  989. m_frame_buffer->color_buffer()->fill(fill_color, fill_rect);
  990. }
  991. void Device::clear_depth(DepthType depth)
  992. {
  993. auto clear_rect = m_frame_buffer->rect();
  994. if (m_options.scissor_enabled)
  995. clear_rect.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  996. m_frame_buffer->depth_buffer()->fill(depth, clear_rect);
  997. }
  998. void Device::clear_stencil(StencilType value)
  999. {
  1000. auto clear_rect = m_frame_buffer->rect();
  1001. if (m_options.scissor_enabled)
  1002. clear_rect.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  1003. m_frame_buffer->stencil_buffer()->fill(value, clear_rect);
  1004. }
  1005. void Device::blit_to_color_buffer_at_raster_position(Gfx::Bitmap const& source)
  1006. {
  1007. if (!m_raster_position.valid)
  1008. return;
  1009. INCREASE_STATISTICS_COUNTER(g_num_pixels, source.width() * source.height());
  1010. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, source.width() * source.height());
  1011. auto const blit_rect = raster_rect_in_target_coordinates(source.size());
  1012. m_frame_buffer->color_buffer()->blit_from_bitmap(source, blit_rect);
  1013. }
  1014. void Device::blit_to_depth_buffer_at_raster_position(Vector<DepthType> const& depth_values, int width, int height)
  1015. {
  1016. if (!m_raster_position.valid)
  1017. return;
  1018. auto const raster_rect = raster_rect_in_target_coordinates({ width, height });
  1019. auto const y1 = raster_rect.y();
  1020. auto const y2 = y1 + height;
  1021. auto const x1 = raster_rect.x();
  1022. auto const x2 = x1 + width;
  1023. auto index = 0;
  1024. for (auto y = y2 - 1; y >= y1; --y) {
  1025. auto depth_line = m_frame_buffer->depth_buffer()->scanline(y);
  1026. for (auto x = x1; x < x2; ++x)
  1027. depth_line[x] = depth_values[index++];
  1028. }
  1029. }
  1030. void Device::blit_color_buffer_to(Gfx::Bitmap& target)
  1031. {
  1032. m_frame_buffer->color_buffer()->blit_to_bitmap(target, m_frame_buffer->rect());
  1033. if constexpr (ENABLE_STATISTICS_OVERLAY)
  1034. draw_statistics_overlay(target);
  1035. }
  1036. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  1037. {
  1038. static Core::ElapsedTimer timer;
  1039. static String debug_string;
  1040. static int frame_counter;
  1041. frame_counter++;
  1042. int milliseconds = 0;
  1043. if (timer.is_valid())
  1044. milliseconds = timer.elapsed();
  1045. else
  1046. timer.start();
  1047. Gfx::Painter painter { target };
  1048. if (milliseconds > MILLISECONDS_PER_STATISTICS_PERIOD) {
  1049. int num_rendertarget_pixels = m_frame_buffer->rect().size().area();
  1050. StringBuilder builder;
  1051. builder.append(String::formatted("Timings : {:.1}ms {:.1}FPS\n",
  1052. static_cast<double>(milliseconds) / frame_counter,
  1053. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  1054. builder.append(String::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  1055. builder.append(String::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  1056. builder.append(String::formatted("Pixels : {}, Stencil: {}%, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  1057. g_num_pixels,
  1058. g_num_pixels > 0 ? g_num_stencil_writes * 100 / g_num_pixels : 0,
  1059. g_num_pixels > 0 ? g_num_pixels_shaded * 100 / g_num_pixels : 0,
  1060. g_num_pixels_shaded > 0 ? g_num_pixels_blended * 100 / g_num_pixels_shaded : 0,
  1061. num_rendertarget_pixels > 0 ? g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100 : 0));
  1062. builder.append(String::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  1063. debug_string = builder.to_string();
  1064. frame_counter = 0;
  1065. timer.start();
  1066. }
  1067. g_num_rasterized_triangles = 0;
  1068. g_num_pixels = 0;
  1069. g_num_pixels_shaded = 0;
  1070. g_num_pixels_blended = 0;
  1071. g_num_sampler_calls = 0;
  1072. g_num_stencil_writes = 0;
  1073. g_num_quads = 0;
  1074. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  1075. for (int y = -1; y < 2; y++)
  1076. for (int x = -1; x < 2; x++)
  1077. if (x != 0 && y != 0)
  1078. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  1079. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  1080. }
  1081. void Device::set_options(const RasterizerOptions& options)
  1082. {
  1083. m_options = options;
  1084. if (m_options.enable_blending)
  1085. setup_blend_factors();
  1086. }
  1087. void Device::set_light_model_params(const LightModelParameters& lighting_model)
  1088. {
  1089. m_lighting_model = lighting_model;
  1090. }
  1091. ColorType Device::get_color_buffer_pixel(int x, int y)
  1092. {
  1093. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1094. if (x < 0 || y < 0 || x >= m_frame_buffer->rect().width() || y >= m_frame_buffer->rect().height())
  1095. return 0;
  1096. return m_frame_buffer->color_buffer()->scanline(y)[x];
  1097. }
  1098. DepthType Device::get_depthbuffer_value(int x, int y)
  1099. {
  1100. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1101. if (x < 0 || y < 0 || x >= m_frame_buffer->rect().width() || y >= m_frame_buffer->rect().height())
  1102. return 1.0f;
  1103. return m_frame_buffer->depth_buffer()->scanline(y)[x];
  1104. }
  1105. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  1106. {
  1107. VERIFY(format == ImageFormat::BGRA8888);
  1108. VERIFY(width > 0);
  1109. VERIFY(height > 0);
  1110. VERIFY(depth > 0);
  1111. VERIFY(levels > 0);
  1112. VERIFY(layers > 0);
  1113. return adopt_ref(*new Image(width, height, depth, levels, layers));
  1114. }
  1115. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  1116. {
  1117. m_samplers[sampler].set_config(config);
  1118. }
  1119. void Device::set_light_state(unsigned int light_id, Light const& light)
  1120. {
  1121. m_lights.at(light_id) = light;
  1122. }
  1123. void Device::set_material_state(Face face, Material const& material)
  1124. {
  1125. m_materials[face] = material;
  1126. }
  1127. void Device::set_stencil_configuration(Face face, StencilConfiguration const& stencil_configuration)
  1128. {
  1129. m_stencil_configuration[face] = stencil_configuration;
  1130. }
  1131. void Device::set_raster_position(RasterPosition const& raster_position)
  1132. {
  1133. m_raster_position = raster_position;
  1134. }
  1135. void Device::set_raster_position(FloatVector4 const& position, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform)
  1136. {
  1137. auto const eye_coordinates = model_view_transform * position;
  1138. auto const clip_coordinates = projection_transform * eye_coordinates;
  1139. // FIXME: implement clipping
  1140. m_raster_position.valid = true;
  1141. auto ndc_coordinates = clip_coordinates / clip_coordinates.w();
  1142. ndc_coordinates.set_w(clip_coordinates.w());
  1143. auto const viewport = m_options.viewport;
  1144. auto const viewport_half_width = viewport.width() / 2.0f;
  1145. auto const viewport_half_height = viewport.height() / 2.0f;
  1146. auto const viewport_center_x = viewport.x() + viewport_half_width;
  1147. auto const viewport_center_y = viewport.y() + viewport_half_height;
  1148. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  1149. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  1150. // FIXME: implement other raster position properties such as color and texcoords
  1151. m_raster_position.window_coordinates = {
  1152. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  1153. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  1154. depth_halfway + ndc_coordinates.z() * depth_half_range,
  1155. ndc_coordinates.w(),
  1156. };
  1157. m_raster_position.eye_coordinate_distance = eye_coordinates.length();
  1158. }
  1159. Gfx::IntRect Device::raster_rect_in_target_coordinates(Gfx::IntSize size)
  1160. {
  1161. auto const raster_rect = Gfx::IntRect {
  1162. static_cast<int>(m_raster_position.window_coordinates.x()),
  1163. static_cast<int>(m_raster_position.window_coordinates.y()),
  1164. size.width(),
  1165. size.height(),
  1166. };
  1167. return window_coordinates_to_target_coordinates(raster_rect);
  1168. }
  1169. }