Device.cpp 63 KB

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