Device.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  4. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Function.h>
  9. #include <AK/Math.h>
  10. #include <AK/NumericLimits.h>
  11. #include <AK/SIMDExtras.h>
  12. #include <AK/SIMDMath.h>
  13. #include <LibCore/ElapsedTimer.h>
  14. #include <LibGfx/Painter.h>
  15. #include <LibGfx/Vector2.h>
  16. #include <LibGfx/Vector3.h>
  17. #include <LibSoftGPU/Config.h>
  18. #include <LibSoftGPU/Device.h>
  19. #include <LibSoftGPU/PixelQuad.h>
  20. #include <LibSoftGPU/SIMD.h>
  21. namespace SoftGPU {
  22. static long long g_num_rasterized_triangles;
  23. static long long g_num_pixels;
  24. static long long g_num_pixels_shaded;
  25. static long long g_num_pixels_blended;
  26. static long long g_num_sampler_calls;
  27. static long long g_num_stencil_writes;
  28. static long long g_num_quads;
  29. using IntVector2 = Gfx::Vector2<int>;
  30. using IntVector3 = Gfx::Vector3<int>;
  31. using AK::SIMD::any;
  32. using AK::SIMD::exp;
  33. using AK::SIMD::expand4;
  34. using AK::SIMD::f32x4;
  35. using AK::SIMD::i32x4;
  36. using AK::SIMD::load4_masked;
  37. using AK::SIMD::maskbits;
  38. using AK::SIMD::maskcount;
  39. using AK::SIMD::none;
  40. using AK::SIMD::store4_masked;
  41. using AK::SIMD::to_f32x4;
  42. using AK::SIMD::to_u32x4;
  43. using AK::SIMD::u32x4;
  44. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  45. {
  46. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  47. }
  48. constexpr static i32x4 edge_function4(const IntVector2& a, const IntVector2& b, const Vector2<i32x4>& c)
  49. {
  50. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  51. }
  52. template<typename T, typename U>
  53. constexpr static auto interpolate(const T& v0, const T& v1, const T& v2, const Vector3<U>& barycentric_coords)
  54. {
  55. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  56. }
  57. ALWAYS_INLINE static u32x4 to_rgba32(const Vector4<f32x4>& v)
  58. {
  59. auto clamped = v.clamped(expand4(0.0f), expand4(1.0f));
  60. auto r = to_u32x4(clamped.x() * 255);
  61. auto g = to_u32x4(clamped.y() * 255);
  62. auto b = to_u32x4(clamped.z() * 255);
  63. auto a = to_u32x4(clamped.w() * 255);
  64. return a << 24 | r << 16 | g << 8 | b;
  65. }
  66. static Vector4<f32x4> to_vec4(u32x4 rgba)
  67. {
  68. auto constexpr one_over_255 = expand4(1.0f / 255);
  69. return {
  70. to_f32x4((rgba >> 16) & 0xff) * one_over_255,
  71. to_f32x4((rgba >> 8) & 0xff) * one_over_255,
  72. to_f32x4(rgba & 0xff) * one_over_255,
  73. to_f32x4((rgba >> 24) & 0xff) * one_over_255,
  74. };
  75. }
  76. Gfx::IntRect Device::window_coordinates_to_target_coordinates(Gfx::IntRect const& window_rect)
  77. {
  78. return {
  79. window_rect.x(),
  80. m_render_target->rect().height() - window_rect.height() - window_rect.y(),
  81. window_rect.width(),
  82. window_rect.height(),
  83. };
  84. }
  85. void Device::setup_blend_factors()
  86. {
  87. m_alpha_blend_factors.src_constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  88. m_alpha_blend_factors.src_factor_src_alpha = 0;
  89. m_alpha_blend_factors.src_factor_dst_alpha = 0;
  90. m_alpha_blend_factors.src_factor_src_color = 0;
  91. m_alpha_blend_factors.src_factor_dst_color = 0;
  92. switch (m_options.blend_source_factor) {
  93. case BlendFactor::Zero:
  94. break;
  95. case BlendFactor::One:
  96. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  97. break;
  98. case BlendFactor::SrcColor:
  99. m_alpha_blend_factors.src_factor_src_color = 1;
  100. break;
  101. case BlendFactor::OneMinusSrcColor:
  102. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  103. m_alpha_blend_factors.src_factor_src_color = -1;
  104. break;
  105. case BlendFactor::SrcAlpha:
  106. m_alpha_blend_factors.src_factor_src_alpha = 1;
  107. break;
  108. case BlendFactor::OneMinusSrcAlpha:
  109. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  110. m_alpha_blend_factors.src_factor_src_alpha = -1;
  111. break;
  112. case BlendFactor::DstAlpha:
  113. m_alpha_blend_factors.src_factor_dst_alpha = 1;
  114. break;
  115. case BlendFactor::OneMinusDstAlpha:
  116. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  117. m_alpha_blend_factors.src_factor_dst_alpha = -1;
  118. break;
  119. case BlendFactor::DstColor:
  120. m_alpha_blend_factors.src_factor_dst_color = 1;
  121. break;
  122. case BlendFactor::OneMinusDstColor:
  123. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  124. m_alpha_blend_factors.src_factor_dst_color = -1;
  125. break;
  126. case BlendFactor::SrcAlphaSaturate:
  127. default:
  128. VERIFY_NOT_REACHED();
  129. }
  130. m_alpha_blend_factors.dst_constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  131. m_alpha_blend_factors.dst_factor_src_alpha = 0;
  132. m_alpha_blend_factors.dst_factor_dst_alpha = 0;
  133. m_alpha_blend_factors.dst_factor_src_color = 0;
  134. m_alpha_blend_factors.dst_factor_dst_color = 0;
  135. switch (m_options.blend_destination_factor) {
  136. case BlendFactor::Zero:
  137. break;
  138. case BlendFactor::One:
  139. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  140. break;
  141. case BlendFactor::SrcColor:
  142. m_alpha_blend_factors.dst_factor_src_color = 1;
  143. break;
  144. case BlendFactor::OneMinusSrcColor:
  145. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  146. m_alpha_blend_factors.dst_factor_src_color = -1;
  147. break;
  148. case BlendFactor::SrcAlpha:
  149. m_alpha_blend_factors.dst_factor_src_alpha = 1;
  150. break;
  151. case BlendFactor::OneMinusSrcAlpha:
  152. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  153. m_alpha_blend_factors.dst_factor_src_alpha = -1;
  154. break;
  155. case BlendFactor::DstAlpha:
  156. m_alpha_blend_factors.dst_factor_dst_alpha = 1;
  157. break;
  158. case BlendFactor::OneMinusDstAlpha:
  159. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  160. m_alpha_blend_factors.dst_factor_dst_alpha = -1;
  161. break;
  162. case BlendFactor::DstColor:
  163. m_alpha_blend_factors.dst_factor_dst_color = 1;
  164. break;
  165. case BlendFactor::OneMinusDstColor:
  166. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  167. m_alpha_blend_factors.dst_factor_dst_color = -1;
  168. break;
  169. case BlendFactor::SrcAlphaSaturate:
  170. default:
  171. VERIFY_NOT_REACHED();
  172. }
  173. }
  174. void Device::rasterize_triangle(const Triangle& triangle)
  175. {
  176. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  177. // Return if alpha testing is a no-op
  178. if (m_options.enable_alpha_test && m_options.alpha_test_func == AlphaTestFunction::Never)
  179. return;
  180. // Vertices
  181. Vertex const vertex0 = triangle.vertices[0];
  182. Vertex const vertex1 = triangle.vertices[1];
  183. Vertex const vertex2 = triangle.vertices[2];
  184. constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  185. // Calculate area of the triangle for later tests
  186. IntVector2 const v0 { static_cast<int>(vertex0.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex0.window_coordinates.y() * subpixel_factor) };
  187. IntVector2 const v1 { static_cast<int>(vertex1.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex1.window_coordinates.y() * subpixel_factor) };
  188. IntVector2 const v2 { static_cast<int>(vertex2.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex2.window_coordinates.y() * subpixel_factor) };
  189. int area = edge_function(v0, v1, v2);
  190. if (area == 0)
  191. return;
  192. auto const one_over_area = 1.0f / area;
  193. auto render_bounds = m_render_target->rect();
  194. if (m_options.scissor_enabled)
  195. render_bounds.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  196. // Obey top-left rule:
  197. // This sets up "zero" for later pixel coverage tests.
  198. // Depending on where on the triangle the edge is located
  199. // it is either tested against 0 or 1, effectively
  200. // turning "< 0" into "<= 0"
  201. IntVector3 zero { 1, 1, 1 };
  202. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  203. zero.set_z(0);
  204. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  205. zero.set_x(0);
  206. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  207. zero.set_y(0);
  208. // This function calculates the 3 edge values for the pixel relative to the triangle.
  209. auto calculate_edge_values4 = [v0, v1, v2](Vector2<i32x4> const& p) -> Vector3<i32x4> {
  210. return {
  211. edge_function4(v1, v2, p),
  212. edge_function4(v2, v0, p),
  213. edge_function4(v0, v1, p),
  214. };
  215. };
  216. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  217. auto test_point4 = [zero](Vector3<i32x4> const& edges) -> i32x4 {
  218. return edges.x() >= zero.x()
  219. && edges.y() >= zero.y()
  220. && edges.z() >= zero.z();
  221. };
  222. // Calculate block-based bounds
  223. // clang-format off
  224. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1;
  225. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1) + 2;
  226. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1;
  227. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1) + 2;
  228. // clang-format on
  229. // Fog depths
  230. float const vertex0_eye_absz = fabs(vertex0.eye_coordinates.z());
  231. float const vertex1_eye_absz = fabs(vertex1.eye_coordinates.z());
  232. float const vertex2_eye_absz = fabs(vertex2.eye_coordinates.z());
  233. int const render_bounds_left = render_bounds.x();
  234. int const render_bounds_right = render_bounds.x() + render_bounds.width();
  235. int const render_bounds_top = render_bounds.y();
  236. int const render_bounds_bottom = render_bounds.y() + render_bounds.height();
  237. auto const half_pixel_offset = Vector2<i32x4> {
  238. expand4(subpixel_factor / 2),
  239. expand4(subpixel_factor / 2),
  240. };
  241. // Stencil configuration and writing
  242. auto const stencil_configuration = m_stencil_configuration[Face::Front];
  243. auto const stencil_reference_value = stencil_configuration.reference_value & stencil_configuration.test_mask;
  244. auto write_to_stencil = [](u8* stencil_ptrs[4], i32x4 stencil_value, StencilOperation op, u8 reference_value, u8 write_mask, i32x4 pixel_mask) {
  245. if (write_mask == 0 || op == StencilOperation::Keep)
  246. return;
  247. switch (op) {
  248. case StencilOperation::Decrement:
  249. stencil_value = (stencil_value & ~write_mask) | (max(stencil_value - 1, expand4(0)) & write_mask);
  250. break;
  251. case StencilOperation::DecrementWrap:
  252. stencil_value = (stencil_value & ~write_mask) | (((stencil_value - 1) & 0xFF) & write_mask);
  253. break;
  254. case StencilOperation::Increment:
  255. stencil_value = (stencil_value & ~write_mask) | (min(stencil_value + 1, expand4(0xFF)) & write_mask);
  256. break;
  257. case StencilOperation::IncrementWrap:
  258. stencil_value = (stencil_value & ~write_mask) | (((stencil_value + 1) & 0xFF) & write_mask);
  259. break;
  260. case StencilOperation::Invert:
  261. stencil_value ^= write_mask;
  262. break;
  263. case StencilOperation::Replace:
  264. stencil_value = (stencil_value & ~write_mask) | (reference_value & write_mask);
  265. break;
  266. case StencilOperation::Zero:
  267. stencil_value &= ~write_mask;
  268. break;
  269. default:
  270. VERIFY_NOT_REACHED();
  271. }
  272. INCREASE_STATISTICS_COUNTER(g_num_stencil_writes, maskcount(pixel_mask));
  273. store4_masked(stencil_value, stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], pixel_mask);
  274. };
  275. // Iterate over all blocks within the bounds of the triangle
  276. for (int by = by0; by < by1; by += 2) {
  277. for (int bx = bx0; bx < bx1; bx += 2) {
  278. PixelQuad quad;
  279. quad.screen_coordinates = {
  280. i32x4 { bx, bx + 1, bx, bx + 1 },
  281. i32x4 { by, by, by + 1, by + 1 },
  282. };
  283. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor + half_pixel_offset);
  284. // Generate triangle coverage mask
  285. quad.mask = test_point4(edge_values);
  286. // Test quad against intersection of render target size and scissor rect
  287. quad.mask &= quad.screen_coordinates.x() >= render_bounds_left
  288. && quad.screen_coordinates.x() < render_bounds_right
  289. && quad.screen_coordinates.y() >= render_bounds_top
  290. && quad.screen_coordinates.y() < render_bounds_bottom;
  291. if (none(quad.mask))
  292. continue;
  293. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  294. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  295. // Calculate barycentric coordinates from previously calculated edge values
  296. quad.barycentrics = Vector3<f32x4> {
  297. to_f32x4(edge_values.x()),
  298. to_f32x4(edge_values.y()),
  299. to_f32x4(edge_values.z()),
  300. } * one_over_area;
  301. int coverage_bits = maskbits(quad.mask);
  302. // Stencil testing
  303. u8* stencil_ptrs[4];
  304. i32x4 stencil_value;
  305. if (m_options.enable_stencil_test) {
  306. stencil_ptrs[0] = coverage_bits & 1 ? &m_stencil_buffer->scanline(by)[bx] : nullptr;
  307. stencil_ptrs[1] = coverage_bits & 2 ? &m_stencil_buffer->scanline(by)[bx + 1] : nullptr;
  308. stencil_ptrs[2] = coverage_bits & 4 ? &m_stencil_buffer->scanline(by + 1)[bx] : nullptr;
  309. stencil_ptrs[3] = coverage_bits & 8 ? &m_stencil_buffer->scanline(by + 1)[bx + 1] : nullptr;
  310. stencil_value = load4_masked(stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], quad.mask);
  311. stencil_value &= stencil_configuration.test_mask;
  312. i32x4 stencil_test_passed;
  313. switch (stencil_configuration.test_function) {
  314. case StencilTestFunction::Always:
  315. stencil_test_passed = expand4(~0);
  316. break;
  317. case StencilTestFunction::Equal:
  318. stencil_test_passed = stencil_value == stencil_reference_value;
  319. break;
  320. case StencilTestFunction::Greater:
  321. stencil_test_passed = stencil_value > stencil_reference_value;
  322. break;
  323. case StencilTestFunction::GreaterOrEqual:
  324. stencil_test_passed = stencil_value >= stencil_reference_value;
  325. break;
  326. case StencilTestFunction::Less:
  327. stencil_test_passed = stencil_value < stencil_reference_value;
  328. break;
  329. case StencilTestFunction::LessOrEqual:
  330. stencil_test_passed = stencil_value <= stencil_reference_value;
  331. break;
  332. case StencilTestFunction::Never:
  333. stencil_test_passed = expand4(0);
  334. break;
  335. case StencilTestFunction::NotEqual:
  336. stencil_test_passed = stencil_value != stencil_reference_value;
  337. break;
  338. default:
  339. VERIFY_NOT_REACHED();
  340. }
  341. // Update stencil buffer for pixels that failed the stencil test
  342. write_to_stencil(
  343. stencil_ptrs,
  344. stencil_value,
  345. stencil_configuration.on_stencil_test_fail,
  346. stencil_reference_value,
  347. stencil_configuration.write_mask,
  348. quad.mask & ~stencil_test_passed);
  349. // Update coverage mask + early quad rejection
  350. quad.mask &= stencil_test_passed;
  351. if (none(quad.mask))
  352. continue;
  353. }
  354. // Depth testing
  355. float* depth_ptrs[4] = {
  356. coverage_bits & 1 ? &m_depth_buffer->scanline(by)[bx] : nullptr,
  357. coverage_bits & 2 ? &m_depth_buffer->scanline(by)[bx + 1] : nullptr,
  358. coverage_bits & 4 ? &m_depth_buffer->scanline(by + 1)[bx] : nullptr,
  359. coverage_bits & 8 ? &m_depth_buffer->scanline(by + 1)[bx + 1] : nullptr,
  360. };
  361. if (m_options.enable_depth_test) {
  362. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  363. quad.depth = interpolate(vertex0.window_coordinates.z(), vertex1.window_coordinates.z(), vertex2.window_coordinates.z(), quad.barycentrics);
  364. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  365. if (m_options.depth_offset_enabled)
  366. quad.depth += m_options.depth_offset_constant * NumericLimits<float>::epsilon();
  367. i32x4 depth_test_passed;
  368. switch (m_options.depth_func) {
  369. case DepthTestFunction::Always:
  370. depth_test_passed = expand4(~0);
  371. break;
  372. case DepthTestFunction::Never:
  373. depth_test_passed = expand4(0);
  374. break;
  375. case DepthTestFunction::Greater:
  376. depth_test_passed = quad.depth > depth;
  377. break;
  378. case DepthTestFunction::GreaterOrEqual:
  379. depth_test_passed = quad.depth >= depth;
  380. break;
  381. case DepthTestFunction::NotEqual:
  382. #ifdef __SSE__
  383. depth_test_passed = quad.depth != depth;
  384. #else
  385. depth_test_passed = i32x4 {
  386. bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0,
  387. bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0,
  388. bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0,
  389. bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0,
  390. };
  391. #endif
  392. break;
  393. case DepthTestFunction::Equal:
  394. #ifdef __SSE__
  395. depth_test_passed = quad.depth == depth;
  396. #else
  397. //
  398. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  399. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  400. // it is an 80-bit x87 floating point number, however, when stored into the DepthBuffer, this is
  401. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  402. // used here the comparison fails.
  403. // This could be solved by using a `long double` for the depth buffer, however this would take
  404. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  405. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  406. // equal, we can pretty much guarantee that it's actually equal.
  407. //
  408. depth_test_passed = i32x4 {
  409. bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0,
  410. bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0,
  411. bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0,
  412. bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0,
  413. };
  414. #endif
  415. break;
  416. case DepthTestFunction::LessOrEqual:
  417. depth_test_passed = quad.depth <= depth;
  418. break;
  419. case DepthTestFunction::Less:
  420. depth_test_passed = quad.depth < depth;
  421. break;
  422. default:
  423. VERIFY_NOT_REACHED();
  424. }
  425. // Update stencil buffer for pixels that failed the depth test
  426. if (m_options.enable_stencil_test) {
  427. write_to_stencil(
  428. stencil_ptrs,
  429. stencil_value,
  430. stencil_configuration.on_depth_test_fail,
  431. stencil_reference_value,
  432. stencil_configuration.write_mask,
  433. quad.mask & ~depth_test_passed);
  434. }
  435. // Update coverage mask + early quad rejection
  436. quad.mask &= depth_test_passed;
  437. if (none(quad.mask))
  438. continue;
  439. }
  440. // Update stencil buffer for passed pixels
  441. if (m_options.enable_stencil_test) {
  442. write_to_stencil(
  443. stencil_ptrs,
  444. stencil_value,
  445. stencil_configuration.on_pass,
  446. stencil_reference_value,
  447. stencil_configuration.write_mask,
  448. quad.mask);
  449. }
  450. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  451. // Draw the pixels according to the previously generated mask
  452. auto const w_coordinates = Vector3<f32x4> {
  453. expand4(vertex0.window_coordinates.w()),
  454. expand4(vertex1.window_coordinates.w()),
  455. expand4(vertex2.window_coordinates.w()),
  456. };
  457. auto const interpolated_reciprocal_w = interpolate(w_coordinates.x(), w_coordinates.y(), w_coordinates.z(), quad.barycentrics);
  458. auto const interpolated_w = 1.0f / interpolated_reciprocal_w;
  459. quad.barycentrics = quad.barycentrics * w_coordinates * interpolated_w;
  460. // FIXME: make this more generic. We want to interpolate more than just color and uv
  461. if (m_options.shade_smooth) {
  462. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  463. } else {
  464. quad.vertex_color = expand4(vertex0.color);
  465. }
  466. for (size_t i = 0; i < NUM_SAMPLERS; ++i)
  467. quad.texture_coordinates[i] = interpolate(expand4(vertex0.tex_coords[i]), expand4(vertex1.tex_coords[i]), expand4(vertex2.tex_coords[i]), quad.barycentrics);
  468. if (m_options.fog_enabled) {
  469. // Calculate depth of fragment for fog
  470. //
  471. // OpenGL 1.5 spec chapter 3.10: "An implementation may choose to approximate the
  472. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  473. quad.fog_depth = interpolate(expand4(vertex0_eye_absz), expand4(vertex1_eye_absz), expand4(vertex2_eye_absz), quad.barycentrics);
  474. }
  475. shade_fragments(quad);
  476. if (m_options.enable_alpha_test && m_options.alpha_test_func != AlphaTestFunction::Always && !test_alpha(quad)) {
  477. continue;
  478. }
  479. // Write to depth buffer
  480. if (m_options.enable_depth_test && m_options.enable_depth_write)
  481. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  482. // We will not update the color buffer at all
  483. if (!m_options.color_mask || !m_options.enable_color_write)
  484. continue;
  485. Gfx::RGBA32* color_ptrs[4] = {
  486. coverage_bits & 1 ? &m_render_target->scanline(by)[bx] : nullptr,
  487. coverage_bits & 2 ? &m_render_target->scanline(by)[bx + 1] : nullptr,
  488. coverage_bits & 4 ? &m_render_target->scanline(by + 1)[bx] : nullptr,
  489. coverage_bits & 8 ? &m_render_target->scanline(by + 1)[bx + 1] : nullptr,
  490. };
  491. u32x4 dst_u32;
  492. if (m_options.enable_blending || m_options.color_mask != 0xffffffff)
  493. dst_u32 = load4_masked(color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  494. if (m_options.enable_blending) {
  495. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  496. // Blend color values from pixel_staging into m_render_target
  497. Vector4<f32x4> const& src = quad.out_color;
  498. auto dst = to_vec4(dst_u32);
  499. auto src_factor = expand4(m_alpha_blend_factors.src_constant)
  500. + src * m_alpha_blend_factors.src_factor_src_color
  501. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.src_factor_src_alpha
  502. + dst * m_alpha_blend_factors.src_factor_dst_color
  503. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.src_factor_dst_alpha;
  504. auto dst_factor = expand4(m_alpha_blend_factors.dst_constant)
  505. + src * m_alpha_blend_factors.dst_factor_src_color
  506. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.dst_factor_src_alpha
  507. + dst * m_alpha_blend_factors.dst_factor_dst_color
  508. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.dst_factor_dst_alpha;
  509. quad.out_color = src * src_factor + dst * dst_factor;
  510. }
  511. if (m_options.color_mask == 0xffffffff)
  512. store4_masked(to_rgba32(quad.out_color), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  513. else
  514. store4_masked((to_rgba32(quad.out_color) & m_options.color_mask) | (dst_u32 & ~m_options.color_mask), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  515. }
  516. }
  517. }
  518. Device::Device(const Gfx::IntSize& size)
  519. : m_render_target(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, size).release_value_but_fixme_should_propagate_errors())
  520. , m_depth_buffer(make<DepthBuffer>(size))
  521. , m_stencil_buffer(MUST(StencilBuffer::try_create(size)))
  522. {
  523. m_options.scissor_box = m_render_target->rect();
  524. m_options.viewport = m_render_target->rect();
  525. }
  526. DeviceInfo Device::info() const
  527. {
  528. return {
  529. .vendor_name = "SerenityOS",
  530. .device_name = "SoftGPU",
  531. .num_texture_units = NUM_SAMPLERS,
  532. .num_lights = NUM_LIGHTS,
  533. .stencil_bits = sizeof(u8) * 8,
  534. .supports_npot_textures = true,
  535. };
  536. }
  537. static void generate_texture_coordinates(Vertex& vertex, RasterizerOptions const& options)
  538. {
  539. auto generate_coordinate = [&](size_t texcoord_index, size_t config_index) -> float {
  540. auto mode = options.texcoord_generation_config[texcoord_index][config_index].mode;
  541. switch (mode) {
  542. case TexCoordGenerationMode::ObjectLinear: {
  543. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  544. return coefficients.dot(vertex.position);
  545. }
  546. case TexCoordGenerationMode::EyeLinear: {
  547. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  548. return coefficients.dot(vertex.eye_coordinates);
  549. }
  550. case TexCoordGenerationMode::SphereMap: {
  551. auto const eye_unit = vertex.eye_coordinates.normalized();
  552. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  553. auto const normal = vertex.normal;
  554. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  555. reflection.set_z(reflection.z() + 1);
  556. auto const reflection_value = (config_index == 0) ? reflection.x() : reflection.y();
  557. return reflection_value / (2 * reflection.length()) + 0.5f;
  558. }
  559. case TexCoordGenerationMode::ReflectionMap: {
  560. auto const eye_unit = vertex.eye_coordinates.normalized();
  561. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  562. auto const normal = vertex.normal;
  563. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  564. switch (config_index) {
  565. case 0:
  566. return reflection.x();
  567. case 1:
  568. return reflection.y();
  569. case 2:
  570. return reflection.z();
  571. default:
  572. VERIFY_NOT_REACHED();
  573. }
  574. }
  575. case TexCoordGenerationMode::NormalMap: {
  576. auto const normal = vertex.normal;
  577. switch (config_index) {
  578. case 0:
  579. return normal.x();
  580. case 1:
  581. return normal.y();
  582. case 2:
  583. return normal.z();
  584. default:
  585. VERIFY_NOT_REACHED();
  586. }
  587. }
  588. default:
  589. VERIFY_NOT_REACHED();
  590. }
  591. };
  592. for (size_t i = 0; i < vertex.tex_coords.size(); ++i) {
  593. auto& tex_coord = vertex.tex_coords[i];
  594. auto const enabled_coords = options.texcoord_generation_enabled_coordinates[i];
  595. tex_coord = {
  596. ((enabled_coords & TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(i, 0) : tex_coord.x(),
  597. ((enabled_coords & TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(i, 1) : tex_coord.y(),
  598. ((enabled_coords & TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(i, 2) : tex_coord.z(),
  599. ((enabled_coords & TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(i, 3) : tex_coord.w(),
  600. };
  601. }
  602. }
  603. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix3x3 const& normal_transform,
  604. FloatMatrix4x4 const& projection_transform, FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices,
  605. Vector<size_t> const& enabled_texture_units)
  606. {
  607. // At this point, the user has effectively specified that they are done with defining the geometry
  608. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  609. //
  610. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  611. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  612. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  613. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  614. // 5. The vertices are sorted (for the rasterizer, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  615. // 6. The vertices are then sent off to the rasterizer and drawn to the screen
  616. m_enabled_texture_units = enabled_texture_units;
  617. m_triangle_list.clear_with_capacity();
  618. m_processed_triangles.clear_with_capacity();
  619. // Let's construct some triangles
  620. if (primitive_type == PrimitiveType::Triangles) {
  621. Triangle triangle;
  622. if (vertices.size() < 3)
  623. return;
  624. for (size_t i = 0; i < vertices.size() - 2; i += 3) {
  625. triangle.vertices[0] = vertices.at(i);
  626. triangle.vertices[1] = vertices.at(i + 1);
  627. triangle.vertices[2] = vertices.at(i + 2);
  628. m_triangle_list.append(triangle);
  629. }
  630. } else if (primitive_type == PrimitiveType::Quads) {
  631. // We need to construct two triangles to form the quad
  632. Triangle triangle;
  633. if (vertices.size() < 4)
  634. return;
  635. for (size_t i = 0; i < vertices.size() - 3; i += 4) {
  636. // Triangle 1
  637. triangle.vertices[0] = vertices.at(i);
  638. triangle.vertices[1] = vertices.at(i + 1);
  639. triangle.vertices[2] = vertices.at(i + 2);
  640. m_triangle_list.append(triangle);
  641. // Triangle 2
  642. triangle.vertices[0] = vertices.at(i + 2);
  643. triangle.vertices[1] = vertices.at(i + 3);
  644. triangle.vertices[2] = vertices.at(i);
  645. m_triangle_list.append(triangle);
  646. }
  647. } else if (primitive_type == PrimitiveType::TriangleFan) {
  648. Triangle triangle;
  649. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  650. for (size_t i = 1; i < vertices.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  651. {
  652. triangle.vertices[1] = vertices.at(i);
  653. triangle.vertices[2] = vertices.at(i + 1);
  654. m_triangle_list.append(triangle);
  655. }
  656. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  657. Triangle triangle;
  658. if (vertices.size() < 3)
  659. return;
  660. for (size_t i = 0; i < vertices.size() - 2; i++) {
  661. if (i % 2 == 0) {
  662. triangle.vertices[0] = vertices.at(i);
  663. triangle.vertices[1] = vertices.at(i + 1);
  664. triangle.vertices[2] = vertices.at(i + 2);
  665. } else {
  666. triangle.vertices[0] = vertices.at(i + 1);
  667. triangle.vertices[1] = vertices.at(i);
  668. triangle.vertices[2] = vertices.at(i + 2);
  669. }
  670. m_triangle_list.append(triangle);
  671. }
  672. }
  673. // Now let's transform each triangle and send that to the GPU
  674. auto const viewport = window_coordinates_to_target_coordinates(m_options.viewport);
  675. auto const viewport_half_width = viewport.width() / 2.0f;
  676. auto const viewport_half_height = viewport.height() / 2.0f;
  677. auto const viewport_center_x = viewport.x() + viewport_half_width;
  678. auto const viewport_center_y = viewport.y() + viewport_half_height;
  679. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  680. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  681. for (auto& triangle : m_triangle_list) {
  682. // Transform vertices into eye coordinates using the model-view transform
  683. triangle.vertices[0].eye_coordinates = model_view_transform * triangle.vertices[0].position;
  684. triangle.vertices[1].eye_coordinates = model_view_transform * triangle.vertices[1].position;
  685. triangle.vertices[2].eye_coordinates = model_view_transform * triangle.vertices[2].position;
  686. // Transform the vertex normals into eye-space
  687. triangle.vertices[0].normal = transform_direction(model_view_transform, triangle.vertices[0].normal);
  688. triangle.vertices[1].normal = transform_direction(model_view_transform, triangle.vertices[1].normal);
  689. triangle.vertices[2].normal = transform_direction(model_view_transform, triangle.vertices[2].normal);
  690. // Calculate per-vertex lighting
  691. if (m_options.lighting_enabled) {
  692. auto const& material = m_materials.at(0);
  693. for (auto& vertex : triangle.vertices) {
  694. auto ambient = material.ambient;
  695. auto diffuse = material.diffuse;
  696. auto emissive = material.emissive;
  697. auto specular = material.specular;
  698. if (m_options.color_material_enabled
  699. && (m_options.color_material_face == ColorMaterialFace::Front || m_options.color_material_face == ColorMaterialFace::FrontAndBack)) {
  700. switch (m_options.color_material_mode) {
  701. case ColorMaterialMode::Ambient:
  702. ambient = vertex.color;
  703. break;
  704. case ColorMaterialMode::AmbientAndDiffuse:
  705. ambient = vertex.color;
  706. diffuse = vertex.color;
  707. break;
  708. case ColorMaterialMode::Diffuse:
  709. diffuse = vertex.color;
  710. break;
  711. case ColorMaterialMode::Emissive:
  712. emissive = vertex.color;
  713. break;
  714. case ColorMaterialMode::Specular:
  715. specular = vertex.color;
  716. break;
  717. }
  718. }
  719. FloatVector4 result_color = emissive + (ambient * m_lighting_model.scene_ambient_color);
  720. for (auto const& light : m_lights) {
  721. if (!light.is_enabled)
  722. continue;
  723. // We need to save the length here because the attenuation factor requires a non
  724. // normalized vector!
  725. auto sgi_arrow_operator = [](FloatVector4 const& p1, FloatVector4 const& p2, float& saved_length) {
  726. if ((p1.w() != 0.0f) && (p2.w() == 0.0f)) {
  727. saved_length = p2.length();
  728. return (p2 / saved_length).xyz();
  729. } else if ((p1.w() == 0.0f) && (p2.w() != 0.0f)) {
  730. saved_length = p2.length();
  731. return -(p1 / saved_length).xyz();
  732. } else {
  733. // FIXME: The OpenGL 1.5 spec says nothing about the case where P1 and P2 BOTH have a w value of 1, which would
  734. // then mean the light position has an implicit value of (0, 0, 0, 0). This doesn't make any logical sense, and it most likely
  735. // a typographical error. Most other GL implementations seem to just fix it to the distance from the vertex to the light, which
  736. // seems to work just fine.
  737. // If somebody with more insight about this could clarify this eventually, that'd be great.
  738. auto distance = (p2 - p1);
  739. saved_length = distance.length();
  740. return (distance / saved_length).xyz();
  741. }
  742. };
  743. auto sgi_dot_operator = [](FloatVector3 const& d1, FloatVector3 const& d2) {
  744. return AK::max(d1.dot(d2), 0.0f);
  745. };
  746. float vector_length = 0.0f;
  747. FloatVector3 vertex_to_light = sgi_arrow_operator(vertex.eye_coordinates, light.position, vector_length);
  748. // Light attenuation value.
  749. float light_attenuation_factor = 1.0f;
  750. if (light.position.w() != 0.0f) {
  751. auto const vertex_to_light_length = vertex_to_light.length();
  752. auto const vertex_to_light_length_squared = vertex_to_light_length * vertex_to_light_length;
  753. light_attenuation_factor = 1.0f / (light.constant_attenuation + (light.linear_attenuation * vertex_to_light_length) + (light.quadratic_attenuation * vertex_to_light_length_squared));
  754. }
  755. // Spotlight factor
  756. float spotlight_factor = 1.0f;
  757. if (light.spotlight_cutoff_angle != 180.0f) {
  758. auto const vertex_to_light_dot_spotlight_direction = sgi_dot_operator(vertex_to_light, light.spotlight_direction.normalized());
  759. auto const cos_spotlight_cutoff = AK::cos<float>(light.spotlight_cutoff_angle * AK::Pi<float> / 180.f);
  760. if (vertex_to_light_dot_spotlight_direction >= cos_spotlight_cutoff)
  761. spotlight_factor = AK::pow<float>(vertex_to_light_dot_spotlight_direction, light.spotlight_exponent);
  762. else
  763. spotlight_factor = 0.0f;
  764. }
  765. // FIXME: The spec allows for splitting the colors calculated here into multiple different colors (primary/secondary color). Investigate what this means.
  766. (void)m_lighting_model.single_color;
  767. // FIXME: Two sided lighting should be implemented eventually (I believe this is where the normals are -ve and then lighting is calculated with the BACK material)
  768. (void)m_lighting_model.two_sided_lighting;
  769. // Ambient
  770. auto const ambient_component = ambient * light.ambient_intensity;
  771. // Diffuse
  772. auto const normal_dot_vertex_to_light = sgi_dot_operator(vertex.normal, vertex_to_light);
  773. auto const diffuse_component = ((diffuse * light.diffuse_intensity) * normal_dot_vertex_to_light);
  774. // Specular
  775. FloatVector4 specular_component = { 0.0f, 0.0f, 0.0f, 0.0f };
  776. if (normal_dot_vertex_to_light > 0.0f) {
  777. FloatVector3 half_vector_normalized;
  778. if (!m_lighting_model.viewer_at_infinity) {
  779. half_vector_normalized = (vertex_to_light + FloatVector3(0.0f, 0.0f, 1.0f)).normalized();
  780. } else {
  781. auto const vertex_to_eye_point = sgi_arrow_operator(vertex.eye_coordinates.normalized(), FloatVector4(0.0f, 0.0f, 0.0f, 1.0f), vector_length);
  782. half_vector_normalized = vertex_to_light + vertex_to_eye_point;
  783. }
  784. auto const normal_dot_half_vector = sgi_dot_operator(vertex.normal.normalized(), half_vector_normalized);
  785. auto const specular_coefficient = AK::pow(normal_dot_half_vector, material.shininess);
  786. specular_component = (specular * light.specular_intensity) * specular_coefficient;
  787. }
  788. FloatVector4 color = ambient_component;
  789. color += diffuse_component;
  790. color += specular_component;
  791. color = color * light_attenuation_factor * spotlight_factor;
  792. result_color += color;
  793. }
  794. vertex.color = result_color;
  795. vertex.color.set_w(diffuse.w()); // OpenGL 1.5 spec, page 59: "The A produced by lighting is the alpha value associated with diffuse color material"
  796. vertex.color.clamp(0.0f, 1.0f);
  797. }
  798. }
  799. // Transform eye coordinates into clip coordinates using the projection transform
  800. triangle.vertices[0].clip_coordinates = projection_transform * triangle.vertices[0].eye_coordinates;
  801. triangle.vertices[1].clip_coordinates = projection_transform * triangle.vertices[1].eye_coordinates;
  802. triangle.vertices[2].clip_coordinates = projection_transform * triangle.vertices[2].eye_coordinates;
  803. // At this point, we're in clip space
  804. // Here's where we do the clipping. This is a really crude implementation of the
  805. // https://learnopengl.com/Getting-started/Coordinate-Systems
  806. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  807. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  808. //
  809. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  810. // Okay, let's do some face culling first
  811. m_clipped_vertices.clear_with_capacity();
  812. m_clipped_vertices.append(triangle.vertices[0]);
  813. m_clipped_vertices.append(triangle.vertices[1]);
  814. m_clipped_vertices.append(triangle.vertices[2]);
  815. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  816. if (m_clipped_vertices.size() < 3)
  817. continue;
  818. for (auto& vec : m_clipped_vertices) {
  819. // To normalized device coordinates (NDC)
  820. auto const one_over_w = 1 / vec.clip_coordinates.w();
  821. auto const ndc_coordinates = FloatVector4 {
  822. vec.clip_coordinates.x() * one_over_w,
  823. vec.clip_coordinates.y() * one_over_w,
  824. vec.clip_coordinates.z() * one_over_w,
  825. one_over_w,
  826. };
  827. // To window coordinates - note that we flip the Y coordinate into target space
  828. vec.window_coordinates = {
  829. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  830. viewport_center_y - ndc_coordinates.y() * viewport_half_height,
  831. depth_halfway + ndc_coordinates.z() * depth_half_range,
  832. ndc_coordinates.w(),
  833. };
  834. }
  835. Triangle tri;
  836. tri.vertices[0] = m_clipped_vertices[0];
  837. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  838. tri.vertices[1] = m_clipped_vertices[i];
  839. tri.vertices[2] = m_clipped_vertices[i + 1];
  840. m_processed_triangles.append(tri);
  841. }
  842. }
  843. // Generate texture coordinates if at least one coordinate is enabled
  844. bool texture_coordinate_generation_enabled = false;
  845. for (auto const coordinates_enabled : m_options.texcoord_generation_enabled_coordinates) {
  846. if (coordinates_enabled != TexCoordGenerationCoordinate::None) {
  847. texture_coordinate_generation_enabled = true;
  848. break;
  849. }
  850. }
  851. for (auto& triangle : m_processed_triangles) {
  852. // Let's calculate the (signed) area of the triangle
  853. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  854. float dxAB = triangle.vertices[0].window_coordinates.x() - triangle.vertices[1].window_coordinates.x(); // A.x - B.x
  855. float dxBC = triangle.vertices[1].window_coordinates.x() - triangle.vertices[2].window_coordinates.x(); // B.X - C.x
  856. float dyAB = triangle.vertices[0].window_coordinates.y() - triangle.vertices[1].window_coordinates.y();
  857. float dyBC = triangle.vertices[1].window_coordinates.y() - triangle.vertices[2].window_coordinates.y();
  858. float area = (dxAB * dyBC) - (dxBC * dyAB);
  859. if (area == 0.0f)
  860. continue;
  861. if (m_options.enable_culling) {
  862. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area < 0 : area > 0);
  863. if (!is_front && m_options.cull_back)
  864. continue;
  865. if (is_front && m_options.cull_front)
  866. continue;
  867. }
  868. if (area > 0)
  869. swap(triangle.vertices[0], triangle.vertices[1]);
  870. // Transform normals
  871. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  872. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  873. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  874. if (m_options.normalization_enabled) {
  875. triangle.vertices[0].normal.normalize();
  876. triangle.vertices[1].normal.normalize();
  877. triangle.vertices[2].normal.normalize();
  878. }
  879. if (texture_coordinate_generation_enabled) {
  880. generate_texture_coordinates(triangle.vertices[0], m_options);
  881. generate_texture_coordinates(triangle.vertices[1], m_options);
  882. generate_texture_coordinates(triangle.vertices[2], m_options);
  883. }
  884. // Apply texture transformation
  885. for (size_t i = 0; i < NUM_SAMPLERS; ++i) {
  886. triangle.vertices[0].tex_coords[i] = texture_transform * triangle.vertices[0].tex_coords[i];
  887. triangle.vertices[1].tex_coords[i] = texture_transform * triangle.vertices[1].tex_coords[i];
  888. triangle.vertices[2].tex_coords[i] = texture_transform * triangle.vertices[2].tex_coords[i];
  889. }
  890. rasterize_triangle(triangle);
  891. }
  892. }
  893. ALWAYS_INLINE void Device::shade_fragments(PixelQuad& quad)
  894. {
  895. quad.out_color = quad.vertex_color;
  896. for (size_t i : m_enabled_texture_units) {
  897. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  898. auto const& sampler = m_samplers[i];
  899. auto texel = sampler.sample_2d({ quad.texture_coordinates[i].x(), quad.texture_coordinates[i].y() });
  900. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  901. // FIXME: Implement more blend modes
  902. switch (sampler.config().fixed_function_texture_env_mode) {
  903. case TextureEnvMode::Modulate:
  904. quad.out_color = quad.out_color * texel;
  905. break;
  906. case TextureEnvMode::Replace:
  907. quad.out_color = texel;
  908. break;
  909. case TextureEnvMode::Decal: {
  910. auto src_alpha = quad.out_color.w();
  911. quad.out_color.set_x(mix(quad.out_color.x(), texel.x(), src_alpha));
  912. quad.out_color.set_y(mix(quad.out_color.y(), texel.y(), src_alpha));
  913. quad.out_color.set_z(mix(quad.out_color.z(), texel.z(), src_alpha));
  914. break;
  915. }
  916. default:
  917. VERIFY_NOT_REACHED();
  918. }
  919. }
  920. // Calculate fog
  921. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  922. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  923. if (m_options.fog_enabled) {
  924. auto factor = expand4(0.0f);
  925. switch (m_options.fog_mode) {
  926. case FogMode::Linear:
  927. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  928. break;
  929. case FogMode::Exp: {
  930. auto argument = -m_options.fog_density * quad.fog_depth;
  931. factor = exp(argument);
  932. } break;
  933. case FogMode::Exp2: {
  934. auto argument = m_options.fog_density * quad.fog_depth;
  935. argument *= -argument;
  936. factor = exp(argument);
  937. } break;
  938. default:
  939. VERIFY_NOT_REACHED();
  940. }
  941. // Mix texel's RGB with fog's RBG - leave alpha alone
  942. auto fog_color = expand4(m_options.fog_color);
  943. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  944. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  945. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  946. }
  947. }
  948. ALWAYS_INLINE bool Device::test_alpha(PixelQuad& quad)
  949. {
  950. auto const alpha = quad.out_color.w();
  951. auto const ref_value = expand4(m_options.alpha_test_ref_value);
  952. switch (m_options.alpha_test_func) {
  953. case AlphaTestFunction::Less:
  954. quad.mask &= alpha < ref_value;
  955. break;
  956. case AlphaTestFunction::Equal:
  957. quad.mask &= alpha == ref_value;
  958. break;
  959. case AlphaTestFunction::LessOrEqual:
  960. quad.mask &= alpha <= ref_value;
  961. break;
  962. case AlphaTestFunction::Greater:
  963. quad.mask &= alpha > ref_value;
  964. break;
  965. case AlphaTestFunction::NotEqual:
  966. quad.mask &= alpha != ref_value;
  967. break;
  968. case AlphaTestFunction::GreaterOrEqual:
  969. quad.mask &= alpha >= ref_value;
  970. break;
  971. case AlphaTestFunction::Never:
  972. case AlphaTestFunction::Always:
  973. default:
  974. VERIFY_NOT_REACHED();
  975. }
  976. return any(quad.mask);
  977. }
  978. void Device::resize(const Gfx::IntSize& size)
  979. {
  980. wait_for_all_threads();
  981. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, size).release_value_but_fixme_should_propagate_errors();
  982. m_depth_buffer = adopt_own(*new DepthBuffer(size));
  983. }
  984. void Device::clear_color(const FloatVector4& color)
  985. {
  986. wait_for_all_threads();
  987. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  988. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  989. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  990. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  991. auto const fill_color = Gfx::Color(r, g, b, a);
  992. if (m_options.scissor_enabled) {
  993. auto fill_rect = m_render_target->rect();
  994. fill_rect.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  995. Gfx::Painter painter { *m_render_target };
  996. painter.fill_rect(fill_rect, fill_color);
  997. return;
  998. }
  999. m_render_target->fill(fill_color);
  1000. }
  1001. void Device::clear_depth(float depth)
  1002. {
  1003. wait_for_all_threads();
  1004. if (m_options.scissor_enabled) {
  1005. m_depth_buffer->clear(window_coordinates_to_target_coordinates(m_options.scissor_box), depth);
  1006. return;
  1007. }
  1008. m_depth_buffer->clear(depth);
  1009. }
  1010. void Device::clear_stencil(u8 value)
  1011. {
  1012. Gfx::IntRect clear_rect = m_stencil_buffer->rect();
  1013. if (m_options.scissor_enabled)
  1014. clear_rect.intersect(window_coordinates_to_target_coordinates(m_options.scissor_box));
  1015. m_stencil_buffer->clear(clear_rect, value);
  1016. }
  1017. void Device::blit_to_color_buffer_at_raster_position(Gfx::Bitmap const& source)
  1018. {
  1019. if (!m_raster_position.valid)
  1020. return;
  1021. wait_for_all_threads();
  1022. INCREASE_STATISTICS_COUNTER(g_num_pixels, source.width() * source.height());
  1023. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, source.width() * source.height());
  1024. Gfx::Painter painter { *m_render_target };
  1025. auto const blit_rect = raster_rect_in_target_coordinates(source.size());
  1026. painter.blit({ blit_rect.x(), blit_rect.y() }, source, source.rect(), 1.0f, true);
  1027. }
  1028. void Device::blit_to_depth_buffer_at_raster_position(Vector<float> const& depth_values, size_t width, size_t height)
  1029. {
  1030. if (!m_raster_position.valid)
  1031. return;
  1032. auto const raster_rect = raster_rect_in_target_coordinates({ width, height });
  1033. auto const y1 = raster_rect.y();
  1034. auto const y2 = y1 + height;
  1035. auto const x1 = raster_rect.x();
  1036. int const x2 = x1 + width;
  1037. auto index = 0;
  1038. for (int y = y2 - 1; y >= y1; --y) {
  1039. auto depth_line = m_depth_buffer->scanline(y);
  1040. for (int x = x1; x < x2; ++x) {
  1041. depth_line[x] = depth_values.at(index++);
  1042. }
  1043. }
  1044. }
  1045. void Device::blit_to(Gfx::Bitmap& target)
  1046. {
  1047. wait_for_all_threads();
  1048. Gfx::Painter painter { target };
  1049. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  1050. if constexpr (ENABLE_STATISTICS_OVERLAY)
  1051. draw_statistics_overlay(target);
  1052. }
  1053. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  1054. {
  1055. static Core::ElapsedTimer timer;
  1056. static String debug_string;
  1057. static int frame_counter;
  1058. frame_counter++;
  1059. int milliseconds = 0;
  1060. if (timer.is_valid())
  1061. milliseconds = timer.elapsed();
  1062. else
  1063. timer.start();
  1064. Gfx::Painter painter { target };
  1065. if (milliseconds > 500) {
  1066. int num_rendertarget_pixels = m_render_target->width() * m_render_target->height();
  1067. StringBuilder builder;
  1068. builder.append(String::formatted("Timings : {:.1}ms {:.1}FPS\n",
  1069. static_cast<double>(milliseconds) / frame_counter,
  1070. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  1071. builder.append(String::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  1072. builder.append(String::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  1073. builder.append(String::formatted("Pixels : {}, Stencil: {}%, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  1074. g_num_pixels,
  1075. g_num_pixels > 0 ? g_num_stencil_writes * 100 / g_num_pixels : 0,
  1076. g_num_pixels > 0 ? g_num_pixels_shaded * 100 / g_num_pixels : 0,
  1077. g_num_pixels_shaded > 0 ? g_num_pixels_blended * 100 / g_num_pixels_shaded : 0,
  1078. num_rendertarget_pixels > 0 ? g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100 : 0));
  1079. builder.append(String::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  1080. debug_string = builder.to_string();
  1081. frame_counter = 0;
  1082. timer.start();
  1083. }
  1084. g_num_rasterized_triangles = 0;
  1085. g_num_pixels = 0;
  1086. g_num_pixels_shaded = 0;
  1087. g_num_pixels_blended = 0;
  1088. g_num_sampler_calls = 0;
  1089. g_num_stencil_writes = 0;
  1090. g_num_quads = 0;
  1091. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  1092. for (int y = -1; y < 2; y++)
  1093. for (int x = -1; x < 2; x++)
  1094. if (x != 0 && y != 0)
  1095. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  1096. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  1097. }
  1098. void Device::wait_for_all_threads() const
  1099. {
  1100. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  1101. }
  1102. void Device::set_options(const RasterizerOptions& options)
  1103. {
  1104. wait_for_all_threads();
  1105. m_options = options;
  1106. if (m_options.enable_blending)
  1107. setup_blend_factors();
  1108. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  1109. }
  1110. void Device::set_light_model_params(const LightModelParameters& lighting_model)
  1111. {
  1112. wait_for_all_threads();
  1113. m_lighting_model = lighting_model;
  1114. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  1115. }
  1116. Gfx::RGBA32 Device::get_backbuffer_pixel(int x, int y)
  1117. {
  1118. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1119. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  1120. return 0;
  1121. return m_render_target->scanline(y)[x];
  1122. }
  1123. float Device::get_depthbuffer_value(int x, int y)
  1124. {
  1125. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1126. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  1127. return 1.0f;
  1128. return m_depth_buffer->scanline(y)[x];
  1129. }
  1130. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  1131. {
  1132. VERIFY(width > 0);
  1133. VERIFY(height > 0);
  1134. VERIFY(depth > 0);
  1135. VERIFY(levels > 0);
  1136. VERIFY(layers > 0);
  1137. return adopt_ref(*new Image(format, width, height, depth, levels, layers));
  1138. }
  1139. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  1140. {
  1141. m_samplers[sampler].set_config(config);
  1142. }
  1143. void Device::set_light_state(unsigned int light_id, Light const& light)
  1144. {
  1145. m_lights.at(light_id) = light;
  1146. }
  1147. void Device::set_material_state(Face face, Material const& material)
  1148. {
  1149. m_materials[face] = material;
  1150. }
  1151. void Device::set_stencil_configuration(Face face, StencilConfiguration const& stencil_configuration)
  1152. {
  1153. m_stencil_configuration[face] = stencil_configuration;
  1154. }
  1155. void Device::set_raster_position(RasterPosition const& raster_position)
  1156. {
  1157. m_raster_position = raster_position;
  1158. }
  1159. void Device::set_raster_position(FloatVector4 const& position, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform)
  1160. {
  1161. auto const eye_coordinates = model_view_transform * position;
  1162. auto const clip_coordinates = projection_transform * eye_coordinates;
  1163. // FIXME: implement clipping
  1164. m_raster_position.valid = true;
  1165. auto ndc_coordinates = clip_coordinates / clip_coordinates.w();
  1166. ndc_coordinates.set_w(clip_coordinates.w());
  1167. auto const viewport = m_options.viewport;
  1168. auto const viewport_half_width = viewport.width() / 2.0f;
  1169. auto const viewport_half_height = viewport.height() / 2.0f;
  1170. auto const viewport_center_x = viewport.x() + viewport_half_width;
  1171. auto const viewport_center_y = viewport.y() + viewport_half_height;
  1172. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  1173. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  1174. // FIXME: implement other raster position properties such as color and texcoords
  1175. m_raster_position.window_coordinates = {
  1176. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  1177. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  1178. depth_halfway + ndc_coordinates.z() * depth_half_range,
  1179. ndc_coordinates.w(),
  1180. };
  1181. m_raster_position.eye_coordinate_distance = eye_coordinates.length();
  1182. }
  1183. Gfx::IntRect Device::raster_rect_in_target_coordinates(Gfx::IntSize size)
  1184. {
  1185. auto const raster_rect = Gfx::IntRect {
  1186. static_cast<int>(m_raster_position.window_coordinates.x()),
  1187. static_cast<int>(m_raster_position.window_coordinates.y()),
  1188. size.width(),
  1189. size.height(),
  1190. };
  1191. return window_coordinates_to_target_coordinates(raster_rect);
  1192. }
  1193. }