vk_rasterizer.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <mutex>
  8. #include <vector>
  9. #include <boost/container/static_vector.hpp>
  10. #include "common/alignment.h"
  11. #include "common/assert.h"
  12. #include "common/logging/log.h"
  13. #include "common/microprofile.h"
  14. #include "common/scope_exit.h"
  15. #include "core/core.h"
  16. #include "core/settings.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  20. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  21. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  22. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  23. #include "video_core/renderer_vulkan/vk_compute_pass.h"
  24. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  25. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  26. #include "video_core/renderer_vulkan/vk_device.h"
  27. #include "video_core/renderer_vulkan/vk_graphics_pipeline.h"
  28. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  29. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  30. #include "video_core/renderer_vulkan/vk_renderpass_cache.h"
  31. #include "video_core/renderer_vulkan/vk_resource_manager.h"
  32. #include "video_core/renderer_vulkan/vk_sampler_cache.h"
  33. #include "video_core/renderer_vulkan/vk_scheduler.h"
  34. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  35. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  36. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  37. #include "video_core/renderer_vulkan/vk_update_descriptor.h"
  38. #include "video_core/renderer_vulkan/wrapper.h"
  39. #include "video_core/shader_cache.h"
  40. namespace Vulkan {
  41. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  42. MICROPROFILE_DEFINE(Vulkan_WaitForWorker, "Vulkan", "Wait for worker", MP_RGB(255, 192, 192));
  43. MICROPROFILE_DEFINE(Vulkan_Drawing, "Vulkan", "Record drawing", MP_RGB(192, 128, 128));
  44. MICROPROFILE_DEFINE(Vulkan_Compute, "Vulkan", "Record compute", MP_RGB(192, 128, 128));
  45. MICROPROFILE_DEFINE(Vulkan_Clearing, "Vulkan", "Record clearing", MP_RGB(192, 128, 128));
  46. MICROPROFILE_DEFINE(Vulkan_Geometry, "Vulkan", "Setup geometry", MP_RGB(192, 128, 128));
  47. MICROPROFILE_DEFINE(Vulkan_ConstBuffers, "Vulkan", "Setup constant buffers", MP_RGB(192, 128, 128));
  48. MICROPROFILE_DEFINE(Vulkan_GlobalBuffers, "Vulkan", "Setup global buffers", MP_RGB(192, 128, 128));
  49. MICROPROFILE_DEFINE(Vulkan_RenderTargets, "Vulkan", "Setup render targets", MP_RGB(192, 128, 128));
  50. MICROPROFILE_DEFINE(Vulkan_Textures, "Vulkan", "Setup textures", MP_RGB(192, 128, 128));
  51. MICROPROFILE_DEFINE(Vulkan_Images, "Vulkan", "Setup images", MP_RGB(192, 128, 128));
  52. MICROPROFILE_DEFINE(Vulkan_PipelineCache, "Vulkan", "Pipeline cache", MP_RGB(192, 128, 128));
  53. namespace {
  54. constexpr auto ComputeShaderIndex = static_cast<std::size_t>(Tegra::Engines::ShaderType::Compute);
  55. VkViewport GetViewportState(const VKDevice& device, const Maxwell& regs, std::size_t index) {
  56. const auto& src = regs.viewport_transform[index];
  57. const float width = src.scale_x * 2.0f;
  58. const float height = src.scale_y * 2.0f;
  59. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne ? 1.0f : 0.0f;
  60. VkViewport viewport{
  61. .x = src.translate_x - src.scale_x,
  62. .y = src.translate_y - src.scale_y,
  63. .width = width != 0.0f ? width : 1.0f,
  64. .height = height != 0.0f ? height : 1.0f,
  65. .minDepth = src.translate_z - src.scale_z * reduce_z,
  66. .maxDepth = src.translate_z + src.scale_z,
  67. };
  68. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  69. viewport.minDepth = std::clamp(viewport.minDepth, 0.0f, 1.0f);
  70. viewport.maxDepth = std::clamp(viewport.maxDepth, 0.0f, 1.0f);
  71. }
  72. return viewport;
  73. }
  74. VkRect2D GetScissorState(const Maxwell& regs, std::size_t index) {
  75. const auto& src = regs.scissor_test[index];
  76. VkRect2D scissor;
  77. if (src.enable) {
  78. scissor.offset.x = static_cast<s32>(src.min_x);
  79. scissor.offset.y = static_cast<s32>(src.min_y);
  80. scissor.extent.width = src.max_x - src.min_x;
  81. scissor.extent.height = src.max_y - src.min_y;
  82. } else {
  83. scissor.offset.x = 0;
  84. scissor.offset.y = 0;
  85. scissor.extent.width = std::numeric_limits<s32>::max();
  86. scissor.extent.height = std::numeric_limits<s32>::max();
  87. }
  88. return scissor;
  89. }
  90. std::array<GPUVAddr, Maxwell::MaxShaderProgram> GetShaderAddresses(
  91. const std::array<Shader*, Maxwell::MaxShaderProgram>& shaders) {
  92. std::array<GPUVAddr, Maxwell::MaxShaderProgram> addresses;
  93. for (std::size_t i = 0; i < std::size(addresses); ++i) {
  94. addresses[i] = shaders[i] ? shaders[i]->GetGpuAddr() : 0;
  95. }
  96. return addresses;
  97. }
  98. void TransitionImages(const std::vector<ImageView>& views, VkPipelineStageFlags pipeline_stage,
  99. VkAccessFlags access) {
  100. for (auto& [view, layout] : views) {
  101. view->Transition(*layout, pipeline_stage, access);
  102. }
  103. }
  104. template <typename Engine, typename Entry>
  105. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  106. std::size_t stage, std::size_t index = 0) {
  107. const auto stage_type = static_cast<Tegra::Engines::ShaderType>(stage);
  108. if constexpr (std::is_same_v<Entry, SamplerEntry>) {
  109. if (entry.is_separated) {
  110. const u32 buffer_1 = entry.buffer;
  111. const u32 buffer_2 = entry.secondary_buffer;
  112. const u32 offset_1 = entry.offset;
  113. const u32 offset_2 = entry.secondary_offset;
  114. const u32 handle_1 = engine.AccessConstBuffer32(stage_type, buffer_1, offset_1);
  115. const u32 handle_2 = engine.AccessConstBuffer32(stage_type, buffer_2, offset_2);
  116. return engine.GetTextureInfo(handle_1 | handle_2);
  117. }
  118. }
  119. if (entry.is_bindless) {
  120. const auto tex_handle = engine.AccessConstBuffer32(stage_type, entry.buffer, entry.offset);
  121. return engine.GetTextureInfo(tex_handle);
  122. }
  123. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  124. const u32 entry_offset = static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  125. const u32 offset = entry.offset + entry_offset;
  126. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  127. return engine.GetStageTexture(stage_type, offset);
  128. } else {
  129. return engine.GetTexture(offset);
  130. }
  131. }
  132. /// @brief Determine if an attachment to be updated has to preserve contents
  133. /// @param is_clear True when a clear is being executed
  134. /// @param regs 3D registers
  135. /// @return True when the contents have to be preserved
  136. bool HasToPreserveColorContents(bool is_clear, const Maxwell& regs) {
  137. if (!is_clear) {
  138. return true;
  139. }
  140. // First we have to make sure all clear masks are enabled.
  141. if (!regs.clear_buffers.R || !regs.clear_buffers.G || !regs.clear_buffers.B ||
  142. !regs.clear_buffers.A) {
  143. return true;
  144. }
  145. // If scissors are disabled, the whole screen is cleared
  146. if (!regs.clear_flags.scissor) {
  147. return false;
  148. }
  149. // Then we have to confirm scissor testing clears the whole image
  150. const std::size_t index = regs.clear_buffers.RT;
  151. const auto& scissor = regs.scissor_test[0];
  152. return scissor.min_x > 0 || scissor.min_y > 0 || scissor.max_x < regs.rt[index].width ||
  153. scissor.max_y < regs.rt[index].height;
  154. }
  155. /// @brief Determine if an attachment to be updated has to preserve contents
  156. /// @param is_clear True when a clear is being executed
  157. /// @param regs 3D registers
  158. /// @return True when the contents have to be preserved
  159. bool HasToPreserveDepthContents(bool is_clear, const Maxwell& regs) {
  160. // If we are not clearing, the contents have to be preserved
  161. if (!is_clear) {
  162. return true;
  163. }
  164. // For depth stencil clears we only have to confirm scissor test covers the whole image
  165. if (!regs.clear_flags.scissor) {
  166. return false;
  167. }
  168. // Make sure the clear cover the whole image
  169. const auto& scissor = regs.scissor_test[0];
  170. return scissor.min_x > 0 || scissor.min_y > 0 || scissor.max_x < regs.zeta_width ||
  171. scissor.max_y < regs.zeta_height;
  172. }
  173. template <std::size_t N>
  174. std::array<VkDeviceSize, N> ExpandStrides(const std::array<u16, N>& strides) {
  175. std::array<VkDeviceSize, N> expanded;
  176. std::copy(strides.begin(), strides.end(), expanded.begin());
  177. return expanded;
  178. }
  179. } // Anonymous namespace
  180. class BufferBindings final {
  181. public:
  182. void AddVertexBinding(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, u32 stride) {
  183. vertex.buffers[vertex.num_buffers] = buffer;
  184. vertex.offsets[vertex.num_buffers] = offset;
  185. vertex.sizes[vertex.num_buffers] = size;
  186. vertex.strides[vertex.num_buffers] = static_cast<u16>(stride);
  187. ++vertex.num_buffers;
  188. }
  189. void SetIndexBinding(VkBuffer buffer, VkDeviceSize offset, VkIndexType type) {
  190. index.buffer = buffer;
  191. index.offset = offset;
  192. index.type = type;
  193. }
  194. void Bind(const VKDevice& device, VKScheduler& scheduler) const {
  195. // Use this large switch case to avoid dispatching more memory in the record lambda than
  196. // what we need. It looks horrible, but it's the best we can do on standard C++.
  197. switch (vertex.num_buffers) {
  198. case 0:
  199. return BindStatic<0>(device, scheduler);
  200. case 1:
  201. return BindStatic<1>(device, scheduler);
  202. case 2:
  203. return BindStatic<2>(device, scheduler);
  204. case 3:
  205. return BindStatic<3>(device, scheduler);
  206. case 4:
  207. return BindStatic<4>(device, scheduler);
  208. case 5:
  209. return BindStatic<5>(device, scheduler);
  210. case 6:
  211. return BindStatic<6>(device, scheduler);
  212. case 7:
  213. return BindStatic<7>(device, scheduler);
  214. case 8:
  215. return BindStatic<8>(device, scheduler);
  216. case 9:
  217. return BindStatic<9>(device, scheduler);
  218. case 10:
  219. return BindStatic<10>(device, scheduler);
  220. case 11:
  221. return BindStatic<11>(device, scheduler);
  222. case 12:
  223. return BindStatic<12>(device, scheduler);
  224. case 13:
  225. return BindStatic<13>(device, scheduler);
  226. case 14:
  227. return BindStatic<14>(device, scheduler);
  228. case 15:
  229. return BindStatic<15>(device, scheduler);
  230. case 16:
  231. return BindStatic<16>(device, scheduler);
  232. case 17:
  233. return BindStatic<17>(device, scheduler);
  234. case 18:
  235. return BindStatic<18>(device, scheduler);
  236. case 19:
  237. return BindStatic<19>(device, scheduler);
  238. case 20:
  239. return BindStatic<20>(device, scheduler);
  240. case 21:
  241. return BindStatic<21>(device, scheduler);
  242. case 22:
  243. return BindStatic<22>(device, scheduler);
  244. case 23:
  245. return BindStatic<23>(device, scheduler);
  246. case 24:
  247. return BindStatic<24>(device, scheduler);
  248. case 25:
  249. return BindStatic<25>(device, scheduler);
  250. case 26:
  251. return BindStatic<26>(device, scheduler);
  252. case 27:
  253. return BindStatic<27>(device, scheduler);
  254. case 28:
  255. return BindStatic<28>(device, scheduler);
  256. case 29:
  257. return BindStatic<29>(device, scheduler);
  258. case 30:
  259. return BindStatic<30>(device, scheduler);
  260. case 31:
  261. return BindStatic<31>(device, scheduler);
  262. case 32:
  263. return BindStatic<32>(device, scheduler);
  264. }
  265. UNREACHABLE();
  266. }
  267. private:
  268. // Some of these fields are intentionally left uninitialized to avoid initializing them twice.
  269. struct {
  270. std::size_t num_buffers = 0;
  271. std::array<VkBuffer, Maxwell::NumVertexArrays> buffers;
  272. std::array<VkDeviceSize, Maxwell::NumVertexArrays> offsets;
  273. std::array<VkDeviceSize, Maxwell::NumVertexArrays> sizes;
  274. std::array<u16, Maxwell::NumVertexArrays> strides;
  275. } vertex;
  276. struct {
  277. VkBuffer buffer = nullptr;
  278. VkDeviceSize offset;
  279. VkIndexType type;
  280. } index;
  281. template <std::size_t N>
  282. void BindStatic(const VKDevice& device, VKScheduler& scheduler) const {
  283. if (device.IsExtExtendedDynamicStateSupported()) {
  284. if (index.buffer) {
  285. BindStatic<N, true, true>(scheduler);
  286. } else {
  287. BindStatic<N, false, true>(scheduler);
  288. }
  289. } else {
  290. if (index.buffer) {
  291. BindStatic<N, true, false>(scheduler);
  292. } else {
  293. BindStatic<N, false, false>(scheduler);
  294. }
  295. }
  296. }
  297. template <std::size_t N, bool is_indexed, bool has_extended_dynamic_state>
  298. void BindStatic(VKScheduler& scheduler) const {
  299. static_assert(N <= Maxwell::NumVertexArrays);
  300. if constexpr (N == 0) {
  301. return;
  302. }
  303. std::array<VkBuffer, N> buffers;
  304. std::array<VkDeviceSize, N> offsets;
  305. std::copy(vertex.buffers.begin(), vertex.buffers.begin() + N, buffers.begin());
  306. std::copy(vertex.offsets.begin(), vertex.offsets.begin() + N, offsets.begin());
  307. if constexpr (has_extended_dynamic_state) {
  308. // With extended dynamic states we can specify the length and stride of a vertex buffer
  309. std::array<VkDeviceSize, N> sizes;
  310. std::array<u16, N> strides;
  311. std::copy(vertex.sizes.begin(), vertex.sizes.begin() + N, sizes.begin());
  312. std::copy(vertex.strides.begin(), vertex.strides.begin() + N, strides.begin());
  313. if constexpr (is_indexed) {
  314. scheduler.Record(
  315. [buffers, offsets, sizes, strides, index = index](vk::CommandBuffer cmdbuf) {
  316. cmdbuf.BindIndexBuffer(index.buffer, index.offset, index.type);
  317. cmdbuf.BindVertexBuffers2EXT(0, static_cast<u32>(N), buffers.data(),
  318. offsets.data(), sizes.data(),
  319. ExpandStrides(strides).data());
  320. });
  321. } else {
  322. scheduler.Record([buffers, offsets, sizes, strides](vk::CommandBuffer cmdbuf) {
  323. cmdbuf.BindVertexBuffers2EXT(0, static_cast<u32>(N), buffers.data(),
  324. offsets.data(), sizes.data(),
  325. ExpandStrides(strides).data());
  326. });
  327. }
  328. return;
  329. }
  330. if constexpr (is_indexed) {
  331. // Indexed draw
  332. scheduler.Record([buffers, offsets, index = index](vk::CommandBuffer cmdbuf) {
  333. cmdbuf.BindIndexBuffer(index.buffer, index.offset, index.type);
  334. cmdbuf.BindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data());
  335. });
  336. } else {
  337. // Array draw
  338. scheduler.Record([buffers, offsets](vk::CommandBuffer cmdbuf) {
  339. cmdbuf.BindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data());
  340. });
  341. }
  342. }
  343. };
  344. void RasterizerVulkan::DrawParameters::Draw(vk::CommandBuffer cmdbuf) const {
  345. if (is_indexed) {
  346. cmdbuf.DrawIndexed(num_vertices, num_instances, 0, base_vertex, base_instance);
  347. } else {
  348. cmdbuf.Draw(num_vertices, num_instances, base_vertex, base_instance);
  349. }
  350. }
  351. RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window, Tegra::GPU& gpu_,
  352. Tegra::MemoryManager& gpu_memory_,
  353. Core::Memory::Memory& cpu_memory, VKScreenInfo& screen_info_,
  354. const VKDevice& device_, VKResourceManager& resource_manager_,
  355. VKMemoryManager& memory_manager_, StateTracker& state_tracker_,
  356. VKScheduler& scheduler_)
  357. : RasterizerAccelerated(cpu_memory), gpu(gpu_), gpu_memory(gpu_memory_),
  358. maxwell3d(gpu.Maxwell3D()), kepler_compute(gpu.KeplerCompute()), screen_info(screen_info_),
  359. device(device_), resource_manager(resource_manager_), memory_manager(memory_manager_),
  360. state_tracker(state_tracker_), scheduler(scheduler_),
  361. staging_pool(device, memory_manager, scheduler), descriptor_pool(device),
  362. update_descriptor_queue(device, scheduler), renderpass_cache(device),
  363. quad_array_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  364. quad_indexed_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  365. uint8_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  366. texture_cache(*this, maxwell3d, gpu_memory, device, resource_manager, memory_manager,
  367. scheduler, staging_pool),
  368. pipeline_cache(*this, gpu, maxwell3d, kepler_compute, gpu_memory, device, scheduler,
  369. descriptor_pool, update_descriptor_queue, renderpass_cache),
  370. buffer_cache(*this, gpu_memory, cpu_memory, device, memory_manager, scheduler, staging_pool),
  371. sampler_cache(device), query_cache(*this, maxwell3d, gpu_memory, device, scheduler),
  372. fence_manager(*this, gpu, gpu_memory, texture_cache, buffer_cache, query_cache, device,
  373. scheduler),
  374. wfi_event(device.GetLogical().CreateNewEvent()), async_shaders(emu_window) {
  375. scheduler.SetQueryCache(query_cache);
  376. if (device.UseAsynchronousShaders()) {
  377. async_shaders.AllocateWorkers();
  378. }
  379. }
  380. RasterizerVulkan::~RasterizerVulkan() = default;
  381. void RasterizerVulkan::Draw(bool is_indexed, bool is_instanced) {
  382. MICROPROFILE_SCOPE(Vulkan_Drawing);
  383. SCOPE_EXIT({ gpu.TickWork(); });
  384. FlushWork();
  385. query_cache.UpdateCounters();
  386. GraphicsPipelineCacheKey key;
  387. key.fixed_state.Fill(maxwell3d.regs, device.IsExtExtendedDynamicStateSupported());
  388. buffer_cache.Map(CalculateGraphicsStreamBufferSize(is_indexed));
  389. BufferBindings buffer_bindings;
  390. const DrawParameters draw_params =
  391. SetupGeometry(key.fixed_state, buffer_bindings, is_indexed, is_instanced);
  392. update_descriptor_queue.Acquire();
  393. sampled_views.clear();
  394. image_views.clear();
  395. const auto shaders = pipeline_cache.GetShaders();
  396. key.shaders = GetShaderAddresses(shaders);
  397. SetupShaderDescriptors(shaders);
  398. buffer_cache.Unmap();
  399. const Texceptions texceptions = UpdateAttachments(false);
  400. SetupImageTransitions(texceptions, color_attachments, zeta_attachment);
  401. key.renderpass_params = GetRenderPassParams(texceptions);
  402. key.padding = 0;
  403. auto* pipeline = pipeline_cache.GetGraphicsPipeline(key, async_shaders);
  404. if (pipeline == nullptr || pipeline->GetHandle() == VK_NULL_HANDLE) {
  405. // Async graphics pipeline was not ready.
  406. return;
  407. }
  408. scheduler.BindGraphicsPipeline(pipeline->GetHandle());
  409. const auto renderpass = pipeline->GetRenderPass();
  410. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  411. scheduler.RequestRenderpass(renderpass, framebuffer, render_area);
  412. UpdateDynamicStates();
  413. buffer_bindings.Bind(device, scheduler);
  414. BeginTransformFeedback();
  415. const auto pipeline_layout = pipeline->GetLayout();
  416. const auto descriptor_set = pipeline->CommitDescriptorSet();
  417. scheduler.Record([pipeline_layout, descriptor_set, draw_params](vk::CommandBuffer cmdbuf) {
  418. if (descriptor_set) {
  419. cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout,
  420. DESCRIPTOR_SET, descriptor_set, {});
  421. }
  422. draw_params.Draw(cmdbuf);
  423. });
  424. EndTransformFeedback();
  425. }
  426. void RasterizerVulkan::Clear() {
  427. MICROPROFILE_SCOPE(Vulkan_Clearing);
  428. if (!maxwell3d.ShouldExecute()) {
  429. return;
  430. }
  431. sampled_views.clear();
  432. image_views.clear();
  433. query_cache.UpdateCounters();
  434. const auto& regs = maxwell3d.regs;
  435. const bool use_color = regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  436. regs.clear_buffers.A;
  437. const bool use_depth = regs.clear_buffers.Z;
  438. const bool use_stencil = regs.clear_buffers.S;
  439. if (!use_color && !use_depth && !use_stencil) {
  440. return;
  441. }
  442. [[maybe_unused]] const auto texceptions = UpdateAttachments(true);
  443. DEBUG_ASSERT(texceptions.none());
  444. SetupImageTransitions(0, color_attachments, zeta_attachment);
  445. const VkRenderPass renderpass = renderpass_cache.GetRenderPass(GetRenderPassParams(0));
  446. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  447. scheduler.RequestRenderpass(renderpass, framebuffer, render_area);
  448. VkClearRect clear_rect;
  449. clear_rect.baseArrayLayer = regs.clear_buffers.layer;
  450. clear_rect.layerCount = 1;
  451. clear_rect.rect = GetScissorState(regs, 0);
  452. clear_rect.rect.extent.width = std::min(clear_rect.rect.extent.width, render_area.width);
  453. clear_rect.rect.extent.height = std::min(clear_rect.rect.extent.height, render_area.height);
  454. if (use_color) {
  455. VkClearValue clear_value;
  456. std::memcpy(clear_value.color.float32, regs.clear_color, sizeof(regs.clear_color));
  457. const u32 color_attachment = regs.clear_buffers.RT;
  458. scheduler.Record([color_attachment, clear_value, clear_rect](vk::CommandBuffer cmdbuf) {
  459. const VkClearAttachment attachment{
  460. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  461. .colorAttachment = color_attachment,
  462. .clearValue = clear_value,
  463. };
  464. cmdbuf.ClearAttachments(attachment, clear_rect);
  465. });
  466. }
  467. if (!use_depth && !use_stencil) {
  468. return;
  469. }
  470. VkImageAspectFlags aspect_flags = 0;
  471. if (use_depth) {
  472. aspect_flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
  473. }
  474. if (use_stencil) {
  475. aspect_flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  476. }
  477. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  478. clear_rect, aspect_flags](vk::CommandBuffer cmdbuf) {
  479. VkClearAttachment attachment;
  480. attachment.aspectMask = aspect_flags;
  481. attachment.colorAttachment = 0;
  482. attachment.clearValue.depthStencil.depth = clear_depth;
  483. attachment.clearValue.depthStencil.stencil = clear_stencil;
  484. cmdbuf.ClearAttachments(attachment, clear_rect);
  485. });
  486. }
  487. void RasterizerVulkan::DispatchCompute(GPUVAddr code_addr) {
  488. MICROPROFILE_SCOPE(Vulkan_Compute);
  489. update_descriptor_queue.Acquire();
  490. sampled_views.clear();
  491. image_views.clear();
  492. query_cache.UpdateCounters();
  493. const auto& launch_desc = kepler_compute.launch_description;
  494. auto& pipeline = pipeline_cache.GetComputePipeline({
  495. .shader = code_addr,
  496. .shared_memory_size = launch_desc.shared_alloc,
  497. .workgroup_size =
  498. {
  499. launch_desc.block_dim_x,
  500. launch_desc.block_dim_y,
  501. launch_desc.block_dim_z,
  502. },
  503. });
  504. // Compute dispatches can't be executed inside a renderpass
  505. scheduler.RequestOutsideRenderPassOperationContext();
  506. buffer_cache.Map(CalculateComputeStreamBufferSize());
  507. const auto& entries = pipeline.GetEntries();
  508. SetupComputeConstBuffers(entries);
  509. SetupComputeGlobalBuffers(entries);
  510. SetupComputeUniformTexels(entries);
  511. SetupComputeTextures(entries);
  512. SetupComputeStorageTexels(entries);
  513. SetupComputeImages(entries);
  514. buffer_cache.Unmap();
  515. TransitionImages(sampled_views, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
  516. VK_ACCESS_SHADER_READ_BIT);
  517. TransitionImages(image_views, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
  518. VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
  519. scheduler.Record([grid_x = launch_desc.grid_dim_x, grid_y = launch_desc.grid_dim_y,
  520. grid_z = launch_desc.grid_dim_z, pipeline_handle = pipeline.GetHandle(),
  521. layout = pipeline.GetLayout(),
  522. descriptor_set = pipeline.CommitDescriptorSet()](vk::CommandBuffer cmdbuf) {
  523. cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_handle);
  524. cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, layout, DESCRIPTOR_SET,
  525. descriptor_set, {});
  526. cmdbuf.Dispatch(grid_x, grid_y, grid_z);
  527. });
  528. }
  529. void RasterizerVulkan::ResetCounter(VideoCore::QueryType type) {
  530. query_cache.ResetCounter(type);
  531. }
  532. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  533. std::optional<u64> timestamp) {
  534. query_cache.Query(gpu_addr, type, timestamp);
  535. }
  536. void RasterizerVulkan::FlushAll() {}
  537. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size) {
  538. if (addr == 0 || size == 0) {
  539. return;
  540. }
  541. texture_cache.FlushRegion(addr, size);
  542. buffer_cache.FlushRegion(addr, size);
  543. query_cache.FlushRegion(addr, size);
  544. }
  545. bool RasterizerVulkan::MustFlushRegion(VAddr addr, u64 size) {
  546. if (!Settings::IsGPULevelHigh()) {
  547. return buffer_cache.MustFlushRegion(addr, size);
  548. }
  549. return texture_cache.MustFlushRegion(addr, size) || buffer_cache.MustFlushRegion(addr, size);
  550. }
  551. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  552. if (addr == 0 || size == 0) {
  553. return;
  554. }
  555. texture_cache.InvalidateRegion(addr, size);
  556. pipeline_cache.InvalidateRegion(addr, size);
  557. buffer_cache.InvalidateRegion(addr, size);
  558. query_cache.InvalidateRegion(addr, size);
  559. }
  560. void RasterizerVulkan::OnCPUWrite(VAddr addr, u64 size) {
  561. if (addr == 0 || size == 0) {
  562. return;
  563. }
  564. texture_cache.OnCPUWrite(addr, size);
  565. pipeline_cache.OnCPUWrite(addr, size);
  566. buffer_cache.OnCPUWrite(addr, size);
  567. }
  568. void RasterizerVulkan::SyncGuestHost() {
  569. texture_cache.SyncGuestHost();
  570. buffer_cache.SyncGuestHost();
  571. pipeline_cache.SyncGuestHost();
  572. }
  573. void RasterizerVulkan::SignalSemaphore(GPUVAddr addr, u32 value) {
  574. if (!gpu.IsAsync()) {
  575. gpu_memory.Write<u32>(addr, value);
  576. return;
  577. }
  578. fence_manager.SignalSemaphore(addr, value);
  579. }
  580. void RasterizerVulkan::SignalSyncPoint(u32 value) {
  581. if (!gpu.IsAsync()) {
  582. gpu.IncrementSyncPoint(value);
  583. return;
  584. }
  585. fence_manager.SignalSyncPoint(value);
  586. }
  587. void RasterizerVulkan::ReleaseFences() {
  588. if (!gpu.IsAsync()) {
  589. return;
  590. }
  591. fence_manager.WaitPendingFences();
  592. }
  593. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  594. if (Settings::IsGPULevelExtreme()) {
  595. FlushRegion(addr, size);
  596. }
  597. InvalidateRegion(addr, size);
  598. }
  599. void RasterizerVulkan::WaitForIdle() {
  600. // Everything but wait pixel operations. This intentionally includes FRAGMENT_SHADER_BIT because
  601. // fragment shaders can still write storage buffers.
  602. VkPipelineStageFlags flags =
  603. VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT |
  604. VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
  605. VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
  606. VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
  607. VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  608. if (device.IsExtTransformFeedbackSupported()) {
  609. flags |= VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT;
  610. }
  611. scheduler.RequestOutsideRenderPassOperationContext();
  612. scheduler.Record([event = *wfi_event, flags](vk::CommandBuffer cmdbuf) {
  613. cmdbuf.SetEvent(event, flags);
  614. cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {});
  615. });
  616. }
  617. void RasterizerVulkan::FlushCommands() {
  618. if (draw_counter > 0) {
  619. draw_counter = 0;
  620. scheduler.Flush();
  621. }
  622. }
  623. void RasterizerVulkan::TickFrame() {
  624. draw_counter = 0;
  625. update_descriptor_queue.TickFrame();
  626. buffer_cache.TickFrame();
  627. staging_pool.TickFrame();
  628. }
  629. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  630. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  631. const Tegra::Engines::Fermi2D::Config& copy_config) {
  632. texture_cache.DoFermiCopy(src, dst, copy_config);
  633. return true;
  634. }
  635. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  636. VAddr framebuffer_addr, u32 pixel_stride) {
  637. if (!framebuffer_addr) {
  638. return false;
  639. }
  640. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  641. if (!surface) {
  642. return false;
  643. }
  644. // Verify that the cached surface is the same size and format as the requested framebuffer
  645. const auto& params{surface->GetSurfaceParams()};
  646. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  647. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  648. screen_info.image = &surface->GetImage();
  649. screen_info.width = params.width;
  650. screen_info.height = params.height;
  651. screen_info.is_srgb = surface->GetSurfaceParams().srgb_conversion;
  652. return true;
  653. }
  654. void RasterizerVulkan::FlushWork() {
  655. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  656. // Only check multiples of 8 draws
  657. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  658. if ((++draw_counter & 7) != 7) {
  659. return;
  660. }
  661. if (draw_counter < DRAWS_TO_DISPATCH) {
  662. // Send recorded tasks to the worker thread
  663. scheduler.DispatchWork();
  664. return;
  665. }
  666. // Otherwise (every certain number of draws) flush execution.
  667. // This submits commands to the Vulkan driver.
  668. scheduler.Flush();
  669. draw_counter = 0;
  670. }
  671. RasterizerVulkan::Texceptions RasterizerVulkan::UpdateAttachments(bool is_clear) {
  672. MICROPROFILE_SCOPE(Vulkan_RenderTargets);
  673. const auto& regs = maxwell3d.regs;
  674. auto& dirty = maxwell3d.dirty.flags;
  675. const bool update_rendertargets = dirty[VideoCommon::Dirty::RenderTargets];
  676. dirty[VideoCommon::Dirty::RenderTargets] = false;
  677. texture_cache.GuardRenderTargets(true);
  678. Texceptions texceptions;
  679. for (std::size_t rt = 0; rt < Maxwell::NumRenderTargets; ++rt) {
  680. if (update_rendertargets) {
  681. const bool preserve_contents = HasToPreserveColorContents(is_clear, regs);
  682. color_attachments[rt] = texture_cache.GetColorBufferSurface(rt, preserve_contents);
  683. }
  684. if (color_attachments[rt] && WalkAttachmentOverlaps(*color_attachments[rt])) {
  685. texceptions[rt] = true;
  686. }
  687. }
  688. if (update_rendertargets) {
  689. const bool preserve_contents = HasToPreserveDepthContents(is_clear, regs);
  690. zeta_attachment = texture_cache.GetDepthBufferSurface(preserve_contents);
  691. }
  692. if (zeta_attachment && WalkAttachmentOverlaps(*zeta_attachment)) {
  693. texceptions[ZETA_TEXCEPTION_INDEX] = true;
  694. }
  695. texture_cache.GuardRenderTargets(false);
  696. return texceptions;
  697. }
  698. bool RasterizerVulkan::WalkAttachmentOverlaps(const CachedSurfaceView& attachment) {
  699. bool overlap = false;
  700. for (auto& [view, layout] : sampled_views) {
  701. if (!attachment.IsSameSurface(*view)) {
  702. continue;
  703. }
  704. overlap = true;
  705. *layout = VK_IMAGE_LAYOUT_GENERAL;
  706. }
  707. return overlap;
  708. }
  709. std::tuple<VkFramebuffer, VkExtent2D> RasterizerVulkan::ConfigureFramebuffers(
  710. VkRenderPass renderpass) {
  711. FramebufferCacheKey key{
  712. .renderpass = renderpass,
  713. .width = std::numeric_limits<u32>::max(),
  714. .height = std::numeric_limits<u32>::max(),
  715. .layers = std::numeric_limits<u32>::max(),
  716. .views = {},
  717. };
  718. const auto try_push = [&key](const View& view) {
  719. if (!view) {
  720. return false;
  721. }
  722. key.views.push_back(view->GetAttachment());
  723. key.width = std::min(key.width, view->GetWidth());
  724. key.height = std::min(key.height, view->GetHeight());
  725. key.layers = std::min(key.layers, view->GetNumLayers());
  726. return true;
  727. };
  728. const auto& regs = maxwell3d.regs;
  729. const std::size_t num_attachments = static_cast<std::size_t>(regs.rt_control.count);
  730. for (std::size_t index = 0; index < num_attachments; ++index) {
  731. if (try_push(color_attachments[index])) {
  732. texture_cache.MarkColorBufferInUse(index);
  733. }
  734. }
  735. if (try_push(zeta_attachment)) {
  736. texture_cache.MarkDepthBufferInUse();
  737. }
  738. const auto [fbentry, is_cache_miss] = framebuffer_cache.try_emplace(key);
  739. auto& framebuffer = fbentry->second;
  740. if (is_cache_miss) {
  741. framebuffer = device.GetLogical().CreateFramebuffer({
  742. .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
  743. .pNext = nullptr,
  744. .flags = 0,
  745. .renderPass = key.renderpass,
  746. .attachmentCount = static_cast<u32>(key.views.size()),
  747. .pAttachments = key.views.data(),
  748. .width = key.width,
  749. .height = key.height,
  750. .layers = key.layers,
  751. });
  752. }
  753. return {*framebuffer, VkExtent2D{key.width, key.height}};
  754. }
  755. RasterizerVulkan::DrawParameters RasterizerVulkan::SetupGeometry(FixedPipelineState& fixed_state,
  756. BufferBindings& buffer_bindings,
  757. bool is_indexed,
  758. bool is_instanced) {
  759. MICROPROFILE_SCOPE(Vulkan_Geometry);
  760. const auto& regs = maxwell3d.regs;
  761. SetupVertexArrays(buffer_bindings);
  762. const u32 base_instance = regs.vb_base_instance;
  763. const u32 num_instances = is_instanced ? maxwell3d.mme_draw.instance_count : 1;
  764. const u32 base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first;
  765. const u32 num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count;
  766. DrawParameters params{base_instance, num_instances, base_vertex, num_vertices, is_indexed};
  767. SetupIndexBuffer(buffer_bindings, params, is_indexed);
  768. return params;
  769. }
  770. void RasterizerVulkan::SetupShaderDescriptors(
  771. const std::array<Shader*, Maxwell::MaxShaderProgram>& shaders) {
  772. texture_cache.GuardSamplers(true);
  773. for (std::size_t stage = 0; stage < Maxwell::MaxShaderStage; ++stage) {
  774. // Skip VertexA stage
  775. Shader* const shader = shaders[stage + 1];
  776. if (!shader) {
  777. continue;
  778. }
  779. const auto& entries = shader->GetEntries();
  780. SetupGraphicsConstBuffers(entries, stage);
  781. SetupGraphicsGlobalBuffers(entries, stage);
  782. SetupGraphicsUniformTexels(entries, stage);
  783. SetupGraphicsTextures(entries, stage);
  784. SetupGraphicsStorageTexels(entries, stage);
  785. SetupGraphicsImages(entries, stage);
  786. }
  787. texture_cache.GuardSamplers(false);
  788. }
  789. void RasterizerVulkan::SetupImageTransitions(
  790. Texceptions texceptions, const std::array<View, Maxwell::NumRenderTargets>& color_attachments,
  791. const View& zeta_attachment) {
  792. TransitionImages(sampled_views, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT);
  793. TransitionImages(image_views, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
  794. VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
  795. for (std::size_t rt = 0; rt < std::size(color_attachments); ++rt) {
  796. const auto color_attachment = color_attachments[rt];
  797. if (color_attachment == nullptr) {
  798. continue;
  799. }
  800. const auto image_layout =
  801. texceptions[rt] ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  802. color_attachment->Transition(image_layout, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  803. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  804. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
  805. }
  806. if (zeta_attachment != nullptr) {
  807. const auto image_layout = texceptions[ZETA_TEXCEPTION_INDEX]
  808. ? VK_IMAGE_LAYOUT_GENERAL
  809. : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  810. zeta_attachment->Transition(image_layout, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
  811. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  812. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
  813. }
  814. }
  815. void RasterizerVulkan::UpdateDynamicStates() {
  816. auto& regs = maxwell3d.regs;
  817. UpdateViewportsState(regs);
  818. UpdateScissorsState(regs);
  819. UpdateDepthBias(regs);
  820. UpdateBlendConstants(regs);
  821. UpdateDepthBounds(regs);
  822. UpdateStencilFaces(regs);
  823. if (device.IsExtExtendedDynamicStateSupported()) {
  824. UpdateCullMode(regs);
  825. UpdateDepthBoundsTestEnable(regs);
  826. UpdateDepthTestEnable(regs);
  827. UpdateDepthWriteEnable(regs);
  828. UpdateDepthCompareOp(regs);
  829. UpdateFrontFace(regs);
  830. UpdatePrimitiveTopology(regs);
  831. UpdateStencilOp(regs);
  832. UpdateStencilTestEnable(regs);
  833. }
  834. }
  835. void RasterizerVulkan::BeginTransformFeedback() {
  836. const auto& regs = maxwell3d.regs;
  837. if (regs.tfb_enabled == 0) {
  838. return;
  839. }
  840. if (!device.IsExtTransformFeedbackSupported()) {
  841. LOG_ERROR(Render_Vulkan, "Transform feedbacks used but not supported");
  842. return;
  843. }
  844. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  845. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  846. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  847. UNIMPLEMENTED_IF(regs.tfb_bindings[1].buffer_enable);
  848. UNIMPLEMENTED_IF(regs.tfb_bindings[2].buffer_enable);
  849. UNIMPLEMENTED_IF(regs.tfb_bindings[3].buffer_enable);
  850. const auto& binding = regs.tfb_bindings[0];
  851. UNIMPLEMENTED_IF(binding.buffer_enable == 0);
  852. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  853. const GPUVAddr gpu_addr = binding.Address();
  854. const VkDeviceSize size = static_cast<VkDeviceSize>(binding.buffer_size);
  855. const auto info = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  856. scheduler.Record([buffer = info.handle, offset = info.offset, size](vk::CommandBuffer cmdbuf) {
  857. cmdbuf.BindTransformFeedbackBuffersEXT(0, 1, &buffer, &offset, &size);
  858. cmdbuf.BeginTransformFeedbackEXT(0, 0, nullptr, nullptr);
  859. });
  860. }
  861. void RasterizerVulkan::EndTransformFeedback() {
  862. const auto& regs = maxwell3d.regs;
  863. if (regs.tfb_enabled == 0) {
  864. return;
  865. }
  866. if (!device.IsExtTransformFeedbackSupported()) {
  867. return;
  868. }
  869. scheduler.Record(
  870. [](vk::CommandBuffer cmdbuf) { cmdbuf.EndTransformFeedbackEXT(0, 0, nullptr, nullptr); });
  871. }
  872. void RasterizerVulkan::SetupVertexArrays(BufferBindings& buffer_bindings) {
  873. const auto& regs = maxwell3d.regs;
  874. for (std::size_t index = 0; index < Maxwell::NumVertexArrays; ++index) {
  875. const auto& vertex_array = regs.vertex_array[index];
  876. if (!vertex_array.IsEnabled()) {
  877. continue;
  878. }
  879. const GPUVAddr start{vertex_array.StartAddress()};
  880. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  881. ASSERT(end >= start);
  882. const std::size_t size = end - start;
  883. if (size == 0) {
  884. buffer_bindings.AddVertexBinding(DefaultBuffer(), 0, DEFAULT_BUFFER_SIZE, 0);
  885. continue;
  886. }
  887. const auto info = buffer_cache.UploadMemory(start, size);
  888. buffer_bindings.AddVertexBinding(info.handle, info.offset, size, vertex_array.stride);
  889. }
  890. }
  891. void RasterizerVulkan::SetupIndexBuffer(BufferBindings& buffer_bindings, DrawParameters& params,
  892. bool is_indexed) {
  893. if (params.num_vertices == 0) {
  894. return;
  895. }
  896. const auto& regs = maxwell3d.regs;
  897. switch (regs.draw.topology) {
  898. case Maxwell::PrimitiveTopology::Quads: {
  899. if (!params.is_indexed) {
  900. const auto [buffer, offset] =
  901. quad_array_pass.Assemble(params.num_vertices, params.base_vertex);
  902. buffer_bindings.SetIndexBinding(buffer, offset, VK_INDEX_TYPE_UINT32);
  903. params.base_vertex = 0;
  904. params.num_vertices = params.num_vertices * 6 / 4;
  905. params.is_indexed = true;
  906. break;
  907. }
  908. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  909. const auto info = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  910. VkBuffer buffer = info.handle;
  911. u64 offset = info.offset;
  912. std::tie(buffer, offset) = quad_indexed_pass.Assemble(
  913. regs.index_array.format, params.num_vertices, params.base_vertex, buffer, offset);
  914. buffer_bindings.SetIndexBinding(buffer, offset, VK_INDEX_TYPE_UINT32);
  915. params.num_vertices = (params.num_vertices / 4) * 6;
  916. params.base_vertex = 0;
  917. break;
  918. }
  919. default: {
  920. if (!is_indexed) {
  921. break;
  922. }
  923. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  924. const auto info = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  925. VkBuffer buffer = info.handle;
  926. u64 offset = info.offset;
  927. auto format = regs.index_array.format;
  928. const bool is_uint8 = format == Maxwell::IndexFormat::UnsignedByte;
  929. if (is_uint8 && !device.IsExtIndexTypeUint8Supported()) {
  930. std::tie(buffer, offset) = uint8_pass.Assemble(params.num_vertices, buffer, offset);
  931. format = Maxwell::IndexFormat::UnsignedShort;
  932. }
  933. buffer_bindings.SetIndexBinding(buffer, offset, MaxwellToVK::IndexFormat(device, format));
  934. break;
  935. }
  936. }
  937. }
  938. void RasterizerVulkan::SetupGraphicsConstBuffers(const ShaderEntries& entries, std::size_t stage) {
  939. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  940. const auto& shader_stage = maxwell3d.state.shader_stages[stage];
  941. for (const auto& entry : entries.const_buffers) {
  942. SetupConstBuffer(entry, shader_stage.const_buffers[entry.GetIndex()]);
  943. }
  944. }
  945. void RasterizerVulkan::SetupGraphicsGlobalBuffers(const ShaderEntries& entries, std::size_t stage) {
  946. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  947. const auto& cbufs{maxwell3d.state.shader_stages[stage]};
  948. for (const auto& entry : entries.global_buffers) {
  949. const auto addr = cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset();
  950. SetupGlobalBuffer(entry, addr);
  951. }
  952. }
  953. void RasterizerVulkan::SetupGraphicsUniformTexels(const ShaderEntries& entries, std::size_t stage) {
  954. MICROPROFILE_SCOPE(Vulkan_Textures);
  955. for (const auto& entry : entries.uniform_texels) {
  956. const auto image = GetTextureInfo(maxwell3d, entry, stage).tic;
  957. SetupUniformTexels(image, entry);
  958. }
  959. }
  960. void RasterizerVulkan::SetupGraphicsTextures(const ShaderEntries& entries, std::size_t stage) {
  961. MICROPROFILE_SCOPE(Vulkan_Textures);
  962. for (const auto& entry : entries.samplers) {
  963. for (std::size_t i = 0; i < entry.size; ++i) {
  964. const auto texture = GetTextureInfo(maxwell3d, entry, stage, i);
  965. SetupTexture(texture, entry);
  966. }
  967. }
  968. }
  969. void RasterizerVulkan::SetupGraphicsStorageTexels(const ShaderEntries& entries, std::size_t stage) {
  970. MICROPROFILE_SCOPE(Vulkan_Textures);
  971. for (const auto& entry : entries.storage_texels) {
  972. const auto image = GetTextureInfo(maxwell3d, entry, stage).tic;
  973. SetupStorageTexel(image, entry);
  974. }
  975. }
  976. void RasterizerVulkan::SetupGraphicsImages(const ShaderEntries& entries, std::size_t stage) {
  977. MICROPROFILE_SCOPE(Vulkan_Images);
  978. for (const auto& entry : entries.images) {
  979. const auto tic = GetTextureInfo(maxwell3d, entry, stage).tic;
  980. SetupImage(tic, entry);
  981. }
  982. }
  983. void RasterizerVulkan::SetupComputeConstBuffers(const ShaderEntries& entries) {
  984. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  985. const auto& launch_desc = kepler_compute.launch_description;
  986. for (const auto& entry : entries.const_buffers) {
  987. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  988. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  989. Tegra::Engines::ConstBufferInfo buffer;
  990. buffer.address = config.Address();
  991. buffer.size = config.size;
  992. buffer.enabled = mask[entry.GetIndex()];
  993. SetupConstBuffer(entry, buffer);
  994. }
  995. }
  996. void RasterizerVulkan::SetupComputeGlobalBuffers(const ShaderEntries& entries) {
  997. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  998. const auto& cbufs{kepler_compute.launch_description.const_buffer_config};
  999. for (const auto& entry : entries.global_buffers) {
  1000. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  1001. SetupGlobalBuffer(entry, addr);
  1002. }
  1003. }
  1004. void RasterizerVulkan::SetupComputeUniformTexels(const ShaderEntries& entries) {
  1005. MICROPROFILE_SCOPE(Vulkan_Textures);
  1006. for (const auto& entry : entries.uniform_texels) {
  1007. const auto image = GetTextureInfo(kepler_compute, entry, ComputeShaderIndex).tic;
  1008. SetupUniformTexels(image, entry);
  1009. }
  1010. }
  1011. void RasterizerVulkan::SetupComputeTextures(const ShaderEntries& entries) {
  1012. MICROPROFILE_SCOPE(Vulkan_Textures);
  1013. for (const auto& entry : entries.samplers) {
  1014. for (std::size_t i = 0; i < entry.size; ++i) {
  1015. const auto texture = GetTextureInfo(kepler_compute, entry, ComputeShaderIndex, i);
  1016. SetupTexture(texture, entry);
  1017. }
  1018. }
  1019. }
  1020. void RasterizerVulkan::SetupComputeStorageTexels(const ShaderEntries& entries) {
  1021. MICROPROFILE_SCOPE(Vulkan_Textures);
  1022. for (const auto& entry : entries.storage_texels) {
  1023. const auto image = GetTextureInfo(kepler_compute, entry, ComputeShaderIndex).tic;
  1024. SetupStorageTexel(image, entry);
  1025. }
  1026. }
  1027. void RasterizerVulkan::SetupComputeImages(const ShaderEntries& entries) {
  1028. MICROPROFILE_SCOPE(Vulkan_Images);
  1029. for (const auto& entry : entries.images) {
  1030. const auto tic = GetTextureInfo(kepler_compute, entry, ComputeShaderIndex).tic;
  1031. SetupImage(tic, entry);
  1032. }
  1033. }
  1034. void RasterizerVulkan::SetupConstBuffer(const ConstBufferEntry& entry,
  1035. const Tegra::Engines::ConstBufferInfo& buffer) {
  1036. if (!buffer.enabled) {
  1037. // Set values to zero to unbind buffers
  1038. update_descriptor_queue.AddBuffer(DefaultBuffer(), 0, DEFAULT_BUFFER_SIZE);
  1039. return;
  1040. }
  1041. // Align the size to avoid bad std140 interactions
  1042. const std::size_t size =
  1043. Common::AlignUp(CalculateConstBufferSize(entry, buffer), 4 * sizeof(float));
  1044. ASSERT(size <= MaxConstbufferSize);
  1045. const auto info =
  1046. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  1047. update_descriptor_queue.AddBuffer(info.handle, info.offset, size);
  1048. }
  1049. void RasterizerVulkan::SetupGlobalBuffer(const GlobalBufferEntry& entry, GPUVAddr address) {
  1050. const u64 actual_addr = gpu_memory.Read<u64>(address);
  1051. const u32 size = gpu_memory.Read<u32>(address + 8);
  1052. if (size == 0) {
  1053. // Sometimes global memory pointers don't have a proper size. Upload a dummy entry
  1054. // because Vulkan doesn't like empty buffers.
  1055. // Note: Do *not* use DefaultBuffer() here, storage buffers can be written breaking the
  1056. // default buffer.
  1057. static constexpr std::size_t dummy_size = 4;
  1058. const auto info = buffer_cache.GetEmptyBuffer(dummy_size);
  1059. update_descriptor_queue.AddBuffer(info.handle, info.offset, dummy_size);
  1060. return;
  1061. }
  1062. const auto info = buffer_cache.UploadMemory(
  1063. actual_addr, size, device.GetStorageBufferAlignment(), entry.IsWritten());
  1064. update_descriptor_queue.AddBuffer(info.handle, info.offset, size);
  1065. }
  1066. void RasterizerVulkan::SetupUniformTexels(const Tegra::Texture::TICEntry& tic,
  1067. const UniformTexelEntry& entry) {
  1068. const auto view = texture_cache.GetTextureSurface(tic, entry);
  1069. ASSERT(view->IsBufferView());
  1070. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  1071. }
  1072. void RasterizerVulkan::SetupTexture(const Tegra::Texture::FullTextureInfo& texture,
  1073. const SamplerEntry& entry) {
  1074. auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  1075. ASSERT(!view->IsBufferView());
  1076. const VkImageView image_view = view->GetImageView(texture.tic.x_source, texture.tic.y_source,
  1077. texture.tic.z_source, texture.tic.w_source);
  1078. const auto sampler = sampler_cache.GetSampler(texture.tsc);
  1079. update_descriptor_queue.AddSampledImage(sampler, image_view);
  1080. VkImageLayout* const image_layout = update_descriptor_queue.LastImageLayout();
  1081. *image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1082. sampled_views.push_back(ImageView{std::move(view), image_layout});
  1083. }
  1084. void RasterizerVulkan::SetupStorageTexel(const Tegra::Texture::TICEntry& tic,
  1085. const StorageTexelEntry& entry) {
  1086. const auto view = texture_cache.GetImageSurface(tic, entry);
  1087. ASSERT(view->IsBufferView());
  1088. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  1089. }
  1090. void RasterizerVulkan::SetupImage(const Tegra::Texture::TICEntry& tic, const ImageEntry& entry) {
  1091. auto view = texture_cache.GetImageSurface(tic, entry);
  1092. if (entry.is_written) {
  1093. view->MarkAsModified(texture_cache.Tick());
  1094. }
  1095. UNIMPLEMENTED_IF(tic.IsBuffer());
  1096. const VkImageView image_view =
  1097. view->GetImageView(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  1098. update_descriptor_queue.AddImage(image_view);
  1099. VkImageLayout* const image_layout = update_descriptor_queue.LastImageLayout();
  1100. *image_layout = VK_IMAGE_LAYOUT_GENERAL;
  1101. image_views.push_back(ImageView{std::move(view), image_layout});
  1102. }
  1103. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  1104. if (!state_tracker.TouchViewports()) {
  1105. return;
  1106. }
  1107. const std::array viewports{
  1108. GetViewportState(device, regs, 0), GetViewportState(device, regs, 1),
  1109. GetViewportState(device, regs, 2), GetViewportState(device, regs, 3),
  1110. GetViewportState(device, regs, 4), GetViewportState(device, regs, 5),
  1111. GetViewportState(device, regs, 6), GetViewportState(device, regs, 7),
  1112. GetViewportState(device, regs, 8), GetViewportState(device, regs, 9),
  1113. GetViewportState(device, regs, 10), GetViewportState(device, regs, 11),
  1114. GetViewportState(device, regs, 12), GetViewportState(device, regs, 13),
  1115. GetViewportState(device, regs, 14), GetViewportState(device, regs, 15)};
  1116. scheduler.Record([viewports](vk::CommandBuffer cmdbuf) { cmdbuf.SetViewport(0, viewports); });
  1117. }
  1118. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  1119. if (!state_tracker.TouchScissors()) {
  1120. return;
  1121. }
  1122. const std::array scissors = {
  1123. GetScissorState(regs, 0), GetScissorState(regs, 1), GetScissorState(regs, 2),
  1124. GetScissorState(regs, 3), GetScissorState(regs, 4), GetScissorState(regs, 5),
  1125. GetScissorState(regs, 6), GetScissorState(regs, 7), GetScissorState(regs, 8),
  1126. GetScissorState(regs, 9), GetScissorState(regs, 10), GetScissorState(regs, 11),
  1127. GetScissorState(regs, 12), GetScissorState(regs, 13), GetScissorState(regs, 14),
  1128. GetScissorState(regs, 15)};
  1129. scheduler.Record([scissors](vk::CommandBuffer cmdbuf) { cmdbuf.SetScissor(0, scissors); });
  1130. }
  1131. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  1132. if (!state_tracker.TouchDepthBias()) {
  1133. return;
  1134. }
  1135. scheduler.Record([constant = regs.polygon_offset_units, clamp = regs.polygon_offset_clamp,
  1136. factor = regs.polygon_offset_factor](vk::CommandBuffer cmdbuf) {
  1137. cmdbuf.SetDepthBias(constant, clamp, factor / 2.0f);
  1138. });
  1139. }
  1140. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  1141. if (!state_tracker.TouchBlendConstants()) {
  1142. return;
  1143. }
  1144. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1145. regs.blend_color.a};
  1146. scheduler.Record(
  1147. [blend_color](vk::CommandBuffer cmdbuf) { cmdbuf.SetBlendConstants(blend_color.data()); });
  1148. }
  1149. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  1150. if (!state_tracker.TouchDepthBounds()) {
  1151. return;
  1152. }
  1153. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  1154. vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthBounds(min, max); });
  1155. }
  1156. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  1157. if (!state_tracker.TouchStencilProperties()) {
  1158. return;
  1159. }
  1160. if (regs.stencil_two_side_enable) {
  1161. // Separate values per face
  1162. scheduler.Record(
  1163. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  1164. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  1165. back_write_mask = regs.stencil_back_mask,
  1166. back_test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  1167. // Front face
  1168. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_BIT, front_ref);
  1169. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_BIT, front_write_mask);
  1170. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_BIT, front_test_mask);
  1171. // Back face
  1172. cmdbuf.SetStencilReference(VK_STENCIL_FACE_BACK_BIT, back_ref);
  1173. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_BACK_BIT, back_write_mask);
  1174. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_BACK_BIT, back_test_mask);
  1175. });
  1176. } else {
  1177. // Front face defines both faces
  1178. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  1179. test_mask = regs.stencil_back_func_mask](vk::CommandBuffer cmdbuf) {
  1180. cmdbuf.SetStencilReference(VK_STENCIL_FACE_FRONT_AND_BACK, ref);
  1181. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_FRONT_AND_BACK, write_mask);
  1182. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_FRONT_AND_BACK, test_mask);
  1183. });
  1184. }
  1185. }
  1186. void RasterizerVulkan::UpdateCullMode(Tegra::Engines::Maxwell3D::Regs& regs) {
  1187. if (!state_tracker.TouchCullMode()) {
  1188. return;
  1189. }
  1190. scheduler.Record(
  1191. [enabled = regs.cull_test_enabled, cull_face = regs.cull_face](vk::CommandBuffer cmdbuf) {
  1192. cmdbuf.SetCullModeEXT(enabled ? MaxwellToVK::CullFace(cull_face) : VK_CULL_MODE_NONE);
  1193. });
  1194. }
  1195. void RasterizerVulkan::UpdateDepthBoundsTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1196. if (!state_tracker.TouchDepthBoundsTestEnable()) {
  1197. return;
  1198. }
  1199. scheduler.Record([enable = regs.depth_bounds_enable](vk::CommandBuffer cmdbuf) {
  1200. cmdbuf.SetDepthBoundsTestEnableEXT(enable);
  1201. });
  1202. }
  1203. void RasterizerVulkan::UpdateDepthTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1204. if (!state_tracker.TouchDepthTestEnable()) {
  1205. return;
  1206. }
  1207. scheduler.Record([enable = regs.depth_test_enable](vk::CommandBuffer cmdbuf) {
  1208. cmdbuf.SetDepthTestEnableEXT(enable);
  1209. });
  1210. }
  1211. void RasterizerVulkan::UpdateDepthWriteEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1212. if (!state_tracker.TouchDepthWriteEnable()) {
  1213. return;
  1214. }
  1215. scheduler.Record([enable = regs.depth_write_enabled](vk::CommandBuffer cmdbuf) {
  1216. cmdbuf.SetDepthWriteEnableEXT(enable);
  1217. });
  1218. }
  1219. void RasterizerVulkan::UpdateDepthCompareOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1220. if (!state_tracker.TouchDepthCompareOp()) {
  1221. return;
  1222. }
  1223. scheduler.Record([func = regs.depth_test_func](vk::CommandBuffer cmdbuf) {
  1224. cmdbuf.SetDepthCompareOpEXT(MaxwellToVK::ComparisonOp(func));
  1225. });
  1226. }
  1227. void RasterizerVulkan::UpdateFrontFace(Tegra::Engines::Maxwell3D::Regs& regs) {
  1228. if (!state_tracker.TouchFrontFace()) {
  1229. return;
  1230. }
  1231. VkFrontFace front_face = MaxwellToVK::FrontFace(regs.front_face);
  1232. if (regs.screen_y_control.triangle_rast_flip != 0) {
  1233. front_face = front_face == VK_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_COUNTER_CLOCKWISE
  1234. : VK_FRONT_FACE_CLOCKWISE;
  1235. }
  1236. scheduler.Record(
  1237. [front_face](vk::CommandBuffer cmdbuf) { cmdbuf.SetFrontFaceEXT(front_face); });
  1238. }
  1239. void RasterizerVulkan::UpdatePrimitiveTopology(Tegra::Engines::Maxwell3D::Regs& regs) {
  1240. const Maxwell::PrimitiveTopology primitive_topology = regs.draw.topology.Value();
  1241. if (!state_tracker.ChangePrimitiveTopology(primitive_topology)) {
  1242. return;
  1243. }
  1244. scheduler.Record([this, primitive_topology](vk::CommandBuffer cmdbuf) {
  1245. cmdbuf.SetPrimitiveTopologyEXT(MaxwellToVK::PrimitiveTopology(device, primitive_topology));
  1246. });
  1247. }
  1248. void RasterizerVulkan::UpdateStencilOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1249. if (!state_tracker.TouchStencilOp()) {
  1250. return;
  1251. }
  1252. const Maxwell::StencilOp fail = regs.stencil_front_op_fail;
  1253. const Maxwell::StencilOp zfail = regs.stencil_front_op_zfail;
  1254. const Maxwell::StencilOp zpass = regs.stencil_front_op_zpass;
  1255. const Maxwell::ComparisonOp compare = regs.stencil_front_func_func;
  1256. if (regs.stencil_two_side_enable) {
  1257. scheduler.Record([fail, zfail, zpass, compare](vk::CommandBuffer cmdbuf) {
  1258. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_AND_BACK, MaxwellToVK::StencilOp(fail),
  1259. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1260. MaxwellToVK::ComparisonOp(compare));
  1261. });
  1262. } else {
  1263. const Maxwell::StencilOp back_fail = regs.stencil_back_op_fail;
  1264. const Maxwell::StencilOp back_zfail = regs.stencil_back_op_zfail;
  1265. const Maxwell::StencilOp back_zpass = regs.stencil_back_op_zpass;
  1266. const Maxwell::ComparisonOp back_compare = regs.stencil_back_func_func;
  1267. scheduler.Record([fail, zfail, zpass, compare, back_fail, back_zfail, back_zpass,
  1268. back_compare](vk::CommandBuffer cmdbuf) {
  1269. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_BIT, MaxwellToVK::StencilOp(fail),
  1270. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1271. MaxwellToVK::ComparisonOp(compare));
  1272. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_BACK_BIT, MaxwellToVK::StencilOp(back_fail),
  1273. MaxwellToVK::StencilOp(back_zpass),
  1274. MaxwellToVK::StencilOp(back_zfail),
  1275. MaxwellToVK::ComparisonOp(back_compare));
  1276. });
  1277. }
  1278. }
  1279. void RasterizerVulkan::UpdateStencilTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1280. if (!state_tracker.TouchStencilTestEnable()) {
  1281. return;
  1282. }
  1283. scheduler.Record([enable = regs.stencil_enable](vk::CommandBuffer cmdbuf) {
  1284. cmdbuf.SetStencilTestEnableEXT(enable);
  1285. });
  1286. }
  1287. std::size_t RasterizerVulkan::CalculateGraphicsStreamBufferSize(bool is_indexed) const {
  1288. std::size_t size = CalculateVertexArraysSize();
  1289. if (is_indexed) {
  1290. size = Common::AlignUp(size, 4) + CalculateIndexBufferSize();
  1291. }
  1292. size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  1293. return size;
  1294. }
  1295. std::size_t RasterizerVulkan::CalculateComputeStreamBufferSize() const {
  1296. return Tegra::Engines::KeplerCompute::NumConstBuffers *
  1297. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  1298. }
  1299. std::size_t RasterizerVulkan::CalculateVertexArraysSize() const {
  1300. const auto& regs = maxwell3d.regs;
  1301. std::size_t size = 0;
  1302. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  1303. // This implementation assumes that all attributes are used in the shader.
  1304. const GPUVAddr start{regs.vertex_array[index].StartAddress()};
  1305. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  1306. DEBUG_ASSERT(end >= start);
  1307. size += (end - start) * regs.vertex_array[index].enable;
  1308. }
  1309. return size;
  1310. }
  1311. std::size_t RasterizerVulkan::CalculateIndexBufferSize() const {
  1312. return static_cast<std::size_t>(maxwell3d.regs.index_array.count) *
  1313. static_cast<std::size_t>(maxwell3d.regs.index_array.FormatSizeInBytes());
  1314. }
  1315. std::size_t RasterizerVulkan::CalculateConstBufferSize(
  1316. const ConstBufferEntry& entry, const Tegra::Engines::ConstBufferInfo& buffer) const {
  1317. if (entry.IsIndirect()) {
  1318. // Buffer is accessed indirectly, so upload the entire thing
  1319. return buffer.size;
  1320. } else {
  1321. // Buffer is accessed directly, upload just what we use
  1322. return entry.GetSize();
  1323. }
  1324. }
  1325. RenderPassParams RasterizerVulkan::GetRenderPassParams(Texceptions texceptions) const {
  1326. const auto& regs = maxwell3d.regs;
  1327. const std::size_t num_attachments = static_cast<std::size_t>(regs.rt_control.count);
  1328. RenderPassParams params;
  1329. params.color_formats = {};
  1330. std::size_t color_texceptions = 0;
  1331. std::size_t index = 0;
  1332. for (std::size_t rt = 0; rt < num_attachments; ++rt) {
  1333. const auto& rendertarget = regs.rt[rt];
  1334. if (rendertarget.Address() == 0 || rendertarget.format == Tegra::RenderTargetFormat::NONE) {
  1335. continue;
  1336. }
  1337. params.color_formats[index] = static_cast<u8>(rendertarget.format);
  1338. color_texceptions |= (texceptions[rt] ? 1ULL : 0ULL) << index;
  1339. ++index;
  1340. }
  1341. params.num_color_attachments = static_cast<u8>(index);
  1342. params.texceptions = static_cast<u8>(color_texceptions);
  1343. params.zeta_format = regs.zeta_enable ? static_cast<u8>(regs.zeta.format) : 0;
  1344. params.zeta_texception = texceptions[ZETA_TEXCEPTION_INDEX];
  1345. return params;
  1346. }
  1347. VkBuffer RasterizerVulkan::DefaultBuffer() {
  1348. if (default_buffer) {
  1349. return *default_buffer;
  1350. }
  1351. default_buffer = device.GetLogical().CreateBuffer({
  1352. .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
  1353. .pNext = nullptr,
  1354. .flags = 0,
  1355. .size = DEFAULT_BUFFER_SIZE,
  1356. .usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
  1357. VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
  1358. .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
  1359. .queueFamilyIndexCount = 0,
  1360. .pQueueFamilyIndices = nullptr,
  1361. });
  1362. default_buffer_commit = memory_manager.Commit(default_buffer, false);
  1363. scheduler.RequestOutsideRenderPassOperationContext();
  1364. scheduler.Record([buffer = *default_buffer](vk::CommandBuffer cmdbuf) {
  1365. cmdbuf.FillBuffer(buffer, 0, DEFAULT_BUFFER_SIZE, 0);
  1366. });
  1367. return *default_buffer;
  1368. }
  1369. } // namespace Vulkan