Device.cpp 56 KB

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