Device.cpp 36 KB

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