Device.cpp 34 KB

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