vk_rasterizer.cpp 53 KB

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