vk_rasterizer.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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 "common/alignment.h"
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "common/microprofile.h"
  13. #include "common/scope_exit.h"
  14. #include "common/settings.h"
  15. #include "core/core.h"
  16. #include "video_core/engines/kepler_compute.h"
  17. #include "video_core/engines/maxwell_3d.h"
  18. #include "video_core/renderer_vulkan/blit_image.h"
  19. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  20. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  21. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  22. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  23. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  24. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  25. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  26. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  27. #include "video_core/renderer_vulkan/vk_scheduler.h"
  28. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  29. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  30. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  31. #include "video_core/renderer_vulkan/vk_update_descriptor.h"
  32. #include "video_core/shader_cache.h"
  33. #include "video_core/texture_cache/texture_cache_base.h"
  34. #include "video_core/vulkan_common/vulkan_device.h"
  35. #include "video_core/vulkan_common/vulkan_wrapper.h"
  36. namespace Vulkan {
  37. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  38. using VideoCommon::ImageViewId;
  39. using VideoCommon::ImageViewType;
  40. MICROPROFILE_DEFINE(Vulkan_WaitForWorker, "Vulkan", "Wait for worker", MP_RGB(255, 192, 192));
  41. MICROPROFILE_DEFINE(Vulkan_Drawing, "Vulkan", "Record drawing", MP_RGB(192, 128, 128));
  42. MICROPROFILE_DEFINE(Vulkan_Compute, "Vulkan", "Record compute", MP_RGB(192, 128, 128));
  43. MICROPROFILE_DEFINE(Vulkan_Clearing, "Vulkan", "Record clearing", MP_RGB(192, 128, 128));
  44. MICROPROFILE_DEFINE(Vulkan_PipelineCache, "Vulkan", "Pipeline cache", MP_RGB(192, 128, 128));
  45. namespace {
  46. struct DrawParams {
  47. u32 base_instance;
  48. u32 num_instances;
  49. u32 base_vertex;
  50. u32 num_vertices;
  51. u32 first_index;
  52. bool is_indexed;
  53. };
  54. VkViewport GetViewportState(const Device& device, const Maxwell& regs, size_t index, float scale) {
  55. const auto& src = regs.viewport_transform[index];
  56. const auto conv = [scale](float value) {
  57. float new_value = value * scale;
  58. if (scale < 1.0f) {
  59. bool sign = std::signbit(new_value);
  60. new_value = std::round(std::abs(new_value));
  61. new_value = sign ? -new_value : new_value;
  62. }
  63. return new_value;
  64. };
  65. const float x = conv(src.translate_x - src.scale_x);
  66. const float width = conv(src.scale_x * 2.0f);
  67. float y = conv(src.translate_y - src.scale_y);
  68. float height = conv(src.scale_y * 2.0f);
  69. if (regs.screen_y_control.y_negate) {
  70. y += height;
  71. height = -height;
  72. }
  73. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne ? 1.0f : 0.0f;
  74. VkViewport viewport{
  75. .x = x,
  76. .y = y,
  77. .width = width != 0.0f ? width : 1.0f,
  78. .height = height != 0.0f ? height : 1.0f,
  79. .minDepth = src.translate_z - src.scale_z * reduce_z,
  80. .maxDepth = src.translate_z + src.scale_z,
  81. };
  82. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  83. viewport.minDepth = std::clamp(viewport.minDepth, 0.0f, 1.0f);
  84. viewport.maxDepth = std::clamp(viewport.maxDepth, 0.0f, 1.0f);
  85. }
  86. return viewport;
  87. }
  88. VkRect2D GetScissorState(const Maxwell& regs, size_t index, u32 up_scale = 1, u32 down_shift = 0) {
  89. const auto& src = regs.scissor_test[index];
  90. VkRect2D scissor;
  91. const auto scale_up = [&](u32 value) -> u32 {
  92. if (value == 0) {
  93. return 0U;
  94. }
  95. const u32 upset = value * up_scale;
  96. u32 acumm = 0;
  97. if ((up_scale >> down_shift) == 0) {
  98. acumm = upset & 0x1;
  99. }
  100. const u32 converted_value = (value * up_scale) >> down_shift;
  101. return std::max<u32>(converted_value + acumm, 1U);
  102. };
  103. if (src.enable) {
  104. scissor.offset.x = static_cast<s32>(scale_up(src.min_x));
  105. scissor.offset.y = static_cast<s32>(scale_up(src.min_y));
  106. scissor.extent.width = scale_up(src.max_x - src.min_x);
  107. scissor.extent.height = scale_up(src.max_y - src.min_y);
  108. } else {
  109. scissor.offset.x = 0;
  110. scissor.offset.y = 0;
  111. scissor.extent.width = std::numeric_limits<s32>::max();
  112. scissor.extent.height = std::numeric_limits<s32>::max();
  113. }
  114. return scissor;
  115. }
  116. DrawParams MakeDrawParams(const Maxwell& regs, u32 num_instances, bool is_instanced,
  117. bool is_indexed) {
  118. DrawParams params{
  119. .base_instance = regs.vb_base_instance,
  120. .num_instances = is_instanced ? num_instances : 1,
  121. .base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first,
  122. .num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count,
  123. .first_index = is_indexed ? regs.index_array.first : 0,
  124. .is_indexed = is_indexed,
  125. };
  126. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  127. // 6 triangle vertices per quad, base vertex is part of the index
  128. // See BindQuadArrayIndexBuffer for more details
  129. params.num_vertices = (params.num_vertices / 4) * 6;
  130. params.base_vertex = 0;
  131. params.is_indexed = true;
  132. }
  133. return params;
  134. }
  135. } // Anonymous namespace
  136. RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
  137. Tegra::MemoryManager& gpu_memory_,
  138. Core::Memory::Memory& cpu_memory_, VKScreenInfo& screen_info_,
  139. const Device& device_, MemoryAllocator& memory_allocator_,
  140. StateTracker& state_tracker_, VKScheduler& scheduler_)
  141. : RasterizerAccelerated{cpu_memory_}, gpu{gpu_},
  142. gpu_memory{gpu_memory_}, maxwell3d{gpu.Maxwell3D()}, kepler_compute{gpu.KeplerCompute()},
  143. screen_info{screen_info_}, device{device_}, memory_allocator{memory_allocator_},
  144. state_tracker{state_tracker_}, scheduler{scheduler_},
  145. staging_pool(device, memory_allocator, scheduler), descriptor_pool(device, scheduler),
  146. update_descriptor_queue(device, scheduler),
  147. blit_image(device, scheduler, state_tracker, descriptor_pool),
  148. astc_decoder_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue,
  149. memory_allocator),
  150. render_pass_cache(device), texture_cache_runtime{device, scheduler,
  151. memory_allocator, staging_pool,
  152. blit_image, astc_decoder_pass,
  153. render_pass_cache},
  154. texture_cache(texture_cache_runtime, *this, maxwell3d, kepler_compute, gpu_memory),
  155. buffer_cache_runtime(device, memory_allocator, scheduler, staging_pool,
  156. update_descriptor_queue, descriptor_pool),
  157. buffer_cache(*this, maxwell3d, kepler_compute, gpu_memory, cpu_memory_, buffer_cache_runtime),
  158. pipeline_cache(*this, maxwell3d, kepler_compute, gpu_memory, device, scheduler,
  159. descriptor_pool, update_descriptor_queue, render_pass_cache, buffer_cache,
  160. texture_cache, gpu.ShaderNotify()),
  161. query_cache{*this, maxwell3d, gpu_memory, device, scheduler}, accelerate_dma{buffer_cache},
  162. fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache, device, scheduler),
  163. wfi_event(device.GetLogical().CreateEvent()) {
  164. scheduler.SetQueryCache(query_cache);
  165. }
  166. RasterizerVulkan::~RasterizerVulkan() = default;
  167. void RasterizerVulkan::Draw(bool is_indexed, bool is_instanced) {
  168. MICROPROFILE_SCOPE(Vulkan_Drawing);
  169. SCOPE_EXIT({ gpu.TickWork(); });
  170. FlushWork();
  171. query_cache.UpdateCounters();
  172. GraphicsPipeline* const pipeline{pipeline_cache.CurrentGraphicsPipeline()};
  173. if (!pipeline) {
  174. return;
  175. }
  176. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  177. pipeline->Configure(is_indexed);
  178. BeginTransformFeedback();
  179. UpdateDynamicStates();
  180. const auto& regs{maxwell3d.regs};
  181. const u32 num_instances{maxwell3d.mme_draw.instance_count};
  182. const DrawParams draw_params{MakeDrawParams(regs, num_instances, is_instanced, is_indexed)};
  183. scheduler.Record([draw_params](vk::CommandBuffer cmdbuf) {
  184. if (draw_params.is_indexed) {
  185. cmdbuf.DrawIndexed(draw_params.num_vertices, draw_params.num_instances,
  186. draw_params.first_index, draw_params.base_vertex,
  187. draw_params.base_instance);
  188. } else {
  189. cmdbuf.Draw(draw_params.num_vertices, draw_params.num_instances,
  190. draw_params.base_vertex, draw_params.base_instance);
  191. }
  192. });
  193. EndTransformFeedback();
  194. }
  195. void RasterizerVulkan::Clear() {
  196. MICROPROFILE_SCOPE(Vulkan_Clearing);
  197. if (!maxwell3d.ShouldExecute()) {
  198. return;
  199. }
  200. FlushWork();
  201. query_cache.UpdateCounters();
  202. auto& regs = maxwell3d.regs;
  203. const bool use_color = regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  204. regs.clear_buffers.A;
  205. const bool use_depth = regs.clear_buffers.Z;
  206. const bool use_stencil = regs.clear_buffers.S;
  207. if (!use_color && !use_depth && !use_stencil) {
  208. return;
  209. }
  210. std::scoped_lock lock{texture_cache.mutex};
  211. texture_cache.UpdateRenderTargets(true);
  212. const Framebuffer* const framebuffer = texture_cache.GetFramebuffer();
  213. const VkExtent2D render_area = framebuffer->RenderArea();
  214. scheduler.RequestRenderpass(framebuffer);
  215. u32 up_scale = 1;
  216. u32 down_shift = 0;
  217. if (texture_cache.IsRescaling()) {
  218. up_scale = Settings::values.resolution_info.up_scale;
  219. down_shift = Settings::values.resolution_info.down_shift;
  220. }
  221. UpdateViewportsState(regs);
  222. VkClearRect clear_rect{
  223. .rect = GetScissorState(regs, 0, up_scale, down_shift),
  224. .baseArrayLayer = regs.clear_buffers.layer,
  225. .layerCount = 1,
  226. };
  227. if (clear_rect.rect.extent.width == 0 || clear_rect.rect.extent.height == 0) {
  228. return;
  229. }
  230. clear_rect.rect.extent = VkExtent2D{
  231. .width = std::min(clear_rect.rect.extent.width, render_area.width),
  232. .height = std::min(clear_rect.rect.extent.height, render_area.height),
  233. };
  234. const u32 color_attachment = regs.clear_buffers.RT;
  235. if (use_color && framebuffer->HasAspectColorBit(color_attachment)) {
  236. VkClearValue clear_value;
  237. bool is_integer = false;
  238. bool is_signed = false;
  239. size_t int_size = 8;
  240. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; ++i) {
  241. const auto& this_rt = regs.rt[i];
  242. if (this_rt.Address() == 0) {
  243. continue;
  244. }
  245. if (this_rt.format == Tegra::RenderTargetFormat::NONE) {
  246. continue;
  247. }
  248. const auto format =
  249. VideoCore::Surface::PixelFormatFromRenderTargetFormat(this_rt.format);
  250. is_integer = IsPixelFormatInteger(format);
  251. is_signed = IsPixelFormatSignedInteger(format);
  252. int_size = PixelComponentSizeBitsInteger(format);
  253. break;
  254. }
  255. if (!is_integer) {
  256. std::memcpy(clear_value.color.float32, regs.clear_color, sizeof(regs.clear_color));
  257. } else if (!is_signed) {
  258. for (size_t i = 0; i < 4; i++) {
  259. clear_value.color.uint32[i] = static_cast<u32>(
  260. static_cast<f32>(static_cast<u64>(int_size) << 1U) * regs.clear_color[i]);
  261. }
  262. } else {
  263. for (size_t i = 0; i < 4; i++) {
  264. clear_value.color.int32[i] =
  265. static_cast<s32>(static_cast<f32>(static_cast<s64>(int_size - 1) << 1) *
  266. (regs.clear_color[i] - 0.5f));
  267. }
  268. }
  269. scheduler.Record([color_attachment, clear_value, clear_rect](vk::CommandBuffer cmdbuf) {
  270. const VkClearAttachment attachment{
  271. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  272. .colorAttachment = color_attachment,
  273. .clearValue = clear_value,
  274. };
  275. cmdbuf.ClearAttachments(attachment, clear_rect);
  276. });
  277. }
  278. if (!use_depth && !use_stencil) {
  279. return;
  280. }
  281. VkImageAspectFlags aspect_flags = 0;
  282. if (use_depth && framebuffer->HasAspectDepthBit()) {
  283. aspect_flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
  284. }
  285. if (use_stencil && framebuffer->HasAspectStencilBit()) {
  286. aspect_flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  287. }
  288. if (aspect_flags == 0) {
  289. return;
  290. }
  291. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  292. clear_rect, aspect_flags](vk::CommandBuffer cmdbuf) {
  293. VkClearAttachment attachment;
  294. attachment.aspectMask = aspect_flags;
  295. attachment.colorAttachment = 0;
  296. attachment.clearValue.depthStencil.depth = clear_depth;
  297. attachment.clearValue.depthStencil.stencil = clear_stencil;
  298. cmdbuf.ClearAttachments(attachment, clear_rect);
  299. });
  300. }
  301. void RasterizerVulkan::DispatchCompute() {
  302. FlushWork();
  303. ComputePipeline* const pipeline{pipeline_cache.CurrentComputePipeline()};
  304. if (!pipeline) {
  305. return;
  306. }
  307. std::scoped_lock lock{texture_cache.mutex, buffer_cache.mutex};
  308. pipeline->Configure(kepler_compute, gpu_memory, scheduler, buffer_cache, texture_cache);
  309. const auto& qmd{kepler_compute.launch_description};
  310. const std::array<u32, 3> dim{qmd.grid_dim_x, qmd.grid_dim_y, qmd.grid_dim_z};
  311. scheduler.RequestOutsideRenderPassOperationContext();
  312. scheduler.Record([dim](vk::CommandBuffer cmdbuf) { cmdbuf.Dispatch(dim[0], dim[1], dim[2]); });
  313. }
  314. void RasterizerVulkan::ResetCounter(VideoCore::QueryType type) {
  315. query_cache.ResetCounter(type);
  316. }
  317. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  318. std::optional<u64> timestamp) {
  319. query_cache.Query(gpu_addr, type, timestamp);
  320. }
  321. void RasterizerVulkan::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  322. u32 size) {
  323. buffer_cache.BindGraphicsUniformBuffer(stage, index, gpu_addr, size);
  324. }
  325. void Vulkan::RasterizerVulkan::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  326. buffer_cache.DisableGraphicsUniformBuffer(stage, index);
  327. }
  328. void RasterizerVulkan::FlushAll() {}
  329. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size) {
  330. if (addr == 0 || size == 0) {
  331. return;
  332. }
  333. {
  334. std::scoped_lock lock{texture_cache.mutex};
  335. texture_cache.DownloadMemory(addr, size);
  336. }
  337. {
  338. std::scoped_lock lock{buffer_cache.mutex};
  339. buffer_cache.DownloadMemory(addr, size);
  340. }
  341. query_cache.FlushRegion(addr, size);
  342. }
  343. bool RasterizerVulkan::MustFlushRegion(VAddr addr, u64 size) {
  344. std::scoped_lock lock{texture_cache.mutex, buffer_cache.mutex};
  345. if (!Settings::IsGPULevelHigh()) {
  346. return buffer_cache.IsRegionGpuModified(addr, size);
  347. }
  348. return texture_cache.IsRegionGpuModified(addr, size) ||
  349. buffer_cache.IsRegionGpuModified(addr, size);
  350. }
  351. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  352. if (addr == 0 || size == 0) {
  353. return;
  354. }
  355. {
  356. std::scoped_lock lock{texture_cache.mutex};
  357. texture_cache.WriteMemory(addr, size);
  358. }
  359. {
  360. std::scoped_lock lock{buffer_cache.mutex};
  361. buffer_cache.WriteMemory(addr, size);
  362. }
  363. pipeline_cache.InvalidateRegion(addr, size);
  364. query_cache.InvalidateRegion(addr, size);
  365. }
  366. void RasterizerVulkan::OnCPUWrite(VAddr addr, u64 size) {
  367. if (addr == 0 || size == 0) {
  368. return;
  369. }
  370. pipeline_cache.OnCPUWrite(addr, size);
  371. {
  372. std::scoped_lock lock{texture_cache.mutex};
  373. texture_cache.WriteMemory(addr, size);
  374. }
  375. {
  376. std::scoped_lock lock{buffer_cache.mutex};
  377. buffer_cache.CachedWriteMemory(addr, size);
  378. }
  379. }
  380. void RasterizerVulkan::SyncGuestHost() {
  381. pipeline_cache.SyncGuestHost();
  382. {
  383. std::scoped_lock lock{buffer_cache.mutex};
  384. buffer_cache.FlushCachedWrites();
  385. }
  386. }
  387. void RasterizerVulkan::UnmapMemory(VAddr addr, u64 size) {
  388. {
  389. std::scoped_lock lock{texture_cache.mutex};
  390. texture_cache.UnmapMemory(addr, size);
  391. }
  392. {
  393. std::scoped_lock lock{buffer_cache.mutex};
  394. buffer_cache.WriteMemory(addr, size);
  395. }
  396. pipeline_cache.OnCPUWrite(addr, size);
  397. }
  398. void RasterizerVulkan::ModifyGPUMemory(GPUVAddr addr, u64 size) {
  399. {
  400. std::scoped_lock lock{texture_cache.mutex};
  401. texture_cache.UnmapGPUMemory(addr, size);
  402. }
  403. }
  404. void RasterizerVulkan::SignalSemaphore(GPUVAddr addr, u32 value) {
  405. if (!gpu.IsAsync()) {
  406. gpu_memory.Write<u32>(addr, value);
  407. return;
  408. }
  409. fence_manager.SignalSemaphore(addr, value);
  410. }
  411. void RasterizerVulkan::SignalSyncPoint(u32 value) {
  412. if (!gpu.IsAsync()) {
  413. gpu.IncrementSyncPoint(value);
  414. return;
  415. }
  416. fence_manager.SignalSyncPoint(value);
  417. }
  418. void RasterizerVulkan::SignalReference() {
  419. if (!gpu.IsAsync()) {
  420. return;
  421. }
  422. fence_manager.SignalOrdering();
  423. }
  424. void RasterizerVulkan::ReleaseFences() {
  425. if (!gpu.IsAsync()) {
  426. return;
  427. }
  428. fence_manager.WaitPendingFences();
  429. }
  430. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  431. if (Settings::IsGPULevelExtreme()) {
  432. FlushRegion(addr, size);
  433. }
  434. InvalidateRegion(addr, size);
  435. }
  436. void RasterizerVulkan::WaitForIdle() {
  437. // Everything but wait pixel operations. This intentionally includes FRAGMENT_SHADER_BIT because
  438. // fragment shaders can still write storage buffers.
  439. VkPipelineStageFlags flags =
  440. VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT |
  441. VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
  442. VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
  443. VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
  444. VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  445. if (device.IsExtTransformFeedbackSupported()) {
  446. flags |= VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT;
  447. }
  448. scheduler.RequestOutsideRenderPassOperationContext();
  449. scheduler.Record([event = *wfi_event, flags](vk::CommandBuffer cmdbuf) {
  450. cmdbuf.SetEvent(event, flags);
  451. cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {});
  452. });
  453. SignalReference();
  454. }
  455. void RasterizerVulkan::FragmentBarrier() {
  456. // We already put barriers when a render pass finishes
  457. scheduler.RequestOutsideRenderPassOperationContext();
  458. }
  459. void RasterizerVulkan::TiledCacheBarrier() {
  460. // TODO: Implementing tiled barriers requires rewriting a good chunk of the Vulkan backend
  461. }
  462. void RasterizerVulkan::FlushCommands() {
  463. if (draw_counter == 0) {
  464. return;
  465. }
  466. draw_counter = 0;
  467. scheduler.Flush();
  468. }
  469. void RasterizerVulkan::TickFrame() {
  470. draw_counter = 0;
  471. update_descriptor_queue.TickFrame();
  472. fence_manager.TickFrame();
  473. staging_pool.TickFrame();
  474. {
  475. std::scoped_lock lock{texture_cache.mutex};
  476. texture_cache.TickFrame();
  477. }
  478. {
  479. std::scoped_lock lock{buffer_cache.mutex};
  480. buffer_cache.TickFrame();
  481. }
  482. }
  483. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
  484. const Tegra::Engines::Fermi2D::Surface& dst,
  485. const Tegra::Engines::Fermi2D::Config& copy_config) {
  486. std::scoped_lock lock{texture_cache.mutex};
  487. texture_cache.BlitImage(dst, src, copy_config);
  488. return true;
  489. }
  490. Tegra::Engines::AccelerateDMAInterface& RasterizerVulkan::AccessAccelerateDMA() {
  491. return accelerate_dma;
  492. }
  493. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  494. VAddr framebuffer_addr, u32 pixel_stride) {
  495. if (!framebuffer_addr) {
  496. return false;
  497. }
  498. std::scoped_lock lock{texture_cache.mutex};
  499. ImageView* const image_view = texture_cache.TryFindFramebufferImageView(framebuffer_addr);
  500. if (!image_view) {
  501. return false;
  502. }
  503. screen_info.image_view = image_view->Handle(Shader::TextureType::Color2D);
  504. screen_info.width = image_view->size.width;
  505. screen_info.height = image_view->size.height;
  506. screen_info.is_srgb = VideoCore::Surface::IsPixelFormatSRGB(image_view->format);
  507. return true;
  508. }
  509. void RasterizerVulkan::LoadDiskResources(u64 title_id, std::stop_token stop_loading,
  510. const VideoCore::DiskResourceLoadCallback& callback) {
  511. pipeline_cache.LoadDiskResources(title_id, stop_loading, callback);
  512. }
  513. void RasterizerVulkan::FlushWork() {
  514. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  515. // Only check multiples of 8 draws
  516. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  517. if ((++draw_counter & 7) != 7) {
  518. return;
  519. }
  520. if (draw_counter < DRAWS_TO_DISPATCH) {
  521. // Send recorded tasks to the worker thread
  522. scheduler.DispatchWork();
  523. return;
  524. }
  525. // Otherwise (every certain number of draws) flush execution.
  526. // This submits commands to the Vulkan driver.
  527. scheduler.Flush();
  528. draw_counter = 0;
  529. }
  530. AccelerateDMA::AccelerateDMA(BufferCache& buffer_cache_) : buffer_cache{buffer_cache_} {}
  531. bool AccelerateDMA::BufferClear(GPUVAddr src_address, u64 amount, u32 value) {
  532. std::scoped_lock lock{buffer_cache.mutex};
  533. return buffer_cache.DMAClear(src_address, amount, value);
  534. }
  535. bool AccelerateDMA::BufferCopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  536. std::scoped_lock lock{buffer_cache.mutex};
  537. return buffer_cache.DMACopy(src_address, dest_address, amount);
  538. }
  539. void RasterizerVulkan::UpdateDynamicStates() {
  540. auto& regs = maxwell3d.regs;
  541. UpdateViewportsState(regs);
  542. UpdateScissorsState(regs);
  543. UpdateDepthBias(regs);
  544. UpdateBlendConstants(regs);
  545. UpdateDepthBounds(regs);
  546. UpdateStencilFaces(regs);
  547. UpdateLineWidth(regs);
  548. if (device.IsExtExtendedDynamicStateSupported()) {
  549. UpdateCullMode(regs);
  550. UpdateDepthBoundsTestEnable(regs);
  551. UpdateDepthTestEnable(regs);
  552. UpdateDepthWriteEnable(regs);
  553. UpdateDepthCompareOp(regs);
  554. UpdateFrontFace(regs);
  555. UpdateStencilOp(regs);
  556. UpdateStencilTestEnable(regs);
  557. if (device.IsExtVertexInputDynamicStateSupported()) {
  558. UpdateVertexInput(regs);
  559. }
  560. }
  561. }
  562. void RasterizerVulkan::BeginTransformFeedback() {
  563. const auto& regs = maxwell3d.regs;
  564. if (regs.tfb_enabled == 0) {
  565. return;
  566. }
  567. if (!device.IsExtTransformFeedbackSupported()) {
  568. LOG_ERROR(Render_Vulkan, "Transform feedbacks used but not supported");
  569. return;
  570. }
  571. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  572. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  573. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  574. scheduler.Record(
  575. [](vk::CommandBuffer cmdbuf) { cmdbuf.BeginTransformFeedbackEXT(0, 0, nullptr, nullptr); });
  576. }
  577. void RasterizerVulkan::EndTransformFeedback() {
  578. const auto& regs = maxwell3d.regs;
  579. if (regs.tfb_enabled == 0) {
  580. return;
  581. }
  582. if (!device.IsExtTransformFeedbackSupported()) {
  583. return;
  584. }
  585. scheduler.Record(
  586. [](vk::CommandBuffer cmdbuf) { cmdbuf.EndTransformFeedbackEXT(0, 0, nullptr, nullptr); });
  587. }
  588. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  589. if (!state_tracker.TouchViewports()) {
  590. return;
  591. }
  592. const bool is_rescaling{texture_cache.IsRescaling()};
  593. const float scale = is_rescaling ? Settings::values.resolution_info.up_factor : 1.0f;
  594. const std::array viewports{
  595. GetViewportState(device, regs, 0, scale), GetViewportState(device, regs, 1, scale),
  596. GetViewportState(device, regs, 2, scale), GetViewportState(device, regs, 3, scale),
  597. GetViewportState(device, regs, 4, scale), GetViewportState(device, regs, 5, scale),
  598. GetViewportState(device, regs, 6, scale), GetViewportState(device, regs, 7, scale),
  599. GetViewportState(device, regs, 8, scale), GetViewportState(device, regs, 9, scale),
  600. GetViewportState(device, regs, 10, scale), GetViewportState(device, regs, 11, scale),
  601. GetViewportState(device, regs, 12, scale), GetViewportState(device, regs, 13, scale),
  602. GetViewportState(device, regs, 14, scale), GetViewportState(device, regs, 15, scale),
  603. };
  604. scheduler.Record([viewports](vk::CommandBuffer cmdbuf) { cmdbuf.SetViewport(0, viewports); });
  605. }
  606. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  607. if (!state_tracker.TouchScissors()) {
  608. return;
  609. }
  610. u32 up_scale = 1;
  611. u32 down_shift = 0;
  612. if (texture_cache.IsRescaling()) {
  613. up_scale = Settings::values.resolution_info.up_scale;
  614. down_shift = Settings::values.resolution_info.down_shift;
  615. }
  616. const std::array scissors{
  617. GetScissorState(regs, 0, up_scale, down_shift),
  618. GetScissorState(regs, 1, up_scale, down_shift),
  619. GetScissorState(regs, 2, up_scale, down_shift),
  620. GetScissorState(regs, 3, up_scale, down_shift),
  621. GetScissorState(regs, 4, up_scale, down_shift),
  622. GetScissorState(regs, 5, up_scale, down_shift),
  623. GetScissorState(regs, 6, up_scale, down_shift),
  624. GetScissorState(regs, 7, up_scale, down_shift),
  625. GetScissorState(regs, 8, up_scale, down_shift),
  626. GetScissorState(regs, 9, up_scale, down_shift),
  627. GetScissorState(regs, 10, up_scale, down_shift),
  628. GetScissorState(regs, 11, up_scale, down_shift),
  629. GetScissorState(regs, 12, up_scale, down_shift),
  630. GetScissorState(regs, 13, up_scale, down_shift),
  631. GetScissorState(regs, 14, up_scale, down_shift),
  632. GetScissorState(regs, 15, up_scale, down_shift),
  633. };
  634. scheduler.Record([scissors](vk::CommandBuffer cmdbuf) { cmdbuf.SetScissor(0, scissors); });
  635. }
  636. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  637. if (!state_tracker.TouchDepthBias()) {
  638. return;
  639. }
  640. float units = regs.polygon_offset_units / 2.0f;
  641. const bool is_d24 = regs.zeta.format == Tegra::DepthFormat::S8_UINT_Z24_UNORM ||
  642. regs.zeta.format == Tegra::DepthFormat::D24X8_UNORM ||
  643. regs.zeta.format == Tegra::DepthFormat::D24S8_UNORM ||
  644. regs.zeta.format == Tegra::DepthFormat::D24C8_UNORM;
  645. if (is_d24 && !device.SupportsD24DepthBuffer()) {
  646. // the base formulas can be obtained from here:
  647. // https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-output-merger-stage-depth-bias
  648. const double rescale_factor =
  649. static_cast<double>(1ULL << (32 - 24)) / (static_cast<double>(0x1.ep+127));
  650. units = static_cast<float>(static_cast<double>(units) * rescale_factor);
  651. }
  652. scheduler.Record([constant = units, clamp = regs.polygon_offset_clamp,
  653. factor = regs.polygon_offset_factor](vk::CommandBuffer cmdbuf) {
  654. cmdbuf.SetDepthBias(constant, clamp, factor);
  655. });
  656. }
  657. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  658. if (!state_tracker.TouchBlendConstants()) {
  659. return;
  660. }
  661. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  662. regs.blend_color.a};
  663. scheduler.Record(
  664. [blend_color](vk::CommandBuffer cmdbuf) { cmdbuf.SetBlendConstants(blend_color.data()); });
  665. }
  666. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  667. if (!state_tracker.TouchDepthBounds()) {
  668. return;
  669. }
  670. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  671. vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthBounds(min, max); });
  672. }
  673. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  674. if (!state_tracker.TouchStencilProperties()) {
  675. return;
  676. }
  677. if (regs.stencil_two_side_enable) {
  678. // Separate values per face
  679. scheduler.Record(
  680. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  681. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  682. back_write_mask = regs.stencil_back_mask,
  683. back_test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  684. // Front face
  685. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_BIT, front_ref);
  686. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_BIT, front_write_mask);
  687. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_BIT, front_test_mask);
  688. // Back face
  689. cmdbuf.SetStencilReference(VK_STENCIL_FACE_BACK_BIT, back_ref);
  690. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_BACK_BIT, back_write_mask);
  691. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_BACK_BIT, back_test_mask);
  692. });
  693. } else {
  694. // Front face defines both faces
  695. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  696. test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  697. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_AND_BACK, ref);
  698. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_AND_BACK, write_mask);
  699. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_AND_BACK, test_mask);
  700. });
  701. }
  702. }
  703. void RasterizerVulkan::UpdateLineWidth(Tegra::Engines::Maxwell3D::Regs& regs) {
  704. if (!state_tracker.TouchLineWidth()) {
  705. return;
  706. }
  707. const float width = regs.line_smooth_enable ? regs.line_width_smooth : regs.line_width_aliased;
  708. scheduler.Record([width](vk::CommandBuffer cmdbuf) { cmdbuf.SetLineWidth(width); });
  709. }
  710. void RasterizerVulkan::UpdateCullMode(Tegra::Engines::Maxwell3D::Regs& regs) {
  711. if (!state_tracker.TouchCullMode()) {
  712. return;
  713. }
  714. scheduler.Record(
  715. [enabled = regs.cull_test_enabled, cull_face = regs.cull_face](vk::CommandBuffer cmdbuf) {
  716. cmdbuf.SetCullModeEXT(enabled ? MaxwellToVK::CullFace(cull_face) : VK_CULL_MODE_NONE);
  717. });
  718. }
  719. void RasterizerVulkan::UpdateDepthBoundsTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  720. if (!state_tracker.TouchDepthBoundsTestEnable()) {
  721. return;
  722. }
  723. bool enabled = regs.depth_bounds_enable;
  724. if (enabled && !device.IsDepthBoundsSupported()) {
  725. LOG_WARNING(Render_Vulkan, "Depth bounds is enabled but not supported");
  726. enabled = false;
  727. }
  728. scheduler.Record([enable = regs.depth_bounds_enable](vk::CommandBuffer cmdbuf) {
  729. cmdbuf.SetDepthBoundsTestEnableEXT(enable);
  730. });
  731. }
  732. void RasterizerVulkan::UpdateDepthTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  733. if (!state_tracker.TouchDepthTestEnable()) {
  734. return;
  735. }
  736. scheduler.Record([enable = regs.depth_test_enable](vk::CommandBuffer cmdbuf) {
  737. cmdbuf.SetDepthTestEnableEXT(enable);
  738. });
  739. }
  740. void RasterizerVulkan::UpdateDepthWriteEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  741. if (!state_tracker.TouchDepthWriteEnable()) {
  742. return;
  743. }
  744. scheduler.Record([enable = regs.depth_write_enabled](vk::CommandBuffer cmdbuf) {
  745. cmdbuf.SetDepthWriteEnableEXT(enable);
  746. });
  747. }
  748. void RasterizerVulkan::UpdateDepthCompareOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  749. if (!state_tracker.TouchDepthCompareOp()) {
  750. return;
  751. }
  752. scheduler.Record([func = regs.depth_test_func](vk::CommandBuffer cmdbuf) {
  753. cmdbuf.SetDepthCompareOpEXT(MaxwellToVK::ComparisonOp(func));
  754. });
  755. }
  756. void RasterizerVulkan::UpdateFrontFace(Tegra::Engines::Maxwell3D::Regs& regs) {
  757. if (!state_tracker.TouchFrontFace()) {
  758. return;
  759. }
  760. VkFrontFace front_face = MaxwellToVK::FrontFace(regs.front_face);
  761. if (regs.screen_y_control.triangle_rast_flip != 0) {
  762. front_face = front_face == VK_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_COUNTER_CLOCKWISE
  763. : VK_FRONT_FACE_CLOCKWISE;
  764. }
  765. scheduler.Record(
  766. [front_face](vk::CommandBuffer cmdbuf) { cmdbuf.SetFrontFaceEXT(front_face); });
  767. }
  768. void RasterizerVulkan::UpdateStencilOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  769. if (!state_tracker.TouchStencilOp()) {
  770. return;
  771. }
  772. const Maxwell::StencilOp fail = regs.stencil_front_op_fail;
  773. const Maxwell::StencilOp zfail = regs.stencil_front_op_zfail;
  774. const Maxwell::StencilOp zpass = regs.stencil_front_op_zpass;
  775. const Maxwell::ComparisonOp compare = regs.stencil_front_func_func;
  776. if (regs.stencil_two_side_enable) {
  777. // Separate stencil op per face
  778. const Maxwell::StencilOp back_fail = regs.stencil_back_op_fail;
  779. const Maxwell::StencilOp back_zfail = regs.stencil_back_op_zfail;
  780. const Maxwell::StencilOp back_zpass = regs.stencil_back_op_zpass;
  781. const Maxwell::ComparisonOp back_compare = regs.stencil_back_func_func;
  782. scheduler.Record([fail, zfail, zpass, compare, back_fail, back_zfail, back_zpass,
  783. back_compare](vk::CommandBuffer cmdbuf) {
  784. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_BIT, MaxwellToVK::StencilOp(fail),
  785. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  786. MaxwellToVK::ComparisonOp(compare));
  787. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_BACK_BIT, MaxwellToVK::StencilOp(back_fail),
  788. MaxwellToVK::StencilOp(back_zpass),
  789. MaxwellToVK::StencilOp(back_zfail),
  790. MaxwellToVK::ComparisonOp(back_compare));
  791. });
  792. } else {
  793. // Front face defines the stencil op of both faces
  794. scheduler.Record([fail, zfail, zpass, compare](vk::CommandBuffer cmdbuf) {
  795. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_AND_BACK, MaxwellToVK::StencilOp(fail),
  796. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  797. MaxwellToVK::ComparisonOp(compare));
  798. });
  799. }
  800. }
  801. void RasterizerVulkan::UpdateStencilTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  802. if (!state_tracker.TouchStencilTestEnable()) {
  803. return;
  804. }
  805. scheduler.Record([enable = regs.stencil_enable](vk::CommandBuffer cmdbuf) {
  806. cmdbuf.SetStencilTestEnableEXT(enable);
  807. });
  808. }
  809. void RasterizerVulkan::UpdateVertexInput(Tegra::Engines::Maxwell3D::Regs& regs) {
  810. auto& dirty{maxwell3d.dirty.flags};
  811. if (!dirty[Dirty::VertexInput]) {
  812. return;
  813. }
  814. dirty[Dirty::VertexInput] = false;
  815. boost::container::static_vector<VkVertexInputBindingDescription2EXT, 32> bindings;
  816. boost::container::static_vector<VkVertexInputAttributeDescription2EXT, 32> attributes;
  817. // There seems to be a bug on Nvidia's driver where updating only higher attributes ends up
  818. // generating dirty state. Track the highest dirty attribute and update all attributes until
  819. // that one.
  820. size_t highest_dirty_attr{};
  821. for (size_t index = 0; index < Maxwell::NumVertexAttributes; ++index) {
  822. if (dirty[Dirty::VertexAttribute0 + index]) {
  823. highest_dirty_attr = index;
  824. }
  825. }
  826. for (size_t index = 0; index < highest_dirty_attr; ++index) {
  827. const Maxwell::VertexAttribute attribute{regs.vertex_attrib_format[index]};
  828. const u32 binding{attribute.buffer};
  829. dirty[Dirty::VertexAttribute0 + index] = false;
  830. dirty[Dirty::VertexBinding0 + static_cast<size_t>(binding)] = true;
  831. if (!attribute.constant) {
  832. attributes.push_back({
  833. .sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_ATTRIBUTE_DESCRIPTION_2_EXT,
  834. .pNext = nullptr,
  835. .location = static_cast<u32>(index),
  836. .binding = binding,
  837. .format = MaxwellToVK::VertexFormat(attribute.type, attribute.size),
  838. .offset = attribute.offset,
  839. });
  840. }
  841. }
  842. for (size_t index = 0; index < Maxwell::NumVertexAttributes; ++index) {
  843. if (!dirty[Dirty::VertexBinding0 + index]) {
  844. continue;
  845. }
  846. dirty[Dirty::VertexBinding0 + index] = false;
  847. const u32 binding{static_cast<u32>(index)};
  848. const auto& input_binding{regs.vertex_array[binding]};
  849. const bool is_instanced{regs.instanced_arrays.IsInstancingEnabled(binding)};
  850. bindings.push_back({
  851. .sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT,
  852. .pNext = nullptr,
  853. .binding = binding,
  854. .stride = input_binding.stride,
  855. .inputRate = is_instanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX,
  856. .divisor = is_instanced ? input_binding.divisor : 1,
  857. });
  858. }
  859. scheduler.Record([bindings, attributes](vk::CommandBuffer cmdbuf) {
  860. cmdbuf.SetVertexInputEXT(bindings, attributes);
  861. });
  862. }
  863. } // namespace Vulkan