SoftwareRasterizer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SoftwareRasterizer.h"
  7. #include <AK/Function.h>
  8. #include <LibGfx/Painter.h>
  9. namespace GL {
  10. static constexpr size_t RASTERIZER_BLOCK_SIZE = 16;
  11. struct FloatVector2 {
  12. float x;
  13. float y;
  14. };
  15. constexpr static float triangle_area(const FloatVector2& a, const FloatVector2& b, const FloatVector2& c)
  16. {
  17. return ((c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x)) / 2;
  18. }
  19. template<typename T>
  20. constexpr static T interpolate(const T& v0, const T& v1, const T& v2, const FloatVector4& barycentric_coords)
  21. {
  22. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  23. }
  24. static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  25. {
  26. auto clamped = v.clamped(0, 1);
  27. u8 r = clamped.x() * 255;
  28. u8 g = clamped.y() * 255;
  29. u8 b = clamped.z() * 255;
  30. u8 a = clamped.w() * 255;
  31. return a << 24 | b << 16 | g << 8 | r;
  32. }
  33. template<typename PS>
  34. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const GLTriangle& triangle, PS pixel_shader)
  35. {
  36. // Since the algorithm is based on blocks of uniform size, we need
  37. // to ensure that our render_target size is actually a multiple of the block size
  38. VERIFY((render_target.width() % RASTERIZER_BLOCK_SIZE) == 0);
  39. VERIFY((render_target.height() % RASTERIZER_BLOCK_SIZE) == 0);
  40. // Calculate area of the triangle for later tests
  41. FloatVector2 v0 = { triangle.vertices[0].x, triangle.vertices[0].y };
  42. FloatVector2 v1 = { triangle.vertices[1].x, triangle.vertices[1].y };
  43. FloatVector2 v2 = { triangle.vertices[2].x, triangle.vertices[2].y };
  44. float area = triangle_area(v0, v1, v2);
  45. if (area == 0)
  46. return;
  47. float one_over_area = 1 / area;
  48. // Obey top-left rule:
  49. // This sets up "zero" for later pixel coverage tests.
  50. // Depending on where on the triangle the edge is located
  51. // it is either tested against 0 or float epsilon, effectively
  52. // turning "< 0" into "<= 0"
  53. float constexpr epsilon = AK::NumericLimits<float>::epsilon();
  54. FloatVector4 zero { epsilon, epsilon, epsilon, 0.0f };
  55. if (v1.y > v0.y || (v1.y == v0.y && v1.x < v0.x))
  56. zero.set_z(0);
  57. if (v2.y > v1.y || (v2.y == v1.y && v2.x < v1.x))
  58. zero.set_x(0);
  59. if (v0.y > v2.y || (v0.y == v2.y && v0.x < v2.x))
  60. zero.set_y(0);
  61. // This function calculates the barycentric coordinates for the pixel relative to the triangle.
  62. auto barycentric_coordinates = [v0, v1, v2, one_over_area](float x, float y) -> FloatVector4 {
  63. FloatVector2 p { x, y };
  64. return {
  65. triangle_area(v1, v2, p) * one_over_area,
  66. triangle_area(v2, v0, p) * one_over_area,
  67. triangle_area(v0, v1, p) * one_over_area,
  68. 0.0f
  69. };
  70. };
  71. // This function tests whether a point lies within the triangle
  72. auto test_point = [zero](const FloatVector4& point) -> bool {
  73. return point.x() >= zero.x()
  74. && point.y() >= zero.y()
  75. && point.z() >= zero.z();
  76. };
  77. // Calculate bounds
  78. FloatVector2 min { AK::min(v0.x, AK::min(v1.x, v2.x)), AK::min(v0.y, AK::min(v1.y, v2.y)) };
  79. FloatVector2 max { AK::max(v0.x, AK::max(v1.x, v2.x)), AK::max(v0.y, AK::max(v1.y, v2.y)) };
  80. // Calculate block-based bounds
  81. int iminx = floorf(min.x);
  82. int iminy = floorf(min.y);
  83. int imaxx = ceilf(max.x);
  84. int imaxy = ceilf(max.y);
  85. iminx = clamp(iminx, 0, render_target.width() - 1);
  86. imaxx = clamp(imaxx, 0, render_target.width() - 1);
  87. iminy = clamp(iminy, 0, render_target.height() - 1);
  88. imaxy = clamp(imaxy, 0, render_target.height() - 1);
  89. int bx0 = iminx / RASTERIZER_BLOCK_SIZE;
  90. int bx1 = imaxx / RASTERIZER_BLOCK_SIZE + 1;
  91. int by0 = iminy / RASTERIZER_BLOCK_SIZE;
  92. int by1 = imaxy / RASTERIZER_BLOCK_SIZE + 1;
  93. // Iterate over all blocks within the bounds of the triangle
  94. for (int by = by0; by < by1; by++) {
  95. for (int bx = bx0; bx < bx1; bx++) {
  96. // The 4 block corners
  97. int x0 = bx * RASTERIZER_BLOCK_SIZE;
  98. int y0 = by * RASTERIZER_BLOCK_SIZE;
  99. int x1 = bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE;
  100. int y1 = by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE;
  101. // Barycentric coordinates of the 4 block corners
  102. auto a = barycentric_coordinates(x0, y0);
  103. auto b = barycentric_coordinates(x1, y0);
  104. auto c = barycentric_coordinates(x0, y1);
  105. auto d = barycentric_coordinates(x1, y1);
  106. // If the whole block is outside any of the triangle edges we can discard it completely
  107. if ((a.x() < zero.x() && b.x() < zero.x() && c.x() < zero.x() && d.x() < zero.x())
  108. || (a.y() < zero.y() && b.y() < zero.y() && c.y() < zero.y() && d.y() < zero.y())
  109. || (a.z() < zero.z() && b.z() < zero.z() && c.z() < zero.z() && d.z() < zero.z()))
  110. continue;
  111. // barycentric coordinate derivatives
  112. auto dcdx = (b - a) / RASTERIZER_BLOCK_SIZE;
  113. auto dcdy = (c - a) / RASTERIZER_BLOCK_SIZE;
  114. if (test_point(a) && test_point(b) && test_point(c) && test_point(d)) {
  115. // The block is fully contained within the triangle
  116. // Fill the block without further coverage tests
  117. for (int y = y0; y < y1; y++) {
  118. auto coords = a;
  119. auto* pixel = &render_target.scanline(y)[x0];
  120. auto* depth = &depth_buffer.scanline(y)[x0];
  121. for (int x = x0; x < x1; x++) {
  122. if (options.enable_depth_test) {
  123. float z = interpolate(triangle.vertices[0].z, triangle.vertices[1].z, triangle.vertices[2].z, coords);
  124. if (z < *depth) {
  125. *pixel = to_rgba32(pixel_shader(coords, triangle));
  126. *depth = z;
  127. }
  128. } else {
  129. *pixel = to_rgba32(pixel_shader(coords, triangle));
  130. }
  131. pixel++;
  132. depth++;
  133. coords = coords + dcdx;
  134. }
  135. a = a + dcdy;
  136. }
  137. } else {
  138. // The block overlaps at least one triangle edge
  139. // We need to test coverage of every pixel within the block
  140. for (int y = y0; y < y1; y++) {
  141. auto coords = a;
  142. auto* pixel = &render_target.scanline(y)[x0];
  143. auto* depth = &depth_buffer.scanline(y)[x0];
  144. for (int x = x0; x < x1; x++) {
  145. if (test_point(coords)) {
  146. if (options.enable_depth_test) {
  147. float z = interpolate(triangle.vertices[0].z, triangle.vertices[1].z, triangle.vertices[2].z, coords);
  148. if (z < *depth) {
  149. *pixel = to_rgba32(pixel_shader(coords, triangle));
  150. *depth = z;
  151. }
  152. } else {
  153. *pixel = to_rgba32(pixel_shader(coords, triangle));
  154. }
  155. }
  156. pixel++;
  157. depth++;
  158. coords = coords + dcdx;
  159. }
  160. a = a + dcdy;
  161. }
  162. }
  163. }
  164. }
  165. }
  166. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  167. {
  168. int width = ((min_size.width() + step - 1) / step) * step;
  169. int height = ((min_size.height() + step - 1) / step) * step;
  170. return { width, height };
  171. }
  172. SoftwareRasterizer::SoftwareRasterizer(const Gfx::IntSize& min_size)
  173. : m_render_target { Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)) }
  174. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, RASTERIZER_BLOCK_SIZE))) }
  175. {
  176. }
  177. void SoftwareRasterizer::submit_triangle(const GLTriangle& triangle)
  178. {
  179. if (m_options.shade_smooth) {
  180. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [](const FloatVector4& v, const GLTriangle& t) -> FloatVector4 {
  181. const float r = t.vertices[0].r * v.x() + t.vertices[1].r * v.y() + t.vertices[2].r * v.z();
  182. const float g = t.vertices[0].g * v.x() + t.vertices[1].g * v.y() + t.vertices[2].g * v.z();
  183. const float b = t.vertices[0].b * v.x() + t.vertices[1].b * v.y() + t.vertices[2].b * v.z();
  184. const float a = t.vertices[0].a * v.x() + t.vertices[1].a * v.y() + t.vertices[2].a * v.z();
  185. return { r, g, b, a };
  186. });
  187. } else {
  188. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [](const FloatVector4&, const GLTriangle& t) -> FloatVector4 {
  189. return { t.vertices[0].r, t.vertices[0].g, t.vertices[0].b, t.vertices[0].a };
  190. });
  191. }
  192. }
  193. void SoftwareRasterizer::resize(const Gfx::IntSize& min_size)
  194. {
  195. wait_for_all_threads();
  196. m_render_target = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE));
  197. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  198. }
  199. void SoftwareRasterizer::clear_color(const FloatVector4& color)
  200. {
  201. wait_for_all_threads();
  202. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  203. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  204. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  205. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  206. m_render_target->fill(Gfx::Color(r, g, b, a));
  207. }
  208. void SoftwareRasterizer::clear_depth(float depth)
  209. {
  210. wait_for_all_threads();
  211. m_depth_buffer->clear(depth);
  212. }
  213. void SoftwareRasterizer::blit_to(Gfx::Bitmap& target)
  214. {
  215. wait_for_all_threads();
  216. Gfx::Painter painter { target };
  217. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  218. }
  219. void SoftwareRasterizer::wait_for_all_threads() const
  220. {
  221. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  222. }
  223. void SoftwareRasterizer::set_options(const RasterizerOptions& options)
  224. {
  225. wait_for_all_threads();
  226. m_options = options;
  227. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  228. }
  229. }