vk_rasterizer.cpp 41 KB

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