Device.cpp 43 KB

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