SoftwareRasterizer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SoftwareRasterizer.h"
  7. #include <AK/Function.h>
  8. #include <LibGfx/Painter.h>
  9. #include <LibGfx/Vector2.h>
  10. #include <LibGfx/Vector3.h>
  11. namespace GL {
  12. using IntVector2 = Gfx::Vector2<int>;
  13. using IntVector3 = Gfx::Vector3<int>;
  14. static constexpr int RASTERIZER_BLOCK_SIZE = 16;
  15. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  16. {
  17. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  18. }
  19. template<typename T>
  20. constexpr static T interpolate(const T& v0, const T& v1, const T& v2, const FloatVector3& barycentric_coords)
  21. {
  22. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  23. }
  24. template<typename T>
  25. constexpr static T mix(const T& x, const T& y, float interp)
  26. {
  27. return x * (1 - interp) + y * interp;
  28. }
  29. ALWAYS_INLINE constexpr static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  30. {
  31. auto clamped = v.clamped(0, 1);
  32. u8 r = clamped.x() * 255;
  33. u8 g = clamped.y() * 255;
  34. u8 b = clamped.z() * 255;
  35. u8 a = clamped.w() * 255;
  36. return a << 24 | r << 16 | g << 8 | b;
  37. }
  38. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  39. {
  40. return {
  41. ((rgba >> 16) & 0xff) / 255.0f,
  42. ((rgba >> 8) & 0xff) / 255.0f,
  43. (rgba & 0xff) / 255.0f,
  44. ((rgba >> 24) & 0xff) / 255.0f
  45. };
  46. }
  47. static Gfx::IntRect scissor_box_to_window_coordinates(Gfx::IntRect const& scissor_box, Gfx::IntRect const& window_rect)
  48. {
  49. return scissor_box.translated(0, window_rect.height() - 2 * scissor_box.y() - scissor_box.height());
  50. }
  51. static constexpr void setup_blend_factors(GLenum mode, FloatVector4& constant, float& src_alpha, float& dst_alpha, float& src_color, float& dst_color)
  52. {
  53. constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  54. src_alpha = 0;
  55. dst_alpha = 0;
  56. src_color = 0;
  57. dst_color = 0;
  58. switch (mode) {
  59. case GL_ZERO:
  60. break;
  61. case GL_ONE:
  62. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  63. break;
  64. case GL_SRC_COLOR:
  65. src_color = 1;
  66. break;
  67. case GL_ONE_MINUS_SRC_COLOR:
  68. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  69. src_color = -1;
  70. break;
  71. case GL_SRC_ALPHA:
  72. src_alpha = 1;
  73. break;
  74. case GL_ONE_MINUS_SRC_ALPHA:
  75. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  76. src_alpha = -1;
  77. break;
  78. case GL_DST_ALPHA:
  79. dst_alpha = 1;
  80. break;
  81. case GL_ONE_MINUS_DST_ALPHA:
  82. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  83. dst_alpha = -1;
  84. break;
  85. case GL_DST_COLOR:
  86. dst_color = 1;
  87. break;
  88. case GL_ONE_MINUS_DST_COLOR:
  89. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  90. dst_color = -1;
  91. break;
  92. case GL_SRC_ALPHA_SATURATE:
  93. // FIXME: How do we implement this?
  94. break;
  95. default:
  96. VERIFY_NOT_REACHED();
  97. }
  98. }
  99. template<typename PS>
  100. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const GLTriangle& triangle, PS pixel_shader)
  101. {
  102. // Since the algorithm is based on blocks of uniform size, we need
  103. // to ensure that our render_target size is actually a multiple of the block size
  104. VERIFY((render_target.width() % RASTERIZER_BLOCK_SIZE) == 0);
  105. VERIFY((render_target.height() % RASTERIZER_BLOCK_SIZE) == 0);
  106. // Calculate area of the triangle for later tests
  107. IntVector2 v0 { (int)triangle.vertices[0].position.x(), (int)triangle.vertices[0].position.y() };
  108. IntVector2 v1 { (int)triangle.vertices[1].position.x(), (int)triangle.vertices[1].position.y() };
  109. IntVector2 v2 { (int)triangle.vertices[2].position.x(), (int)triangle.vertices[2].position.y() };
  110. int area = edge_function(v0, v1, v2);
  111. if (area == 0)
  112. return;
  113. float one_over_area = 1.0f / area;
  114. FloatVector4 src_constant {};
  115. float src_factor_src_alpha = 0;
  116. float src_factor_dst_alpha = 0;
  117. float src_factor_src_color = 0;
  118. float src_factor_dst_color = 0;
  119. FloatVector4 dst_constant {};
  120. float dst_factor_src_alpha = 0;
  121. float dst_factor_dst_alpha = 0;
  122. float dst_factor_src_color = 0;
  123. float dst_factor_dst_color = 0;
  124. if (options.enable_blending) {
  125. setup_blend_factors(
  126. options.blend_source_factor,
  127. src_constant,
  128. src_factor_src_alpha,
  129. src_factor_dst_alpha,
  130. src_factor_src_color,
  131. src_factor_dst_color);
  132. setup_blend_factors(
  133. options.blend_destination_factor,
  134. dst_constant,
  135. dst_factor_src_alpha,
  136. dst_factor_dst_alpha,
  137. dst_factor_src_color,
  138. dst_factor_dst_color);
  139. }
  140. // Obey top-left rule:
  141. // This sets up "zero" for later pixel coverage tests.
  142. // Depending on where on the triangle the edge is located
  143. // it is either tested against 0 or 1, effectively
  144. // turning "< 0" into "<= 0"
  145. IntVector3 zero { 1, 1, 1 };
  146. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  147. zero.set_z(0);
  148. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  149. zero.set_x(0);
  150. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  151. zero.set_y(0);
  152. // This function calculates the 3 edge values for the pixel relative to the triangle.
  153. auto calculate_edge_values = [v0, v1, v2](const IntVector2& p) -> IntVector3 {
  154. return {
  155. edge_function(v1, v2, p),
  156. edge_function(v2, v0, p),
  157. edge_function(v0, v1, p),
  158. };
  159. };
  160. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  161. auto test_point = [zero](const IntVector3& edges) -> bool {
  162. return edges.x() >= zero.x()
  163. && edges.y() >= zero.y()
  164. && edges.z() >= zero.z();
  165. };
  166. // Calculate block-based bounds
  167. auto render_bounds = render_target.rect();
  168. if (options.scissor_enabled)
  169. render_bounds.intersect(scissor_box_to_window_coordinates(options.scissor_box, render_target.rect()));
  170. int const block_padding = RASTERIZER_BLOCK_SIZE - 1;
  171. // clang-format off
  172. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x())) / RASTERIZER_BLOCK_SIZE;
  173. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x())) + block_padding) / RASTERIZER_BLOCK_SIZE;
  174. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y())) / RASTERIZER_BLOCK_SIZE;
  175. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y())) + block_padding) / RASTERIZER_BLOCK_SIZE;
  176. // clang-format on
  177. static_assert(RASTERIZER_BLOCK_SIZE < sizeof(int) * 8, "RASTERIZER_BLOCK_SIZE must be smaller than the pixel_mask's width in bits");
  178. int pixel_mask[RASTERIZER_BLOCK_SIZE];
  179. FloatVector4 pixel_buffer[RASTERIZER_BLOCK_SIZE][RASTERIZER_BLOCK_SIZE];
  180. // FIXME: implement stencil testing
  181. // Iterate over all blocks within the bounds of the triangle
  182. for (int by = by0; by < by1; by++) {
  183. for (int bx = bx0; bx < bx1; bx++) {
  184. // Edge values of the 4 block corners
  185. // clang-format off
  186. auto b0 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  187. auto b1 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  188. auto b2 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  189. auto b3 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  190. // clang-format on
  191. // If the whole block is outside any of the triangle edges we can discard it completely
  192. // We test this by and'ing the relevant edge function values together for all block corners
  193. // and checking if the negative sign bit is set for all of them
  194. if ((b0.x() & b1.x() & b2.x() & b3.x()) & 0x80000000)
  195. continue;
  196. if ((b0.y() & b1.y() & b2.y() & b3.y()) & 0x80000000)
  197. continue;
  198. if ((b0.z() & b1.z() & b2.z() & b3.z()) & 0x80000000)
  199. continue;
  200. // edge value derivatives
  201. auto dbdx = (b1 - b0) / RASTERIZER_BLOCK_SIZE;
  202. auto dbdy = (b2 - b0) / RASTERIZER_BLOCK_SIZE;
  203. // step edge value after each horizontal span: 1 down, BLOCK_SIZE left
  204. auto step_y = dbdy - dbdx * RASTERIZER_BLOCK_SIZE;
  205. int x0 = bx * RASTERIZER_BLOCK_SIZE;
  206. int y0 = by * RASTERIZER_BLOCK_SIZE;
  207. // Generate the coverage mask
  208. if (!options.scissor_enabled && test_point(b0) && test_point(b1) && test_point(b2) && test_point(b3)) {
  209. // The block is fully contained within the triangle. Fill the mask with all 1s
  210. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++)
  211. pixel_mask[y] = -1;
  212. } else {
  213. // The block overlaps at least one triangle edge.
  214. // We need to test coverage of every pixel within the block.
  215. auto coords = b0;
  216. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  217. pixel_mask[y] = 0;
  218. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx) {
  219. if (test_point(coords) && (!options.scissor_enabled || render_bounds.contains(x0 + x, y0 + y)))
  220. pixel_mask[y] |= 1 << x;
  221. }
  222. }
  223. }
  224. // AND the depth mask onto the coverage mask
  225. if (options.enable_depth_test) {
  226. int z_pass_count = 0;
  227. auto coords = b0;
  228. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  229. if (pixel_mask[y] == 0) {
  230. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  231. continue;
  232. }
  233. auto* depth = &depth_buffer.scanline(y0 + y)[x0];
  234. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, depth++) {
  235. if (~pixel_mask[y] & (1 << x))
  236. continue;
  237. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  238. float z = interpolate(triangle.vertices[0].position.z(), triangle.vertices[1].position.z(), triangle.vertices[2].position.z(), barycentric);
  239. z = options.depth_min + (options.depth_max - options.depth_min) * (z + 1) / 2;
  240. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  241. z += options.depth_offset_constant * NumericLimits<float>::epsilon();
  242. bool pass = false;
  243. switch (options.depth_func) {
  244. case GL_ALWAYS:
  245. pass = true;
  246. break;
  247. case GL_NEVER:
  248. pass = false;
  249. break;
  250. case GL_GREATER:
  251. pass = z > *depth;
  252. break;
  253. case GL_GEQUAL:
  254. pass = z >= *depth;
  255. break;
  256. case GL_NOTEQUAL:
  257. #ifdef __SSE__
  258. pass = z != *depth;
  259. #else
  260. pass = bit_cast<u32>(z) != bit_cast<u32>(*depth);
  261. #endif
  262. break;
  263. case GL_EQUAL:
  264. #ifdef __SSE__
  265. pass = z == *depth;
  266. #else
  267. //
  268. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  269. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  270. // it is an 80-bit x87 floating point number, however, when stored into the DepthBuffer, this is
  271. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  272. // used here the comparison fails.
  273. // This could be solved by using a `long double` for the depth buffer, however this would take
  274. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  275. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  276. // equal, we can pretty much guarantee that it's actually equal.
  277. //
  278. pass = bit_cast<u32>(z) == bit_cast<u32>(*depth);
  279. #endif
  280. break;
  281. case GL_LEQUAL:
  282. pass = z <= *depth;
  283. break;
  284. case GL_LESS:
  285. pass = z < *depth;
  286. break;
  287. }
  288. if (!pass) {
  289. pixel_mask[y] ^= 1 << x;
  290. continue;
  291. }
  292. if (options.enable_depth_write)
  293. *depth = z;
  294. z_pass_count++;
  295. }
  296. }
  297. // Nice, no pixels passed the depth test -> block rejected by early z
  298. if (z_pass_count == 0)
  299. continue;
  300. }
  301. // We will not update the color buffer at all
  302. if (!options.color_mask || options.draw_buffer == GL_NONE)
  303. continue;
  304. // Draw the pixels according to the previously generated mask
  305. auto coords = b0;
  306. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  307. if (pixel_mask[y] == 0) {
  308. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  309. continue;
  310. }
  311. auto* pixel = pixel_buffer[y];
  312. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, pixel++) {
  313. if (~pixel_mask[y] & (1 << x))
  314. continue;
  315. // Perspective correct barycentric coordinates
  316. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  317. float interpolated_reciprocal_w = interpolate(triangle.vertices[0].position.w(), triangle.vertices[1].position.w(), triangle.vertices[2].position.w(), barycentric);
  318. float interpolated_w = 1 / interpolated_reciprocal_w;
  319. barycentric = barycentric * FloatVector3(triangle.vertices[0].position.w(), triangle.vertices[1].position.w(), triangle.vertices[2].position.w()) * interpolated_w;
  320. // FIXME: make this more generic. We want to interpolate more than just color and uv
  321. FloatVector4 vertex_color;
  322. if (options.shade_smooth) {
  323. vertex_color = interpolate(
  324. triangle.vertices[0].color,
  325. triangle.vertices[1].color,
  326. triangle.vertices[2].color,
  327. barycentric);
  328. } else {
  329. vertex_color = triangle.vertices[0].color;
  330. }
  331. auto uv = interpolate(
  332. triangle.vertices[0].tex_coord,
  333. triangle.vertices[1].tex_coord,
  334. triangle.vertices[2].tex_coord,
  335. barycentric);
  336. // Calculate depth of fragment for fog
  337. float z = interpolate(triangle.vertices[0].position.z(), triangle.vertices[1].position.z(), triangle.vertices[2].position.z(), barycentric);
  338. z = options.depth_min + (options.depth_max - options.depth_min) * (z + 1) / 2;
  339. *pixel = pixel_shader(uv, vertex_color, z);
  340. }
  341. }
  342. if (options.enable_alpha_test && options.alpha_test_func != GL_ALWAYS) {
  343. // FIXME: I'm not sure if this is the right place to test this.
  344. // If we tested this right at the beginning of our rasterizer routine
  345. // we could skip a lot of work but the GL spec might disagree.
  346. if (options.alpha_test_func == GL_NEVER)
  347. continue;
  348. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  349. auto src = pixel_buffer[y];
  350. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++) {
  351. if (~pixel_mask[y] & (1 << x))
  352. continue;
  353. bool passed = true;
  354. switch (options.alpha_test_func) {
  355. case GL_LESS:
  356. passed = src->w() < options.alpha_test_ref_value;
  357. break;
  358. case GL_EQUAL:
  359. passed = src->w() == options.alpha_test_ref_value;
  360. break;
  361. case GL_LEQUAL:
  362. passed = src->w() <= options.alpha_test_ref_value;
  363. break;
  364. case GL_GREATER:
  365. passed = src->w() > options.alpha_test_ref_value;
  366. break;
  367. case GL_NOTEQUAL:
  368. passed = src->w() != options.alpha_test_ref_value;
  369. break;
  370. case GL_GEQUAL:
  371. passed = src->w() >= options.alpha_test_ref_value;
  372. break;
  373. }
  374. if (!passed)
  375. pixel_mask[y] ^= (1 << x);
  376. }
  377. }
  378. }
  379. if (options.enable_blending) {
  380. // Blend color values from pixel_buffer into render_target
  381. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  382. auto src = pixel_buffer[y];
  383. auto dst = &render_target.scanline(y + y0)[x0];
  384. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  385. if (~pixel_mask[y] & (1 << x))
  386. continue;
  387. auto float_dst = to_vec4(*dst);
  388. auto src_factor = src_constant
  389. + *src * src_factor_src_color
  390. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * src_factor_src_alpha
  391. + float_dst * src_factor_dst_color
  392. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * src_factor_dst_alpha;
  393. auto dst_factor = dst_constant
  394. + *src * dst_factor_src_color
  395. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * dst_factor_src_alpha
  396. + float_dst * dst_factor_dst_color
  397. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * dst_factor_dst_alpha;
  398. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src * src_factor + float_dst * dst_factor) & options.color_mask);
  399. }
  400. }
  401. } else {
  402. // Copy color values from pixel_buffer into render_target
  403. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  404. auto src = pixel_buffer[y];
  405. auto dst = &render_target.scanline(y + y0)[x0];
  406. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  407. if (~pixel_mask[y] & (1 << x))
  408. continue;
  409. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src) & options.color_mask);
  410. }
  411. }
  412. }
  413. }
  414. }
  415. }
  416. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  417. {
  418. int width = ((min_size.width() + step - 1) / step) * step;
  419. int height = ((min_size.height() + step - 1) / step) * step;
  420. return { width, height };
  421. }
  422. SoftwareRasterizer::SoftwareRasterizer(const Gfx::IntSize& min_size)
  423. : m_render_target { Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)).release_value_but_fixme_should_propagate_errors() }
  424. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, RASTERIZER_BLOCK_SIZE))) }
  425. {
  426. m_options.scissor_box = m_render_target->rect();
  427. }
  428. void SoftwareRasterizer::submit_triangle(const GLTriangle& triangle, const Array<TextureUnit, 32>& texture_units)
  429. {
  430. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [this, &texture_units](const FloatVector2& uv, const FloatVector4& color, float z) -> FloatVector4 {
  431. FloatVector4 fragment = color;
  432. for (const auto& texture_unit : texture_units) {
  433. // No texture is bound to this texture unit
  434. if (!texture_unit.is_bound())
  435. continue;
  436. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  437. FloatVector4 texel;
  438. switch (texture_unit.currently_bound_target()) {
  439. case GL_TEXTURE_2D:
  440. if (!texture_unit.texture_2d_enabled() || texture_unit.texture_3d_enabled() || texture_unit.texture_cube_map_enabled())
  441. continue;
  442. texel = texture_unit.bound_texture_2d()->sampler().sample(uv);
  443. break;
  444. default:
  445. VERIFY_NOT_REACHED();
  446. }
  447. // FIXME: Implement more blend modes
  448. switch (texture_unit.env_mode()) {
  449. case GL_MODULATE:
  450. default:
  451. fragment = fragment * texel;
  452. break;
  453. case GL_REPLACE:
  454. fragment = texel;
  455. break;
  456. case GL_DECAL: {
  457. float src_alpha = fragment.w();
  458. float one_minus_src_alpha = 1 - src_alpha;
  459. fragment.set_x(texel.x() * src_alpha + fragment.x() * one_minus_src_alpha);
  460. fragment.set_y(texel.y() * src_alpha + fragment.y() * one_minus_src_alpha);
  461. fragment.set_z(texel.z() * src_alpha + fragment.z() * one_minus_src_alpha);
  462. break;
  463. }
  464. }
  465. }
  466. // Calculate fog
  467. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  468. if (m_options.fog_enabled) {
  469. float factor = 0.0f;
  470. switch (m_options.fog_mode) {
  471. case GL_LINEAR:
  472. factor = (m_options.fog_end - z) / (m_options.fog_end - m_options.fog_start);
  473. break;
  474. case GL_EXP:
  475. factor = exp(-((m_options.fog_density * z)));
  476. break;
  477. case GL_EXP2:
  478. factor = exp(-((m_options.fog_density * z) * (m_options.fog_density * z)));
  479. break;
  480. default:
  481. break;
  482. }
  483. // Mix texel with fog
  484. fragment = mix(m_options.fog_color, fragment, factor);
  485. }
  486. return fragment;
  487. });
  488. }
  489. void SoftwareRasterizer::resize(const Gfx::IntSize& min_size)
  490. {
  491. wait_for_all_threads();
  492. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)).release_value_but_fixme_should_propagate_errors();
  493. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  494. }
  495. void SoftwareRasterizer::clear_color(const FloatVector4& color)
  496. {
  497. wait_for_all_threads();
  498. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  499. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  500. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  501. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  502. auto const fill_color = Gfx::Color(r, g, b, a);
  503. if (m_options.scissor_enabled) {
  504. auto fill_rect = m_render_target->rect();
  505. fill_rect.intersect(scissor_box_to_window_coordinates(m_options.scissor_box, fill_rect));
  506. Gfx::Painter painter { *m_render_target };
  507. painter.fill_rect(fill_rect, fill_color);
  508. return;
  509. }
  510. m_render_target->fill(fill_color);
  511. }
  512. void SoftwareRasterizer::clear_depth(float depth)
  513. {
  514. wait_for_all_threads();
  515. if (m_options.scissor_enabled) {
  516. m_depth_buffer->clear(scissor_box_to_window_coordinates(m_options.scissor_box, m_render_target->rect()), depth);
  517. return;
  518. }
  519. m_depth_buffer->clear(depth);
  520. }
  521. void SoftwareRasterizer::blit_to(Gfx::Bitmap& target)
  522. {
  523. wait_for_all_threads();
  524. Gfx::Painter painter { target };
  525. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  526. }
  527. void SoftwareRasterizer::wait_for_all_threads() const
  528. {
  529. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  530. }
  531. void SoftwareRasterizer::set_options(const RasterizerOptions& options)
  532. {
  533. wait_for_all_threads();
  534. m_options = options;
  535. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  536. }
  537. Gfx::RGBA32 SoftwareRasterizer::get_backbuffer_pixel(int x, int y)
  538. {
  539. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  540. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  541. return 0;
  542. return m_render_target->scanline(y)[x];
  543. }
  544. float SoftwareRasterizer::get_depthbuffer_value(int x, int y)
  545. {
  546. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  547. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  548. return 1.0f;
  549. return m_depth_buffer->scanline(y)[x];
  550. }
  551. }