Device.cpp 66 KB

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