vk_rasterizer.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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 <boost/functional/hash.hpp>
  11. #include "common/alignment.h"
  12. #include "common/assert.h"
  13. #include "common/logging/log.h"
  14. #include "common/microprofile.h"
  15. #include "core/core.h"
  16. #include "core/memory.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/renderer_vulkan/declarations.h"
  20. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  21. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  22. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  23. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  24. #include "video_core/renderer_vulkan/vk_compute_pass.h"
  25. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  26. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  27. #include "video_core/renderer_vulkan/vk_device.h"
  28. #include "video_core/renderer_vulkan/vk_graphics_pipeline.h"
  29. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  30. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  31. #include "video_core/renderer_vulkan/vk_renderpass_cache.h"
  32. #include "video_core/renderer_vulkan/vk_resource_manager.h"
  33. #include "video_core/renderer_vulkan/vk_sampler_cache.h"
  34. #include "video_core/renderer_vulkan/vk_scheduler.h"
  35. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  36. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  37. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  38. #include "video_core/renderer_vulkan/vk_update_descriptor.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. vk::Viewport GetViewportState(const VKDevice& device, const Maxwell& regs, std::size_t index) {
  55. const auto& viewport = regs.viewport_transform[index];
  56. const float x = viewport.translate_x - viewport.scale_x;
  57. const float y = viewport.translate_y - viewport.scale_y;
  58. const float width = viewport.scale_x * 2.0f;
  59. const float height = viewport.scale_y * 2.0f;
  60. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  61. float near = viewport.translate_z - viewport.scale_z * reduce_z;
  62. float far = viewport.translate_z + viewport.scale_z;
  63. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  64. near = std::clamp(near, 0.0f, 1.0f);
  65. far = std::clamp(far, 0.0f, 1.0f);
  66. }
  67. return vk::Viewport(x, y, width != 0 ? width : 1.0f, height != 0 ? height : 1.0f, near, far);
  68. }
  69. constexpr vk::Rect2D GetScissorState(const Maxwell& regs, std::size_t index) {
  70. const auto& scissor = regs.scissor_test[index];
  71. if (!scissor.enable) {
  72. return {{0, 0}, {INT32_MAX, INT32_MAX}};
  73. }
  74. const u32 width = scissor.max_x - scissor.min_x;
  75. const u32 height = scissor.max_y - scissor.min_y;
  76. return {{static_cast<s32>(scissor.min_x), static_cast<s32>(scissor.min_y)}, {width, height}};
  77. }
  78. std::array<GPUVAddr, Maxwell::MaxShaderProgram> GetShaderAddresses(
  79. const std::array<Shader, Maxwell::MaxShaderProgram>& shaders) {
  80. std::array<GPUVAddr, Maxwell::MaxShaderProgram> addresses;
  81. for (std::size_t i = 0; i < std::size(addresses); ++i) {
  82. addresses[i] = shaders[i] ? shaders[i]->GetGpuAddr() : 0;
  83. }
  84. return addresses;
  85. }
  86. void TransitionImages(const std::vector<ImageView>& views, vk::PipelineStageFlags pipeline_stage,
  87. vk::AccessFlags access) {
  88. for (auto& [view, layout] : views) {
  89. view->Transition(*layout, pipeline_stage, access);
  90. }
  91. }
  92. template <typename Engine, typename Entry>
  93. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  94. std::size_t stage, std::size_t index = 0) {
  95. const auto stage_type = static_cast<Tegra::Engines::ShaderType>(stage);
  96. if (entry.IsBindless()) {
  97. const Tegra::Texture::TextureHandle tex_handle =
  98. engine.AccessConstBuffer32(stage_type, entry.GetBuffer(), entry.GetOffset());
  99. return engine.GetTextureInfo(tex_handle);
  100. }
  101. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  102. const u32 entry_offset = static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  103. const u32 offset = entry.GetOffset() + entry_offset;
  104. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  105. return engine.GetStageTexture(stage_type, offset);
  106. } else {
  107. return engine.GetTexture(offset);
  108. }
  109. }
  110. } // Anonymous namespace
  111. class BufferBindings final {
  112. public:
  113. void AddVertexBinding(const vk::Buffer* buffer, vk::DeviceSize offset) {
  114. vertex.buffer_ptrs[vertex.num_buffers] = buffer;
  115. vertex.offsets[vertex.num_buffers] = offset;
  116. ++vertex.num_buffers;
  117. }
  118. void SetIndexBinding(const vk::Buffer* buffer, vk::DeviceSize offset, vk::IndexType type) {
  119. index.buffer = buffer;
  120. index.offset = offset;
  121. index.type = type;
  122. }
  123. void Bind(VKScheduler& scheduler) const {
  124. // Use this large switch case to avoid dispatching more memory in the record lambda than
  125. // what we need. It looks horrible, but it's the best we can do on standard C++.
  126. switch (vertex.num_buffers) {
  127. case 0:
  128. return BindStatic<0>(scheduler);
  129. case 1:
  130. return BindStatic<1>(scheduler);
  131. case 2:
  132. return BindStatic<2>(scheduler);
  133. case 3:
  134. return BindStatic<3>(scheduler);
  135. case 4:
  136. return BindStatic<4>(scheduler);
  137. case 5:
  138. return BindStatic<5>(scheduler);
  139. case 6:
  140. return BindStatic<6>(scheduler);
  141. case 7:
  142. return BindStatic<7>(scheduler);
  143. case 8:
  144. return BindStatic<8>(scheduler);
  145. case 9:
  146. return BindStatic<9>(scheduler);
  147. case 10:
  148. return BindStatic<10>(scheduler);
  149. case 11:
  150. return BindStatic<11>(scheduler);
  151. case 12:
  152. return BindStatic<12>(scheduler);
  153. case 13:
  154. return BindStatic<13>(scheduler);
  155. case 14:
  156. return BindStatic<14>(scheduler);
  157. case 15:
  158. return BindStatic<15>(scheduler);
  159. case 16:
  160. return BindStatic<16>(scheduler);
  161. case 17:
  162. return BindStatic<17>(scheduler);
  163. case 18:
  164. return BindStatic<18>(scheduler);
  165. case 19:
  166. return BindStatic<19>(scheduler);
  167. case 20:
  168. return BindStatic<20>(scheduler);
  169. case 21:
  170. return BindStatic<21>(scheduler);
  171. case 22:
  172. return BindStatic<22>(scheduler);
  173. case 23:
  174. return BindStatic<23>(scheduler);
  175. case 24:
  176. return BindStatic<24>(scheduler);
  177. case 25:
  178. return BindStatic<25>(scheduler);
  179. case 26:
  180. return BindStatic<26>(scheduler);
  181. case 27:
  182. return BindStatic<27>(scheduler);
  183. case 28:
  184. return BindStatic<28>(scheduler);
  185. case 29:
  186. return BindStatic<29>(scheduler);
  187. case 30:
  188. return BindStatic<30>(scheduler);
  189. case 31:
  190. return BindStatic<31>(scheduler);
  191. case 32:
  192. return BindStatic<32>(scheduler);
  193. }
  194. UNREACHABLE();
  195. }
  196. private:
  197. // Some of these fields are intentionally left uninitialized to avoid initializing them twice.
  198. struct {
  199. std::size_t num_buffers = 0;
  200. std::array<const vk::Buffer*, Maxwell::NumVertexArrays> buffer_ptrs;
  201. std::array<vk::DeviceSize, Maxwell::NumVertexArrays> offsets;
  202. } vertex;
  203. struct {
  204. const vk::Buffer* buffer = nullptr;
  205. vk::DeviceSize offset;
  206. vk::IndexType type;
  207. } index;
  208. template <std::size_t N>
  209. void BindStatic(VKScheduler& scheduler) const {
  210. if (index.buffer != nullptr) {
  211. BindStatic<N, true>(scheduler);
  212. } else {
  213. BindStatic<N, false>(scheduler);
  214. }
  215. }
  216. template <std::size_t N, bool is_indexed>
  217. void BindStatic(VKScheduler& scheduler) const {
  218. static_assert(N <= Maxwell::NumVertexArrays);
  219. if constexpr (N == 0) {
  220. return;
  221. }
  222. std::array<vk::Buffer, N> buffers;
  223. std::transform(vertex.buffer_ptrs.begin(), vertex.buffer_ptrs.begin() + N, buffers.begin(),
  224. [](const auto ptr) { return *ptr; });
  225. std::array<vk::DeviceSize, N> offsets;
  226. std::copy(vertex.offsets.begin(), vertex.offsets.begin() + N, offsets.begin());
  227. if constexpr (is_indexed) {
  228. // Indexed draw
  229. scheduler.Record([buffers, offsets, index_buffer = *index.buffer,
  230. index_offset = index.offset,
  231. index_type = index.type](auto cmdbuf, auto& dld) {
  232. cmdbuf.bindIndexBuffer(index_buffer, index_offset, index_type, dld);
  233. cmdbuf.bindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data(),
  234. dld);
  235. });
  236. } else {
  237. // Array draw
  238. scheduler.Record([buffers, offsets](auto cmdbuf, auto& dld) {
  239. cmdbuf.bindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data(),
  240. dld);
  241. });
  242. }
  243. }
  244. };
  245. void RasterizerVulkan::DrawParameters::Draw(vk::CommandBuffer cmdbuf,
  246. const vk::DispatchLoaderDynamic& dld) const {
  247. if (is_indexed) {
  248. cmdbuf.drawIndexed(num_vertices, num_instances, 0, base_vertex, base_instance, dld);
  249. } else {
  250. cmdbuf.draw(num_vertices, num_instances, base_vertex, base_instance, dld);
  251. }
  252. }
  253. RasterizerVulkan::RasterizerVulkan(Core::System& system, Core::Frontend::EmuWindow& renderer,
  254. VKScreenInfo& screen_info, const VKDevice& device,
  255. VKResourceManager& resource_manager,
  256. VKMemoryManager& memory_manager, StateTracker& state_tracker,
  257. VKScheduler& scheduler)
  258. : RasterizerAccelerated{system.Memory()}, system{system}, render_window{renderer},
  259. screen_info{screen_info}, device{device}, resource_manager{resource_manager},
  260. memory_manager{memory_manager}, state_tracker{state_tracker}, scheduler{scheduler},
  261. staging_pool(device, memory_manager, scheduler), descriptor_pool(device),
  262. update_descriptor_queue(device, scheduler), renderpass_cache(device),
  263. quad_array_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  264. uint8_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  265. texture_cache(system, *this, device, resource_manager, memory_manager, scheduler,
  266. staging_pool),
  267. pipeline_cache(system, *this, device, scheduler, descriptor_pool, update_descriptor_queue,
  268. renderpass_cache),
  269. buffer_cache(*this, system, device, memory_manager, scheduler, staging_pool),
  270. sampler_cache(device), query_cache(system, *this, device, scheduler) {
  271. scheduler.SetQueryCache(query_cache);
  272. }
  273. RasterizerVulkan::~RasterizerVulkan() = default;
  274. void RasterizerVulkan::Draw(bool is_indexed, bool is_instanced) {
  275. MICROPROFILE_SCOPE(Vulkan_Drawing);
  276. FlushWork();
  277. query_cache.UpdateCounters();
  278. const auto& gpu = system.GPU().Maxwell3D();
  279. GraphicsPipelineCacheKey key{GetFixedPipelineState(gpu.regs)};
  280. buffer_cache.Map(CalculateGraphicsStreamBufferSize(is_indexed));
  281. BufferBindings buffer_bindings;
  282. const DrawParameters draw_params =
  283. SetupGeometry(key.fixed_state, buffer_bindings, is_indexed, is_instanced);
  284. update_descriptor_queue.Acquire();
  285. sampled_views.clear();
  286. image_views.clear();
  287. const auto shaders = pipeline_cache.GetShaders();
  288. key.shaders = GetShaderAddresses(shaders);
  289. SetupShaderDescriptors(shaders);
  290. buffer_cache.Unmap();
  291. const auto texceptions = UpdateAttachments();
  292. SetupImageTransitions(texceptions, color_attachments, zeta_attachment);
  293. key.renderpass_params = GetRenderPassParams(texceptions);
  294. auto& pipeline = pipeline_cache.GetGraphicsPipeline(key);
  295. scheduler.BindGraphicsPipeline(pipeline.GetHandle());
  296. const auto renderpass = pipeline.GetRenderPass();
  297. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  298. scheduler.RequestRenderpass({renderpass, framebuffer, {{0, 0}, render_area}, 0, nullptr});
  299. UpdateDynamicStates();
  300. buffer_bindings.Bind(scheduler);
  301. if (device.IsNvDeviceDiagnosticCheckpoints()) {
  302. scheduler.Record(
  303. [&pipeline](auto cmdbuf, auto& dld) { cmdbuf.setCheckpointNV(&pipeline, dld); });
  304. }
  305. BeginTransformFeedback();
  306. const auto pipeline_layout = pipeline.GetLayout();
  307. const auto descriptor_set = pipeline.CommitDescriptorSet();
  308. scheduler.Record([pipeline_layout, descriptor_set, draw_params](auto cmdbuf, auto& dld) {
  309. if (descriptor_set) {
  310. cmdbuf.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout,
  311. DESCRIPTOR_SET, 1, &descriptor_set, 0, nullptr, dld);
  312. }
  313. draw_params.Draw(cmdbuf, dld);
  314. });
  315. EndTransformFeedback();
  316. }
  317. void RasterizerVulkan::Clear() {
  318. MICROPROFILE_SCOPE(Vulkan_Clearing);
  319. const auto& gpu = system.GPU().Maxwell3D();
  320. if (!system.GPU().Maxwell3D().ShouldExecute()) {
  321. return;
  322. }
  323. sampled_views.clear();
  324. image_views.clear();
  325. query_cache.UpdateCounters();
  326. const auto& regs = gpu.regs;
  327. const bool use_color = regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  328. regs.clear_buffers.A;
  329. const bool use_depth = regs.clear_buffers.Z;
  330. const bool use_stencil = regs.clear_buffers.S;
  331. if (!use_color && !use_depth && !use_stencil) {
  332. return;
  333. }
  334. [[maybe_unused]] const auto texceptions = UpdateAttachments();
  335. DEBUG_ASSERT(texceptions.none());
  336. SetupImageTransitions(0, color_attachments, zeta_attachment);
  337. const vk::RenderPass renderpass = renderpass_cache.GetRenderPass(GetRenderPassParams(0));
  338. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  339. scheduler.RequestRenderpass({renderpass, framebuffer, {{0, 0}, render_area}, 0, nullptr});
  340. const auto& scissor = regs.scissor_test[0];
  341. const vk::Offset2D scissor_offset(scissor.min_x, scissor.min_y);
  342. vk::Extent2D scissor_extent{scissor.max_x - scissor.min_x, scissor.max_y - scissor.min_y};
  343. scissor_extent.width = std::min(scissor_extent.width, render_area.width);
  344. scissor_extent.height = std::min(scissor_extent.height, render_area.height);
  345. const u32 layer = regs.clear_buffers.layer;
  346. const vk::ClearRect clear_rect({scissor_offset, scissor_extent}, layer, 1);
  347. if (use_color) {
  348. const std::array clear_color = {regs.clear_color[0], regs.clear_color[1],
  349. regs.clear_color[2], regs.clear_color[3]};
  350. const vk::ClearValue clear_value{clear_color};
  351. const u32 color_attachment = regs.clear_buffers.RT;
  352. scheduler.Record([color_attachment, clear_value, clear_rect](auto cmdbuf, auto& dld) {
  353. const vk::ClearAttachment attachment(vk::ImageAspectFlagBits::eColor, color_attachment,
  354. clear_value);
  355. cmdbuf.clearAttachments(1, &attachment, 1, &clear_rect, dld);
  356. });
  357. }
  358. if (!use_depth && !use_stencil) {
  359. return;
  360. }
  361. vk::ImageAspectFlags aspect_flags;
  362. if (use_depth) {
  363. aspect_flags |= vk::ImageAspectFlagBits::eDepth;
  364. }
  365. if (use_stencil) {
  366. aspect_flags |= vk::ImageAspectFlagBits::eStencil;
  367. }
  368. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  369. clear_rect, aspect_flags](auto cmdbuf, auto& dld) {
  370. const vk::ClearDepthStencilValue clear_zeta(clear_depth, clear_stencil);
  371. const vk::ClearValue clear_value{clear_zeta};
  372. const vk::ClearAttachment attachment(aspect_flags, 0, clear_value);
  373. cmdbuf.clearAttachments(1, &attachment, 1, &clear_rect, dld);
  374. });
  375. }
  376. void RasterizerVulkan::DispatchCompute(GPUVAddr code_addr) {
  377. MICROPROFILE_SCOPE(Vulkan_Compute);
  378. update_descriptor_queue.Acquire();
  379. sampled_views.clear();
  380. image_views.clear();
  381. query_cache.UpdateCounters();
  382. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  383. const ComputePipelineCacheKey key{
  384. code_addr,
  385. launch_desc.shared_alloc,
  386. {launch_desc.block_dim_x, launch_desc.block_dim_y, launch_desc.block_dim_z}};
  387. auto& pipeline = pipeline_cache.GetComputePipeline(key);
  388. // Compute dispatches can't be executed inside a renderpass
  389. scheduler.RequestOutsideRenderPassOperationContext();
  390. buffer_cache.Map(CalculateComputeStreamBufferSize());
  391. const auto& entries = pipeline.GetEntries();
  392. SetupComputeConstBuffers(entries);
  393. SetupComputeGlobalBuffers(entries);
  394. SetupComputeTexelBuffers(entries);
  395. SetupComputeTextures(entries);
  396. SetupComputeImages(entries);
  397. buffer_cache.Unmap();
  398. TransitionImages(sampled_views, vk::PipelineStageFlagBits::eComputeShader,
  399. vk::AccessFlagBits::eShaderRead);
  400. TransitionImages(image_views, vk::PipelineStageFlagBits::eComputeShader,
  401. vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite);
  402. if (device.IsNvDeviceDiagnosticCheckpoints()) {
  403. scheduler.Record(
  404. [&pipeline](auto cmdbuf, auto& dld) { cmdbuf.setCheckpointNV(nullptr, dld); });
  405. }
  406. scheduler.Record([grid_x = launch_desc.grid_dim_x, grid_y = launch_desc.grid_dim_y,
  407. grid_z = launch_desc.grid_dim_z, pipeline_handle = pipeline.GetHandle(),
  408. layout = pipeline.GetLayout(),
  409. descriptor_set = pipeline.CommitDescriptorSet()](auto cmdbuf, auto& dld) {
  410. cmdbuf.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline_handle, dld);
  411. cmdbuf.bindDescriptorSets(vk::PipelineBindPoint::eCompute, layout, DESCRIPTOR_SET, 1,
  412. &descriptor_set, 0, nullptr, dld);
  413. cmdbuf.dispatch(grid_x, grid_y, grid_z, dld);
  414. });
  415. }
  416. void RasterizerVulkan::ResetCounter(VideoCore::QueryType type) {
  417. query_cache.ResetCounter(type);
  418. }
  419. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  420. std::optional<u64> timestamp) {
  421. query_cache.Query(gpu_addr, type, timestamp);
  422. }
  423. void RasterizerVulkan::FlushAll() {}
  424. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size) {
  425. if (!addr || !size) {
  426. return;
  427. }
  428. CacheAddr cache_addr = ToCacheAddr(system.Memory().GetPointer(addr));
  429. texture_cache.FlushRegion(cache_addr, size);
  430. buffer_cache.FlushRegion(cache_addr, size);
  431. query_cache.FlushRegion(cache_addr, size);
  432. }
  433. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  434. if (!addr || !size) {
  435. return;
  436. }
  437. CacheAddr cache_addr = ToCacheAddr(system.Memory().GetPointer(addr));
  438. texture_cache.InvalidateRegion(cache_addr, size);
  439. pipeline_cache.InvalidateRegion(cache_addr, size);
  440. buffer_cache.InvalidateRegion(cache_addr, size);
  441. query_cache.InvalidateRegion(cache_addr, size);
  442. }
  443. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  444. FlushRegion(addr, size);
  445. InvalidateRegion(addr, size);
  446. }
  447. void RasterizerVulkan::FlushCommands() {
  448. if (draw_counter > 0) {
  449. draw_counter = 0;
  450. scheduler.Flush();
  451. }
  452. }
  453. void RasterizerVulkan::TickFrame() {
  454. draw_counter = 0;
  455. update_descriptor_queue.TickFrame();
  456. buffer_cache.TickFrame();
  457. staging_pool.TickFrame();
  458. }
  459. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  460. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  461. const Tegra::Engines::Fermi2D::Config& copy_config) {
  462. texture_cache.DoFermiCopy(src, dst, copy_config);
  463. return true;
  464. }
  465. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  466. VAddr framebuffer_addr, u32 pixel_stride) {
  467. if (!framebuffer_addr) {
  468. return false;
  469. }
  470. const u8* host_ptr{system.Memory().GetPointer(framebuffer_addr)};
  471. const auto surface{texture_cache.TryFindFramebufferSurface(host_ptr)};
  472. if (!surface) {
  473. return false;
  474. }
  475. // Verify that the cached surface is the same size and format as the requested framebuffer
  476. const auto& params{surface->GetSurfaceParams()};
  477. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  478. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  479. screen_info.image = &surface->GetImage();
  480. screen_info.width = params.width;
  481. screen_info.height = params.height;
  482. screen_info.is_srgb = surface->GetSurfaceParams().srgb_conversion;
  483. return true;
  484. }
  485. void RasterizerVulkan::SetupDirtyFlags() {
  486. state_tracker.Initialize();
  487. }
  488. void RasterizerVulkan::FlushWork() {
  489. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  490. // Only check multiples of 8 draws
  491. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  492. if ((++draw_counter & 7) != 7) {
  493. return;
  494. }
  495. if (draw_counter < DRAWS_TO_DISPATCH) {
  496. // Send recorded tasks to the worker thread
  497. scheduler.DispatchWork();
  498. return;
  499. }
  500. // Otherwise (every certain number of draws) flush execution.
  501. // This submits commands to the Vulkan driver.
  502. scheduler.Flush();
  503. draw_counter = 0;
  504. }
  505. RasterizerVulkan::Texceptions RasterizerVulkan::UpdateAttachments() {
  506. MICROPROFILE_SCOPE(Vulkan_RenderTargets);
  507. auto& dirty = system.GPU().Maxwell3D().dirty.flags;
  508. const bool update_rendertargets = dirty[VideoCommon::Dirty::RenderTargets];
  509. dirty[VideoCommon::Dirty::RenderTargets] = false;
  510. texture_cache.GuardRenderTargets(true);
  511. Texceptions texceptions;
  512. for (std::size_t rt = 0; rt < Maxwell::NumRenderTargets; ++rt) {
  513. if (update_rendertargets) {
  514. color_attachments[rt] = texture_cache.GetColorBufferSurface(rt, true);
  515. }
  516. if (color_attachments[rt] && WalkAttachmentOverlaps(*color_attachments[rt])) {
  517. texceptions[rt] = true;
  518. }
  519. }
  520. if (update_rendertargets) {
  521. zeta_attachment = texture_cache.GetDepthBufferSurface(true);
  522. }
  523. if (zeta_attachment && WalkAttachmentOverlaps(*zeta_attachment)) {
  524. texceptions[ZETA_TEXCEPTION_INDEX] = true;
  525. }
  526. texture_cache.GuardRenderTargets(false);
  527. return texceptions;
  528. }
  529. bool RasterizerVulkan::WalkAttachmentOverlaps(const CachedSurfaceView& attachment) {
  530. bool overlap = false;
  531. for (auto& [view, layout] : sampled_views) {
  532. if (!attachment.IsSameSurface(*view)) {
  533. continue;
  534. }
  535. overlap = true;
  536. *layout = vk::ImageLayout::eGeneral;
  537. }
  538. return overlap;
  539. }
  540. std::tuple<vk::Framebuffer, vk::Extent2D> RasterizerVulkan::ConfigureFramebuffers(
  541. vk::RenderPass renderpass) {
  542. FramebufferCacheKey key{renderpass, std::numeric_limits<u32>::max(),
  543. std::numeric_limits<u32>::max(), std::numeric_limits<u32>::max()};
  544. const auto try_push = [&](const View& view) {
  545. if (!view) {
  546. return false;
  547. }
  548. key.views.push_back(view->GetHandle());
  549. key.width = std::min(key.width, view->GetWidth());
  550. key.height = std::min(key.height, view->GetHeight());
  551. key.layers = std::min(key.layers, view->GetNumLayers());
  552. return true;
  553. };
  554. for (std::size_t index = 0; index < std::size(color_attachments); ++index) {
  555. if (try_push(color_attachments[index])) {
  556. texture_cache.MarkColorBufferInUse(index);
  557. }
  558. }
  559. if (try_push(zeta_attachment)) {
  560. texture_cache.MarkDepthBufferInUse();
  561. }
  562. const auto [fbentry, is_cache_miss] = framebuffer_cache.try_emplace(key);
  563. auto& framebuffer = fbentry->second;
  564. if (is_cache_miss) {
  565. const vk::FramebufferCreateInfo framebuffer_ci(
  566. {}, key.renderpass, static_cast<u32>(key.views.size()), key.views.data(), key.width,
  567. key.height, key.layers);
  568. const auto dev = device.GetLogical();
  569. const auto& dld = device.GetDispatchLoader();
  570. framebuffer = dev.createFramebufferUnique(framebuffer_ci, nullptr, dld);
  571. }
  572. return {*framebuffer, vk::Extent2D{key.width, key.height}};
  573. }
  574. RasterizerVulkan::DrawParameters RasterizerVulkan::SetupGeometry(FixedPipelineState& fixed_state,
  575. BufferBindings& buffer_bindings,
  576. bool is_indexed,
  577. bool is_instanced) {
  578. MICROPROFILE_SCOPE(Vulkan_Geometry);
  579. const auto& gpu = system.GPU().Maxwell3D();
  580. const auto& regs = gpu.regs;
  581. SetupVertexArrays(fixed_state.vertex_input, buffer_bindings);
  582. const u32 base_instance = regs.vb_base_instance;
  583. const u32 num_instances = is_instanced ? gpu.mme_draw.instance_count : 1;
  584. const u32 base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first;
  585. const u32 num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count;
  586. DrawParameters params{base_instance, num_instances, base_vertex, num_vertices, is_indexed};
  587. SetupIndexBuffer(buffer_bindings, params, is_indexed);
  588. return params;
  589. }
  590. void RasterizerVulkan::SetupShaderDescriptors(
  591. const std::array<Shader, Maxwell::MaxShaderProgram>& shaders) {
  592. texture_cache.GuardSamplers(true);
  593. for (std::size_t stage = 0; stage < Maxwell::MaxShaderStage; ++stage) {
  594. // Skip VertexA stage
  595. const auto& shader = shaders[stage + 1];
  596. if (!shader) {
  597. continue;
  598. }
  599. const auto& entries = shader->GetEntries();
  600. SetupGraphicsConstBuffers(entries, stage);
  601. SetupGraphicsGlobalBuffers(entries, stage);
  602. SetupGraphicsTexelBuffers(entries, stage);
  603. SetupGraphicsTextures(entries, stage);
  604. SetupGraphicsImages(entries, stage);
  605. }
  606. texture_cache.GuardSamplers(false);
  607. }
  608. void RasterizerVulkan::SetupImageTransitions(
  609. Texceptions texceptions, const std::array<View, Maxwell::NumRenderTargets>& color_attachments,
  610. const View& zeta_attachment) {
  611. TransitionImages(sampled_views, vk::PipelineStageFlagBits::eAllGraphics,
  612. vk::AccessFlagBits::eShaderRead);
  613. TransitionImages(image_views, vk::PipelineStageFlagBits::eAllGraphics,
  614. vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite);
  615. for (std::size_t rt = 0; rt < std::size(color_attachments); ++rt) {
  616. const auto color_attachment = color_attachments[rt];
  617. if (color_attachment == nullptr) {
  618. continue;
  619. }
  620. const auto image_layout =
  621. texceptions[rt] ? vk::ImageLayout::eGeneral : vk::ImageLayout::eColorAttachmentOptimal;
  622. color_attachment->Transition(
  623. image_layout, vk::PipelineStageFlagBits::eColorAttachmentOutput,
  624. vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite);
  625. }
  626. if (zeta_attachment != nullptr) {
  627. const auto image_layout = texceptions[ZETA_TEXCEPTION_INDEX]
  628. ? vk::ImageLayout::eGeneral
  629. : vk::ImageLayout::eDepthStencilAttachmentOptimal;
  630. zeta_attachment->Transition(image_layout, vk::PipelineStageFlagBits::eLateFragmentTests,
  631. vk::AccessFlagBits::eDepthStencilAttachmentRead |
  632. vk::AccessFlagBits::eDepthStencilAttachmentWrite);
  633. }
  634. }
  635. void RasterizerVulkan::UpdateDynamicStates() {
  636. auto& regs = system.GPU().Maxwell3D().regs;
  637. UpdateViewportsState(regs);
  638. UpdateScissorsState(regs);
  639. UpdateDepthBias(regs);
  640. UpdateBlendConstants(regs);
  641. UpdateDepthBounds(regs);
  642. UpdateStencilFaces(regs);
  643. }
  644. void RasterizerVulkan::BeginTransformFeedback() {
  645. const auto& regs = system.GPU().Maxwell3D().regs;
  646. if (regs.tfb_enabled == 0) {
  647. return;
  648. }
  649. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  650. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  651. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  652. UNIMPLEMENTED_IF(regs.tfb_bindings[1].buffer_enable);
  653. UNIMPLEMENTED_IF(regs.tfb_bindings[2].buffer_enable);
  654. UNIMPLEMENTED_IF(regs.tfb_bindings[3].buffer_enable);
  655. const auto& binding = regs.tfb_bindings[0];
  656. UNIMPLEMENTED_IF(binding.buffer_enable == 0);
  657. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  658. const GPUVAddr gpu_addr = binding.Address();
  659. const std::size_t size = binding.buffer_size;
  660. const auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  661. scheduler.Record([buffer = *buffer, offset = offset, size](auto cmdbuf, auto& dld) {
  662. cmdbuf.bindTransformFeedbackBuffersEXT(0, {buffer}, {offset}, {size}, dld);
  663. cmdbuf.beginTransformFeedbackEXT(0, {}, {}, dld);
  664. });
  665. }
  666. void RasterizerVulkan::EndTransformFeedback() {
  667. const auto& regs = system.GPU().Maxwell3D().regs;
  668. if (regs.tfb_enabled == 0) {
  669. return;
  670. }
  671. scheduler.Record(
  672. [](auto cmdbuf, auto& dld) { cmdbuf.endTransformFeedbackEXT(0, {}, {}, dld); });
  673. }
  674. void RasterizerVulkan::SetupVertexArrays(FixedPipelineState::VertexInput& vertex_input,
  675. BufferBindings& buffer_bindings) {
  676. const auto& regs = system.GPU().Maxwell3D().regs;
  677. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexAttributes); ++index) {
  678. const auto& attrib = regs.vertex_attrib_format[index];
  679. if (!attrib.IsValid()) {
  680. continue;
  681. }
  682. const auto& buffer = regs.vertex_array[attrib.buffer];
  683. ASSERT(buffer.IsEnabled());
  684. vertex_input.attributes[vertex_input.num_attributes++] =
  685. FixedPipelineState::VertexAttribute(index, attrib.buffer, attrib.type, attrib.size,
  686. attrib.offset);
  687. }
  688. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexArrays); ++index) {
  689. const auto& vertex_array = regs.vertex_array[index];
  690. if (!vertex_array.IsEnabled()) {
  691. continue;
  692. }
  693. const GPUVAddr start{vertex_array.StartAddress()};
  694. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  695. ASSERT(end > start);
  696. const std::size_t size{end - start + 1};
  697. const auto [buffer, offset] = buffer_cache.UploadMemory(start, size);
  698. vertex_input.bindings[vertex_input.num_bindings++] = FixedPipelineState::VertexBinding(
  699. index, vertex_array.stride,
  700. regs.instanced_arrays.IsInstancingEnabled(index) ? vertex_array.divisor : 0);
  701. buffer_bindings.AddVertexBinding(buffer, offset);
  702. }
  703. }
  704. void RasterizerVulkan::SetupIndexBuffer(BufferBindings& buffer_bindings, DrawParameters& params,
  705. bool is_indexed) {
  706. const auto& regs = system.GPU().Maxwell3D().regs;
  707. switch (regs.draw.topology) {
  708. case Maxwell::PrimitiveTopology::Quads:
  709. if (params.is_indexed) {
  710. UNIMPLEMENTED();
  711. } else {
  712. const auto [buffer, offset] =
  713. quad_array_pass.Assemble(params.num_vertices, params.base_vertex);
  714. buffer_bindings.SetIndexBinding(&buffer, offset, vk::IndexType::eUint32);
  715. params.base_vertex = 0;
  716. params.num_vertices = params.num_vertices * 6 / 4;
  717. params.is_indexed = true;
  718. }
  719. break;
  720. default: {
  721. if (!is_indexed) {
  722. break;
  723. }
  724. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  725. auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  726. auto format = regs.index_array.format;
  727. const bool is_uint8 = format == Maxwell::IndexFormat::UnsignedByte;
  728. if (is_uint8 && !device.IsExtIndexTypeUint8Supported()) {
  729. std::tie(buffer, offset) = uint8_pass.Assemble(params.num_vertices, *buffer, offset);
  730. format = Maxwell::IndexFormat::UnsignedShort;
  731. }
  732. buffer_bindings.SetIndexBinding(buffer, offset, MaxwellToVK::IndexFormat(device, format));
  733. break;
  734. }
  735. }
  736. }
  737. void RasterizerVulkan::SetupGraphicsConstBuffers(const ShaderEntries& entries, std::size_t stage) {
  738. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  739. const auto& gpu = system.GPU().Maxwell3D();
  740. const auto& shader_stage = gpu.state.shader_stages[stage];
  741. for (const auto& entry : entries.const_buffers) {
  742. SetupConstBuffer(entry, shader_stage.const_buffers[entry.GetIndex()]);
  743. }
  744. }
  745. void RasterizerVulkan::SetupGraphicsGlobalBuffers(const ShaderEntries& entries, std::size_t stage) {
  746. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  747. auto& gpu{system.GPU()};
  748. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage]};
  749. for (const auto& entry : entries.global_buffers) {
  750. const auto addr = cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset();
  751. SetupGlobalBuffer(entry, addr);
  752. }
  753. }
  754. void RasterizerVulkan::SetupGraphicsTexelBuffers(const ShaderEntries& entries, std::size_t stage) {
  755. MICROPROFILE_SCOPE(Vulkan_Textures);
  756. const auto& gpu = system.GPU().Maxwell3D();
  757. for (const auto& entry : entries.texel_buffers) {
  758. const auto image = GetTextureInfo(gpu, entry, stage).tic;
  759. SetupTexelBuffer(image, entry);
  760. }
  761. }
  762. void RasterizerVulkan::SetupGraphicsTextures(const ShaderEntries& entries, std::size_t stage) {
  763. MICROPROFILE_SCOPE(Vulkan_Textures);
  764. const auto& gpu = system.GPU().Maxwell3D();
  765. for (const auto& entry : entries.samplers) {
  766. for (std::size_t i = 0; i < entry.Size(); ++i) {
  767. const auto texture = GetTextureInfo(gpu, entry, stage, i);
  768. SetupTexture(texture, entry);
  769. }
  770. }
  771. }
  772. void RasterizerVulkan::SetupGraphicsImages(const ShaderEntries& entries, std::size_t stage) {
  773. MICROPROFILE_SCOPE(Vulkan_Images);
  774. const auto& gpu = system.GPU().Maxwell3D();
  775. for (const auto& entry : entries.images) {
  776. const auto tic = GetTextureInfo(gpu, entry, stage).tic;
  777. SetupImage(tic, entry);
  778. }
  779. }
  780. void RasterizerVulkan::SetupComputeConstBuffers(const ShaderEntries& entries) {
  781. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  782. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  783. for (const auto& entry : entries.const_buffers) {
  784. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  785. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  786. Tegra::Engines::ConstBufferInfo buffer;
  787. buffer.address = config.Address();
  788. buffer.size = config.size;
  789. buffer.enabled = mask[entry.GetIndex()];
  790. SetupConstBuffer(entry, buffer);
  791. }
  792. }
  793. void RasterizerVulkan::SetupComputeGlobalBuffers(const ShaderEntries& entries) {
  794. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  795. const auto cbufs{system.GPU().KeplerCompute().launch_description.const_buffer_config};
  796. for (const auto& entry : entries.global_buffers) {
  797. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  798. SetupGlobalBuffer(entry, addr);
  799. }
  800. }
  801. void RasterizerVulkan::SetupComputeTexelBuffers(const ShaderEntries& entries) {
  802. MICROPROFILE_SCOPE(Vulkan_Textures);
  803. const auto& gpu = system.GPU().KeplerCompute();
  804. for (const auto& entry : entries.texel_buffers) {
  805. const auto image = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  806. SetupTexelBuffer(image, entry);
  807. }
  808. }
  809. void RasterizerVulkan::SetupComputeTextures(const ShaderEntries& entries) {
  810. MICROPROFILE_SCOPE(Vulkan_Textures);
  811. const auto& gpu = system.GPU().KeplerCompute();
  812. for (const auto& entry : entries.samplers) {
  813. for (std::size_t i = 0; i < entry.Size(); ++i) {
  814. const auto texture = GetTextureInfo(gpu, entry, ComputeShaderIndex, i);
  815. SetupTexture(texture, entry);
  816. }
  817. }
  818. }
  819. void RasterizerVulkan::SetupComputeImages(const ShaderEntries& entries) {
  820. MICROPROFILE_SCOPE(Vulkan_Images);
  821. const auto& gpu = system.GPU().KeplerCompute();
  822. for (const auto& entry : entries.images) {
  823. const auto tic = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  824. SetupImage(tic, entry);
  825. }
  826. }
  827. void RasterizerVulkan::SetupConstBuffer(const ConstBufferEntry& entry,
  828. const Tegra::Engines::ConstBufferInfo& buffer) {
  829. if (!buffer.enabled) {
  830. // Set values to zero to unbind buffers
  831. update_descriptor_queue.AddBuffer(buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  832. sizeof(float));
  833. return;
  834. }
  835. // Align the size to avoid bad std140 interactions
  836. const std::size_t size =
  837. Common::AlignUp(CalculateConstBufferSize(entry, buffer), 4 * sizeof(float));
  838. ASSERT(size <= MaxConstbufferSize);
  839. const auto [buffer_handle, offset] =
  840. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  841. update_descriptor_queue.AddBuffer(buffer_handle, offset, size);
  842. }
  843. void RasterizerVulkan::SetupGlobalBuffer(const GlobalBufferEntry& entry, GPUVAddr address) {
  844. auto& memory_manager{system.GPU().MemoryManager()};
  845. const auto actual_addr = memory_manager.Read<u64>(address);
  846. const auto size = memory_manager.Read<u32>(address + 8);
  847. if (size == 0) {
  848. // Sometimes global memory pointers don't have a proper size. Upload a dummy entry because
  849. // Vulkan doesn't like empty buffers.
  850. constexpr std::size_t dummy_size = 4;
  851. const auto buffer = buffer_cache.GetEmptyBuffer(dummy_size);
  852. update_descriptor_queue.AddBuffer(buffer, 0, dummy_size);
  853. return;
  854. }
  855. const auto [buffer, offset] = buffer_cache.UploadMemory(
  856. actual_addr, size, device.GetStorageBufferAlignment(), entry.IsWritten());
  857. update_descriptor_queue.AddBuffer(buffer, offset, size);
  858. }
  859. void RasterizerVulkan::SetupTexelBuffer(const Tegra::Texture::TICEntry& tic,
  860. const TexelBufferEntry& entry) {
  861. const auto view = texture_cache.GetTextureSurface(tic, entry);
  862. ASSERT(view->IsBufferView());
  863. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  864. }
  865. void RasterizerVulkan::SetupTexture(const Tegra::Texture::FullTextureInfo& texture,
  866. const SamplerEntry& entry) {
  867. auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  868. ASSERT(!view->IsBufferView());
  869. const auto image_view = view->GetHandle(texture.tic.x_source, texture.tic.y_source,
  870. texture.tic.z_source, texture.tic.w_source);
  871. const auto sampler = sampler_cache.GetSampler(texture.tsc);
  872. update_descriptor_queue.AddSampledImage(sampler, image_view);
  873. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  874. *image_layout = vk::ImageLayout::eShaderReadOnlyOptimal;
  875. sampled_views.push_back(ImageView{std::move(view), image_layout});
  876. }
  877. void RasterizerVulkan::SetupImage(const Tegra::Texture::TICEntry& tic, const ImageEntry& entry) {
  878. auto view = texture_cache.GetImageSurface(tic, entry);
  879. if (entry.IsWritten()) {
  880. view->MarkAsModified(texture_cache.Tick());
  881. }
  882. UNIMPLEMENTED_IF(tic.IsBuffer());
  883. const auto image_view = view->GetHandle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  884. update_descriptor_queue.AddImage(image_view);
  885. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  886. *image_layout = vk::ImageLayout::eGeneral;
  887. image_views.push_back(ImageView{std::move(view), image_layout});
  888. }
  889. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  890. if (!state_tracker.TouchViewports()) {
  891. return;
  892. }
  893. const std::array viewports{
  894. GetViewportState(device, regs, 0), GetViewportState(device, regs, 1),
  895. GetViewportState(device, regs, 2), GetViewportState(device, regs, 3),
  896. GetViewportState(device, regs, 4), GetViewportState(device, regs, 5),
  897. GetViewportState(device, regs, 6), GetViewportState(device, regs, 7),
  898. GetViewportState(device, regs, 8), GetViewportState(device, regs, 9),
  899. GetViewportState(device, regs, 10), GetViewportState(device, regs, 11),
  900. GetViewportState(device, regs, 12), GetViewportState(device, regs, 13),
  901. GetViewportState(device, regs, 14), GetViewportState(device, regs, 15)};
  902. scheduler.Record([viewports](auto cmdbuf, auto& dld) {
  903. cmdbuf.setViewport(0, static_cast<u32>(viewports.size()), viewports.data(), dld);
  904. });
  905. }
  906. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  907. if (!state_tracker.TouchScissors()) {
  908. return;
  909. }
  910. const std::array scissors = {
  911. GetScissorState(regs, 0), GetScissorState(regs, 1), GetScissorState(regs, 2),
  912. GetScissorState(regs, 3), GetScissorState(regs, 4), GetScissorState(regs, 5),
  913. GetScissorState(regs, 6), GetScissorState(regs, 7), GetScissorState(regs, 8),
  914. GetScissorState(regs, 9), GetScissorState(regs, 10), GetScissorState(regs, 11),
  915. GetScissorState(regs, 12), GetScissorState(regs, 13), GetScissorState(regs, 14),
  916. GetScissorState(regs, 15)};
  917. scheduler.Record([scissors](auto cmdbuf, auto& dld) {
  918. cmdbuf.setScissor(0, static_cast<u32>(scissors.size()), scissors.data(), dld);
  919. });
  920. }
  921. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  922. if (!state_tracker.TouchDepthBias()) {
  923. return;
  924. }
  925. scheduler.Record([constant = regs.polygon_offset_units, clamp = regs.polygon_offset_clamp,
  926. factor = regs.polygon_offset_factor](auto cmdbuf, auto& dld) {
  927. cmdbuf.setDepthBias(constant, clamp, factor / 2.0f, dld);
  928. });
  929. }
  930. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  931. if (!state_tracker.TouchBlendConstants()) {
  932. return;
  933. }
  934. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  935. regs.blend_color.a};
  936. scheduler.Record([blend_color](auto cmdbuf, auto& dld) {
  937. cmdbuf.setBlendConstants(blend_color.data(), dld);
  938. });
  939. }
  940. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  941. if (!state_tracker.TouchDepthBounds()) {
  942. return;
  943. }
  944. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  945. auto cmdbuf, auto& dld) { cmdbuf.setDepthBounds(min, max, dld); });
  946. }
  947. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  948. if (!state_tracker.TouchStencilProperties()) {
  949. return;
  950. }
  951. if (regs.stencil_two_side_enable) {
  952. // Separate values per face
  953. scheduler.Record(
  954. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  955. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  956. back_write_mask = regs.stencil_back_mask,
  957. back_test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  958. // Front face
  959. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFront, front_ref, dld);
  960. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFront, front_write_mask, dld);
  961. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFront, front_test_mask, dld);
  962. // Back face
  963. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eBack, back_ref, dld);
  964. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eBack, back_write_mask, dld);
  965. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eBack, back_test_mask, dld);
  966. });
  967. } else {
  968. // Front face defines both faces
  969. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  970. test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  971. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, ref, dld);
  972. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, write_mask, dld);
  973. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFrontAndBack, test_mask, dld);
  974. });
  975. }
  976. }
  977. std::size_t RasterizerVulkan::CalculateGraphicsStreamBufferSize(bool is_indexed) const {
  978. std::size_t size = CalculateVertexArraysSize();
  979. if (is_indexed) {
  980. size = Common::AlignUp(size, 4) + CalculateIndexBufferSize();
  981. }
  982. size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  983. return size;
  984. }
  985. std::size_t RasterizerVulkan::CalculateComputeStreamBufferSize() const {
  986. return Tegra::Engines::KeplerCompute::NumConstBuffers *
  987. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  988. }
  989. std::size_t RasterizerVulkan::CalculateVertexArraysSize() const {
  990. const auto& regs = system.GPU().Maxwell3D().regs;
  991. std::size_t size = 0;
  992. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  993. // This implementation assumes that all attributes are used in the shader.
  994. const GPUVAddr start{regs.vertex_array[index].StartAddress()};
  995. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  996. DEBUG_ASSERT(end >= start);
  997. size += (end - start + 1) * regs.vertex_array[index].enable;
  998. }
  999. return size;
  1000. }
  1001. std::size_t RasterizerVulkan::CalculateIndexBufferSize() const {
  1002. const auto& regs = system.GPU().Maxwell3D().regs;
  1003. return static_cast<std::size_t>(regs.index_array.count) *
  1004. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  1005. }
  1006. std::size_t RasterizerVulkan::CalculateConstBufferSize(
  1007. const ConstBufferEntry& entry, const Tegra::Engines::ConstBufferInfo& buffer) const {
  1008. if (entry.IsIndirect()) {
  1009. // Buffer is accessed indirectly, so upload the entire thing
  1010. return buffer.size;
  1011. } else {
  1012. // Buffer is accessed directly, upload just what we use
  1013. return entry.GetSize();
  1014. }
  1015. }
  1016. RenderPassParams RasterizerVulkan::GetRenderPassParams(Texceptions texceptions) const {
  1017. using namespace VideoCore::Surface;
  1018. const auto& regs = system.GPU().Maxwell3D().regs;
  1019. RenderPassParams renderpass_params;
  1020. for (std::size_t rt = 0; rt < static_cast<std::size_t>(regs.rt_control.count); ++rt) {
  1021. const auto& rendertarget = regs.rt[rt];
  1022. if (rendertarget.Address() == 0 || rendertarget.format == Tegra::RenderTargetFormat::NONE) {
  1023. continue;
  1024. }
  1025. renderpass_params.color_attachments.push_back(RenderPassParams::ColorAttachment{
  1026. static_cast<u32>(rt), PixelFormatFromRenderTargetFormat(rendertarget.format),
  1027. texceptions[rt]});
  1028. }
  1029. renderpass_params.has_zeta = regs.zeta_enable;
  1030. if (renderpass_params.has_zeta) {
  1031. renderpass_params.zeta_pixel_format = PixelFormatFromDepthFormat(regs.zeta.format);
  1032. renderpass_params.zeta_texception = texceptions[ZETA_TEXCEPTION_INDEX];
  1033. }
  1034. return renderpass_params;
  1035. }
  1036. } // namespace Vulkan