Device.cpp 58 KB

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