vk_rasterizer.cpp 63 KB

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