Device.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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/AnyOf.h>
  9. #include <AK/Error.h>
  10. #include <AK/Math.h>
  11. #include <AK/NumericLimits.h>
  12. #include <AK/SIMDExtras.h>
  13. #include <AK/SIMDMath.h>
  14. #include <LibCore/ElapsedTimer.h>
  15. #include <LibGfx/Painter.h>
  16. #include <LibGfx/Vector2.h>
  17. #include <LibGfx/Vector3.h>
  18. #include <LibSoftGPU/Config.h>
  19. #include <LibSoftGPU/Device.h>
  20. #include <LibSoftGPU/Image.h>
  21. #include <LibSoftGPU/PixelConverter.h>
  22. #include <LibSoftGPU/PixelQuad.h>
  23. #include <LibSoftGPU/SIMD.h>
  24. #include <LibSoftGPU/Shader.h>
  25. #include <math.h>
  26. namespace SoftGPU {
  27. static i64 g_num_rasterized_triangles;
  28. static i64 g_num_pixels;
  29. static i64 g_num_pixels_shaded;
  30. static i64 g_num_pixels_blended;
  31. static i64 g_num_sampler_calls;
  32. static i64 g_num_stencil_writes;
  33. static i64 g_num_quads;
  34. using AK::abs;
  35. using AK::SIMD::any;
  36. using AK::SIMD::exp;
  37. using AK::SIMD::expand4;
  38. using AK::SIMD::f32x4;
  39. using AK::SIMD::i32x4;
  40. using AK::SIMD::load4_masked;
  41. using AK::SIMD::maskbits;
  42. using AK::SIMD::maskcount;
  43. using AK::SIMD::store4_masked;
  44. using AK::SIMD::to_f32x4;
  45. using AK::SIMD::to_u32x4;
  46. using AK::SIMD::u32x4;
  47. static constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  48. // Returns positive values for counter-clockwise rotation of vertices. Note that it returns the
  49. // area of a parallelogram with sides {a, b} and {b, c}, so _double_ the area of the triangle {a, b, c}.
  50. constexpr static i32 edge_function(IntVector2 const& a, IntVector2 const& b, IntVector2 const& c)
  51. {
  52. return (c.y() - a.y()) * (b.x() - a.x()) - (c.x() - a.x()) * (b.y() - a.y());
  53. }
  54. constexpr static i32x4 edge_function4(IntVector2 const& a, IntVector2 const& b, Vector2<i32x4> const& c)
  55. {
  56. return (c.y() - a.y()) * (b.x() - a.x()) - (c.x() - a.x()) * (b.y() - a.y());
  57. }
  58. template<typename T, typename U>
  59. constexpr static auto interpolate(T const& v0, T const& v1, T const& v2, Vector3<U> const& barycentric_coords)
  60. {
  61. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  62. }
  63. static GPU::ColorType to_argb32(FloatVector4 const& color)
  64. {
  65. auto clamped = color.clamped(0.0f, 1.0f);
  66. auto r = static_cast<u8>(clamped.x() * 255);
  67. auto g = static_cast<u8>(clamped.y() * 255);
  68. auto b = static_cast<u8>(clamped.z() * 255);
  69. auto a = static_cast<u8>(clamped.w() * 255);
  70. return a << 24 | r << 16 | g << 8 | b;
  71. }
  72. ALWAYS_INLINE static u32x4 to_argb32(Vector4<f32x4> const& color)
  73. {
  74. auto clamped = color.clamped(expand4(0.0f), expand4(1.0f));
  75. auto r = to_u32x4(clamped.x() * 255);
  76. auto g = to_u32x4(clamped.y() * 255);
  77. auto b = to_u32x4(clamped.z() * 255);
  78. auto a = to_u32x4(clamped.w() * 255);
  79. return a << 24 | r << 16 | g << 8 | b;
  80. }
  81. static Vector4<f32x4> to_vec4(u32x4 bgra)
  82. {
  83. auto constexpr one_over_255 = expand4(1.0f / 255);
  84. return {
  85. to_f32x4((bgra >> 16) & 0xff) * one_over_255,
  86. to_f32x4((bgra >> 8) & 0xff) * one_over_255,
  87. to_f32x4(bgra & 0xff) * one_over_255,
  88. to_f32x4((bgra >> 24) & 0xff) * one_over_255,
  89. };
  90. }
  91. void Device::setup_blend_factors()
  92. {
  93. m_alpha_blend_factors = {};
  94. switch (m_options.blend_source_factor) {
  95. case GPU::BlendFactor::Zero:
  96. break;
  97. case GPU::BlendFactor::One:
  98. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  99. break;
  100. case GPU::BlendFactor::SrcColor:
  101. m_alpha_blend_factors.src_factor_src_color = 1;
  102. break;
  103. case GPU::BlendFactor::OneMinusSrcColor:
  104. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  105. m_alpha_blend_factors.src_factor_src_color = -1;
  106. break;
  107. case GPU::BlendFactor::SrcAlpha:
  108. m_alpha_blend_factors.src_factor_src_alpha = 1;
  109. break;
  110. case GPU::BlendFactor::OneMinusSrcAlpha:
  111. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  112. m_alpha_blend_factors.src_factor_src_alpha = -1;
  113. break;
  114. case GPU::BlendFactor::DstAlpha:
  115. m_alpha_blend_factors.src_factor_dst_alpha = 1;
  116. break;
  117. case GPU::BlendFactor::OneMinusDstAlpha:
  118. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  119. m_alpha_blend_factors.src_factor_dst_alpha = -1;
  120. break;
  121. case GPU::BlendFactor::DstColor:
  122. m_alpha_blend_factors.src_factor_dst_color = 1;
  123. break;
  124. case GPU::BlendFactor::OneMinusDstColor:
  125. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  126. m_alpha_blend_factors.src_factor_dst_color = -1;
  127. break;
  128. case GPU::BlendFactor::SrcAlphaSaturate:
  129. default:
  130. VERIFY_NOT_REACHED();
  131. }
  132. switch (m_options.blend_destination_factor) {
  133. case GPU::BlendFactor::Zero:
  134. break;
  135. case GPU::BlendFactor::One:
  136. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  137. break;
  138. case GPU::BlendFactor::SrcColor:
  139. m_alpha_blend_factors.dst_factor_src_color = 1;
  140. break;
  141. case GPU::BlendFactor::OneMinusSrcColor:
  142. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  143. m_alpha_blend_factors.dst_factor_src_color = -1;
  144. break;
  145. case GPU::BlendFactor::SrcAlpha:
  146. m_alpha_blend_factors.dst_factor_src_alpha = 1;
  147. break;
  148. case GPU::BlendFactor::OneMinusSrcAlpha:
  149. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  150. m_alpha_blend_factors.dst_factor_src_alpha = -1;
  151. break;
  152. case GPU::BlendFactor::DstAlpha:
  153. m_alpha_blend_factors.dst_factor_dst_alpha = 1;
  154. break;
  155. case GPU::BlendFactor::OneMinusDstAlpha:
  156. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  157. m_alpha_blend_factors.dst_factor_dst_alpha = -1;
  158. break;
  159. case GPU::BlendFactor::DstColor:
  160. m_alpha_blend_factors.dst_factor_dst_color = 1;
  161. break;
  162. case GPU::BlendFactor::OneMinusDstColor:
  163. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  164. m_alpha_blend_factors.dst_factor_dst_color = -1;
  165. break;
  166. case GPU::BlendFactor::SrcAlphaSaturate:
  167. default:
  168. VERIFY_NOT_REACHED();
  169. }
  170. }
  171. ALWAYS_INLINE static void test_alpha(PixelQuad& quad, GPU::AlphaTestFunction alpha_test_function, f32x4 const& reference_value)
  172. {
  173. auto const alpha = quad.get_output_float(SHADER_OUTPUT_FIRST_COLOR + 3);
  174. switch (alpha_test_function) {
  175. case GPU::AlphaTestFunction::Always:
  176. quad.mask &= expand4(~0);
  177. break;
  178. case GPU::AlphaTestFunction::Equal:
  179. quad.mask &= alpha == reference_value;
  180. break;
  181. case GPU::AlphaTestFunction::Greater:
  182. quad.mask &= alpha > reference_value;
  183. break;
  184. case GPU::AlphaTestFunction::GreaterOrEqual:
  185. quad.mask &= alpha >= reference_value;
  186. break;
  187. case GPU::AlphaTestFunction::Less:
  188. quad.mask &= alpha < reference_value;
  189. break;
  190. case GPU::AlphaTestFunction::LessOrEqual:
  191. quad.mask &= alpha <= reference_value;
  192. break;
  193. case GPU::AlphaTestFunction::NotEqual:
  194. quad.mask &= alpha != reference_value;
  195. break;
  196. case GPU::AlphaTestFunction::Never:
  197. default:
  198. VERIFY_NOT_REACHED();
  199. }
  200. }
  201. template<typename CB1, typename CB2, typename CB3>
  202. ALWAYS_INLINE void Device::rasterize(Gfx::IntRect& render_bounds, CB1 set_coverage_mask, CB2 set_quad_depth, CB3 set_quad_attributes)
  203. {
  204. // Return if alpha testing is a no-op
  205. if (m_options.enable_alpha_test && m_options.alpha_test_func == GPU::AlphaTestFunction::Never)
  206. return;
  207. auto const alpha_test_ref_value = expand4(m_options.alpha_test_ref_value);
  208. // Buffers
  209. auto color_buffer = m_frame_buffer->color_buffer();
  210. auto depth_buffer = m_frame_buffer->depth_buffer();
  211. auto stencil_buffer = m_frame_buffer->stencil_buffer();
  212. // Stencil configuration and writing
  213. auto const& stencil_configuration = m_stencil_configuration[GPU::Face::Front];
  214. auto const stencil_reference_value = stencil_configuration.reference_value & stencil_configuration.test_mask;
  215. auto write_to_stencil = [](GPU::StencilType* stencil_ptrs[4], i32x4 stencil_value, GPU::StencilOperation op, GPU::StencilType reference_value, GPU::StencilType write_mask, i32x4 pixel_mask) {
  216. if (write_mask == 0 || op == GPU::StencilOperation::Keep)
  217. return;
  218. switch (op) {
  219. case GPU::StencilOperation::Decrement:
  220. stencil_value = (stencil_value & ~write_mask) | (max(stencil_value - 1, expand4(0)) & write_mask);
  221. break;
  222. case GPU::StencilOperation::DecrementWrap:
  223. stencil_value = (stencil_value & ~write_mask) | (((stencil_value - 1) & 0xFF) & write_mask);
  224. break;
  225. case GPU::StencilOperation::Increment:
  226. stencil_value = (stencil_value & ~write_mask) | (min(stencil_value + 1, expand4(0xFF)) & write_mask);
  227. break;
  228. case GPU::StencilOperation::IncrementWrap:
  229. stencil_value = (stencil_value & ~write_mask) | (((stencil_value + 1) & 0xFF) & write_mask);
  230. break;
  231. case GPU::StencilOperation::Invert:
  232. stencil_value ^= write_mask;
  233. break;
  234. case GPU::StencilOperation::Replace:
  235. stencil_value = (stencil_value & ~write_mask) | (reference_value & write_mask);
  236. break;
  237. case GPU::StencilOperation::Zero:
  238. stencil_value &= ~write_mask;
  239. break;
  240. default:
  241. VERIFY_NOT_REACHED();
  242. }
  243. INCREASE_STATISTICS_COUNTER(g_num_stencil_writes, maskcount(pixel_mask));
  244. store4_masked(stencil_value, stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], pixel_mask);
  245. };
  246. // Limit rendering to framebuffer and scissor rects
  247. render_bounds.intersect(m_frame_buffer->rect());
  248. if (m_options.scissor_enabled)
  249. render_bounds.intersect(m_options.scissor_box);
  250. // Quad bounds
  251. auto const render_bounds_left = render_bounds.left();
  252. auto const render_bounds_right = render_bounds.right();
  253. auto const render_bounds_top = render_bounds.top();
  254. auto const render_bounds_bottom = render_bounds.bottom();
  255. auto const qx0 = render_bounds_left & ~1;
  256. auto const qx1 = render_bounds_right & ~1;
  257. auto const qy0 = render_bounds_top & ~1;
  258. auto const qy1 = render_bounds_bottom & ~1;
  259. // Rasterize all quads
  260. // FIXME: this could be embarrassingly parallel
  261. for (int qy = qy0; qy <= qy1; qy += 2) {
  262. for (int qx = qx0; qx <= qx1; qx += 2) {
  263. PixelQuad quad;
  264. quad.screen_coordinates = {
  265. i32x4 { qx, qx + 1, qx, qx + 1 },
  266. i32x4 { qy, qy, qy + 1, qy + 1 },
  267. };
  268. // Set coverage mask and test against render bounds
  269. set_coverage_mask(quad);
  270. quad.mask &= quad.screen_coordinates.x() >= render_bounds_left
  271. && quad.screen_coordinates.x() <= render_bounds_right
  272. && quad.screen_coordinates.y() >= render_bounds_top
  273. && quad.screen_coordinates.y() <= render_bounds_bottom;
  274. auto coverage_bits = maskbits(quad.mask);
  275. if (coverage_bits == 0)
  276. continue;
  277. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  278. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  279. // Stencil testing
  280. GPU::StencilType* stencil_ptrs[4];
  281. i32x4 stencil_value;
  282. if (m_options.enable_stencil_test) {
  283. stencil_ptrs[0] = coverage_bits & 1 ? &stencil_buffer->scanline(qy)[qx] : nullptr;
  284. stencil_ptrs[1] = coverage_bits & 2 ? &stencil_buffer->scanline(qy)[qx + 1] : nullptr;
  285. stencil_ptrs[2] = coverage_bits & 4 ? &stencil_buffer->scanline(qy + 1)[qx] : nullptr;
  286. stencil_ptrs[3] = coverage_bits & 8 ? &stencil_buffer->scanline(qy + 1)[qx + 1] : nullptr;
  287. stencil_value = load4_masked(stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], quad.mask);
  288. stencil_value &= stencil_configuration.test_mask;
  289. i32x4 stencil_test_passed;
  290. switch (stencil_configuration.test_function) {
  291. case GPU::StencilTestFunction::Always:
  292. stencil_test_passed = expand4(~0);
  293. break;
  294. case GPU::StencilTestFunction::Equal:
  295. stencil_test_passed = stencil_value == stencil_reference_value;
  296. break;
  297. case GPU::StencilTestFunction::Greater:
  298. stencil_test_passed = stencil_value > stencil_reference_value;
  299. break;
  300. case GPU::StencilTestFunction::GreaterOrEqual:
  301. stencil_test_passed = stencil_value >= stencil_reference_value;
  302. break;
  303. case GPU::StencilTestFunction::Less:
  304. stencil_test_passed = stencil_value < stencil_reference_value;
  305. break;
  306. case GPU::StencilTestFunction::LessOrEqual:
  307. stencil_test_passed = stencil_value <= stencil_reference_value;
  308. break;
  309. case GPU::StencilTestFunction::Never:
  310. stencil_test_passed = expand4(0);
  311. break;
  312. case GPU::StencilTestFunction::NotEqual:
  313. stencil_test_passed = stencil_value != stencil_reference_value;
  314. break;
  315. default:
  316. VERIFY_NOT_REACHED();
  317. }
  318. // Update stencil buffer for pixels that failed the stencil test
  319. write_to_stencil(
  320. stencil_ptrs,
  321. stencil_value,
  322. stencil_configuration.on_stencil_test_fail,
  323. stencil_reference_value,
  324. stencil_configuration.write_mask,
  325. quad.mask & ~stencil_test_passed);
  326. // Update coverage mask + early quad rejection
  327. quad.mask &= stencil_test_passed;
  328. coverage_bits = maskbits(quad.mask);
  329. if (coverage_bits == 0)
  330. continue;
  331. }
  332. // Depth testing
  333. GPU::DepthType* depth_ptrs[4] = {
  334. coverage_bits & 1 ? &depth_buffer->scanline(qy)[qx] : nullptr,
  335. coverage_bits & 2 ? &depth_buffer->scanline(qy)[qx + 1] : nullptr,
  336. coverage_bits & 4 ? &depth_buffer->scanline(qy + 1)[qx] : nullptr,
  337. coverage_bits & 8 ? &depth_buffer->scanline(qy + 1)[qx + 1] : nullptr,
  338. };
  339. if (m_options.enable_depth_test) {
  340. set_quad_depth(quad);
  341. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  342. i32x4 depth_test_passed;
  343. switch (m_options.depth_func) {
  344. case GPU::DepthTestFunction::Always:
  345. depth_test_passed = expand4(~0);
  346. break;
  347. case GPU::DepthTestFunction::Never:
  348. depth_test_passed = expand4(0);
  349. break;
  350. case GPU::DepthTestFunction::Greater:
  351. depth_test_passed = quad.depth > depth;
  352. break;
  353. case GPU::DepthTestFunction::GreaterOrEqual:
  354. depth_test_passed = quad.depth >= depth;
  355. break;
  356. case GPU::DepthTestFunction::NotEqual:
  357. #ifdef __SSE__
  358. depth_test_passed = quad.depth != depth;
  359. #else
  360. depth_test_passed = i32x4 {
  361. bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0,
  362. bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0,
  363. bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0,
  364. bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0,
  365. };
  366. #endif
  367. break;
  368. case GPU::DepthTestFunction::Equal:
  369. #ifdef __SSE__
  370. depth_test_passed = quad.depth == depth;
  371. #else
  372. //
  373. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  374. // compiled for the i686 target. When we calculate our depth value to be stored in the buffer,
  375. // it is an 80-bit x87 floating point number, however, when stored into the depth buffer, this is
  376. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  377. // used here the comparison fails.
  378. // This could be solved by using a `long double` for the depth buffer, however this would take
  379. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  380. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  381. // equal, we can pretty much guarantee that it's actually equal.
  382. //
  383. depth_test_passed = i32x4 {
  384. bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0,
  385. bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0,
  386. bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0,
  387. bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0,
  388. };
  389. #endif
  390. break;
  391. case GPU::DepthTestFunction::LessOrEqual:
  392. depth_test_passed = quad.depth <= depth;
  393. break;
  394. case GPU::DepthTestFunction::Less:
  395. depth_test_passed = quad.depth < depth;
  396. break;
  397. default:
  398. VERIFY_NOT_REACHED();
  399. }
  400. // Update stencil buffer for pixels that failed the depth test
  401. if (m_options.enable_stencil_test) {
  402. write_to_stencil(
  403. stencil_ptrs,
  404. stencil_value,
  405. stencil_configuration.on_depth_test_fail,
  406. stencil_reference_value,
  407. stencil_configuration.write_mask,
  408. quad.mask & ~depth_test_passed);
  409. }
  410. // Update coverage mask + early quad rejection
  411. quad.mask &= depth_test_passed;
  412. coverage_bits = maskbits(quad.mask);
  413. if (coverage_bits == 0)
  414. continue;
  415. }
  416. // Update stencil buffer for passed pixels
  417. if (m_options.enable_stencil_test) {
  418. write_to_stencil(
  419. stencil_ptrs,
  420. stencil_value,
  421. stencil_configuration.on_pass,
  422. stencil_reference_value,
  423. stencil_configuration.write_mask,
  424. quad.mask);
  425. }
  426. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  427. set_quad_attributes(quad);
  428. shade_fragments(quad);
  429. // Alpha testing
  430. if (m_options.enable_alpha_test) {
  431. test_alpha(quad, m_options.alpha_test_func, alpha_test_ref_value);
  432. coverage_bits = maskbits(quad.mask);
  433. if (coverage_bits == 0)
  434. continue;
  435. }
  436. // Write to depth buffer
  437. if (m_options.enable_depth_test && m_options.enable_depth_write)
  438. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  439. // We will not update the color buffer at all
  440. if ((m_options.color_mask == 0) || !m_options.enable_color_write)
  441. continue;
  442. GPU::ColorType* color_ptrs[4] = {
  443. coverage_bits & 1 ? &color_buffer->scanline(qy)[qx] : nullptr,
  444. coverage_bits & 2 ? &color_buffer->scanline(qy)[qx + 1] : nullptr,
  445. coverage_bits & 4 ? &color_buffer->scanline(qy + 1)[qx] : nullptr,
  446. coverage_bits & 8 ? &color_buffer->scanline(qy + 1)[qx + 1] : nullptr,
  447. };
  448. u32x4 dst_u32;
  449. if (m_options.enable_blending || m_options.color_mask != 0xffffffff)
  450. dst_u32 = load4_masked(color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  451. auto out_color = quad.get_output_vector4(SHADER_OUTPUT_FIRST_COLOR);
  452. if (m_options.enable_blending) {
  453. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  454. // Blend color values from pixel_staging into color_buffer
  455. auto const& src = out_color;
  456. auto dst = to_vec4(dst_u32);
  457. auto src_factor = expand4(m_alpha_blend_factors.src_constant)
  458. + src * m_alpha_blend_factors.src_factor_src_color
  459. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.src_factor_src_alpha
  460. + dst * m_alpha_blend_factors.src_factor_dst_color
  461. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.src_factor_dst_alpha;
  462. auto dst_factor = expand4(m_alpha_blend_factors.dst_constant)
  463. + src * m_alpha_blend_factors.dst_factor_src_color
  464. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.dst_factor_src_alpha
  465. + dst * m_alpha_blend_factors.dst_factor_dst_color
  466. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.dst_factor_dst_alpha;
  467. out_color = src * src_factor + dst * dst_factor;
  468. }
  469. auto const argb32_color = to_argb32(out_color);
  470. if (m_options.color_mask == 0xffffffff)
  471. store4_masked(argb32_color, color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  472. else
  473. store4_masked((argb32_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);
  474. }
  475. }
  476. }
  477. void Device::rasterize_line_aliased(GPU::Vertex& from, GPU::Vertex& to)
  478. {
  479. // FIXME: implement aliased lines; for now we fall back to anti-aliased logic
  480. rasterize_line_antialiased(from, to);
  481. }
  482. void Device::rasterize_line_antialiased(GPU::Vertex& from, GPU::Vertex& to)
  483. {
  484. auto const from_coords = from.window_coordinates.xy();
  485. auto const to_coords = to.window_coordinates.xy();
  486. auto const line_width = ceilf(m_options.line_width);
  487. auto const line_radius = line_width / 2;
  488. auto render_bounds = Gfx::IntRect {
  489. min(from_coords.x(), to_coords.x()),
  490. min(from_coords.y(), to_coords.y()),
  491. abs(from_coords.x() - to_coords.x()) + 1,
  492. abs(from_coords.y() - to_coords.y()) + 1,
  493. };
  494. render_bounds.inflate(line_width, line_width);
  495. auto const from_coords4 = expand4(from_coords);
  496. auto const line_vector = to_coords - from_coords;
  497. auto const line_vector4 = expand4(line_vector);
  498. auto const line_dot4 = expand4(line_vector.dot(line_vector));
  499. auto const from_depth4 = expand4(from.window_coordinates.z());
  500. auto const to_depth4 = expand4(to.window_coordinates.z());
  501. auto const from_color4 = expand4(from.color);
  502. auto const from_fog_depth4 = expand4(abs(from.eye_coordinates.z()));
  503. // Rasterize using a 2D signed distance field for a line segment
  504. // FIXME: performance-wise, this might be the absolute worst way to draw an anti-aliased line
  505. f32x4 distance_along_line;
  506. rasterize(
  507. render_bounds,
  508. [&from_coords4, &distance_along_line, &line_vector4, &line_dot4, &line_radius](auto& quad) {
  509. auto const screen_coordinates4 = to_vec2_f32x4(quad.screen_coordinates);
  510. auto const pixel_vector = screen_coordinates4 - from_coords4;
  511. distance_along_line = AK::SIMD::clamp(pixel_vector.dot(line_vector4) / line_dot4, 0.f, 1.f);
  512. auto distance_to_line = length(pixel_vector - line_vector4 * distance_along_line) - line_radius;
  513. // Add .5f to the distance so coverage transitions half a pixel before the actual border
  514. quad.coverage = 1.f - AK::SIMD::clamp(distance_to_line + 0.5f, 0.f, 1.f);
  515. quad.mask = quad.coverage > 0.f;
  516. },
  517. [&from_depth4, &to_depth4, &distance_along_line](auto& quad) {
  518. quad.depth = mix(from_depth4, to_depth4, distance_along_line);
  519. },
  520. [&from_color4, &from, &from_fog_depth4](auto& quad) {
  521. // FIXME: interpolate color, tex coords and fog depth along the distance of the line
  522. // in clip space (i.e. NOT distance_from_line)
  523. quad.set_input(SHADER_INPUT_VERTEX_COLOR, from_color4);
  524. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  525. quad.set_input(SHADER_INPUT_FIRST_TEXCOORD + i * 4, expand4(from.tex_coords[i]));
  526. quad.fog_depth = from_fog_depth4;
  527. });
  528. }
  529. void Device::rasterize_line(GPU::Vertex& from, GPU::Vertex& to)
  530. {
  531. if (m_options.line_smooth)
  532. rasterize_line_antialiased(from, to);
  533. else
  534. rasterize_line_aliased(from, to);
  535. }
  536. void Device::rasterize_point_aliased(GPU::Vertex& point)
  537. {
  538. // Determine aliased point width
  539. constexpr size_t maximum_aliased_point_size = 64;
  540. auto point_width = clamp(round_to<int>(m_options.point_size), 1, maximum_aliased_point_size);
  541. // Determine aliased center coordinates
  542. IntVector2 point_center;
  543. if (point_width % 2 == 1)
  544. point_center = point.window_coordinates.xy().to_type<int>();
  545. else
  546. point_center = (point.window_coordinates.xy() + FloatVector2 { .5f, .5f }).to_type<int>();
  547. // Aliased points are rects; calculate boundaries around center
  548. auto point_rect = Gfx::IntRect {
  549. point_center.x() - point_width / 2,
  550. point_center.y() - point_width / 2,
  551. point_width,
  552. point_width,
  553. };
  554. // Rasterize the point as a rect
  555. rasterize(
  556. point_rect,
  557. [](auto& quad) {
  558. // We already passed in point_rect, so this doesn't matter
  559. quad.mask = expand4(~0);
  560. },
  561. [&point](auto& quad) {
  562. quad.depth = expand4(point.window_coordinates.z());
  563. },
  564. [&point](auto& quad) {
  565. quad.set_input(SHADER_INPUT_VERTEX_COLOR, expand4(point.color));
  566. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  567. quad.set_input(SHADER_INPUT_FIRST_TEXCOORD + i * 4, expand4(point.tex_coords[i]));
  568. quad.fog_depth = expand4(abs(point.eye_coordinates.z()));
  569. });
  570. }
  571. void Device::rasterize_point_antialiased(GPU::Vertex& point)
  572. {
  573. auto const center = point.window_coordinates.xy();
  574. auto const center4 = expand4(center);
  575. auto const radius = m_options.point_size / 2;
  576. auto render_bounds = Gfx::IntRect {
  577. center.x() - radius,
  578. center.y() - radius,
  579. radius * 2 + 1,
  580. radius * 2 + 1,
  581. };
  582. // Rasterize using a 2D signed distance field for a circle
  583. rasterize(
  584. render_bounds,
  585. [&center4, &radius](auto& quad) {
  586. auto screen_coords = to_vec2_f32x4(quad.screen_coordinates);
  587. auto distance_to_point = length(center4 - screen_coords) - radius;
  588. // Add .5f to the distance so coverage transitions half a pixel before the actual border
  589. quad.coverage = 1.f - AK::SIMD::clamp(distance_to_point + .5f, 0.f, 1.f);
  590. quad.mask = quad.coverage > 0.f;
  591. },
  592. [&point](auto& quad) {
  593. quad.depth = expand4(point.window_coordinates.z());
  594. },
  595. [&point](auto& quad) {
  596. quad.set_input(SHADER_INPUT_VERTEX_COLOR, expand4(point.color));
  597. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  598. quad.set_input(SHADER_INPUT_FIRST_TEXCOORD + i * 4, expand4(point.tex_coords[i]));
  599. quad.fog_depth = expand4(abs(point.eye_coordinates.z()));
  600. });
  601. }
  602. void Device::rasterize_point(GPU::Vertex& point)
  603. {
  604. if (m_options.point_smooth)
  605. rasterize_point_antialiased(point);
  606. else
  607. rasterize_point_aliased(point);
  608. }
  609. void Device::rasterize_triangle(Triangle& triangle)
  610. {
  611. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  612. auto v0 = (triangle.vertices[0].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  613. auto v1 = (triangle.vertices[1].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  614. auto v2 = (triangle.vertices[2].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  615. auto triangle_area = edge_function(v0, v1, v2);
  616. if (triangle_area == 0)
  617. return;
  618. // Perform face culling
  619. if (m_options.enable_culling) {
  620. bool is_front = (m_options.front_face == GPU::WindingOrder::CounterClockwise ? triangle_area > 0 : triangle_area < 0);
  621. if (!is_front && m_options.cull_back)
  622. return;
  623. if (is_front && m_options.cull_front)
  624. return;
  625. }
  626. // Force counter-clockwise ordering of vertices
  627. if (triangle_area < 0) {
  628. swap(triangle.vertices[0], triangle.vertices[1]);
  629. swap(v0, v1);
  630. triangle_area *= -1;
  631. }
  632. auto const& vertex0 = triangle.vertices[0];
  633. auto const& vertex1 = triangle.vertices[1];
  634. auto const& vertex2 = triangle.vertices[2];
  635. auto const one_over_area = 1.0f / triangle_area;
  636. // This function calculates the 3 edge values for the pixel relative to the triangle.
  637. auto calculate_edge_values4 = [v0, v1, v2](Vector2<i32x4> const& p) -> Vector3<i32x4> {
  638. return {
  639. edge_function4(v1, v2, p),
  640. edge_function4(v2, v0, p),
  641. edge_function4(v0, v1, p),
  642. };
  643. };
  644. // Zero is used in testing against edge values below, applying the "top-left rule". If a pixel
  645. // lies exactly on an edge shared by two triangles, we only render that pixel if the edge in
  646. // question is a "top" or "left" edge. By setting either a 1 or 0, we effectively change the
  647. // comparisons against the edge values below from "> 0" into ">= 0".
  648. IntVector3 const zero {
  649. (v2.y() < v1.y() || (v2.y() == v1.y() && v2.x() < v1.x())) ? 0 : 1,
  650. (v0.y() < v2.y() || (v0.y() == v2.y() && v0.x() < v2.x())) ? 0 : 1,
  651. (v1.y() < v0.y() || (v1.y() == v0.y() && v1.x() < v0.x())) ? 0 : 1,
  652. };
  653. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  654. auto test_point4 = [zero](Vector3<i32x4> const& edges) -> i32x4 {
  655. return edges.x() >= zero.x()
  656. && edges.y() >= zero.y()
  657. && edges.z() >= zero.z();
  658. };
  659. // Calculate render bounds based on the triangle's vertices
  660. Gfx::IntRect render_bounds;
  661. render_bounds.set_left(min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor);
  662. render_bounds.set_right(max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor);
  663. render_bounds.set_top(min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor);
  664. render_bounds.set_bottom(max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor);
  665. // Calculate depth of fragment for fog;
  666. // OpenGL 1.5 chapter 3.10: "An implementation may choose to approximate the
  667. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  668. Vector3<f32x4> fog_depth;
  669. if (m_options.fog_enabled) {
  670. fog_depth = {
  671. expand4(abs(vertex0.eye_coordinates.z())),
  672. expand4(abs(vertex1.eye_coordinates.z())),
  673. expand4(abs(vertex2.eye_coordinates.z())),
  674. };
  675. }
  676. auto const half_pixel_offset = Vector2<i32x4> { expand4(subpixel_factor / 2), expand4(subpixel_factor / 2) };
  677. auto const window_w_coordinates = Vector3<f32x4> {
  678. expand4(vertex0.window_coordinates.w()),
  679. expand4(vertex1.window_coordinates.w()),
  680. expand4(vertex2.window_coordinates.w()),
  681. };
  682. // Calculate depth offset to apply
  683. float depth_offset = 0.f;
  684. if (m_options.depth_offset_enabled) {
  685. // OpenGL 2.0 § 3.5.5 allows us to approximate the maximum slope
  686. auto delta_z = max(
  687. max(
  688. abs(vertex0.window_coordinates.z() - vertex1.window_coordinates.z()),
  689. abs(vertex1.window_coordinates.z() - vertex2.window_coordinates.z())),
  690. abs(vertex2.window_coordinates.z() - vertex0.window_coordinates.z()));
  691. auto depth_max_slope = max(delta_z / render_bounds.width(), delta_z / render_bounds.height());
  692. // Calculate total depth offset
  693. depth_offset = depth_max_slope * m_options.depth_offset_factor + NumericLimits<float>::epsilon() * m_options.depth_offset_constant;
  694. }
  695. auto const window_z_coordinates = Vector3<f32x4> {
  696. expand4(vertex0.window_coordinates.z() + depth_offset),
  697. expand4(vertex1.window_coordinates.z() + depth_offset),
  698. expand4(vertex2.window_coordinates.z() + depth_offset),
  699. };
  700. rasterize(
  701. render_bounds,
  702. [&](auto& quad) {
  703. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor + half_pixel_offset);
  704. quad.mask = test_point4(edge_values);
  705. quad.barycentrics = {
  706. to_f32x4(edge_values.x()),
  707. to_f32x4(edge_values.y()),
  708. to_f32x4(edge_values.z()),
  709. };
  710. },
  711. [&](auto& quad) {
  712. // Determine each edge's ratio to the total area
  713. quad.barycentrics = quad.barycentrics * one_over_area;
  714. // Because the Z coordinates were divided by W, we can interpolate between them
  715. quad.depth = AK::SIMD::clamp(window_z_coordinates.dot(quad.barycentrics), 0.f, 1.f);
  716. },
  717. [&](auto& quad) {
  718. auto const interpolated_reciprocal_w = window_w_coordinates.dot(quad.barycentrics);
  719. quad.barycentrics = quad.barycentrics * window_w_coordinates / interpolated_reciprocal_w;
  720. // FIXME: make this more generic. We want to interpolate more than just color and uv
  721. if (m_options.shade_smooth)
  722. quad.set_input(SHADER_INPUT_VERTEX_COLOR, interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics));
  723. else
  724. quad.set_input(SHADER_INPUT_VERTEX_COLOR, expand4(vertex0.color));
  725. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  726. quad.set_input(SHADER_INPUT_FIRST_TEXCOORD + i * 4, interpolate(expand4(vertex0.tex_coords[i]), expand4(vertex1.tex_coords[i]), expand4(vertex2.tex_coords[i]), quad.barycentrics));
  727. if (m_options.fog_enabled)
  728. quad.fog_depth = fog_depth.dot(quad.barycentrics);
  729. });
  730. }
  731. Device::Device(Gfx::IntSize size)
  732. : m_frame_buffer(FrameBuffer<GPU::ColorType, GPU::DepthType, GPU::StencilType>::try_create(size).release_value_but_fixme_should_propagate_errors())
  733. {
  734. m_options.scissor_box = m_frame_buffer->rect();
  735. m_options.viewport = m_frame_buffer->rect();
  736. }
  737. GPU::DeviceInfo Device::info() const
  738. {
  739. return {
  740. .vendor_name = "SerenityOS",
  741. .device_name = "SoftGPU",
  742. .num_texture_units = GPU::NUM_TEXTURE_UNITS,
  743. .num_lights = NUM_LIGHTS,
  744. .max_clip_planes = MAX_CLIP_PLANES,
  745. .max_texture_size = MAX_TEXTURE_SIZE,
  746. .max_texture_lod_bias = MAX_TEXTURE_LOD_BIAS,
  747. .stencil_bits = sizeof(GPU::StencilType) * 8,
  748. .supports_npot_textures = true,
  749. .supports_texture_clamp_to_edge = true,
  750. .supports_texture_env_add = true,
  751. };
  752. }
  753. static void generate_texture_coordinates(GPU::Vertex const& vertex, FloatVector4& tex_coord, GPU::TextureUnitConfiguration const& texture_unit_configuration)
  754. {
  755. auto generate_coordinate = [&](size_t config_index) -> float {
  756. auto const& tex_coord_generation = texture_unit_configuration.tex_coord_generation[config_index];
  757. switch (tex_coord_generation.mode) {
  758. case GPU::TexCoordGenerationMode::ObjectLinear: {
  759. auto coefficients = tex_coord_generation.coefficients;
  760. return coefficients.dot(vertex.position);
  761. }
  762. case GPU::TexCoordGenerationMode::EyeLinear: {
  763. auto coefficients = tex_coord_generation.coefficients;
  764. return coefficients.dot(vertex.eye_coordinates);
  765. }
  766. case GPU::TexCoordGenerationMode::SphereMap: {
  767. auto const eye_unit = vertex.eye_coordinates.normalized();
  768. FloatVector3 const eye_unit_xyz = eye_unit.xyz();
  769. auto const normal = vertex.normal;
  770. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  771. reflection.set_z(reflection.z() + 1);
  772. auto const reflection_value = reflection[config_index];
  773. return reflection_value / (2 * reflection.length()) + 0.5f;
  774. }
  775. case GPU::TexCoordGenerationMode::ReflectionMap: {
  776. auto const eye_unit = vertex.eye_coordinates.normalized();
  777. FloatVector3 const eye_unit_xyz = eye_unit.xyz();
  778. auto const normal = vertex.normal;
  779. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  780. return reflection[config_index];
  781. }
  782. case GPU::TexCoordGenerationMode::NormalMap: {
  783. return vertex.normal[config_index];
  784. }
  785. }
  786. VERIFY_NOT_REACHED();
  787. };
  788. auto const enabled_coords = texture_unit_configuration.tex_coord_generation_enabled;
  789. if (enabled_coords == GPU::TexCoordGenerationCoordinate::None)
  790. return;
  791. tex_coord = {
  792. ((enabled_coords & GPU::TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(0) : tex_coord.x(),
  793. ((enabled_coords & GPU::TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(1) : tex_coord.y(),
  794. ((enabled_coords & GPU::TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(2) : tex_coord.z(),
  795. ((enabled_coords & GPU::TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(3) : tex_coord.w(),
  796. };
  797. }
  798. void Device::calculate_vertex_lighting(GPU::Vertex& vertex) const
  799. {
  800. if (!m_options.lighting_enabled)
  801. return;
  802. auto const& material = m_materials.at(0);
  803. auto ambient = material.ambient;
  804. auto diffuse = material.diffuse;
  805. auto emissive = material.emissive;
  806. auto specular = material.specular;
  807. if (m_options.color_material_enabled
  808. && (m_options.color_material_face == GPU::ColorMaterialFace::Front || m_options.color_material_face == GPU::ColorMaterialFace::FrontAndBack)) {
  809. switch (m_options.color_material_mode) {
  810. case GPU::ColorMaterialMode::Ambient:
  811. ambient = vertex.color;
  812. break;
  813. case GPU::ColorMaterialMode::AmbientAndDiffuse:
  814. ambient = vertex.color;
  815. diffuse = vertex.color;
  816. break;
  817. case GPU::ColorMaterialMode::Diffuse:
  818. diffuse = vertex.color;
  819. break;
  820. case GPU::ColorMaterialMode::Emissive:
  821. emissive = vertex.color;
  822. break;
  823. case GPU::ColorMaterialMode::Specular:
  824. specular = vertex.color;
  825. break;
  826. }
  827. }
  828. FloatVector4 result_color = emissive + ambient * m_lighting_model.scene_ambient_color;
  829. for (auto const& light : m_lights) {
  830. if (!light.is_enabled)
  831. continue;
  832. // We need to save the length here because the attenuation factor requires a non-normalized vector!
  833. auto sgi_arrow_operator = [](FloatVector4 const& p1, FloatVector4 const& p2, float& output_length) {
  834. FloatVector3 light_vector;
  835. if ((p1.w() != 0.f) && (p2.w() == 0.f))
  836. light_vector = p2.xyz();
  837. else if ((p1.w() == 0.f) && (p2.w() != 0.f))
  838. light_vector = -p1.xyz();
  839. else
  840. light_vector = p2.xyz() - p1.xyz();
  841. output_length = light_vector.length();
  842. if (output_length == 0.f)
  843. return light_vector;
  844. return light_vector / output_length;
  845. };
  846. auto sgi_dot_operator = [](FloatVector3 const& d1, FloatVector3 const& d2) {
  847. return AK::max(d1.dot(d2), 0.0f);
  848. };
  849. float vertex_to_light_length = 0.f;
  850. FloatVector3 vertex_to_light = sgi_arrow_operator(vertex.eye_coordinates, light.position, vertex_to_light_length);
  851. // Light attenuation value.
  852. float light_attenuation_factor = 1.0f;
  853. if (light.position.w() != 0.0f)
  854. light_attenuation_factor = 1.0f / (light.constant_attenuation + (light.linear_attenuation * vertex_to_light_length) + (light.quadratic_attenuation * vertex_to_light_length * vertex_to_light_length));
  855. // Spotlight factor
  856. float spotlight_factor = 1.0f;
  857. if (light.spotlight_cutoff_angle != 180.0f) {
  858. auto const vertex_to_light_dot_spotlight_direction = sgi_dot_operator(vertex_to_light, light.spotlight_direction.normalized());
  859. auto const cos_spotlight_cutoff = AK::cos<float>(light.spotlight_cutoff_angle * AK::Pi<float> / 180.f);
  860. if (vertex_to_light_dot_spotlight_direction >= cos_spotlight_cutoff)
  861. spotlight_factor = AK::pow<float>(vertex_to_light_dot_spotlight_direction, light.spotlight_exponent);
  862. else
  863. spotlight_factor = 0.0f;
  864. }
  865. // FIXME: The spec allows for splitting the colors calculated here into multiple different colors (primary/secondary color). Investigate what this means.
  866. (void)m_lighting_model.color_control;
  867. // 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)
  868. (void)m_lighting_model.two_sided_lighting;
  869. // Ambient
  870. auto const ambient_component = ambient * light.ambient_intensity;
  871. // Diffuse
  872. auto const normal_dot_vertex_to_light = sgi_dot_operator(vertex.normal, vertex_to_light);
  873. auto const diffuse_component = diffuse * light.diffuse_intensity * normal_dot_vertex_to_light;
  874. // Specular
  875. FloatVector4 specular_component = { 0.0f, 0.0f, 0.0f, 0.0f };
  876. if (normal_dot_vertex_to_light > 0.0f) {
  877. FloatVector3 half_vector_normalized;
  878. if (!m_lighting_model.viewer_at_infinity) {
  879. half_vector_normalized = vertex_to_light + FloatVector3(0.0f, 0.0f, 1.0f);
  880. } else {
  881. auto const vertex_to_eye_point = sgi_arrow_operator(vertex.eye_coordinates, { 0.f, 0.f, 0.f, 1.f }, vertex_to_light_length);
  882. half_vector_normalized = vertex_to_light + vertex_to_eye_point;
  883. }
  884. half_vector_normalized.normalize();
  885. auto const normal_dot_half_vector = sgi_dot_operator(vertex.normal, half_vector_normalized);
  886. auto const specular_coefficient = AK::pow(normal_dot_half_vector, material.shininess);
  887. specular_component = specular * light.specular_intensity * specular_coefficient;
  888. }
  889. auto color = ambient_component + diffuse_component + specular_component;
  890. color = color * light_attenuation_factor * spotlight_factor;
  891. result_color += color;
  892. }
  893. vertex.color = result_color;
  894. 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"
  895. vertex.color.clamp(0.0f, 1.0f);
  896. }
  897. void Device::draw_primitives(GPU::PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform, Vector<GPU::Vertex>& vertices)
  898. {
  899. // At this point, the user has effectively specified that they are done with defining the geometry
  900. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  901. //
  902. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  903. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  904. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  905. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  906. // 5. The triangle's vertices are sorted in a counter-clockwise orientation
  907. // 6. The triangles are then sent off to the rasterizer and drawn to the screen
  908. if (vertices.is_empty())
  909. return;
  910. // Set up normals transform by taking the upper left 3x3 elements from the model view matrix
  911. // See section 2.11.3 of the OpenGL 1.5 spec
  912. auto const normal_transform = model_view_transform.submatrix_from_topleft<3>().transpose().inverse();
  913. // First, transform all vertices
  914. for (auto& vertex : vertices) {
  915. vertex.eye_coordinates = model_view_transform * vertex.position;
  916. vertex.normal = normal_transform * vertex.normal;
  917. if (m_options.normalization_enabled)
  918. vertex.normal.normalize();
  919. calculate_vertex_lighting(vertex);
  920. vertex.clip_coordinates = projection_transform * vertex.eye_coordinates;
  921. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i) {
  922. auto const& texture_unit_configuration = m_texture_unit_configuration[i];
  923. if (!texture_unit_configuration.enabled)
  924. continue;
  925. generate_texture_coordinates(vertex, vertex.tex_coords[i], texture_unit_configuration);
  926. vertex.tex_coords[i] = texture_unit_configuration.transformation_matrix * vertex.tex_coords[i];
  927. }
  928. }
  929. // Window coordinate calculation
  930. auto const viewport = m_options.viewport;
  931. auto const viewport_half_width = viewport.width() / 2.f;
  932. auto const viewport_half_height = viewport.height() / 2.f;
  933. auto const viewport_center_x = viewport.x() + viewport_half_width;
  934. auto const viewport_center_y = viewport.y() + viewport_half_height;
  935. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  936. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  937. auto calculate_vertex_window_coordinates = [&](GPU::Vertex& vertex) {
  938. auto const one_over_w = 1 / vertex.clip_coordinates.w();
  939. auto const ndc_coordinates = vertex.clip_coordinates.xyz() * one_over_w;
  940. vertex.window_coordinates = {
  941. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  942. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  943. depth_halfway + ndc_coordinates.z() * depth_half_range,
  944. one_over_w,
  945. };
  946. };
  947. // Process points
  948. if (primitive_type == GPU::PrimitiveType::Points) {
  949. m_clipper.clip_points_against_frustum(vertices);
  950. for (auto& vertex : vertices) {
  951. calculate_vertex_window_coordinates(vertex);
  952. rasterize_point(vertex);
  953. }
  954. return;
  955. }
  956. // Process lines, line loop and line strips
  957. auto rasterize_line_segment = [&](GPU::Vertex& from, GPU::Vertex& to) {
  958. if (!m_clipper.clip_line_against_frustum(from, to))
  959. return;
  960. calculate_vertex_window_coordinates(from);
  961. calculate_vertex_window_coordinates(to);
  962. rasterize_line(from, to);
  963. };
  964. if (primitive_type == GPU::PrimitiveType::Lines) {
  965. if (vertices.size() < 2)
  966. return;
  967. for (size_t i = 0; i < vertices.size() - 1; i += 2)
  968. rasterize_line_segment(vertices[i], vertices[i + 1]);
  969. return;
  970. } else if (primitive_type == GPU::PrimitiveType::LineLoop) {
  971. if (vertices.size() < 2)
  972. return;
  973. for (size_t i = 0; i < vertices.size(); ++i)
  974. rasterize_line_segment(vertices[i], vertices[(i + 1) % vertices.size()]);
  975. return;
  976. } else if (primitive_type == GPU::PrimitiveType::LineStrip) {
  977. if (vertices.size() < 2)
  978. return;
  979. for (size_t i = 0; i < vertices.size() - 1; ++i)
  980. rasterize_line_segment(vertices[i], vertices[i + 1]);
  981. return;
  982. }
  983. // Let's construct some triangles
  984. m_triangle_list.clear_with_capacity();
  985. m_processed_triangles.clear_with_capacity();
  986. if (primitive_type == GPU::PrimitiveType::Triangles) {
  987. Triangle triangle;
  988. if (vertices.size() < 3)
  989. return;
  990. for (size_t i = 0; i < vertices.size() - 2; i += 3) {
  991. triangle.vertices[0] = vertices.at(i);
  992. triangle.vertices[1] = vertices.at(i + 1);
  993. triangle.vertices[2] = vertices.at(i + 2);
  994. m_triangle_list.append(triangle);
  995. }
  996. } else if (primitive_type == GPU::PrimitiveType::Quads) {
  997. // We need to construct two triangles to form the quad
  998. Triangle triangle;
  999. if (vertices.size() < 4)
  1000. return;
  1001. for (size_t i = 0; i < vertices.size() - 3; i += 4) {
  1002. // Triangle 1
  1003. triangle.vertices[0] = vertices.at(i);
  1004. triangle.vertices[1] = vertices.at(i + 1);
  1005. triangle.vertices[2] = vertices.at(i + 2);
  1006. m_triangle_list.append(triangle);
  1007. // Triangle 2
  1008. triangle.vertices[0] = vertices.at(i + 2);
  1009. triangle.vertices[1] = vertices.at(i + 3);
  1010. triangle.vertices[2] = vertices.at(i);
  1011. m_triangle_list.append(triangle);
  1012. }
  1013. } else if (primitive_type == GPU::PrimitiveType::TriangleFan) {
  1014. Triangle triangle;
  1015. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  1016. // This is technically `n-2` triangles. We start at index 1
  1017. for (size_t i = 1; i < vertices.size() - 1; i++) {
  1018. triangle.vertices[1] = vertices.at(i);
  1019. triangle.vertices[2] = vertices.at(i + 1);
  1020. m_triangle_list.append(triangle);
  1021. }
  1022. } else if (primitive_type == GPU::PrimitiveType::TriangleStrip) {
  1023. Triangle triangle;
  1024. if (vertices.size() < 3)
  1025. return;
  1026. for (size_t i = 0; i < vertices.size() - 2; i++) {
  1027. if (i % 2 == 0) {
  1028. triangle.vertices[0] = vertices.at(i);
  1029. triangle.vertices[1] = vertices.at(i + 1);
  1030. triangle.vertices[2] = vertices.at(i + 2);
  1031. } else {
  1032. triangle.vertices[0] = vertices.at(i + 1);
  1033. triangle.vertices[1] = vertices.at(i);
  1034. triangle.vertices[2] = vertices.at(i + 2);
  1035. }
  1036. m_triangle_list.append(triangle);
  1037. }
  1038. }
  1039. // Clip triangles
  1040. for (auto& triangle : m_triangle_list) {
  1041. m_clipped_vertices.clear_with_capacity();
  1042. m_clipped_vertices.append(triangle.vertices[0]);
  1043. m_clipped_vertices.append(triangle.vertices[1]);
  1044. m_clipped_vertices.append(triangle.vertices[2]);
  1045. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  1046. if (m_clip_planes.size() > 0)
  1047. m_clipper.clip_triangle_against_user_defined(m_clipped_vertices, m_clip_planes);
  1048. if (m_clipped_vertices.size() < 3)
  1049. continue;
  1050. for (auto& vertex : m_clipped_vertices)
  1051. calculate_vertex_window_coordinates(vertex);
  1052. Triangle tri;
  1053. tri.vertices[0] = m_clipped_vertices[0];
  1054. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  1055. tri.vertices[1] = m_clipped_vertices[i];
  1056. tri.vertices[2] = m_clipped_vertices[i + 1];
  1057. m_processed_triangles.append(tri);
  1058. }
  1059. }
  1060. for (auto& triangle : m_processed_triangles)
  1061. rasterize_triangle(triangle);
  1062. }
  1063. ALWAYS_INLINE void Device::shade_fragments(PixelQuad& quad)
  1064. {
  1065. Array<Vector4<f32x4>, GPU::NUM_TEXTURE_UNITS> texture_stage_texel;
  1066. auto current_color = quad.get_input_vector4(SHADER_INPUT_VERTEX_COLOR);
  1067. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i) {
  1068. if (!m_texture_unit_configuration[i].enabled)
  1069. continue;
  1070. auto const& sampler = m_samplers[i];
  1071. // OpenGL 2.0 ¶ 3.5.1 states (in a roundabout way) that texture coordinates must be divided by Q
  1072. auto homogeneous_texture_coordinate = quad.get_input_vector4(SHADER_INPUT_FIRST_TEXCOORD + i * 4);
  1073. auto texel = sampler.sample_2d(homogeneous_texture_coordinate.xy() / homogeneous_texture_coordinate.w());
  1074. texture_stage_texel[i] = texel;
  1075. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  1076. // FIXME: implement support for GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_INTENSITY and GL_RGB internal formats
  1077. auto& fixed_function_env = sampler.config().fixed_function_texture_environment;
  1078. switch (fixed_function_env.env_mode) {
  1079. case GPU::TextureEnvMode::Add:
  1080. current_color.set_x(current_color.x() + texel.x());
  1081. current_color.set_y(current_color.y() + texel.y());
  1082. current_color.set_z(current_color.z() + texel.z());
  1083. current_color.set_w(current_color.w() * texel.w());
  1084. break;
  1085. case GPU::TextureEnvMode::Blend: {
  1086. auto blend_color = expand4(fixed_function_env.color);
  1087. current_color.set_x(mix(current_color.x(), blend_color.x(), texel.x()));
  1088. current_color.set_y(mix(current_color.y(), blend_color.y(), texel.y()));
  1089. current_color.set_z(mix(current_color.z(), blend_color.z(), texel.z()));
  1090. current_color.set_w(current_color.w() * texel.w());
  1091. break;
  1092. }
  1093. case GPU::TextureEnvMode::Combine: {
  1094. auto get_source_color = [&](GPU::TextureSource source, u8 texture_stage) {
  1095. switch (source) {
  1096. case GPU::TextureSource::Constant:
  1097. return expand4(fixed_function_env.color);
  1098. case GPU::TextureSource::Previous:
  1099. return current_color;
  1100. case GPU::TextureSource::PrimaryColor:
  1101. return quad.get_input_vector4(SHADER_INPUT_VERTEX_COLOR);
  1102. case GPU::TextureSource::Texture:
  1103. return texel;
  1104. case GPU::TextureSource::TextureStage:
  1105. return texture_stage_texel[texture_stage];
  1106. }
  1107. VERIFY_NOT_REACHED();
  1108. };
  1109. auto get_argument_value = [](GPU::TextureOperand operand, auto value) {
  1110. switch (operand) {
  1111. case GPU::TextureOperand::OneMinusSourceAlpha:
  1112. case GPU::TextureOperand::OneMinusSourceColor:
  1113. return expand4(FloatVector4 { 1.f, 1.f, 1.f, 1.f }) - value;
  1114. case GPU::TextureOperand::SourceAlpha:
  1115. case GPU::TextureOperand::SourceColor:
  1116. return value;
  1117. }
  1118. VERIFY_NOT_REACHED();
  1119. };
  1120. auto calculate_combinator = [](GPU::TextureCombinator combinator, auto arg0, auto arg1, auto arg2) {
  1121. switch (combinator) {
  1122. case GPU::TextureCombinator::Add:
  1123. return arg0 + arg1;
  1124. case GPU::TextureCombinator::AddSigned:
  1125. return arg0 + arg1 - expand4(FloatVector4 { .5f, .5f, .5f, .5f });
  1126. case GPU::TextureCombinator::Dot3RGB:
  1127. case GPU::TextureCombinator::Dot3RGBA: {
  1128. auto scalar = 4.f * ((arg0.x() - .5f) * (arg1.x() - .5f) + (arg0.y() - 0.5f) * (arg1.y() - 0.5f) + (arg0.z() - 0.5f) * (arg1.z() - 0.5f));
  1129. return Vector4<f32x4> { scalar, scalar, scalar, scalar };
  1130. }
  1131. case GPU::TextureCombinator::Interpolate:
  1132. return mix(arg0, arg1, arg2);
  1133. case GPU::TextureCombinator::Modulate:
  1134. return arg0 * arg1;
  1135. case GPU::TextureCombinator::Replace:
  1136. return arg0;
  1137. case GPU::TextureCombinator::Subtract:
  1138. return arg0 - arg1;
  1139. }
  1140. VERIFY_NOT_REACHED();
  1141. };
  1142. auto calculate_color = [&](GPU::TextureCombinator combinator, auto& operands, auto& sources, u8 texture_stage) {
  1143. auto arg0 = get_argument_value(operands[0], get_source_color(sources[0], texture_stage));
  1144. auto arg1 = get_argument_value(operands[1], get_source_color(sources[1], texture_stage));
  1145. auto arg2 = get_argument_value(operands[2], get_source_color(sources[2], texture_stage));
  1146. return calculate_combinator(combinator, arg0, arg1, arg2);
  1147. };
  1148. auto rgb_color = calculate_color(
  1149. fixed_function_env.rgb_combinator,
  1150. fixed_function_env.rgb_operand,
  1151. fixed_function_env.rgb_source,
  1152. fixed_function_env.rgb_source_texture_stage);
  1153. auto alpha_color = calculate_color(
  1154. fixed_function_env.alpha_combinator,
  1155. fixed_function_env.alpha_operand,
  1156. fixed_function_env.alpha_source,
  1157. fixed_function_env.alpha_source_texture_stage);
  1158. current_color.set_x(rgb_color.x() * fixed_function_env.rgb_scale);
  1159. current_color.set_y(rgb_color.y() * fixed_function_env.rgb_scale);
  1160. current_color.set_z(rgb_color.z() * fixed_function_env.rgb_scale);
  1161. current_color.set_w(alpha_color.w() * fixed_function_env.alpha_scale);
  1162. current_color.clamp(expand4(0.f), expand4(1.f));
  1163. break;
  1164. }
  1165. case GPU::TextureEnvMode::Decal: {
  1166. auto dst_alpha = texel.w();
  1167. current_color.set_x(mix(current_color.x(), texel.x(), dst_alpha));
  1168. current_color.set_y(mix(current_color.y(), texel.y(), dst_alpha));
  1169. current_color.set_z(mix(current_color.z(), texel.z(), dst_alpha));
  1170. break;
  1171. }
  1172. case GPU::TextureEnvMode::Modulate:
  1173. current_color = current_color * texel;
  1174. break;
  1175. case GPU::TextureEnvMode::Replace:
  1176. current_color = texel;
  1177. break;
  1178. }
  1179. }
  1180. // Calculate fog
  1181. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  1182. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  1183. if (m_options.fog_enabled) {
  1184. f32x4 factor;
  1185. switch (m_options.fog_mode) {
  1186. case GPU::FogMode::Linear:
  1187. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  1188. break;
  1189. case GPU::FogMode::Exp: {
  1190. auto argument = -m_options.fog_density * quad.fog_depth;
  1191. factor = exp(argument);
  1192. } break;
  1193. case GPU::FogMode::Exp2: {
  1194. auto argument = m_options.fog_density * quad.fog_depth;
  1195. argument *= -argument;
  1196. factor = exp(argument);
  1197. } break;
  1198. default:
  1199. VERIFY_NOT_REACHED();
  1200. }
  1201. // Mix texel's RGB with fog's RBG - leave alpha alone
  1202. auto fog_color = expand4(m_options.fog_color);
  1203. current_color.set_x(mix(fog_color.x(), current_color.x(), factor));
  1204. current_color.set_y(mix(fog_color.y(), current_color.y(), factor));
  1205. current_color.set_z(mix(fog_color.z(), current_color.z(), factor));
  1206. }
  1207. quad.set_output(SHADER_OUTPUT_FIRST_COLOR, current_color.x());
  1208. quad.set_output(SHADER_OUTPUT_FIRST_COLOR + 1, current_color.y());
  1209. quad.set_output(SHADER_OUTPUT_FIRST_COLOR + 2, current_color.z());
  1210. // Multiply coverage with the fragment's alpha to obtain the final alpha value
  1211. quad.set_output(SHADER_OUTPUT_FIRST_COLOR + 3, current_color.w() * quad.coverage);
  1212. }
  1213. void Device::resize(Gfx::IntSize size)
  1214. {
  1215. auto frame_buffer_or_error = FrameBuffer<GPU::ColorType, GPU::DepthType, GPU::StencilType>::try_create(size);
  1216. m_frame_buffer = MUST(frame_buffer_or_error);
  1217. }
  1218. void Device::clear_color(FloatVector4 const& color)
  1219. {
  1220. auto const fill_color = to_argb32(color);
  1221. auto clear_rect = m_frame_buffer->rect();
  1222. if (m_options.scissor_enabled)
  1223. clear_rect.intersect(m_options.scissor_box);
  1224. m_frame_buffer->color_buffer()->fill(fill_color, clear_rect);
  1225. }
  1226. void Device::clear_depth(GPU::DepthType depth)
  1227. {
  1228. auto clear_rect = m_frame_buffer->rect();
  1229. if (m_options.scissor_enabled)
  1230. clear_rect.intersect(m_options.scissor_box);
  1231. m_frame_buffer->depth_buffer()->fill(depth, clear_rect);
  1232. }
  1233. void Device::clear_stencil(GPU::StencilType value)
  1234. {
  1235. auto clear_rect = m_frame_buffer->rect();
  1236. if (m_options.scissor_enabled)
  1237. clear_rect.intersect(m_options.scissor_box);
  1238. m_frame_buffer->stencil_buffer()->fill(value, clear_rect);
  1239. }
  1240. GPU::ImageDataLayout Device::color_buffer_data_layout(Vector2<u32> size, Vector2<i32> offset)
  1241. {
  1242. return {
  1243. .pixel_type = {
  1244. .format = GPU::PixelFormat::BGRA,
  1245. .bits = GPU::PixelComponentBits::B8_8_8_8,
  1246. .data_type = GPU::PixelDataType::UnsignedInt,
  1247. .components_order = GPU::ComponentsOrder::Reversed,
  1248. },
  1249. .dimensions = {
  1250. .width = static_cast<u32>(m_frame_buffer->rect().width()),
  1251. .height = static_cast<u32>(m_frame_buffer->rect().height()),
  1252. .depth = 1,
  1253. },
  1254. .selection = {
  1255. .offset_x = offset.x(),
  1256. .offset_y = offset.y(),
  1257. .offset_z = 0,
  1258. .width = size.x(),
  1259. .height = size.y(),
  1260. .depth = 1,
  1261. },
  1262. };
  1263. }
  1264. GPU::ImageDataLayout Device::depth_buffer_data_layout(Vector2<u32> size, Vector2<i32> offset)
  1265. {
  1266. return {
  1267. .pixel_type = {
  1268. .format = GPU::PixelFormat::DepthComponent,
  1269. .bits = GPU::PixelComponentBits::AllBits,
  1270. .data_type = GPU::PixelDataType::Float,
  1271. },
  1272. .dimensions = {
  1273. .width = static_cast<u32>(m_frame_buffer->rect().width()),
  1274. .height = static_cast<u32>(m_frame_buffer->rect().height()),
  1275. .depth = 1,
  1276. },
  1277. .selection = {
  1278. .offset_x = offset.x(),
  1279. .offset_y = offset.y(),
  1280. .offset_z = 0,
  1281. .width = size.x(),
  1282. .height = size.y(),
  1283. .depth = 1,
  1284. },
  1285. };
  1286. }
  1287. void Device::blit_from_color_buffer(Gfx::Bitmap& target)
  1288. {
  1289. m_frame_buffer->color_buffer()->blit_flipped_to_bitmap(target, m_frame_buffer->rect());
  1290. if constexpr (ENABLE_STATISTICS_OVERLAY)
  1291. draw_statistics_overlay(target);
  1292. }
  1293. void Device::blit_from_color_buffer(NonnullRefPtr<GPU::Image> image, u32 level, Vector2<u32> input_size, Vector2<i32> input_offset, Vector3<i32> output_offset)
  1294. {
  1295. auto input_layout = color_buffer_data_layout(input_size, input_offset);
  1296. auto const* input_data = m_frame_buffer->color_buffer()->scanline(0);
  1297. auto const& softgpu_image = reinterpret_cast<Image*>(image.ptr());
  1298. auto output_layout = softgpu_image->image_data_layout(level, output_offset);
  1299. auto* output_data = softgpu_image->texel_pointer(level, 0, 0, 0);
  1300. PixelConverter converter { input_layout, output_layout };
  1301. auto conversion_result = converter.convert(input_data, output_data, {});
  1302. if (conversion_result.is_error())
  1303. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1304. }
  1305. void Device::blit_from_color_buffer(void* output_data, Vector2<i32> input_offset, GPU::ImageDataLayout const& output_layout)
  1306. {
  1307. auto const& output_selection = output_layout.selection;
  1308. auto input_layout = color_buffer_data_layout({ output_selection.width, output_selection.height }, input_offset);
  1309. PixelConverter converter { input_layout, output_layout };
  1310. auto const* input_data = m_frame_buffer->color_buffer()->scanline(0);
  1311. auto conversion_result = converter.convert(input_data, output_data, {});
  1312. if (conversion_result.is_error())
  1313. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1314. }
  1315. void Device::blit_from_depth_buffer(void* output_data, Vector2<i32> input_offset, GPU::ImageDataLayout const& output_layout)
  1316. {
  1317. auto const& output_selection = output_layout.selection;
  1318. auto input_layout = depth_buffer_data_layout({ output_selection.width, output_selection.height }, input_offset);
  1319. PixelConverter converter { input_layout, output_layout };
  1320. auto const* input_data = m_frame_buffer->depth_buffer()->scanline(0);
  1321. auto conversion_result = converter.convert(input_data, output_data, {});
  1322. if (conversion_result.is_error())
  1323. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1324. }
  1325. void Device::blit_from_depth_buffer(NonnullRefPtr<GPU::Image> image, u32 level, Vector2<u32> input_size, Vector2<i32> input_offset, Vector3<i32> output_offset)
  1326. {
  1327. auto input_layout = depth_buffer_data_layout(input_size, input_offset);
  1328. auto const* input_data = m_frame_buffer->depth_buffer()->scanline(0);
  1329. auto const& softgpu_image = reinterpret_cast<Image*>(image.ptr());
  1330. auto output_layout = softgpu_image->image_data_layout(level, output_offset);
  1331. auto* output_data = softgpu_image->texel_pointer(level, 0, 0, 0);
  1332. PixelConverter converter { input_layout, output_layout };
  1333. auto conversion_result = converter.convert(input_data, output_data, {});
  1334. if (conversion_result.is_error())
  1335. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1336. }
  1337. void Device::blit_to_color_buffer_at_raster_position(void const* input_data, GPU::ImageDataLayout const& input_layout)
  1338. {
  1339. if (!m_raster_position.valid)
  1340. return;
  1341. auto input_selection = input_layout.selection;
  1342. INCREASE_STATISTICS_COUNTER(g_num_pixels, input_selection.width * input_selection.height);
  1343. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, input_selection.width * input_selection.height);
  1344. auto const rasterization_rect = get_rasterization_rect_of_size({ input_selection.width, input_selection.height });
  1345. auto output_layout = color_buffer_data_layout(
  1346. { static_cast<u32>(rasterization_rect.width()), static_cast<u32>(rasterization_rect.height()) },
  1347. { rasterization_rect.x(), rasterization_rect.y() });
  1348. PixelConverter converter { input_layout, output_layout };
  1349. auto* output_data = m_frame_buffer->color_buffer()->scanline(0);
  1350. auto conversion_result = converter.convert(input_data, output_data, {});
  1351. if (conversion_result.is_error())
  1352. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1353. }
  1354. void Device::blit_to_depth_buffer_at_raster_position(void const* input_data, GPU::ImageDataLayout const& input_layout)
  1355. {
  1356. if (!m_raster_position.valid)
  1357. return;
  1358. auto input_selection = input_layout.selection;
  1359. auto const rasterization_rect = get_rasterization_rect_of_size({ input_selection.width, input_selection.height });
  1360. auto output_layout = depth_buffer_data_layout(
  1361. { static_cast<u32>(rasterization_rect.width()), static_cast<u32>(rasterization_rect.height()) },
  1362. { rasterization_rect.x(), rasterization_rect.y() });
  1363. PixelConverter converter { input_layout, output_layout };
  1364. auto* output_data = m_frame_buffer->depth_buffer()->scanline(0);
  1365. auto conversion_result = converter.convert(input_data, output_data, {});
  1366. if (conversion_result.is_error())
  1367. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1368. }
  1369. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  1370. {
  1371. static Core::ElapsedTimer timer;
  1372. static DeprecatedString debug_string;
  1373. static int frame_counter;
  1374. frame_counter++;
  1375. int milliseconds = 0;
  1376. if (timer.is_valid())
  1377. milliseconds = timer.elapsed();
  1378. else
  1379. timer.start();
  1380. Gfx::Painter painter { target };
  1381. if (milliseconds > MILLISECONDS_PER_STATISTICS_PERIOD) {
  1382. int num_rendertarget_pixels = m_frame_buffer->rect().size().area();
  1383. StringBuilder builder;
  1384. builder.append(DeprecatedString::formatted("Timings : {:.1}ms {:.1}FPS\n",
  1385. static_cast<double>(milliseconds) / frame_counter,
  1386. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  1387. builder.append(DeprecatedString::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  1388. builder.append(DeprecatedString::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  1389. builder.append(DeprecatedString::formatted("Pixels : {}, Stencil: {}%, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  1390. g_num_pixels,
  1391. g_num_pixels > 0 ? g_num_stencil_writes * 100 / g_num_pixels : 0,
  1392. g_num_pixels > 0 ? g_num_pixels_shaded * 100 / g_num_pixels : 0,
  1393. g_num_pixels_shaded > 0 ? g_num_pixels_blended * 100 / g_num_pixels_shaded : 0,
  1394. num_rendertarget_pixels > 0 ? g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100 : 0));
  1395. builder.append(DeprecatedString::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  1396. debug_string = builder.to_deprecated_string();
  1397. frame_counter = 0;
  1398. timer.start();
  1399. }
  1400. g_num_rasterized_triangles = 0;
  1401. g_num_pixels = 0;
  1402. g_num_pixels_shaded = 0;
  1403. g_num_pixels_blended = 0;
  1404. g_num_sampler_calls = 0;
  1405. g_num_stencil_writes = 0;
  1406. g_num_quads = 0;
  1407. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  1408. for (int y = -1; y < 2; y++)
  1409. for (int x = -1; x < 2; x++)
  1410. if (x != 0 && y != 0)
  1411. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  1412. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  1413. }
  1414. void Device::set_options(GPU::RasterizerOptions const& options)
  1415. {
  1416. m_options = options;
  1417. if (m_options.enable_blending)
  1418. setup_blend_factors();
  1419. }
  1420. void Device::set_light_model_params(GPU::LightModelParameters const& lighting_model)
  1421. {
  1422. m_lighting_model = lighting_model;
  1423. }
  1424. NonnullRefPtr<GPU::Image> Device::create_image(GPU::PixelFormat const& pixel_format, u32 width, u32 height, u32 depth, u32 max_levels)
  1425. {
  1426. VERIFY(width > 0);
  1427. VERIFY(height > 0);
  1428. VERIFY(depth > 0);
  1429. VERIFY(max_levels > 0);
  1430. return adopt_ref(*new Image(this, pixel_format, width, height, depth, max_levels));
  1431. }
  1432. ErrorOr<NonnullRefPtr<GPU::Shader>> Device::create_shader(GPU::IR::Shader const&)
  1433. {
  1434. return adopt_ref(*new Shader(this, {}));
  1435. }
  1436. void Device::set_sampler_config(unsigned sampler, GPU::SamplerConfig const& config)
  1437. {
  1438. VERIFY(config.bound_image.is_null() || config.bound_image->ownership_token() == this);
  1439. m_samplers[sampler].set_config(config);
  1440. }
  1441. void Device::set_light_state(unsigned int light_id, GPU::Light const& light)
  1442. {
  1443. m_lights.at(light_id) = light;
  1444. }
  1445. void Device::set_material_state(GPU::Face face, GPU::Material const& material)
  1446. {
  1447. m_materials[face] = material;
  1448. }
  1449. void Device::set_stencil_configuration(GPU::Face face, GPU::StencilConfiguration const& stencil_configuration)
  1450. {
  1451. m_stencil_configuration[face] = stencil_configuration;
  1452. }
  1453. void Device::set_texture_unit_configuration(GPU::TextureUnitIndex index, GPU::TextureUnitConfiguration const& configuration)
  1454. {
  1455. m_texture_unit_configuration[index] = configuration;
  1456. }
  1457. void Device::set_raster_position(GPU::RasterPosition const& raster_position)
  1458. {
  1459. m_raster_position = raster_position;
  1460. }
  1461. void Device::set_clip_planes(Vector<FloatVector4> const& clip_planes)
  1462. {
  1463. m_clip_planes = clip_planes;
  1464. }
  1465. void Device::set_raster_position(FloatVector4 const& position, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform)
  1466. {
  1467. auto const eye_coordinates = model_view_transform * position;
  1468. auto const clip_coordinates = projection_transform * eye_coordinates;
  1469. // FIXME: implement clipping
  1470. m_raster_position.valid = true;
  1471. auto ndc_coordinates = clip_coordinates / clip_coordinates.w();
  1472. ndc_coordinates.set_w(clip_coordinates.w());
  1473. auto const viewport = m_options.viewport;
  1474. auto const viewport_half_width = viewport.width() / 2.0f;
  1475. auto const viewport_half_height = viewport.height() / 2.0f;
  1476. auto const viewport_center_x = viewport.x() + viewport_half_width;
  1477. auto const viewport_center_y = viewport.y() + viewport_half_height;
  1478. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  1479. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  1480. // FIXME: implement other raster position properties such as color and texcoords
  1481. m_raster_position.window_coordinates = {
  1482. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  1483. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  1484. depth_halfway + ndc_coordinates.z() * depth_half_range,
  1485. ndc_coordinates.w(),
  1486. };
  1487. m_raster_position.eye_coordinate_distance = eye_coordinates.length();
  1488. }
  1489. void Device::bind_fragment_shader(RefPtr<GPU::Shader> shader)
  1490. {
  1491. VERIFY(shader.is_null() || shader->ownership_token() == this);
  1492. if (shader.is_null()) {
  1493. m_current_fragment_shader = nullptr;
  1494. return;
  1495. }
  1496. auto softgpu_shader = static_ptr_cast<Shader>(shader);
  1497. m_current_fragment_shader = softgpu_shader;
  1498. }
  1499. Gfx::IntRect Device::get_rasterization_rect_of_size(Gfx::IntSize size) const
  1500. {
  1501. // Round the X and Y floating point coordinates to the nearest integer; OpenGL 1.5 spec:
  1502. // "Any fragments whose centers lie inside of this rectangle (or on its bottom or left
  1503. // boundaries) are produced in correspondence with this particular group of elements."
  1504. return {
  1505. round_to<int>(m_raster_position.window_coordinates.x()),
  1506. round_to<int>(m_raster_position.window_coordinates.y()),
  1507. size.width(),
  1508. size.height(),
  1509. };
  1510. }
  1511. }
  1512. extern "C" {
  1513. GPU::Device* serenity_gpu_create_device(Gfx::IntSize size)
  1514. {
  1515. return make<SoftGPU::Device>(size).leak_ptr();
  1516. }
  1517. }