vk_rasterizer.cpp 49 KB

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