Device.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Function.h>
  8. #include <AK/SIMDExtras.h>
  9. #include <AK/SIMDMath.h>
  10. #include <LibCore/ElapsedTimer.h>
  11. #include <LibGfx/Painter.h>
  12. #include <LibGfx/Vector2.h>
  13. #include <LibGfx/Vector3.h>
  14. #include <LibSoftGPU/Config.h>
  15. #include <LibSoftGPU/Device.h>
  16. #include <LibSoftGPU/PixelQuad.h>
  17. #include <LibSoftGPU/SIMD.h>
  18. namespace SoftGPU {
  19. static long long g_num_rasterized_triangles;
  20. static long long g_num_pixels;
  21. static long long g_num_pixels_shaded;
  22. static long long g_num_pixels_blended;
  23. static long long g_num_sampler_calls;
  24. using IntVector2 = Gfx::Vector2<int>;
  25. using IntVector3 = Gfx::Vector3<int>;
  26. using AK::SIMD::exp;
  27. using AK::SIMD::expand4;
  28. using AK::SIMD::f32x4;
  29. using AK::SIMD::i32x4;
  30. using AK::SIMD::load4_masked;
  31. using AK::SIMD::maskbits;
  32. using AK::SIMD::maskcount;
  33. using AK::SIMD::none;
  34. using AK::SIMD::store4_masked;
  35. using AK::SIMD::to_f32x4;
  36. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  37. {
  38. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  39. }
  40. constexpr static i32x4 edge_function4(const IntVector2& a, const IntVector2& b, const Vector2<i32x4>& c)
  41. {
  42. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  43. }
  44. template<typename T, typename U>
  45. constexpr static auto interpolate(const T& v0, const T& v1, const T& v2, const Vector3<U>& barycentric_coords)
  46. {
  47. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  48. }
  49. ALWAYS_INLINE constexpr static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  50. {
  51. auto clamped = v.clamped(0, 1);
  52. u8 r = clamped.x() * 255;
  53. u8 g = clamped.y() * 255;
  54. u8 b = clamped.z() * 255;
  55. u8 a = clamped.w() * 255;
  56. return a << 24 | r << 16 | g << 8 | b;
  57. }
  58. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  59. {
  60. auto constexpr one_over_255 = 1.0f / 255;
  61. return {
  62. ((rgba >> 16) & 0xff) * one_over_255,
  63. ((rgba >> 8) & 0xff) * one_over_255,
  64. (rgba & 0xff) * one_over_255,
  65. ((rgba >> 24) & 0xff) * one_over_255,
  66. };
  67. }
  68. static Gfx::IntRect scissor_box_to_window_coordinates(Gfx::IntRect const& scissor_box, Gfx::IntRect const& window_rect)
  69. {
  70. return scissor_box.translated(0, window_rect.height() - 2 * scissor_box.y() - scissor_box.height());
  71. }
  72. static constexpr void setup_blend_factors(BlendFactor mode, FloatVector4& constant, float& src_alpha, float& dst_alpha, float& src_color, float& dst_color)
  73. {
  74. constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  75. src_alpha = 0;
  76. dst_alpha = 0;
  77. src_color = 0;
  78. dst_color = 0;
  79. switch (mode) {
  80. case BlendFactor::Zero:
  81. break;
  82. case BlendFactor::One:
  83. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  84. break;
  85. case BlendFactor::SrcColor:
  86. src_color = 1;
  87. break;
  88. case BlendFactor::OneMinusSrcColor:
  89. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  90. src_color = -1;
  91. break;
  92. case BlendFactor::SrcAlpha:
  93. src_alpha = 1;
  94. break;
  95. case BlendFactor::OneMinusSrcAlpha:
  96. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  97. src_alpha = -1;
  98. break;
  99. case BlendFactor::DstAlpha:
  100. dst_alpha = 1;
  101. break;
  102. case BlendFactor::OneMinusDstAlpha:
  103. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  104. dst_alpha = -1;
  105. break;
  106. case BlendFactor::DstColor:
  107. dst_color = 1;
  108. break;
  109. case BlendFactor::OneMinusDstColor:
  110. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  111. dst_color = -1;
  112. break;
  113. case BlendFactor::SrcAlphaSaturate:
  114. // FIXME: How do we implement this?
  115. break;
  116. default:
  117. VERIFY_NOT_REACHED();
  118. }
  119. }
  120. template<typename PS>
  121. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const Triangle& triangle, PS pixel_shader)
  122. {
  123. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  124. // Since the algorithm is based on blocks of uniform size, we need
  125. // to ensure that our render_target size is actually a multiple of the block size
  126. VERIFY((render_target.width() % 2) == 0);
  127. VERIFY((render_target.height() % 2) == 0);
  128. // Return if alpha testing is a no-op
  129. if (options.enable_alpha_test && options.alpha_test_func == AlphaTestFunction::Never)
  130. return;
  131. // Vertices
  132. Vertex const vertex0 = triangle.vertices[0];
  133. Vertex const vertex1 = triangle.vertices[1];
  134. Vertex const vertex2 = triangle.vertices[2];
  135. constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  136. // Calculate area of the triangle for later tests
  137. IntVector2 const v0 { static_cast<int>(vertex0.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex0.window_coordinates.y() * subpixel_factor) };
  138. IntVector2 const v1 { static_cast<int>(vertex1.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex1.window_coordinates.y() * subpixel_factor) };
  139. IntVector2 const v2 { static_cast<int>(vertex2.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex2.window_coordinates.y() * subpixel_factor) };
  140. int area = edge_function(v0, v1, v2);
  141. if (area == 0)
  142. return;
  143. auto const one_over_area = 1.0f / area;
  144. FloatVector4 src_constant {};
  145. float src_factor_src_alpha = 0;
  146. float src_factor_dst_alpha = 0;
  147. float src_factor_src_color = 0;
  148. float src_factor_dst_color = 0;
  149. FloatVector4 dst_constant {};
  150. float dst_factor_src_alpha = 0;
  151. float dst_factor_dst_alpha = 0;
  152. float dst_factor_src_color = 0;
  153. float dst_factor_dst_color = 0;
  154. if (options.enable_blending) {
  155. setup_blend_factors(
  156. options.blend_source_factor,
  157. src_constant,
  158. src_factor_src_alpha,
  159. src_factor_dst_alpha,
  160. src_factor_src_color,
  161. src_factor_dst_color);
  162. setup_blend_factors(
  163. options.blend_destination_factor,
  164. dst_constant,
  165. dst_factor_src_alpha,
  166. dst_factor_dst_alpha,
  167. dst_factor_src_color,
  168. dst_factor_dst_color);
  169. }
  170. auto render_bounds = render_target.rect();
  171. auto window_scissor_rect = scissor_box_to_window_coordinates(options.scissor_box, render_target.rect());
  172. if (options.scissor_enabled)
  173. render_bounds.intersect(window_scissor_rect);
  174. // Obey top-left rule:
  175. // This sets up "zero" for later pixel coverage tests.
  176. // Depending on where on the triangle the edge is located
  177. // it is either tested against 0 or 1, effectively
  178. // turning "< 0" into "<= 0"
  179. IntVector3 zero { 1, 1, 1 };
  180. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  181. zero.set_z(0);
  182. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  183. zero.set_x(0);
  184. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  185. zero.set_y(0);
  186. // This function calculates the 3 edge values for the pixel relative to the triangle.
  187. auto calculate_edge_values4 = [v0, v1, v2](const Vector2<i32x4>& p) -> Vector3<i32x4> {
  188. return {
  189. edge_function4(v1, v2, p),
  190. edge_function4(v2, v0, p),
  191. edge_function4(v0, v1, p),
  192. };
  193. };
  194. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  195. auto test_point4 = [zero](const Vector3<i32x4>& edges) -> i32x4 {
  196. return edges.x() >= zero.x()
  197. && edges.y() >= zero.y()
  198. && edges.z() >= zero.z();
  199. };
  200. auto test_scissor4 = [window_scissor_rect](const Vector2<i32x4>& screen_coordinates) -> i32x4 {
  201. return screen_coordinates.x() >= window_scissor_rect.x()
  202. && screen_coordinates.x() < window_scissor_rect.x() + window_scissor_rect.width()
  203. && screen_coordinates.y() >= window_scissor_rect.y()
  204. && screen_coordinates.y() < window_scissor_rect.y() + window_scissor_rect.height();
  205. };
  206. // Calculate block-based bounds
  207. // clang-format off
  208. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1;
  209. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1) + 2;
  210. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1;
  211. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1) + 2;
  212. // clang-format on
  213. // Fog depths
  214. float const vertex0_eye_absz = fabs(vertex0.eye_coordinates.z());
  215. float const vertex1_eye_absz = fabs(vertex1.eye_coordinates.z());
  216. float const vertex2_eye_absz = fabs(vertex2.eye_coordinates.z());
  217. // FIXME: implement stencil testing
  218. // Iterate over all blocks within the bounds of the triangle
  219. for (int by = by0; by < by1; by += 2) {
  220. for (int bx = bx0; bx < bx1; bx += 2) {
  221. PixelQuad quad;
  222. quad.screen_coordinates = {
  223. i32x4 { bx, bx + 1, bx, bx + 1 },
  224. i32x4 { by, by, by + 1, by + 1 },
  225. };
  226. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor);
  227. // Generate triangle coverage mask
  228. quad.mask = test_point4(edge_values);
  229. if (options.scissor_enabled) {
  230. quad.mask &= test_scissor4(quad.screen_coordinates);
  231. }
  232. if (none(quad.mask))
  233. continue;
  234. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  235. // Calculate barycentric coordinates from previously calculated edge values
  236. quad.barycentrics = Vector3<f32x4> {
  237. to_f32x4(edge_values.x()),
  238. to_f32x4(edge_values.y()),
  239. to_f32x4(edge_values.z()),
  240. } * one_over_area;
  241. float* depth_ptrs[4] = {
  242. &depth_buffer.scanline(by)[bx],
  243. &depth_buffer.scanline(by)[bx + 1],
  244. &depth_buffer.scanline(by + 1)[bx],
  245. &depth_buffer.scanline(by + 1)[bx + 1],
  246. };
  247. // AND the depth mask onto the coverage mask
  248. if (options.enable_depth_test) {
  249. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  250. quad.depth = interpolate(vertex0.window_coordinates.z(), vertex1.window_coordinates.z(), vertex2.window_coordinates.z(), quad.barycentrics);
  251. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  252. quad.depth += options.depth_offset_constant * NumericLimits<float>::epsilon();
  253. switch (options.depth_func) {
  254. case DepthTestFunction::Always:
  255. break;
  256. case DepthTestFunction::Never:
  257. quad.mask ^= quad.mask;
  258. break;
  259. case DepthTestFunction::Greater:
  260. quad.mask &= quad.depth > depth;
  261. break;
  262. case DepthTestFunction::GreaterOrEqual:
  263. quad.mask &= quad.depth >= depth;
  264. break;
  265. case DepthTestFunction::NotEqual:
  266. #ifdef __SSE__
  267. quad.mask &= quad.depth != depth;
  268. #else
  269. quad.mask[0] = bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0;
  270. quad.mask[1] = bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0;
  271. quad.mask[2] = bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0;
  272. quad.mask[3] = bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0;
  273. #endif
  274. break;
  275. case DepthTestFunction::Equal:
  276. #ifdef __SSE__
  277. quad.mask &= quad.depth == depth;
  278. #else
  279. //
  280. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  281. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  282. // it is an 80-bit x87 floating point number, however, when stored into the DepthBuffer, this is
  283. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  284. // used here the comparison fails.
  285. // This could be solved by using a `long double` for the depth buffer, however this would take
  286. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  287. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  288. // equal, we can pretty much guarantee that it's actually equal.
  289. //
  290. quad.mask[0] = bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0;
  291. quad.mask[1] = bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0;
  292. quad.mask[2] = bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0;
  293. quad.mask[3] = bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0;
  294. #endif
  295. break;
  296. case DepthTestFunction::LessOrEqual:
  297. quad.mask &= quad.depth <= depth;
  298. break;
  299. case DepthTestFunction::Less:
  300. quad.mask &= quad.depth < depth;
  301. break;
  302. }
  303. // Nice, no pixels passed the depth test -> block rejected by early z
  304. if (none(quad.mask))
  305. continue;
  306. }
  307. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  308. // Draw the pixels according to the previously generated mask
  309. auto const w_coordinates = Vector3<f32x4> {
  310. expand4(vertex0.window_coordinates.w()),
  311. expand4(vertex1.window_coordinates.w()),
  312. expand4(vertex2.window_coordinates.w()),
  313. };
  314. auto const interpolated_reciprocal_w = interpolate(w_coordinates.x(), w_coordinates.y(), w_coordinates.z(), quad.barycentrics);
  315. auto const interpolated_w = 1.0f / interpolated_reciprocal_w;
  316. quad.barycentrics = quad.barycentrics * w_coordinates * interpolated_w;
  317. // FIXME: make this more generic. We want to interpolate more than just color and uv
  318. if (options.shade_smooth) {
  319. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  320. } else {
  321. quad.vertex_color = expand4(vertex0.color);
  322. }
  323. quad.uv = interpolate(expand4(vertex0.tex_coord), expand4(vertex1.tex_coord), expand4(vertex2.tex_coord), quad.barycentrics);
  324. // Calculate depth of fragment for fog
  325. //
  326. // OpenGL 1.5 spec chapter 3.10: "An implementation may choose to approximate the
  327. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  328. quad.fog_depth = interpolate(expand4(vertex0_eye_absz), expand4(vertex1_eye_absz), expand4(vertex2_eye_absz), quad.barycentrics);
  329. pixel_shader(quad);
  330. if (options.enable_alpha_test && options.alpha_test_func != AlphaTestFunction::Always) {
  331. switch (options.alpha_test_func) {
  332. case AlphaTestFunction::Less:
  333. quad.mask &= quad.out_color.w() < options.alpha_test_ref_value;
  334. break;
  335. case AlphaTestFunction::Equal:
  336. quad.mask &= quad.out_color.w() == options.alpha_test_ref_value;
  337. break;
  338. case AlphaTestFunction::LessOrEqual:
  339. quad.mask &= quad.out_color.w() <= options.alpha_test_ref_value;
  340. break;
  341. case AlphaTestFunction::Greater:
  342. quad.mask &= quad.out_color.w() > options.alpha_test_ref_value;
  343. break;
  344. case AlphaTestFunction::NotEqual:
  345. quad.mask &= quad.out_color.w() != options.alpha_test_ref_value;
  346. break;
  347. case AlphaTestFunction::GreaterOrEqual:
  348. quad.mask &= quad.out_color.w() >= options.alpha_test_ref_value;
  349. break;
  350. case AlphaTestFunction::Never:
  351. case AlphaTestFunction::Always:
  352. VERIFY_NOT_REACHED();
  353. }
  354. }
  355. // Write to depth buffer
  356. if (options.enable_depth_test && options.enable_depth_write) {
  357. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  358. }
  359. // We will not update the color buffer at all
  360. if (!options.color_mask || !options.enable_color_write)
  361. continue;
  362. Gfx::RGBA32* color_ptrs[4] = {
  363. &render_target.scanline(by)[bx],
  364. &render_target.scanline(by)[bx + 1],
  365. &render_target.scanline(by + 1)[bx],
  366. &render_target.scanline(by + 1)[bx + 1],
  367. };
  368. int bits = maskbits(quad.mask);
  369. if (options.enable_blending) {
  370. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  371. // Blend color values from pixel_staging into render_target
  372. FloatVector4 dst_aos[4] {
  373. bits & 1 ? to_vec4(*color_ptrs[0]) : FloatVector4 { 0, 0, 0, 0 },
  374. bits & 2 ? to_vec4(*color_ptrs[1]) : FloatVector4 { 0, 0, 0, 0 },
  375. bits & 4 ? to_vec4(*color_ptrs[2]) : FloatVector4 { 0, 0, 0, 0 },
  376. bits & 8 ? to_vec4(*color_ptrs[3]) : FloatVector4 { 0, 0, 0, 0 },
  377. };
  378. auto dst = Vector4<f32x4> {
  379. f32x4 { dst_aos[0].x(), dst_aos[1].x(), dst_aos[2].x(), dst_aos[3].x() },
  380. f32x4 { dst_aos[0].y(), dst_aos[1].y(), dst_aos[2].y(), dst_aos[3].y() },
  381. f32x4 { dst_aos[0].z(), dst_aos[1].z(), dst_aos[2].z(), dst_aos[3].z() },
  382. f32x4 { dst_aos[0].w(), dst_aos[1].w(), dst_aos[2].w(), dst_aos[3].w() },
  383. };
  384. Vector4<f32x4> const& src = quad.out_color;
  385. auto src_factor = expand4(src_constant)
  386. + src * src_factor_src_color
  387. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * src_factor_src_alpha
  388. + dst * src_factor_dst_color
  389. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * src_factor_dst_alpha;
  390. auto dst_factor = expand4(dst_constant)
  391. + src * dst_factor_src_color
  392. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * dst_factor_src_alpha
  393. + dst * dst_factor_dst_color
  394. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * dst_factor_dst_alpha;
  395. quad.out_color = src * src_factor + dst * dst_factor;
  396. }
  397. if (bits & 1)
  398. *color_ptrs[0] = to_rgba32(FloatVector4 { quad.out_color.x()[0], quad.out_color.y()[0], quad.out_color.z()[0], quad.out_color.w()[0] });
  399. if (bits & 2)
  400. *color_ptrs[1] = to_rgba32(FloatVector4 { quad.out_color.x()[1], quad.out_color.y()[1], quad.out_color.z()[1], quad.out_color.w()[1] });
  401. if (bits & 4)
  402. *color_ptrs[2] = to_rgba32(FloatVector4 { quad.out_color.x()[2], quad.out_color.y()[2], quad.out_color.z()[2], quad.out_color.w()[2] });
  403. if (bits & 8)
  404. *color_ptrs[3] = to_rgba32(FloatVector4 { quad.out_color.x()[3], quad.out_color.y()[3], quad.out_color.z()[3], quad.out_color.w()[3] });
  405. }
  406. }
  407. }
  408. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  409. {
  410. int width = ((min_size.width() + step - 1) / step) * step;
  411. int height = ((min_size.height() + step - 1) / step) * step;
  412. return { width, height };
  413. }
  414. Device::Device(const Gfx::IntSize& min_size)
  415. : m_render_target { Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, 2)).release_value_but_fixme_should_propagate_errors() }
  416. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, 2))) }
  417. {
  418. m_options.scissor_box = m_render_target->rect();
  419. }
  420. DeviceInfo Device::info() const
  421. {
  422. return {
  423. .vendor_name = "SerenityOS",
  424. .device_name = "SoftGPU",
  425. .num_texture_units = NUM_SAMPLERS
  426. };
  427. }
  428. static void generate_texture_coordinates(Vertex& vertex, RasterizerOptions const& options)
  429. {
  430. auto generate_coordinate = [&](size_t config_index) -> float {
  431. auto mode = options.texcoord_generation_config[config_index].mode;
  432. switch (mode) {
  433. case TexCoordGenerationMode::ObjectLinear: {
  434. auto coefficients = options.texcoord_generation_config[config_index].coefficients;
  435. return coefficients.dot(vertex.position);
  436. }
  437. case TexCoordGenerationMode::EyeLinear: {
  438. auto coefficients = options.texcoord_generation_config[config_index].coefficients;
  439. return coefficients.dot(vertex.eye_coordinates);
  440. }
  441. case TexCoordGenerationMode::SphereMap: {
  442. auto const eye_unit = vertex.eye_coordinates.normalized();
  443. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  444. auto const normal = vertex.normal;
  445. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  446. reflection.set_z(reflection.z() + 1);
  447. auto const reflection_value = (config_index == 0) ? reflection.x() : reflection.y();
  448. return reflection_value / (2 * reflection.length()) + 0.5f;
  449. }
  450. case TexCoordGenerationMode::ReflectionMap: {
  451. auto const eye_unit = vertex.eye_coordinates.normalized();
  452. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  453. auto const normal = vertex.normal;
  454. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  455. switch (config_index) {
  456. case 0:
  457. return reflection.x();
  458. case 1:
  459. return reflection.y();
  460. case 2:
  461. return reflection.z();
  462. default:
  463. VERIFY_NOT_REACHED();
  464. }
  465. }
  466. case TexCoordGenerationMode::NormalMap: {
  467. auto const normal = vertex.normal;
  468. switch (config_index) {
  469. case 0:
  470. return normal.x();
  471. case 1:
  472. return normal.y();
  473. case 2:
  474. return normal.z();
  475. default:
  476. VERIFY_NOT_REACHED();
  477. }
  478. }
  479. default:
  480. VERIFY_NOT_REACHED();
  481. }
  482. };
  483. auto const enabled_coords = options.texcoord_generation_enabled_coordinates;
  484. vertex.tex_coord = {
  485. ((enabled_coords & TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(0) : vertex.tex_coord.x(),
  486. ((enabled_coords & TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(1) : vertex.tex_coord.y(),
  487. ((enabled_coords & TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(2) : vertex.tex_coord.z(),
  488. ((enabled_coords & TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(3) : vertex.tex_coord.w(),
  489. };
  490. }
  491. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix3x3 const& normal_transform,
  492. FloatMatrix4x4 const& projection_transform, FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices,
  493. Vector<size_t> const& enabled_texture_units)
  494. {
  495. // At this point, the user has effectively specified that they are done with defining the geometry
  496. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  497. //
  498. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  499. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  500. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  501. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  502. // 5. The vertices are sorted (for the rasterizer, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  503. // 6. The vertices are then sent off to the rasterizer and drawn to the screen
  504. float scr_width = m_render_target->width();
  505. float scr_height = m_render_target->height();
  506. m_triangle_list.clear_with_capacity();
  507. m_processed_triangles.clear_with_capacity();
  508. // Let's construct some triangles
  509. if (primitive_type == PrimitiveType::Triangles) {
  510. Triangle triangle;
  511. for (size_t i = 0; i < vertices.size(); i += 3) {
  512. triangle.vertices[0] = vertices.at(i);
  513. triangle.vertices[1] = vertices.at(i + 1);
  514. triangle.vertices[2] = vertices.at(i + 2);
  515. m_triangle_list.append(triangle);
  516. }
  517. } else if (primitive_type == PrimitiveType::Quads) {
  518. // We need to construct two triangles to form the quad
  519. Triangle triangle;
  520. VERIFY(vertices.size() % 4 == 0);
  521. for (size_t i = 0; i < vertices.size(); i += 4) {
  522. // Triangle 1
  523. triangle.vertices[0] = vertices.at(i);
  524. triangle.vertices[1] = vertices.at(i + 1);
  525. triangle.vertices[2] = vertices.at(i + 2);
  526. m_triangle_list.append(triangle);
  527. // Triangle 2
  528. triangle.vertices[0] = vertices.at(i + 2);
  529. triangle.vertices[1] = vertices.at(i + 3);
  530. triangle.vertices[2] = vertices.at(i);
  531. m_triangle_list.append(triangle);
  532. }
  533. } else if (primitive_type == PrimitiveType::TriangleFan) {
  534. Triangle triangle;
  535. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  536. for (size_t i = 1; i < vertices.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  537. {
  538. triangle.vertices[1] = vertices.at(i);
  539. triangle.vertices[2] = vertices.at(i + 1);
  540. m_triangle_list.append(triangle);
  541. }
  542. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  543. Triangle triangle;
  544. for (size_t i = 0; i < vertices.size() - 2; i++) {
  545. if (i % 2 == 0) {
  546. triangle.vertices[0] = vertices.at(i);
  547. triangle.vertices[1] = vertices.at(i + 1);
  548. triangle.vertices[2] = vertices.at(i + 2);
  549. } else {
  550. triangle.vertices[0] = vertices.at(i + 1);
  551. triangle.vertices[1] = vertices.at(i);
  552. triangle.vertices[2] = vertices.at(i + 2);
  553. }
  554. m_triangle_list.append(triangle);
  555. }
  556. }
  557. // Now let's transform each triangle and send that to the GPU
  558. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  559. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  560. for (auto& triangle : m_triangle_list) {
  561. // Transform vertices into eye coordinates using the model-view transform
  562. triangle.vertices[0].eye_coordinates = model_view_transform * triangle.vertices[0].position;
  563. triangle.vertices[1].eye_coordinates = model_view_transform * triangle.vertices[1].position;
  564. triangle.vertices[2].eye_coordinates = model_view_transform * triangle.vertices[2].position;
  565. // Transform eye coordinates into clip coordinates using the projection transform
  566. triangle.vertices[0].clip_coordinates = projection_transform * triangle.vertices[0].eye_coordinates;
  567. triangle.vertices[1].clip_coordinates = projection_transform * triangle.vertices[1].eye_coordinates;
  568. triangle.vertices[2].clip_coordinates = projection_transform * triangle.vertices[2].eye_coordinates;
  569. // At this point, we're in clip space
  570. // Here's where we do the clipping. This is a really crude implementation of the
  571. // https://learnopengl.com/Getting-started/Coordinate-Systems
  572. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  573. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  574. //
  575. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  576. // Okay, let's do some face culling first
  577. m_clipped_vertices.clear_with_capacity();
  578. m_clipped_vertices.append(triangle.vertices[0]);
  579. m_clipped_vertices.append(triangle.vertices[1]);
  580. m_clipped_vertices.append(triangle.vertices[2]);
  581. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  582. if (m_clipped_vertices.size() < 3)
  583. continue;
  584. for (auto& vec : m_clipped_vertices) {
  585. // To normalized device coordinates (NDC)
  586. auto const one_over_w = 1 / vec.clip_coordinates.w();
  587. auto const ndc_coordinates = FloatVector4 {
  588. vec.clip_coordinates.x() * one_over_w,
  589. vec.clip_coordinates.y() * one_over_w,
  590. vec.clip_coordinates.z() * one_over_w,
  591. one_over_w,
  592. };
  593. // To window coordinates
  594. // FIXME: implement viewport functionality
  595. vec.window_coordinates = {
  596. scr_width / 2 + ndc_coordinates.x() * scr_width / 2,
  597. scr_height / 2 - ndc_coordinates.y() * scr_height / 2,
  598. depth_half_range * ndc_coordinates.z() + depth_halfway,
  599. ndc_coordinates.w(),
  600. };
  601. }
  602. Triangle tri;
  603. tri.vertices[0] = m_clipped_vertices[0];
  604. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  605. tri.vertices[1] = m_clipped_vertices[i];
  606. tri.vertices[2] = m_clipped_vertices[i + 1];
  607. m_processed_triangles.append(tri);
  608. }
  609. }
  610. for (auto& triangle : m_processed_triangles) {
  611. // Let's calculate the (signed) area of the triangle
  612. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  613. float dxAB = triangle.vertices[0].window_coordinates.x() - triangle.vertices[1].window_coordinates.x(); // A.x - B.x
  614. float dxBC = triangle.vertices[1].window_coordinates.x() - triangle.vertices[2].window_coordinates.x(); // B.X - C.x
  615. float dyAB = triangle.vertices[0].window_coordinates.y() - triangle.vertices[1].window_coordinates.y();
  616. float dyBC = triangle.vertices[1].window_coordinates.y() - triangle.vertices[2].window_coordinates.y();
  617. float area = (dxAB * dyBC) - (dxBC * dyAB);
  618. if (area == 0.0f)
  619. continue;
  620. if (m_options.enable_culling) {
  621. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area < 0 : area > 0);
  622. if (!is_front && m_options.cull_back)
  623. continue;
  624. if (is_front && m_options.cull_front)
  625. continue;
  626. }
  627. if (area > 0)
  628. swap(triangle.vertices[0], triangle.vertices[1]);
  629. // Transform normals
  630. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  631. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  632. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  633. if (m_options.normalization_enabled) {
  634. triangle.vertices[0].normal.normalize();
  635. triangle.vertices[1].normal.normalize();
  636. triangle.vertices[2].normal.normalize();
  637. }
  638. // Generate texture coordinates if at least one coordinate is enabled
  639. if (m_options.texcoord_generation_enabled_coordinates != TexCoordGenerationCoordinate::None) {
  640. generate_texture_coordinates(triangle.vertices[0], m_options);
  641. generate_texture_coordinates(triangle.vertices[1], m_options);
  642. generate_texture_coordinates(triangle.vertices[2], m_options);
  643. }
  644. // Apply texture transformation
  645. // FIXME: implement multi-texturing: texcoords should be stored per texture unit
  646. triangle.vertices[0].tex_coord = texture_transform * triangle.vertices[0].tex_coord;
  647. triangle.vertices[1].tex_coord = texture_transform * triangle.vertices[1].tex_coord;
  648. triangle.vertices[2].tex_coord = texture_transform * triangle.vertices[2].tex_coord;
  649. submit_triangle(triangle, enabled_texture_units);
  650. }
  651. }
  652. void Device::submit_triangle(const Triangle& triangle, Vector<size_t> const& enabled_texture_units)
  653. {
  654. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [this, &enabled_texture_units](PixelQuad& quad) {
  655. quad.out_color = quad.vertex_color;
  656. for (size_t i : enabled_texture_units) {
  657. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  658. auto const& sampler = m_samplers[i];
  659. auto texel = sampler.sample_2d({ quad.uv.x(), quad.uv.y() });
  660. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  661. // FIXME: Implement more blend modes
  662. switch (sampler.config().fixed_function_texture_env_mode) {
  663. case TextureEnvMode::Modulate:
  664. quad.out_color = quad.out_color * texel;
  665. break;
  666. case TextureEnvMode::Replace:
  667. quad.out_color = texel;
  668. break;
  669. case TextureEnvMode::Decal: {
  670. auto src_alpha = quad.out_color.w();
  671. quad.out_color.set_x(mix(quad.out_color.x(), texel.x(), src_alpha));
  672. quad.out_color.set_y(mix(quad.out_color.y(), texel.y(), src_alpha));
  673. quad.out_color.set_z(mix(quad.out_color.z(), texel.z(), src_alpha));
  674. break;
  675. }
  676. default:
  677. VERIFY_NOT_REACHED();
  678. }
  679. }
  680. // Calculate fog
  681. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  682. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  683. if (m_options.fog_enabled) {
  684. auto factor = expand4(0.0f);
  685. switch (m_options.fog_mode) {
  686. case FogMode::Linear:
  687. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  688. break;
  689. case FogMode::Exp: {
  690. auto argument = -m_options.fog_density * quad.fog_depth;
  691. factor = exp(argument);
  692. } break;
  693. case FogMode::Exp2: {
  694. auto argument = m_options.fog_density * quad.fog_depth;
  695. argument *= -argument;
  696. factor = exp(argument);
  697. } break;
  698. default:
  699. VERIFY_NOT_REACHED();
  700. }
  701. // Mix texel's RGB with fog's RBG - leave alpha alone
  702. auto fog_color = expand4(m_options.fog_color);
  703. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  704. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  705. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  706. }
  707. });
  708. }
  709. void Device::resize(const Gfx::IntSize& min_size)
  710. {
  711. wait_for_all_threads();
  712. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, 2)).release_value_but_fixme_should_propagate_errors();
  713. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  714. }
  715. void Device::clear_color(const FloatVector4& color)
  716. {
  717. wait_for_all_threads();
  718. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  719. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  720. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  721. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  722. auto const fill_color = Gfx::Color(r, g, b, a);
  723. if (m_options.scissor_enabled) {
  724. auto fill_rect = m_render_target->rect();
  725. fill_rect.intersect(scissor_box_to_window_coordinates(m_options.scissor_box, fill_rect));
  726. Gfx::Painter painter { *m_render_target };
  727. painter.fill_rect(fill_rect, fill_color);
  728. return;
  729. }
  730. m_render_target->fill(fill_color);
  731. }
  732. void Device::clear_depth(float depth)
  733. {
  734. wait_for_all_threads();
  735. if (m_options.scissor_enabled) {
  736. m_depth_buffer->clear(scissor_box_to_window_coordinates(m_options.scissor_box, m_render_target->rect()), depth);
  737. return;
  738. }
  739. m_depth_buffer->clear(depth);
  740. }
  741. void Device::blit(Gfx::Bitmap const& source, int x, int y)
  742. {
  743. wait_for_all_threads();
  744. INCREASE_STATISTICS_COUNTER(g_num_pixels, source.width() * source.height());
  745. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, source.width() * source.height());
  746. Gfx::Painter painter { *m_render_target };
  747. painter.blit({ x, y }, source, source.rect(), 1.0f, true);
  748. }
  749. void Device::blit_to(Gfx::Bitmap& target)
  750. {
  751. wait_for_all_threads();
  752. Gfx::Painter painter { target };
  753. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  754. if constexpr (ENABLE_STATISTICS_OVERLAY)
  755. draw_statistics_overlay(target);
  756. }
  757. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  758. {
  759. static Core::ElapsedTimer timer;
  760. static String debug_string;
  761. static int frame_counter;
  762. frame_counter++;
  763. int milliseconds = 0;
  764. if (timer.is_valid())
  765. milliseconds = timer.elapsed();
  766. else
  767. timer.start();
  768. Gfx::Painter painter { target };
  769. if (milliseconds > 500) {
  770. if (g_num_pixels == 0)
  771. g_num_pixels = 1;
  772. int num_rendertarget_pixels = m_render_target->width() * m_render_target->height();
  773. StringBuilder builder;
  774. builder.append(String::formatted("Timings : {:.1}ms {:.1}FPS\n",
  775. static_cast<double>(milliseconds) / frame_counter,
  776. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  777. builder.append(String::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  778. builder.append(String::formatted("Pixels : {}, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  779. g_num_pixels,
  780. g_num_pixels_shaded * 100 / g_num_pixels,
  781. g_num_pixels_blended * 100 / g_num_pixels_shaded,
  782. g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100));
  783. builder.append(String::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  784. debug_string = builder.to_string();
  785. frame_counter = 0;
  786. timer.start();
  787. }
  788. g_num_rasterized_triangles = 0;
  789. g_num_pixels = 0;
  790. g_num_pixels_shaded = 0;
  791. g_num_pixels_blended = 0;
  792. g_num_sampler_calls = 0;
  793. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  794. for (int y = -1; y < 2; y++)
  795. for (int x = -1; x < 2; x++)
  796. if (x != 0 && y != 0)
  797. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  798. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  799. }
  800. void Device::wait_for_all_threads() const
  801. {
  802. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  803. }
  804. void Device::set_options(const RasterizerOptions& options)
  805. {
  806. wait_for_all_threads();
  807. m_options = options;
  808. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  809. }
  810. Gfx::RGBA32 Device::get_backbuffer_pixel(int x, int y)
  811. {
  812. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  813. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  814. return 0;
  815. return m_render_target->scanline(y)[x];
  816. }
  817. float Device::get_depthbuffer_value(int x, int y)
  818. {
  819. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  820. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  821. return 1.0f;
  822. return m_depth_buffer->scanline(y)[x];
  823. }
  824. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  825. {
  826. VERIFY(width > 0);
  827. VERIFY(height > 0);
  828. VERIFY(depth > 0);
  829. VERIFY(levels > 0);
  830. VERIFY(layers > 0);
  831. return adopt_ref(*new Image(format, width, height, depth, levels, layers));
  832. }
  833. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  834. {
  835. m_samplers[sampler].set_config(config);
  836. }
  837. }