vk_rasterizer.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <mutex>
  8. #include <vector>
  9. #include <boost/container/static_vector.hpp>
  10. #include "common/alignment.h"
  11. #include "common/assert.h"
  12. #include "common/logging/log.h"
  13. #include "common/microprofile.h"
  14. #include "common/scope_exit.h"
  15. #include "core/core.h"
  16. #include "core/settings.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  20. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  21. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  22. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  23. #include "video_core/renderer_vulkan/vk_compute_pass.h"
  24. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  25. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  26. #include "video_core/renderer_vulkan/vk_device.h"
  27. #include "video_core/renderer_vulkan/vk_graphics_pipeline.h"
  28. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  29. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  30. #include "video_core/renderer_vulkan/vk_renderpass_cache.h"
  31. #include "video_core/renderer_vulkan/vk_resource_manager.h"
  32. #include "video_core/renderer_vulkan/vk_sampler_cache.h"
  33. #include "video_core/renderer_vulkan/vk_scheduler.h"
  34. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  35. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  36. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  37. #include "video_core/renderer_vulkan/vk_update_descriptor.h"
  38. #include "video_core/renderer_vulkan/wrapper.h"
  39. #include "video_core/shader_cache.h"
  40. namespace Vulkan {
  41. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  42. MICROPROFILE_DEFINE(Vulkan_WaitForWorker, "Vulkan", "Wait for worker", MP_RGB(255, 192, 192));
  43. MICROPROFILE_DEFINE(Vulkan_Drawing, "Vulkan", "Record drawing", MP_RGB(192, 128, 128));
  44. MICROPROFILE_DEFINE(Vulkan_Compute, "Vulkan", "Record compute", MP_RGB(192, 128, 128));
  45. MICROPROFILE_DEFINE(Vulkan_Clearing, "Vulkan", "Record clearing", MP_RGB(192, 128, 128));
  46. MICROPROFILE_DEFINE(Vulkan_Geometry, "Vulkan", "Setup geometry", MP_RGB(192, 128, 128));
  47. MICROPROFILE_DEFINE(Vulkan_ConstBuffers, "Vulkan", "Setup constant buffers", MP_RGB(192, 128, 128));
  48. MICROPROFILE_DEFINE(Vulkan_GlobalBuffers, "Vulkan", "Setup global buffers", MP_RGB(192, 128, 128));
  49. MICROPROFILE_DEFINE(Vulkan_RenderTargets, "Vulkan", "Setup render targets", MP_RGB(192, 128, 128));
  50. MICROPROFILE_DEFINE(Vulkan_Textures, "Vulkan", "Setup textures", MP_RGB(192, 128, 128));
  51. MICROPROFILE_DEFINE(Vulkan_Images, "Vulkan", "Setup images", MP_RGB(192, 128, 128));
  52. MICROPROFILE_DEFINE(Vulkan_PipelineCache, "Vulkan", "Pipeline cache", MP_RGB(192, 128, 128));
  53. namespace {
  54. constexpr auto ComputeShaderIndex = static_cast<std::size_t>(Tegra::Engines::ShaderType::Compute);
  55. VkViewport GetViewportState(const VKDevice& device, const Maxwell& regs, std::size_t index) {
  56. const auto& src = regs.viewport_transform[index];
  57. const float width = src.scale_x * 2.0f;
  58. const float height = src.scale_y * 2.0f;
  59. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne ? 1.0f : 0.0f;
  60. VkViewport viewport{
  61. .x = src.translate_x - src.scale_x,
  62. .y = src.translate_y - src.scale_y,
  63. .width = width != 0.0f ? width : 1.0f,
  64. .height = height != 0.0f ? height : 1.0f,
  65. .minDepth = src.translate_z - src.scale_z * reduce_z,
  66. .maxDepth = src.translate_z + src.scale_z,
  67. };
  68. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  69. viewport.minDepth = std::clamp(viewport.minDepth, 0.0f, 1.0f);
  70. viewport.maxDepth = std::clamp(viewport.maxDepth, 0.0f, 1.0f);
  71. }
  72. return viewport;
  73. }
  74. VkRect2D GetScissorState(const Maxwell& regs, std::size_t index) {
  75. const auto& src = regs.scissor_test[index];
  76. VkRect2D scissor;
  77. if (src.enable) {
  78. scissor.offset.x = static_cast<s32>(src.min_x);
  79. scissor.offset.y = static_cast<s32>(src.min_y);
  80. scissor.extent.width = src.max_x - src.min_x;
  81. scissor.extent.height = src.max_y - src.min_y;
  82. } else {
  83. scissor.offset.x = 0;
  84. scissor.offset.y = 0;
  85. scissor.extent.width = std::numeric_limits<s32>::max();
  86. scissor.extent.height = std::numeric_limits<s32>::max();
  87. }
  88. return scissor;
  89. }
  90. std::array<GPUVAddr, Maxwell::MaxShaderProgram> GetShaderAddresses(
  91. const std::array<Shader*, Maxwell::MaxShaderProgram>& shaders) {
  92. std::array<GPUVAddr, Maxwell::MaxShaderProgram> addresses;
  93. for (std::size_t i = 0; i < std::size(addresses); ++i) {
  94. addresses[i] = shaders[i] ? shaders[i]->GetGpuAddr() : 0;
  95. }
  96. return addresses;
  97. }
  98. void TransitionImages(const std::vector<ImageView>& views, VkPipelineStageFlags pipeline_stage,
  99. VkAccessFlags access) {
  100. for (auto& [view, layout] : views) {
  101. view->Transition(*layout, pipeline_stage, access);
  102. }
  103. }
  104. template <typename Engine, typename Entry>
  105. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  106. std::size_t stage, std::size_t index = 0) {
  107. const auto stage_type = static_cast<Tegra::Engines::ShaderType>(stage);
  108. if constexpr (std::is_same_v<Entry, SamplerEntry>) {
  109. if (entry.is_separated) {
  110. const u32 buffer_1 = entry.buffer;
  111. const u32 buffer_2 = entry.secondary_buffer;
  112. const u32 offset_1 = entry.offset;
  113. const u32 offset_2 = entry.secondary_offset;
  114. const u32 handle_1 = engine.AccessConstBuffer32(stage_type, buffer_1, offset_1);
  115. const u32 handle_2 = engine.AccessConstBuffer32(stage_type, buffer_2, offset_2);
  116. return engine.GetTextureInfo(handle_1 | handle_2);
  117. }
  118. }
  119. if (entry.is_bindless) {
  120. const auto tex_handle = engine.AccessConstBuffer32(stage_type, entry.buffer, entry.offset);
  121. return engine.GetTextureInfo(tex_handle);
  122. }
  123. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  124. const u32 entry_offset = static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  125. const u32 offset = entry.offset + entry_offset;
  126. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  127. return engine.GetStageTexture(stage_type, offset);
  128. } else {
  129. return engine.GetTexture(offset);
  130. }
  131. }
  132. /// @brief Determine if an attachment to be updated has to preserve contents
  133. /// @param is_clear True when a clear is being executed
  134. /// @param regs 3D registers
  135. /// @return True when the contents have to be preserved
  136. bool HasToPreserveColorContents(bool is_clear, const Maxwell& regs) {
  137. if (!is_clear) {
  138. return true;
  139. }
  140. // First we have to make sure all clear masks are enabled.
  141. if (!regs.clear_buffers.R || !regs.clear_buffers.G || !regs.clear_buffers.B ||
  142. !regs.clear_buffers.A) {
  143. return true;
  144. }
  145. // If scissors are disabled, the whole screen is cleared
  146. if (!regs.clear_flags.scissor) {
  147. return false;
  148. }
  149. // Then we have to confirm scissor testing clears the whole image
  150. const std::size_t index = regs.clear_buffers.RT;
  151. const auto& scissor = regs.scissor_test[0];
  152. return scissor.min_x > 0 || scissor.min_y > 0 || scissor.max_x < regs.rt[index].width ||
  153. scissor.max_y < regs.rt[index].height;
  154. }
  155. /// @brief Determine if an attachment to be updated has to preserve contents
  156. /// @param is_clear True when a clear is being executed
  157. /// @param regs 3D registers
  158. /// @return True when the contents have to be preserved
  159. bool HasToPreserveDepthContents(bool is_clear, const Maxwell& regs) {
  160. // If we are not clearing, the contents have to be preserved
  161. if (!is_clear) {
  162. return true;
  163. }
  164. // For depth stencil clears we only have to confirm scissor test covers the whole image
  165. if (!regs.clear_flags.scissor) {
  166. return false;
  167. }
  168. // Make sure the clear cover the whole image
  169. const auto& scissor = regs.scissor_test[0];
  170. return scissor.min_x > 0 || scissor.min_y > 0 || scissor.max_x < regs.zeta_width ||
  171. scissor.max_y < regs.zeta_height;
  172. }
  173. template <std::size_t N>
  174. std::array<VkDeviceSize, N> ExpandStrides(const std::array<u16, N>& strides) {
  175. std::array<VkDeviceSize, N> expanded;
  176. std::copy(strides.begin(), strides.end(), expanded.begin());
  177. return expanded;
  178. }
  179. } // Anonymous namespace
  180. class BufferBindings final {
  181. public:
  182. void AddVertexBinding(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, u32 stride) {
  183. vertex.buffers[vertex.num_buffers] = buffer;
  184. vertex.offsets[vertex.num_buffers] = offset;
  185. vertex.sizes[vertex.num_buffers] = size;
  186. vertex.strides[vertex.num_buffers] = static_cast<u16>(stride);
  187. ++vertex.num_buffers;
  188. }
  189. void SetIndexBinding(VkBuffer buffer, VkDeviceSize offset, VkIndexType type) {
  190. index.buffer = buffer;
  191. index.offset = offset;
  192. index.type = type;
  193. }
  194. void Bind(const VKDevice& device, VKScheduler& scheduler) const {
  195. // Use this large switch case to avoid dispatching more memory in the record lambda than
  196. // what we need. It looks horrible, but it's the best we can do on standard C++.
  197. switch (vertex.num_buffers) {
  198. case 0:
  199. return BindStatic<0>(device, scheduler);
  200. case 1:
  201. return BindStatic<1>(device, scheduler);
  202. case 2:
  203. return BindStatic<2>(device, scheduler);
  204. case 3:
  205. return BindStatic<3>(device, scheduler);
  206. case 4:
  207. return BindStatic<4>(device, scheduler);
  208. case 5:
  209. return BindStatic<5>(device, scheduler);
  210. case 6:
  211. return BindStatic<6>(device, scheduler);
  212. case 7:
  213. return BindStatic<7>(device, scheduler);
  214. case 8:
  215. return BindStatic<8>(device, scheduler);
  216. case 9:
  217. return BindStatic<9>(device, scheduler);
  218. case 10:
  219. return BindStatic<10>(device, scheduler);
  220. case 11:
  221. return BindStatic<11>(device, scheduler);
  222. case 12:
  223. return BindStatic<12>(device, scheduler);
  224. case 13:
  225. return BindStatic<13>(device, scheduler);
  226. case 14:
  227. return BindStatic<14>(device, scheduler);
  228. case 15:
  229. return BindStatic<15>(device, scheduler);
  230. case 16:
  231. return BindStatic<16>(device, scheduler);
  232. case 17:
  233. return BindStatic<17>(device, scheduler);
  234. case 18:
  235. return BindStatic<18>(device, scheduler);
  236. case 19:
  237. return BindStatic<19>(device, scheduler);
  238. case 20:
  239. return BindStatic<20>(device, scheduler);
  240. case 21:
  241. return BindStatic<21>(device, scheduler);
  242. case 22:
  243. return BindStatic<22>(device, scheduler);
  244. case 23:
  245. return BindStatic<23>(device, scheduler);
  246. case 24:
  247. return BindStatic<24>(device, scheduler);
  248. case 25:
  249. return BindStatic<25>(device, scheduler);
  250. case 26:
  251. return BindStatic<26>(device, scheduler);
  252. case 27:
  253. return BindStatic<27>(device, scheduler);
  254. case 28:
  255. return BindStatic<28>(device, scheduler);
  256. case 29:
  257. return BindStatic<29>(device, scheduler);
  258. case 30:
  259. return BindStatic<30>(device, scheduler);
  260. case 31:
  261. return BindStatic<31>(device, scheduler);
  262. case 32:
  263. return BindStatic<32>(device, scheduler);
  264. }
  265. UNREACHABLE();
  266. }
  267. private:
  268. // Some of these fields are intentionally left uninitialized to avoid initializing them twice.
  269. struct {
  270. std::size_t num_buffers = 0;
  271. std::array<VkBuffer, Maxwell::NumVertexArrays> buffers;
  272. std::array<VkDeviceSize, Maxwell::NumVertexArrays> offsets;
  273. std::array<VkDeviceSize, Maxwell::NumVertexArrays> sizes;
  274. std::array<u16, Maxwell::NumVertexArrays> strides;
  275. } vertex;
  276. struct {
  277. VkBuffer buffer = nullptr;
  278. VkDeviceSize offset;
  279. VkIndexType type;
  280. } index;
  281. template <std::size_t N>
  282. void BindStatic(const VKDevice& device, VKScheduler& scheduler) const {
  283. if (device.IsExtExtendedDynamicStateSupported()) {
  284. if (index.buffer) {
  285. BindStatic<N, true, true>(scheduler);
  286. } else {
  287. BindStatic<N, false, true>(scheduler);
  288. }
  289. } else {
  290. if (index.buffer) {
  291. BindStatic<N, true, false>(scheduler);
  292. } else {
  293. BindStatic<N, false, false>(scheduler);
  294. }
  295. }
  296. }
  297. template <std::size_t N, bool is_indexed, bool has_extended_dynamic_state>
  298. void BindStatic(VKScheduler& scheduler) const {
  299. static_assert(N <= Maxwell::NumVertexArrays);
  300. if constexpr (N == 0) {
  301. return;
  302. }
  303. std::array<VkBuffer, N> buffers;
  304. std::array<VkDeviceSize, N> offsets;
  305. std::copy(vertex.buffers.begin(), vertex.buffers.begin() + N, buffers.begin());
  306. std::copy(vertex.offsets.begin(), vertex.offsets.begin() + N, offsets.begin());
  307. if constexpr (has_extended_dynamic_state) {
  308. // With extended dynamic states we can specify the length and stride of a vertex buffer
  309. std::array<VkDeviceSize, N> sizes;
  310. std::array<u16, N> strides;
  311. std::copy(vertex.sizes.begin(), vertex.sizes.begin() + N, sizes.begin());
  312. std::copy(vertex.strides.begin(), vertex.strides.begin() + N, strides.begin());
  313. if constexpr (is_indexed) {
  314. scheduler.Record(
  315. [buffers, offsets, sizes, strides, index = index](vk::CommandBuffer cmdbuf) {
  316. cmdbuf.BindIndexBuffer(index.buffer, index.offset, index.type);
  317. cmdbuf.BindVertexBuffers2EXT(0, static_cast<u32>(N), buffers.data(),
  318. offsets.data(), sizes.data(),
  319. ExpandStrides(strides).data());
  320. });
  321. } else {
  322. scheduler.Record([buffers, offsets, sizes, strides](vk::CommandBuffer cmdbuf) {
  323. cmdbuf.BindVertexBuffers2EXT(0, static_cast<u32>(N), buffers.data(),
  324. offsets.data(), sizes.data(),
  325. ExpandStrides(strides).data());
  326. });
  327. }
  328. return;
  329. }
  330. if constexpr (is_indexed) {
  331. // Indexed draw
  332. scheduler.Record([buffers, offsets, index = index](vk::CommandBuffer cmdbuf) {
  333. cmdbuf.BindIndexBuffer(index.buffer, index.offset, index.type);
  334. cmdbuf.BindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data());
  335. });
  336. } else {
  337. // Array draw
  338. scheduler.Record([buffers, offsets](vk::CommandBuffer cmdbuf) {
  339. cmdbuf.BindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data());
  340. });
  341. }
  342. }
  343. };
  344. void RasterizerVulkan::DrawParameters::Draw(vk::CommandBuffer cmdbuf) const {
  345. if (is_indexed) {
  346. cmdbuf.DrawIndexed(num_vertices, num_instances, 0, base_vertex, base_instance);
  347. } else {
  348. cmdbuf.Draw(num_vertices, num_instances, base_vertex, base_instance);
  349. }
  350. }
  351. RasterizerVulkan::RasterizerVulkan(Core::System& system, Core::Frontend::EmuWindow& renderer,
  352. VKScreenInfo& screen_info, const VKDevice& device,
  353. VKResourceManager& resource_manager,
  354. VKMemoryManager& memory_manager, StateTracker& state_tracker,
  355. VKScheduler& scheduler)
  356. : RasterizerAccelerated{system.Memory()}, system{system}, render_window{renderer},
  357. screen_info{screen_info}, device{device}, resource_manager{resource_manager},
  358. memory_manager{memory_manager}, state_tracker{state_tracker}, scheduler{scheduler},
  359. staging_pool(device, memory_manager, scheduler), descriptor_pool(device),
  360. update_descriptor_queue(device, scheduler), renderpass_cache(device),
  361. quad_array_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  362. quad_indexed_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  363. uint8_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  364. texture_cache(system, *this, device, resource_manager, memory_manager, scheduler,
  365. staging_pool),
  366. pipeline_cache(system, *this, device, scheduler, descriptor_pool, update_descriptor_queue,
  367. renderpass_cache),
  368. buffer_cache(*this, system, device, memory_manager, scheduler, staging_pool),
  369. sampler_cache(device),
  370. fence_manager(system, *this, device, scheduler, texture_cache, buffer_cache, query_cache),
  371. query_cache(system, *this, device, scheduler),
  372. wfi_event{device.GetLogical().CreateNewEvent()}, async_shaders{renderer} {
  373. scheduler.SetQueryCache(query_cache);
  374. if (device.UseAsynchronousShaders()) {
  375. async_shaders.AllocateWorkers();
  376. }
  377. }
  378. RasterizerVulkan::~RasterizerVulkan() = default;
  379. void RasterizerVulkan::Draw(bool is_indexed, bool is_instanced) {
  380. MICROPROFILE_SCOPE(Vulkan_Drawing);
  381. FlushWork();
  382. query_cache.UpdateCounters();
  383. SCOPE_EXIT({ system.GPU().TickWork(); });
  384. const auto& gpu = system.GPU().Maxwell3D();
  385. GraphicsPipelineCacheKey key;
  386. key.fixed_state.Fill(gpu.regs, device.IsExtExtendedDynamicStateSupported());
  387. buffer_cache.Map(CalculateGraphicsStreamBufferSize(is_indexed));
  388. BufferBindings buffer_bindings;
  389. const DrawParameters draw_params =
  390. SetupGeometry(key.fixed_state, buffer_bindings, is_indexed, is_instanced);
  391. update_descriptor_queue.Acquire();
  392. sampled_views.clear();
  393. image_views.clear();
  394. const auto shaders = pipeline_cache.GetShaders();
  395. key.shaders = GetShaderAddresses(shaders);
  396. SetupShaderDescriptors(shaders);
  397. buffer_cache.Unmap();
  398. const Texceptions texceptions = UpdateAttachments(false);
  399. SetupImageTransitions(texceptions, color_attachments, zeta_attachment);
  400. key.renderpass_params = GetRenderPassParams(texceptions);
  401. key.padding = 0;
  402. auto* pipeline = pipeline_cache.GetGraphicsPipeline(key, async_shaders);
  403. if (pipeline == nullptr || pipeline->GetHandle() == VK_NULL_HANDLE) {
  404. // Async graphics pipeline was not ready.
  405. return;
  406. }
  407. scheduler.BindGraphicsPipeline(pipeline->GetHandle());
  408. const auto renderpass = pipeline->GetRenderPass();
  409. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  410. scheduler.RequestRenderpass(renderpass, framebuffer, render_area);
  411. UpdateDynamicStates();
  412. buffer_bindings.Bind(device, scheduler);
  413. BeginTransformFeedback();
  414. const auto pipeline_layout = pipeline->GetLayout();
  415. const auto descriptor_set = pipeline->CommitDescriptorSet();
  416. scheduler.Record([pipeline_layout, descriptor_set, draw_params](vk::CommandBuffer cmdbuf) {
  417. if (descriptor_set) {
  418. cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout,
  419. DESCRIPTOR_SET, descriptor_set, {});
  420. }
  421. draw_params.Draw(cmdbuf);
  422. });
  423. EndTransformFeedback();
  424. }
  425. void RasterizerVulkan::Clear() {
  426. MICROPROFILE_SCOPE(Vulkan_Clearing);
  427. const auto& gpu = system.GPU().Maxwell3D();
  428. if (!system.GPU().Maxwell3D().ShouldExecute()) {
  429. return;
  430. }
  431. sampled_views.clear();
  432. image_views.clear();
  433. query_cache.UpdateCounters();
  434. const auto& regs = gpu.regs;
  435. const bool use_color = regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  436. regs.clear_buffers.A;
  437. const bool use_depth = regs.clear_buffers.Z;
  438. const bool use_stencil = regs.clear_buffers.S;
  439. if (!use_color && !use_depth && !use_stencil) {
  440. return;
  441. }
  442. [[maybe_unused]] const auto texceptions = UpdateAttachments(true);
  443. DEBUG_ASSERT(texceptions.none());
  444. SetupImageTransitions(0, color_attachments, zeta_attachment);
  445. const VkRenderPass renderpass = renderpass_cache.GetRenderPass(GetRenderPassParams(0));
  446. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  447. scheduler.RequestRenderpass(renderpass, framebuffer, render_area);
  448. VkClearRect clear_rect;
  449. clear_rect.baseArrayLayer = regs.clear_buffers.layer;
  450. clear_rect.layerCount = 1;
  451. clear_rect.rect = GetScissorState(regs, 0);
  452. clear_rect.rect.extent.width = std::min(clear_rect.rect.extent.width, render_area.width);
  453. clear_rect.rect.extent.height = std::min(clear_rect.rect.extent.height, render_area.height);
  454. if (use_color) {
  455. VkClearValue clear_value;
  456. std::memcpy(clear_value.color.float32, regs.clear_color, sizeof(regs.clear_color));
  457. const u32 color_attachment = regs.clear_buffers.RT;
  458. scheduler.Record([color_attachment, clear_value, clear_rect](vk::CommandBuffer cmdbuf) {
  459. const VkClearAttachment attachment{
  460. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  461. .colorAttachment = color_attachment,
  462. .clearValue = clear_value,
  463. };
  464. cmdbuf.ClearAttachments(attachment, clear_rect);
  465. });
  466. }
  467. if (!use_depth && !use_stencil) {
  468. return;
  469. }
  470. VkImageAspectFlags aspect_flags = 0;
  471. if (use_depth) {
  472. aspect_flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
  473. }
  474. if (use_stencil) {
  475. aspect_flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  476. }
  477. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  478. clear_rect, aspect_flags](vk::CommandBuffer cmdbuf) {
  479. VkClearAttachment attachment;
  480. attachment.aspectMask = aspect_flags;
  481. attachment.colorAttachment = 0;
  482. attachment.clearValue.depthStencil.depth = clear_depth;
  483. attachment.clearValue.depthStencil.stencil = clear_stencil;
  484. cmdbuf.ClearAttachments(attachment, clear_rect);
  485. });
  486. }
  487. void RasterizerVulkan::DispatchCompute(GPUVAddr code_addr) {
  488. MICROPROFILE_SCOPE(Vulkan_Compute);
  489. update_descriptor_queue.Acquire();
  490. sampled_views.clear();
  491. image_views.clear();
  492. query_cache.UpdateCounters();
  493. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  494. auto& pipeline = pipeline_cache.GetComputePipeline({
  495. .shader = code_addr,
  496. .shared_memory_size = launch_desc.shared_alloc,
  497. .workgroup_size =
  498. {
  499. launch_desc.block_dim_x,
  500. launch_desc.block_dim_y,
  501. launch_desc.block_dim_z,
  502. },
  503. });
  504. // Compute dispatches can't be executed inside a renderpass
  505. scheduler.RequestOutsideRenderPassOperationContext();
  506. buffer_cache.Map(CalculateComputeStreamBufferSize());
  507. const auto& entries = pipeline.GetEntries();
  508. SetupComputeConstBuffers(entries);
  509. SetupComputeGlobalBuffers(entries);
  510. SetupComputeUniformTexels(entries);
  511. SetupComputeTextures(entries);
  512. SetupComputeStorageTexels(entries);
  513. SetupComputeImages(entries);
  514. buffer_cache.Unmap();
  515. TransitionImages(sampled_views, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
  516. VK_ACCESS_SHADER_READ_BIT);
  517. TransitionImages(image_views, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
  518. VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
  519. scheduler.Record([grid_x = launch_desc.grid_dim_x, grid_y = launch_desc.grid_dim_y,
  520. grid_z = launch_desc.grid_dim_z, pipeline_handle = pipeline.GetHandle(),
  521. layout = pipeline.GetLayout(),
  522. descriptor_set = pipeline.CommitDescriptorSet()](vk::CommandBuffer cmdbuf) {
  523. cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_handle);
  524. cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, layout, DESCRIPTOR_SET,
  525. descriptor_set, {});
  526. cmdbuf.Dispatch(grid_x, grid_y, grid_z);
  527. });
  528. }
  529. void RasterizerVulkan::ResetCounter(VideoCore::QueryType type) {
  530. query_cache.ResetCounter(type);
  531. }
  532. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  533. std::optional<u64> timestamp) {
  534. query_cache.Query(gpu_addr, type, timestamp);
  535. }
  536. void RasterizerVulkan::FlushAll() {}
  537. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size) {
  538. if (addr == 0 || size == 0) {
  539. return;
  540. }
  541. texture_cache.FlushRegion(addr, size);
  542. buffer_cache.FlushRegion(addr, size);
  543. query_cache.FlushRegion(addr, size);
  544. }
  545. bool RasterizerVulkan::MustFlushRegion(VAddr addr, u64 size) {
  546. if (!Settings::IsGPULevelHigh()) {
  547. return buffer_cache.MustFlushRegion(addr, size);
  548. }
  549. return texture_cache.MustFlushRegion(addr, size) || buffer_cache.MustFlushRegion(addr, size);
  550. }
  551. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  552. if (addr == 0 || size == 0) {
  553. return;
  554. }
  555. texture_cache.InvalidateRegion(addr, size);
  556. pipeline_cache.InvalidateRegion(addr, size);
  557. buffer_cache.InvalidateRegion(addr, size);
  558. query_cache.InvalidateRegion(addr, size);
  559. }
  560. void RasterizerVulkan::OnCPUWrite(VAddr addr, u64 size) {
  561. if (addr == 0 || size == 0) {
  562. return;
  563. }
  564. texture_cache.OnCPUWrite(addr, size);
  565. pipeline_cache.OnCPUWrite(addr, size);
  566. buffer_cache.OnCPUWrite(addr, size);
  567. }
  568. void RasterizerVulkan::SyncGuestHost() {
  569. texture_cache.SyncGuestHost();
  570. buffer_cache.SyncGuestHost();
  571. pipeline_cache.SyncGuestHost();
  572. }
  573. void RasterizerVulkan::SignalSemaphore(GPUVAddr addr, u32 value) {
  574. auto& gpu{system.GPU()};
  575. if (!gpu.IsAsync()) {
  576. gpu.MemoryManager().Write<u32>(addr, value);
  577. return;
  578. }
  579. fence_manager.SignalSemaphore(addr, value);
  580. }
  581. void RasterizerVulkan::SignalSyncPoint(u32 value) {
  582. auto& gpu{system.GPU()};
  583. if (!gpu.IsAsync()) {
  584. gpu.IncrementSyncPoint(value);
  585. return;
  586. }
  587. fence_manager.SignalSyncPoint(value);
  588. }
  589. void RasterizerVulkan::ReleaseFences() {
  590. auto& gpu{system.GPU()};
  591. if (!gpu.IsAsync()) {
  592. return;
  593. }
  594. fence_manager.WaitPendingFences();
  595. }
  596. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  597. if (Settings::IsGPULevelExtreme()) {
  598. FlushRegion(addr, size);
  599. }
  600. InvalidateRegion(addr, size);
  601. }
  602. void RasterizerVulkan::WaitForIdle() {
  603. // Everything but wait pixel operations. This intentionally includes FRAGMENT_SHADER_BIT because
  604. // fragment shaders can still write storage buffers.
  605. VkPipelineStageFlags flags =
  606. VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT |
  607. VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
  608. VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
  609. VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
  610. VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  611. if (device.IsExtTransformFeedbackSupported()) {
  612. flags |= VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT;
  613. }
  614. scheduler.RequestOutsideRenderPassOperationContext();
  615. scheduler.Record([event = *wfi_event, flags](vk::CommandBuffer cmdbuf) {
  616. cmdbuf.SetEvent(event, flags);
  617. cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {});
  618. });
  619. }
  620. void RasterizerVulkan::FlushCommands() {
  621. if (draw_counter > 0) {
  622. draw_counter = 0;
  623. scheduler.Flush();
  624. }
  625. }
  626. void RasterizerVulkan::TickFrame() {
  627. draw_counter = 0;
  628. update_descriptor_queue.TickFrame();
  629. buffer_cache.TickFrame();
  630. staging_pool.TickFrame();
  631. }
  632. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  633. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  634. const Tegra::Engines::Fermi2D::Config& copy_config) {
  635. texture_cache.DoFermiCopy(src, dst, copy_config);
  636. return true;
  637. }
  638. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  639. VAddr framebuffer_addr, u32 pixel_stride) {
  640. if (!framebuffer_addr) {
  641. return false;
  642. }
  643. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  644. if (!surface) {
  645. return false;
  646. }
  647. // Verify that the cached surface is the same size and format as the requested framebuffer
  648. const auto& params{surface->GetSurfaceParams()};
  649. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  650. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  651. screen_info.image = &surface->GetImage();
  652. screen_info.width = params.width;
  653. screen_info.height = params.height;
  654. screen_info.is_srgb = surface->GetSurfaceParams().srgb_conversion;
  655. return true;
  656. }
  657. void RasterizerVulkan::SetupDirtyFlags() {
  658. state_tracker.Initialize();
  659. }
  660. void RasterizerVulkan::FlushWork() {
  661. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  662. // Only check multiples of 8 draws
  663. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  664. if ((++draw_counter & 7) != 7) {
  665. return;
  666. }
  667. if (draw_counter < DRAWS_TO_DISPATCH) {
  668. // Send recorded tasks to the worker thread
  669. scheduler.DispatchWork();
  670. return;
  671. }
  672. // Otherwise (every certain number of draws) flush execution.
  673. // This submits commands to the Vulkan driver.
  674. scheduler.Flush();
  675. draw_counter = 0;
  676. }
  677. RasterizerVulkan::Texceptions RasterizerVulkan::UpdateAttachments(bool is_clear) {
  678. MICROPROFILE_SCOPE(Vulkan_RenderTargets);
  679. auto& maxwell3d = system.GPU().Maxwell3D();
  680. auto& dirty = maxwell3d.dirty.flags;
  681. auto& regs = maxwell3d.regs;
  682. const bool update_rendertargets = dirty[VideoCommon::Dirty::RenderTargets];
  683. dirty[VideoCommon::Dirty::RenderTargets] = false;
  684. texture_cache.GuardRenderTargets(true);
  685. Texceptions texceptions;
  686. for (std::size_t rt = 0; rt < Maxwell::NumRenderTargets; ++rt) {
  687. if (update_rendertargets) {
  688. const bool preserve_contents = HasToPreserveColorContents(is_clear, regs);
  689. color_attachments[rt] = texture_cache.GetColorBufferSurface(rt, preserve_contents);
  690. }
  691. if (color_attachments[rt] && WalkAttachmentOverlaps(*color_attachments[rt])) {
  692. texceptions[rt] = true;
  693. }
  694. }
  695. if (update_rendertargets) {
  696. const bool preserve_contents = HasToPreserveDepthContents(is_clear, regs);
  697. zeta_attachment = texture_cache.GetDepthBufferSurface(preserve_contents);
  698. }
  699. if (zeta_attachment && WalkAttachmentOverlaps(*zeta_attachment)) {
  700. texceptions[ZETA_TEXCEPTION_INDEX] = true;
  701. }
  702. texture_cache.GuardRenderTargets(false);
  703. return texceptions;
  704. }
  705. bool RasterizerVulkan::WalkAttachmentOverlaps(const CachedSurfaceView& attachment) {
  706. bool overlap = false;
  707. for (auto& [view, layout] : sampled_views) {
  708. if (!attachment.IsSameSurface(*view)) {
  709. continue;
  710. }
  711. overlap = true;
  712. *layout = VK_IMAGE_LAYOUT_GENERAL;
  713. }
  714. return overlap;
  715. }
  716. std::tuple<VkFramebuffer, VkExtent2D> RasterizerVulkan::ConfigureFramebuffers(
  717. VkRenderPass renderpass) {
  718. FramebufferCacheKey key{
  719. .renderpass = renderpass,
  720. .width = std::numeric_limits<u32>::max(),
  721. .height = std::numeric_limits<u32>::max(),
  722. .layers = std::numeric_limits<u32>::max(),
  723. .views = {},
  724. };
  725. const auto try_push = [&key](const View& view) {
  726. if (!view) {
  727. return false;
  728. }
  729. key.views.push_back(view->GetAttachment());
  730. key.width = std::min(key.width, view->GetWidth());
  731. key.height = std::min(key.height, view->GetHeight());
  732. key.layers = std::min(key.layers, view->GetNumLayers());
  733. return true;
  734. };
  735. const auto& regs = system.GPU().Maxwell3D().regs;
  736. const std::size_t num_attachments = static_cast<std::size_t>(regs.rt_control.count);
  737. for (std::size_t index = 0; index < num_attachments; ++index) {
  738. if (try_push(color_attachments[index])) {
  739. texture_cache.MarkColorBufferInUse(index);
  740. }
  741. }
  742. if (try_push(zeta_attachment)) {
  743. texture_cache.MarkDepthBufferInUse();
  744. }
  745. const auto [fbentry, is_cache_miss] = framebuffer_cache.try_emplace(key);
  746. auto& framebuffer = fbentry->second;
  747. if (is_cache_miss) {
  748. framebuffer = device.GetLogical().CreateFramebuffer({
  749. .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
  750. .pNext = nullptr,
  751. .flags = 0,
  752. .renderPass = key.renderpass,
  753. .attachmentCount = static_cast<u32>(key.views.size()),
  754. .pAttachments = key.views.data(),
  755. .width = key.width,
  756. .height = key.height,
  757. .layers = key.layers,
  758. });
  759. }
  760. return {*framebuffer, VkExtent2D{key.width, key.height}};
  761. }
  762. RasterizerVulkan::DrawParameters RasterizerVulkan::SetupGeometry(FixedPipelineState& fixed_state,
  763. BufferBindings& buffer_bindings,
  764. bool is_indexed,
  765. bool is_instanced) {
  766. MICROPROFILE_SCOPE(Vulkan_Geometry);
  767. const auto& gpu = system.GPU().Maxwell3D();
  768. const auto& regs = gpu.regs;
  769. SetupVertexArrays(buffer_bindings);
  770. const u32 base_instance = regs.vb_base_instance;
  771. const u32 num_instances = is_instanced ? gpu.mme_draw.instance_count : 1;
  772. const u32 base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first;
  773. const u32 num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count;
  774. DrawParameters params{base_instance, num_instances, base_vertex, num_vertices, is_indexed};
  775. SetupIndexBuffer(buffer_bindings, params, is_indexed);
  776. return params;
  777. }
  778. void RasterizerVulkan::SetupShaderDescriptors(
  779. const std::array<Shader*, Maxwell::MaxShaderProgram>& shaders) {
  780. texture_cache.GuardSamplers(true);
  781. for (std::size_t stage = 0; stage < Maxwell::MaxShaderStage; ++stage) {
  782. // Skip VertexA stage
  783. Shader* const shader = shaders[stage + 1];
  784. if (!shader) {
  785. continue;
  786. }
  787. const auto& entries = shader->GetEntries();
  788. SetupGraphicsConstBuffers(entries, stage);
  789. SetupGraphicsGlobalBuffers(entries, stage);
  790. SetupGraphicsUniformTexels(entries, stage);
  791. SetupGraphicsTextures(entries, stage);
  792. SetupGraphicsStorageTexels(entries, stage);
  793. SetupGraphicsImages(entries, stage);
  794. }
  795. texture_cache.GuardSamplers(false);
  796. }
  797. void RasterizerVulkan::SetupImageTransitions(
  798. Texceptions texceptions, const std::array<View, Maxwell::NumRenderTargets>& color_attachments,
  799. const View& zeta_attachment) {
  800. TransitionImages(sampled_views, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT);
  801. TransitionImages(image_views, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
  802. VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
  803. for (std::size_t rt = 0; rt < std::size(color_attachments); ++rt) {
  804. const auto color_attachment = color_attachments[rt];
  805. if (color_attachment == nullptr) {
  806. continue;
  807. }
  808. const auto image_layout =
  809. texceptions[rt] ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  810. color_attachment->Transition(image_layout, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  811. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  812. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
  813. }
  814. if (zeta_attachment != nullptr) {
  815. const auto image_layout = texceptions[ZETA_TEXCEPTION_INDEX]
  816. ? VK_IMAGE_LAYOUT_GENERAL
  817. : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  818. zeta_attachment->Transition(image_layout, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
  819. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  820. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
  821. }
  822. }
  823. void RasterizerVulkan::UpdateDynamicStates() {
  824. auto& regs = system.GPU().Maxwell3D().regs;
  825. UpdateViewportsState(regs);
  826. UpdateScissorsState(regs);
  827. UpdateDepthBias(regs);
  828. UpdateBlendConstants(regs);
  829. UpdateDepthBounds(regs);
  830. UpdateStencilFaces(regs);
  831. if (device.IsExtExtendedDynamicStateSupported()) {
  832. UpdateCullMode(regs);
  833. UpdateDepthBoundsTestEnable(regs);
  834. UpdateDepthTestEnable(regs);
  835. UpdateDepthWriteEnable(regs);
  836. UpdateDepthCompareOp(regs);
  837. UpdateFrontFace(regs);
  838. UpdatePrimitiveTopology(regs);
  839. UpdateStencilOp(regs);
  840. UpdateStencilTestEnable(regs);
  841. }
  842. }
  843. void RasterizerVulkan::BeginTransformFeedback() {
  844. const auto& regs = system.GPU().Maxwell3D().regs;
  845. if (regs.tfb_enabled == 0) {
  846. return;
  847. }
  848. if (!device.IsExtTransformFeedbackSupported()) {
  849. LOG_ERROR(Render_Vulkan, "Transform feedbacks used but not supported");
  850. return;
  851. }
  852. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  853. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  854. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  855. UNIMPLEMENTED_IF(regs.tfb_bindings[1].buffer_enable);
  856. UNIMPLEMENTED_IF(regs.tfb_bindings[2].buffer_enable);
  857. UNIMPLEMENTED_IF(regs.tfb_bindings[3].buffer_enable);
  858. const auto& binding = regs.tfb_bindings[0];
  859. UNIMPLEMENTED_IF(binding.buffer_enable == 0);
  860. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  861. const GPUVAddr gpu_addr = binding.Address();
  862. const VkDeviceSize size = static_cast<VkDeviceSize>(binding.buffer_size);
  863. const auto info = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  864. scheduler.Record([buffer = info.handle, offset = info.offset, size](vk::CommandBuffer cmdbuf) {
  865. cmdbuf.BindTransformFeedbackBuffersEXT(0, 1, &buffer, &offset, &size);
  866. cmdbuf.BeginTransformFeedbackEXT(0, 0, nullptr, nullptr);
  867. });
  868. }
  869. void RasterizerVulkan::EndTransformFeedback() {
  870. const auto& regs = system.GPU().Maxwell3D().regs;
  871. if (regs.tfb_enabled == 0) {
  872. return;
  873. }
  874. if (!device.IsExtTransformFeedbackSupported()) {
  875. return;
  876. }
  877. scheduler.Record(
  878. [](vk::CommandBuffer cmdbuf) { cmdbuf.EndTransformFeedbackEXT(0, 0, nullptr, nullptr); });
  879. }
  880. void RasterizerVulkan::SetupVertexArrays(BufferBindings& buffer_bindings) {
  881. const auto& regs = system.GPU().Maxwell3D().regs;
  882. for (std::size_t index = 0; index < Maxwell::NumVertexArrays; ++index) {
  883. const auto& vertex_array = regs.vertex_array[index];
  884. if (!vertex_array.IsEnabled()) {
  885. continue;
  886. }
  887. const GPUVAddr start{vertex_array.StartAddress()};
  888. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  889. ASSERT(end >= start);
  890. const std::size_t size = end - start;
  891. if (size == 0) {
  892. buffer_bindings.AddVertexBinding(DefaultBuffer(), 0, DEFAULT_BUFFER_SIZE, 0);
  893. continue;
  894. }
  895. const auto info = buffer_cache.UploadMemory(start, size);
  896. buffer_bindings.AddVertexBinding(info.handle, info.offset, size, vertex_array.stride);
  897. }
  898. }
  899. void RasterizerVulkan::SetupIndexBuffer(BufferBindings& buffer_bindings, DrawParameters& params,
  900. bool is_indexed) {
  901. if (params.num_vertices == 0) {
  902. return;
  903. }
  904. const auto& regs = system.GPU().Maxwell3D().regs;
  905. switch (regs.draw.topology) {
  906. case Maxwell::PrimitiveTopology::Quads: {
  907. if (!params.is_indexed) {
  908. const auto [buffer, offset] =
  909. quad_array_pass.Assemble(params.num_vertices, params.base_vertex);
  910. buffer_bindings.SetIndexBinding(buffer, offset, VK_INDEX_TYPE_UINT32);
  911. params.base_vertex = 0;
  912. params.num_vertices = params.num_vertices * 6 / 4;
  913. params.is_indexed = true;
  914. break;
  915. }
  916. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  917. const auto info = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  918. VkBuffer buffer = info.handle;
  919. u64 offset = info.offset;
  920. std::tie(buffer, offset) = quad_indexed_pass.Assemble(
  921. regs.index_array.format, params.num_vertices, params.base_vertex, buffer, offset);
  922. buffer_bindings.SetIndexBinding(buffer, offset, VK_INDEX_TYPE_UINT32);
  923. params.num_vertices = (params.num_vertices / 4) * 6;
  924. params.base_vertex = 0;
  925. break;
  926. }
  927. default: {
  928. if (!is_indexed) {
  929. break;
  930. }
  931. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  932. const auto info = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  933. VkBuffer buffer = info.handle;
  934. u64 offset = info.offset;
  935. auto format = regs.index_array.format;
  936. const bool is_uint8 = format == Maxwell::IndexFormat::UnsignedByte;
  937. if (is_uint8 && !device.IsExtIndexTypeUint8Supported()) {
  938. std::tie(buffer, offset) = uint8_pass.Assemble(params.num_vertices, buffer, offset);
  939. format = Maxwell::IndexFormat::UnsignedShort;
  940. }
  941. buffer_bindings.SetIndexBinding(buffer, offset, MaxwellToVK::IndexFormat(device, format));
  942. break;
  943. }
  944. }
  945. }
  946. void RasterizerVulkan::SetupGraphicsConstBuffers(const ShaderEntries& entries, std::size_t stage) {
  947. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  948. const auto& gpu = system.GPU().Maxwell3D();
  949. const auto& shader_stage = gpu.state.shader_stages[stage];
  950. for (const auto& entry : entries.const_buffers) {
  951. SetupConstBuffer(entry, shader_stage.const_buffers[entry.GetIndex()]);
  952. }
  953. }
  954. void RasterizerVulkan::SetupGraphicsGlobalBuffers(const ShaderEntries& entries, std::size_t stage) {
  955. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  956. auto& gpu{system.GPU()};
  957. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage]};
  958. for (const auto& entry : entries.global_buffers) {
  959. const auto addr = cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset();
  960. SetupGlobalBuffer(entry, addr);
  961. }
  962. }
  963. void RasterizerVulkan::SetupGraphicsUniformTexels(const ShaderEntries& entries, std::size_t stage) {
  964. MICROPROFILE_SCOPE(Vulkan_Textures);
  965. const auto& gpu = system.GPU().Maxwell3D();
  966. for (const auto& entry : entries.uniform_texels) {
  967. const auto image = GetTextureInfo(gpu, entry, stage).tic;
  968. SetupUniformTexels(image, entry);
  969. }
  970. }
  971. void RasterizerVulkan::SetupGraphicsTextures(const ShaderEntries& entries, std::size_t stage) {
  972. MICROPROFILE_SCOPE(Vulkan_Textures);
  973. const auto& gpu = system.GPU().Maxwell3D();
  974. for (const auto& entry : entries.samplers) {
  975. for (std::size_t i = 0; i < entry.size; ++i) {
  976. const auto texture = GetTextureInfo(gpu, entry, stage, i);
  977. SetupTexture(texture, entry);
  978. }
  979. }
  980. }
  981. void RasterizerVulkan::SetupGraphicsStorageTexels(const ShaderEntries& entries, std::size_t stage) {
  982. MICROPROFILE_SCOPE(Vulkan_Textures);
  983. const auto& gpu = system.GPU().Maxwell3D();
  984. for (const auto& entry : entries.storage_texels) {
  985. const auto image = GetTextureInfo(gpu, entry, stage).tic;
  986. SetupStorageTexel(image, entry);
  987. }
  988. }
  989. void RasterizerVulkan::SetupGraphicsImages(const ShaderEntries& entries, std::size_t stage) {
  990. MICROPROFILE_SCOPE(Vulkan_Images);
  991. const auto& gpu = system.GPU().Maxwell3D();
  992. for (const auto& entry : entries.images) {
  993. const auto tic = GetTextureInfo(gpu, entry, stage).tic;
  994. SetupImage(tic, entry);
  995. }
  996. }
  997. void RasterizerVulkan::SetupComputeConstBuffers(const ShaderEntries& entries) {
  998. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  999. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  1000. for (const auto& entry : entries.const_buffers) {
  1001. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  1002. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  1003. Tegra::Engines::ConstBufferInfo buffer;
  1004. buffer.address = config.Address();
  1005. buffer.size = config.size;
  1006. buffer.enabled = mask[entry.GetIndex()];
  1007. SetupConstBuffer(entry, buffer);
  1008. }
  1009. }
  1010. void RasterizerVulkan::SetupComputeGlobalBuffers(const ShaderEntries& entries) {
  1011. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  1012. const auto cbufs{system.GPU().KeplerCompute().launch_description.const_buffer_config};
  1013. for (const auto& entry : entries.global_buffers) {
  1014. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  1015. SetupGlobalBuffer(entry, addr);
  1016. }
  1017. }
  1018. void RasterizerVulkan::SetupComputeUniformTexels(const ShaderEntries& entries) {
  1019. MICROPROFILE_SCOPE(Vulkan_Textures);
  1020. const auto& gpu = system.GPU().KeplerCompute();
  1021. for (const auto& entry : entries.uniform_texels) {
  1022. const auto image = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  1023. SetupUniformTexels(image, entry);
  1024. }
  1025. }
  1026. void RasterizerVulkan::SetupComputeTextures(const ShaderEntries& entries) {
  1027. MICROPROFILE_SCOPE(Vulkan_Textures);
  1028. const auto& gpu = system.GPU().KeplerCompute();
  1029. for (const auto& entry : entries.samplers) {
  1030. for (std::size_t i = 0; i < entry.size; ++i) {
  1031. const auto texture = GetTextureInfo(gpu, entry, ComputeShaderIndex, i);
  1032. SetupTexture(texture, entry);
  1033. }
  1034. }
  1035. }
  1036. void RasterizerVulkan::SetupComputeStorageTexels(const ShaderEntries& entries) {
  1037. MICROPROFILE_SCOPE(Vulkan_Textures);
  1038. const auto& gpu = system.GPU().KeplerCompute();
  1039. for (const auto& entry : entries.storage_texels) {
  1040. const auto image = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  1041. SetupStorageTexel(image, entry);
  1042. }
  1043. }
  1044. void RasterizerVulkan::SetupComputeImages(const ShaderEntries& entries) {
  1045. MICROPROFILE_SCOPE(Vulkan_Images);
  1046. const auto& gpu = system.GPU().KeplerCompute();
  1047. for (const auto& entry : entries.images) {
  1048. const auto tic = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  1049. SetupImage(tic, entry);
  1050. }
  1051. }
  1052. void RasterizerVulkan::SetupConstBuffer(const ConstBufferEntry& entry,
  1053. const Tegra::Engines::ConstBufferInfo& buffer) {
  1054. if (!buffer.enabled) {
  1055. // Set values to zero to unbind buffers
  1056. update_descriptor_queue.AddBuffer(DefaultBuffer(), 0, DEFAULT_BUFFER_SIZE);
  1057. return;
  1058. }
  1059. // Align the size to avoid bad std140 interactions
  1060. const std::size_t size =
  1061. Common::AlignUp(CalculateConstBufferSize(entry, buffer), 4 * sizeof(float));
  1062. ASSERT(size <= MaxConstbufferSize);
  1063. const auto info =
  1064. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  1065. update_descriptor_queue.AddBuffer(info.handle, info.offset, size);
  1066. }
  1067. void RasterizerVulkan::SetupGlobalBuffer(const GlobalBufferEntry& entry, GPUVAddr address) {
  1068. auto& memory_manager{system.GPU().MemoryManager()};
  1069. const auto actual_addr = memory_manager.Read<u64>(address);
  1070. const auto size = memory_manager.Read<u32>(address + 8);
  1071. if (size == 0) {
  1072. // Sometimes global memory pointers don't have a proper size. Upload a dummy entry
  1073. // because Vulkan doesn't like empty buffers.
  1074. // Note: Do *not* use DefaultBuffer() here, storage buffers can be written breaking the
  1075. // default buffer.
  1076. static constexpr std::size_t dummy_size = 4;
  1077. const auto info = buffer_cache.GetEmptyBuffer(dummy_size);
  1078. update_descriptor_queue.AddBuffer(info.handle, info.offset, dummy_size);
  1079. return;
  1080. }
  1081. const auto info = buffer_cache.UploadMemory(
  1082. actual_addr, size, device.GetStorageBufferAlignment(), entry.IsWritten());
  1083. update_descriptor_queue.AddBuffer(info.handle, info.offset, size);
  1084. }
  1085. void RasterizerVulkan::SetupUniformTexels(const Tegra::Texture::TICEntry& tic,
  1086. const UniformTexelEntry& entry) {
  1087. const auto view = texture_cache.GetTextureSurface(tic, entry);
  1088. ASSERT(view->IsBufferView());
  1089. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  1090. }
  1091. void RasterizerVulkan::SetupTexture(const Tegra::Texture::FullTextureInfo& texture,
  1092. const SamplerEntry& entry) {
  1093. auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  1094. ASSERT(!view->IsBufferView());
  1095. const VkImageView image_view = view->GetImageView(texture.tic.x_source, texture.tic.y_source,
  1096. texture.tic.z_source, texture.tic.w_source);
  1097. const auto sampler = sampler_cache.GetSampler(texture.tsc);
  1098. update_descriptor_queue.AddSampledImage(sampler, image_view);
  1099. VkImageLayout* const image_layout = update_descriptor_queue.LastImageLayout();
  1100. *image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1101. sampled_views.push_back(ImageView{std::move(view), image_layout});
  1102. }
  1103. void RasterizerVulkan::SetupStorageTexel(const Tegra::Texture::TICEntry& tic,
  1104. const StorageTexelEntry& entry) {
  1105. const auto view = texture_cache.GetImageSurface(tic, entry);
  1106. ASSERT(view->IsBufferView());
  1107. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  1108. }
  1109. void RasterizerVulkan::SetupImage(const Tegra::Texture::TICEntry& tic, const ImageEntry& entry) {
  1110. auto view = texture_cache.GetImageSurface(tic, entry);
  1111. if (entry.is_written) {
  1112. view->MarkAsModified(texture_cache.Tick());
  1113. }
  1114. UNIMPLEMENTED_IF(tic.IsBuffer());
  1115. const VkImageView image_view =
  1116. view->GetImageView(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  1117. update_descriptor_queue.AddImage(image_view);
  1118. VkImageLayout* const image_layout = update_descriptor_queue.LastImageLayout();
  1119. *image_layout = VK_IMAGE_LAYOUT_GENERAL;
  1120. image_views.push_back(ImageView{std::move(view), image_layout});
  1121. }
  1122. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  1123. if (!state_tracker.TouchViewports()) {
  1124. return;
  1125. }
  1126. const std::array viewports{
  1127. GetViewportState(device, regs, 0), GetViewportState(device, regs, 1),
  1128. GetViewportState(device, regs, 2), GetViewportState(device, regs, 3),
  1129. GetViewportState(device, regs, 4), GetViewportState(device, regs, 5),
  1130. GetViewportState(device, regs, 6), GetViewportState(device, regs, 7),
  1131. GetViewportState(device, regs, 8), GetViewportState(device, regs, 9),
  1132. GetViewportState(device, regs, 10), GetViewportState(device, regs, 11),
  1133. GetViewportState(device, regs, 12), GetViewportState(device, regs, 13),
  1134. GetViewportState(device, regs, 14), GetViewportState(device, regs, 15)};
  1135. scheduler.Record([viewports](vk::CommandBuffer cmdbuf) { cmdbuf.SetViewport(0, viewports); });
  1136. }
  1137. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  1138. if (!state_tracker.TouchScissors()) {
  1139. return;
  1140. }
  1141. const std::array scissors = {
  1142. GetScissorState(regs, 0), GetScissorState(regs, 1), GetScissorState(regs, 2),
  1143. GetScissorState(regs, 3), GetScissorState(regs, 4), GetScissorState(regs, 5),
  1144. GetScissorState(regs, 6), GetScissorState(regs, 7), GetScissorState(regs, 8),
  1145. GetScissorState(regs, 9), GetScissorState(regs, 10), GetScissorState(regs, 11),
  1146. GetScissorState(regs, 12), GetScissorState(regs, 13), GetScissorState(regs, 14),
  1147. GetScissorState(regs, 15)};
  1148. scheduler.Record([scissors](vk::CommandBuffer cmdbuf) { cmdbuf.SetScissor(0, scissors); });
  1149. }
  1150. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  1151. if (!state_tracker.TouchDepthBias()) {
  1152. return;
  1153. }
  1154. scheduler.Record([constant = regs.polygon_offset_units, clamp = regs.polygon_offset_clamp,
  1155. factor = regs.polygon_offset_factor](vk::CommandBuffer cmdbuf) {
  1156. cmdbuf.SetDepthBias(constant, clamp, factor / 2.0f);
  1157. });
  1158. }
  1159. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  1160. if (!state_tracker.TouchBlendConstants()) {
  1161. return;
  1162. }
  1163. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1164. regs.blend_color.a};
  1165. scheduler.Record(
  1166. [blend_color](vk::CommandBuffer cmdbuf) { cmdbuf.SetBlendConstants(blend_color.data()); });
  1167. }
  1168. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  1169. if (!state_tracker.TouchDepthBounds()) {
  1170. return;
  1171. }
  1172. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  1173. vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthBounds(min, max); });
  1174. }
  1175. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  1176. if (!state_tracker.TouchStencilProperties()) {
  1177. return;
  1178. }
  1179. if (regs.stencil_two_side_enable) {
  1180. // Separate values per face
  1181. scheduler.Record(
  1182. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  1183. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  1184. back_write_mask = regs.stencil_back_mask,
  1185. back_test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  1186. // Front face
  1187. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_BIT, front_ref);
  1188. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_BIT, front_write_mask);
  1189. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_BIT, front_test_mask);
  1190. // Back face
  1191. cmdbuf.SetStencilReference(VK_STENCIL_FACE_BACK_BIT, back_ref);
  1192. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_BACK_BIT, back_write_mask);
  1193. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_BACK_BIT, back_test_mask);
  1194. });
  1195. } else {
  1196. // Front face defines both faces
  1197. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  1198. test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  1199. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_AND_BACK, ref);
  1200. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_AND_BACK, write_mask);
  1201. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_AND_BACK, test_mask);
  1202. });
  1203. }
  1204. }
  1205. void RasterizerVulkan::UpdateCullMode(Tegra::Engines::Maxwell3D::Regs& regs) {
  1206. if (!state_tracker.TouchCullMode()) {
  1207. return;
  1208. }
  1209. scheduler.Record(
  1210. [enabled = regs.cull_test_enabled, cull_face = regs.cull_face](vk::CommandBuffer cmdbuf) {
  1211. cmdbuf.SetCullModeEXT(enabled ? MaxwellToVK::CullFace(cull_face) : VK_CULL_MODE_NONE);
  1212. });
  1213. }
  1214. void RasterizerVulkan::UpdateDepthBoundsTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1215. if (!state_tracker.TouchDepthBoundsTestEnable()) {
  1216. return;
  1217. }
  1218. scheduler.Record([enable = regs.depth_bounds_enable](vk::CommandBuffer cmdbuf) {
  1219. cmdbuf.SetDepthBoundsTestEnableEXT(enable);
  1220. });
  1221. }
  1222. void RasterizerVulkan::UpdateDepthTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1223. if (!state_tracker.TouchDepthTestEnable()) {
  1224. return;
  1225. }
  1226. scheduler.Record([enable = regs.depth_test_enable](vk::CommandBuffer cmdbuf) {
  1227. cmdbuf.SetDepthTestEnableEXT(enable);
  1228. });
  1229. }
  1230. void RasterizerVulkan::UpdateDepthWriteEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1231. if (!state_tracker.TouchDepthWriteEnable()) {
  1232. return;
  1233. }
  1234. scheduler.Record([enable = regs.depth_write_enabled](vk::CommandBuffer cmdbuf) {
  1235. cmdbuf.SetDepthWriteEnableEXT(enable);
  1236. });
  1237. }
  1238. void RasterizerVulkan::UpdateDepthCompareOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1239. if (!state_tracker.TouchDepthCompareOp()) {
  1240. return;
  1241. }
  1242. scheduler.Record([func = regs.depth_test_func](vk::CommandBuffer cmdbuf) {
  1243. cmdbuf.SetDepthCompareOpEXT(MaxwellToVK::ComparisonOp(func));
  1244. });
  1245. }
  1246. void RasterizerVulkan::UpdateFrontFace(Tegra::Engines::Maxwell3D::Regs& regs) {
  1247. if (!state_tracker.TouchFrontFace()) {
  1248. return;
  1249. }
  1250. VkFrontFace front_face = MaxwellToVK::FrontFace(regs.front_face);
  1251. if (regs.screen_y_control.triangle_rast_flip != 0) {
  1252. front_face = front_face == VK_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_COUNTER_CLOCKWISE
  1253. : VK_FRONT_FACE_CLOCKWISE;
  1254. }
  1255. scheduler.Record(
  1256. [front_face](vk::CommandBuffer cmdbuf) { cmdbuf.SetFrontFaceEXT(front_face); });
  1257. }
  1258. void RasterizerVulkan::UpdatePrimitiveTopology(Tegra::Engines::Maxwell3D::Regs& regs) {
  1259. if (!state_tracker.TouchPrimitiveTopology()) {
  1260. return;
  1261. }
  1262. const Maxwell::PrimitiveTopology primitive_topology = regs.draw.topology.Value();
  1263. scheduler.Record([this, primitive_topology](vk::CommandBuffer cmdbuf) {
  1264. cmdbuf.SetPrimitiveTopologyEXT(MaxwellToVK::PrimitiveTopology(device, primitive_topology));
  1265. });
  1266. }
  1267. void RasterizerVulkan::UpdateStencilOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1268. if (!state_tracker.TouchStencilOp()) {
  1269. return;
  1270. }
  1271. const Maxwell::StencilOp fail = regs.stencil_front_op_fail;
  1272. const Maxwell::StencilOp zfail = regs.stencil_front_op_zfail;
  1273. const Maxwell::StencilOp zpass = regs.stencil_front_op_zpass;
  1274. const Maxwell::ComparisonOp compare = regs.stencil_front_func_func;
  1275. if (regs.stencil_two_side_enable) {
  1276. scheduler.Record([fail, zfail, zpass, compare](vk::CommandBuffer cmdbuf) {
  1277. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_AND_BACK, MaxwellToVK::StencilOp(fail),
  1278. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1279. MaxwellToVK::ComparisonOp(compare));
  1280. });
  1281. } else {
  1282. const Maxwell::StencilOp back_fail = regs.stencil_back_op_fail;
  1283. const Maxwell::StencilOp back_zfail = regs.stencil_back_op_zfail;
  1284. const Maxwell::StencilOp back_zpass = regs.stencil_back_op_zpass;
  1285. const Maxwell::ComparisonOp back_compare = regs.stencil_back_func_func;
  1286. scheduler.Record([fail, zfail, zpass, compare, back_fail, back_zfail, back_zpass,
  1287. back_compare](vk::CommandBuffer cmdbuf) {
  1288. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_BIT, MaxwellToVK::StencilOp(fail),
  1289. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1290. MaxwellToVK::ComparisonOp(compare));
  1291. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_BACK_BIT, MaxwellToVK::StencilOp(back_fail),
  1292. MaxwellToVK::StencilOp(back_zpass),
  1293. MaxwellToVK::StencilOp(back_zfail),
  1294. MaxwellToVK::ComparisonOp(back_compare));
  1295. });
  1296. }
  1297. }
  1298. void RasterizerVulkan::UpdateStencilTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1299. if (!state_tracker.TouchStencilTestEnable()) {
  1300. return;
  1301. }
  1302. scheduler.Record([enable = regs.stencil_enable](vk::CommandBuffer cmdbuf) {
  1303. cmdbuf.SetStencilTestEnableEXT(enable);
  1304. });
  1305. }
  1306. std::size_t RasterizerVulkan::CalculateGraphicsStreamBufferSize(bool is_indexed) const {
  1307. std::size_t size = CalculateVertexArraysSize();
  1308. if (is_indexed) {
  1309. size = Common::AlignUp(size, 4) + CalculateIndexBufferSize();
  1310. }
  1311. size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  1312. return size;
  1313. }
  1314. std::size_t RasterizerVulkan::CalculateComputeStreamBufferSize() const {
  1315. return Tegra::Engines::KeplerCompute::NumConstBuffers *
  1316. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  1317. }
  1318. std::size_t RasterizerVulkan::CalculateVertexArraysSize() const {
  1319. const auto& regs = system.GPU().Maxwell3D().regs;
  1320. std::size_t size = 0;
  1321. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  1322. // This implementation assumes that all attributes are used in the shader.
  1323. const GPUVAddr start{regs.vertex_array[index].StartAddress()};
  1324. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  1325. DEBUG_ASSERT(end >= start);
  1326. size += (end - start) * regs.vertex_array[index].enable;
  1327. }
  1328. return size;
  1329. }
  1330. std::size_t RasterizerVulkan::CalculateIndexBufferSize() const {
  1331. const auto& regs = system.GPU().Maxwell3D().regs;
  1332. return static_cast<std::size_t>(regs.index_array.count) *
  1333. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  1334. }
  1335. std::size_t RasterizerVulkan::CalculateConstBufferSize(
  1336. const ConstBufferEntry& entry, const Tegra::Engines::ConstBufferInfo& buffer) const {
  1337. if (entry.IsIndirect()) {
  1338. // Buffer is accessed indirectly, so upload the entire thing
  1339. return buffer.size;
  1340. } else {
  1341. // Buffer is accessed directly, upload just what we use
  1342. return entry.GetSize();
  1343. }
  1344. }
  1345. RenderPassParams RasterizerVulkan::GetRenderPassParams(Texceptions texceptions) const {
  1346. const auto& regs = system.GPU().Maxwell3D().regs;
  1347. const std::size_t num_attachments = static_cast<std::size_t>(regs.rt_control.count);
  1348. RenderPassParams params;
  1349. params.color_formats = {};
  1350. std::size_t color_texceptions = 0;
  1351. std::size_t index = 0;
  1352. for (std::size_t rt = 0; rt < num_attachments; ++rt) {
  1353. const auto& rendertarget = regs.rt[rt];
  1354. if (rendertarget.Address() == 0 || rendertarget.format == Tegra::RenderTargetFormat::NONE) {
  1355. continue;
  1356. }
  1357. params.color_formats[index] = static_cast<u8>(rendertarget.format);
  1358. color_texceptions |= (texceptions[rt] ? 1ULL : 0ULL) << index;
  1359. ++index;
  1360. }
  1361. params.num_color_attachments = static_cast<u8>(index);
  1362. params.texceptions = static_cast<u8>(color_texceptions);
  1363. params.zeta_format = regs.zeta_enable ? static_cast<u8>(regs.zeta.format) : 0;
  1364. params.zeta_texception = texceptions[ZETA_TEXCEPTION_INDEX];
  1365. return params;
  1366. }
  1367. VkBuffer RasterizerVulkan::DefaultBuffer() {
  1368. if (default_buffer) {
  1369. return *default_buffer;
  1370. }
  1371. default_buffer = device.GetLogical().CreateBuffer({
  1372. .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
  1373. .pNext = nullptr,
  1374. .flags = 0,
  1375. .size = DEFAULT_BUFFER_SIZE,
  1376. .usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
  1377. VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
  1378. .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
  1379. .queueFamilyIndexCount = 0,
  1380. .pQueueFamilyIndices = nullptr,
  1381. });
  1382. default_buffer_commit = memory_manager.Commit(default_buffer, false);
  1383. scheduler.RequestOutsideRenderPassOperationContext();
  1384. scheduler.Record([buffer = *default_buffer](vk::CommandBuffer cmdbuf) {
  1385. cmdbuf.FillBuffer(buffer, 0, DEFAULT_BUFFER_SIZE, 0);
  1386. });
  1387. return *default_buffer;
  1388. }
  1389. } // namespace Vulkan