texture_cache.h 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <algorithm>
  6. #include <array>
  7. #include <list>
  8. #include <memory>
  9. #include <mutex>
  10. #include <set>
  11. #include <tuple>
  12. #include <unordered_map>
  13. #include <vector>
  14. #include <boost/icl/interval_map.hpp>
  15. #include <boost/range/iterator_range.hpp>
  16. #include "common/assert.h"
  17. #include "common/common_types.h"
  18. #include "common/math_util.h"
  19. #include "core/core.h"
  20. #include "core/memory.h"
  21. #include "core/settings.h"
  22. #include "video_core/dirty_flags.h"
  23. #include "video_core/engines/fermi_2d.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/gpu.h"
  26. #include "video_core/memory_manager.h"
  27. #include "video_core/rasterizer_interface.h"
  28. #include "video_core/surface.h"
  29. #include "video_core/texture_cache/copy_params.h"
  30. #include "video_core/texture_cache/format_lookup_table.h"
  31. #include "video_core/texture_cache/surface_base.h"
  32. #include "video_core/texture_cache/surface_params.h"
  33. #include "video_core/texture_cache/surface_view.h"
  34. namespace Tegra::Texture {
  35. struct FullTextureInfo;
  36. }
  37. namespace VideoCore {
  38. class RasterizerInterface;
  39. }
  40. namespace VideoCommon {
  41. using VideoCore::Surface::PixelFormat;
  42. using VideoCore::Surface::SurfaceTarget;
  43. using RenderTargetConfig = Tegra::Engines::Maxwell3D::Regs::RenderTargetConfig;
  44. template <typename TSurface, typename TView>
  45. class TextureCache {
  46. public:
  47. void InvalidateRegion(VAddr addr, std::size_t size) {
  48. std::lock_guard lock{mutex};
  49. for (const auto& surface : GetSurfacesInRegion(addr, size)) {
  50. Unregister(surface);
  51. }
  52. }
  53. void OnCPUWrite(VAddr addr, std::size_t size) {
  54. std::lock_guard lock{mutex};
  55. for (const auto& surface : GetSurfacesInRegion(addr, size)) {
  56. if (surface->IsMemoryMarked()) {
  57. Unmark(surface);
  58. surface->SetSyncPending(true);
  59. marked_for_unregister.emplace_back(surface);
  60. }
  61. }
  62. }
  63. void SyncGuestHost() {
  64. std::lock_guard lock{mutex};
  65. for (const auto& surface : marked_for_unregister) {
  66. if (surface->IsRegistered()) {
  67. surface->SetSyncPending(false);
  68. Unregister(surface);
  69. }
  70. }
  71. marked_for_unregister.clear();
  72. }
  73. /**
  74. * Guarantees that rendertargets don't unregister themselves if the
  75. * collide. Protection is currently only done on 3D slices.
  76. */
  77. void GuardRenderTargets(bool new_guard) {
  78. guard_render_targets = new_guard;
  79. }
  80. void GuardSamplers(bool new_guard) {
  81. guard_samplers = new_guard;
  82. }
  83. void FlushRegion(VAddr addr, std::size_t size) {
  84. std::lock_guard lock{mutex};
  85. auto surfaces = GetSurfacesInRegion(addr, size);
  86. if (surfaces.empty()) {
  87. return;
  88. }
  89. std::sort(surfaces.begin(), surfaces.end(), [](const TSurface& a, const TSurface& b) {
  90. return a->GetModificationTick() < b->GetModificationTick();
  91. });
  92. for (const auto& surface : surfaces) {
  93. mutex.unlock();
  94. FlushSurface(surface);
  95. mutex.lock();
  96. }
  97. }
  98. TView GetTextureSurface(const Tegra::Texture::TICEntry& tic,
  99. const VideoCommon::Shader::Sampler& entry) {
  100. std::lock_guard lock{mutex};
  101. const auto gpu_addr{tic.Address()};
  102. if (!gpu_addr) {
  103. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  104. }
  105. const std::optional<VAddr> cpu_addr =
  106. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  107. if (!cpu_addr) {
  108. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  109. }
  110. if (!IsTypeCompatible(tic.texture_type, entry)) {
  111. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  112. }
  113. const auto params{SurfaceParams::CreateForTexture(format_lookup_table, tic, entry)};
  114. const auto [surface, view] = GetSurface(gpu_addr, *cpu_addr, params, false);
  115. if (guard_samplers) {
  116. sampled_textures.push_back(surface);
  117. }
  118. return view;
  119. }
  120. TView GetImageSurface(const Tegra::Texture::TICEntry& tic,
  121. const VideoCommon::Shader::Image& entry) {
  122. std::lock_guard lock{mutex};
  123. const auto gpu_addr{tic.Address()};
  124. if (!gpu_addr) {
  125. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  126. }
  127. const std::optional<VAddr> cpu_addr =
  128. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  129. if (!cpu_addr) {
  130. return GetNullSurface(SurfaceParams::ExpectedTarget(entry));
  131. }
  132. const auto params{SurfaceParams::CreateForImage(format_lookup_table, tic, entry)};
  133. const auto [surface, view] = GetSurface(gpu_addr, *cpu_addr, params, false);
  134. if (guard_samplers) {
  135. sampled_textures.push_back(surface);
  136. }
  137. return view;
  138. }
  139. bool TextureBarrier() {
  140. const bool any_rt =
  141. std::any_of(sampled_textures.begin(), sampled_textures.end(),
  142. [](const auto& surface) { return surface->IsRenderTarget(); });
  143. sampled_textures.clear();
  144. return any_rt;
  145. }
  146. TView GetDepthBufferSurface() {
  147. std::lock_guard lock{mutex};
  148. auto& maxwell3d = system.GPU().Maxwell3D();
  149. if (!maxwell3d.dirty.flags[VideoCommon::Dirty::ZetaBuffer]) {
  150. return depth_buffer.view;
  151. }
  152. maxwell3d.dirty.flags[VideoCommon::Dirty::ZetaBuffer] = false;
  153. const auto& regs{maxwell3d.regs};
  154. const auto gpu_addr{regs.zeta.Address()};
  155. if (!gpu_addr || !regs.zeta_enable) {
  156. SetEmptyDepthBuffer();
  157. return {};
  158. }
  159. const std::optional<VAddr> cpu_addr =
  160. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  161. if (!cpu_addr) {
  162. SetEmptyDepthBuffer();
  163. return {};
  164. }
  165. const auto depth_params{SurfaceParams::CreateForDepthBuffer(system)};
  166. auto surface_view = GetSurface(gpu_addr, *cpu_addr, depth_params, true);
  167. if (depth_buffer.target)
  168. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  169. depth_buffer.target = surface_view.first;
  170. depth_buffer.view = surface_view.second;
  171. if (depth_buffer.target)
  172. depth_buffer.target->MarkAsRenderTarget(true, DEPTH_RT);
  173. return surface_view.second;
  174. }
  175. TView GetColorBufferSurface(std::size_t index) {
  176. std::lock_guard lock{mutex};
  177. ASSERT(index < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets);
  178. auto& maxwell3d = system.GPU().Maxwell3D();
  179. if (!maxwell3d.dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index]) {
  180. return render_targets[index].view;
  181. }
  182. maxwell3d.dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index] = false;
  183. const auto& regs{maxwell3d.regs};
  184. if (index >= regs.rt_control.count || regs.rt[index].Address() == 0 ||
  185. regs.rt[index].format == Tegra::RenderTargetFormat::NONE) {
  186. SetEmptyColorBuffer(index);
  187. return {};
  188. }
  189. const auto& config{regs.rt[index]};
  190. const auto gpu_addr{config.Address()};
  191. if (!gpu_addr) {
  192. SetEmptyColorBuffer(index);
  193. return {};
  194. }
  195. const std::optional<VAddr> cpu_addr =
  196. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  197. if (!cpu_addr) {
  198. SetEmptyColorBuffer(index);
  199. return {};
  200. }
  201. auto surface_view = GetSurface(gpu_addr, *cpu_addr,
  202. SurfaceParams::CreateForFramebuffer(system, index), true);
  203. if (render_targets[index].target) {
  204. auto& surface = render_targets[index].target;
  205. surface->MarkAsRenderTarget(false, NO_RT);
  206. const auto& cr_params = surface->GetSurfaceParams();
  207. if (!cr_params.is_tiled) {
  208. AsyncFlushSurface(surface);
  209. }
  210. }
  211. render_targets[index].target = surface_view.first;
  212. render_targets[index].view = surface_view.second;
  213. if (render_targets[index].target)
  214. render_targets[index].target->MarkAsRenderTarget(true, static_cast<u32>(index));
  215. return surface_view.second;
  216. }
  217. void MarkColorBufferInUse(std::size_t index) {
  218. if (auto& render_target = render_targets[index].target) {
  219. render_target->MarkAsModified(true, Tick());
  220. }
  221. }
  222. void MarkDepthBufferInUse() {
  223. if (depth_buffer.target) {
  224. depth_buffer.target->MarkAsModified(true, Tick());
  225. }
  226. }
  227. void SetEmptyDepthBuffer() {
  228. if (depth_buffer.target == nullptr) {
  229. return;
  230. }
  231. depth_buffer.target->MarkAsRenderTarget(false, NO_RT);
  232. depth_buffer.target = nullptr;
  233. depth_buffer.view = nullptr;
  234. }
  235. void SetEmptyColorBuffer(std::size_t index) {
  236. if (render_targets[index].target == nullptr) {
  237. return;
  238. }
  239. render_targets[index].target->MarkAsRenderTarget(false, NO_RT);
  240. render_targets[index].target = nullptr;
  241. render_targets[index].view = nullptr;
  242. }
  243. void DoFermiCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src_config,
  244. const Tegra::Engines::Fermi2D::Regs::Surface& dst_config,
  245. const Tegra::Engines::Fermi2D::Config& copy_config) {
  246. std::lock_guard lock{mutex};
  247. SurfaceParams src_params = SurfaceParams::CreateForFermiCopySurface(src_config);
  248. SurfaceParams dst_params = SurfaceParams::CreateForFermiCopySurface(dst_config);
  249. const GPUVAddr src_gpu_addr = src_config.Address();
  250. const GPUVAddr dst_gpu_addr = dst_config.Address();
  251. DeduceBestBlit(src_params, dst_params, src_gpu_addr, dst_gpu_addr);
  252. const std::optional<VAddr> dst_cpu_addr =
  253. system.GPU().MemoryManager().GpuToCpuAddress(dst_gpu_addr);
  254. const std::optional<VAddr> src_cpu_addr =
  255. system.GPU().MemoryManager().GpuToCpuAddress(src_gpu_addr);
  256. std::pair<TSurface, TView> dst_surface =
  257. GetSurface(dst_gpu_addr, *dst_cpu_addr, dst_params, false);
  258. std::pair<TSurface, TView> src_surface =
  259. GetSurface(src_gpu_addr, *src_cpu_addr, src_params, false);
  260. ImageBlit(src_surface.second, dst_surface.second, copy_config);
  261. dst_surface.first->MarkAsModified(true, Tick());
  262. }
  263. TSurface TryFindFramebufferSurface(VAddr addr) {
  264. if (!addr) {
  265. return nullptr;
  266. }
  267. const VAddr page = addr >> registry_page_bits;
  268. std::vector<TSurface>& list = registry[page];
  269. for (auto& surface : list) {
  270. if (surface->GetCpuAddr() == addr) {
  271. return surface;
  272. }
  273. }
  274. return nullptr;
  275. }
  276. u64 Tick() {
  277. return ++ticks;
  278. }
  279. void CommitAsyncFlushes() {
  280. commited_flushes.push_back(uncommited_flushes);
  281. uncommited_flushes.reset();
  282. }
  283. void PopAsyncFlushes() {
  284. if (commited_flushes.empty()) {
  285. return;
  286. }
  287. auto& flush_list = commited_flushes.front();
  288. if (!flush_list) {
  289. commited_flushes.pop_front();
  290. return;
  291. }
  292. for (TSurface& surface : *flush_list) {
  293. FlushSurface(surface);
  294. }
  295. commited_flushes.pop_front();
  296. }
  297. protected:
  298. explicit TextureCache(Core::System& system, VideoCore::RasterizerInterface& rasterizer,
  299. bool is_astc_supported)
  300. : system{system}, is_astc_supported{is_astc_supported}, rasterizer{rasterizer} {
  301. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  302. SetEmptyColorBuffer(i);
  303. }
  304. SetEmptyDepthBuffer();
  305. staging_cache.SetSize(2);
  306. const auto make_siblings = [this](PixelFormat a, PixelFormat b) {
  307. siblings_table[static_cast<std::size_t>(a)] = b;
  308. siblings_table[static_cast<std::size_t>(b)] = a;
  309. };
  310. std::fill(siblings_table.begin(), siblings_table.end(), PixelFormat::Invalid);
  311. make_siblings(PixelFormat::Z16, PixelFormat::R16U);
  312. make_siblings(PixelFormat::Z32F, PixelFormat::R32F);
  313. make_siblings(PixelFormat::Z32FS8, PixelFormat::RG32F);
  314. sampled_textures.reserve(64);
  315. }
  316. ~TextureCache() = default;
  317. virtual TSurface CreateSurface(GPUVAddr gpu_addr, const SurfaceParams& params) = 0;
  318. virtual void ImageCopy(TSurface& src_surface, TSurface& dst_surface,
  319. const CopyParams& copy_params) = 0;
  320. virtual void ImageBlit(TView& src_view, TView& dst_view,
  321. const Tegra::Engines::Fermi2D::Config& copy_config) = 0;
  322. // Depending on the backend, a buffer copy can be slow as it means deoptimizing the texture
  323. // and reading it from a separate buffer.
  324. virtual void BufferCopy(TSurface& src_surface, TSurface& dst_surface) = 0;
  325. void ManageRenderTargetUnregister(TSurface& surface) {
  326. auto& dirty = system.GPU().Maxwell3D().dirty;
  327. const u32 index = surface->GetRenderTarget();
  328. if (index == DEPTH_RT) {
  329. dirty.flags[VideoCommon::Dirty::ZetaBuffer] = true;
  330. } else {
  331. dirty.flags[VideoCommon::Dirty::ColorBuffer0 + index] = true;
  332. }
  333. dirty.flags[VideoCommon::Dirty::RenderTargets] = true;
  334. }
  335. void Register(TSurface surface) {
  336. const GPUVAddr gpu_addr = surface->GetGpuAddr();
  337. const std::size_t size = surface->GetSizeInBytes();
  338. const std::optional<VAddr> cpu_addr =
  339. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  340. if (!cpu_addr) {
  341. LOG_CRITICAL(HW_GPU, "Failed to register surface with unmapped gpu_address 0x{:016x}",
  342. gpu_addr);
  343. return;
  344. }
  345. surface->SetCpuAddr(*cpu_addr);
  346. RegisterInnerCache(surface);
  347. surface->MarkAsRegistered(true);
  348. surface->SetMemoryMarked(true);
  349. rasterizer.UpdatePagesCachedCount(*cpu_addr, size, 1);
  350. }
  351. void Unmark(TSurface surface) {
  352. if (!surface->IsMemoryMarked()) {
  353. return;
  354. }
  355. const std::size_t size = surface->GetSizeInBytes();
  356. const VAddr cpu_addr = surface->GetCpuAddr();
  357. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  358. surface->SetMemoryMarked(false);
  359. }
  360. void Unregister(TSurface surface) {
  361. if (guard_render_targets && surface->IsProtected()) {
  362. return;
  363. }
  364. if (!guard_render_targets && surface->IsRenderTarget()) {
  365. ManageRenderTargetUnregister(surface);
  366. }
  367. Unmark(surface);
  368. if (surface->IsSyncPending()) {
  369. marked_for_unregister.remove(surface);
  370. surface->SetSyncPending(false);
  371. }
  372. UnregisterInnerCache(surface);
  373. surface->MarkAsRegistered(false);
  374. ReserveSurface(surface->GetSurfaceParams(), surface);
  375. }
  376. TSurface GetUncachedSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  377. if (const auto surface = TryGetReservedSurface(params); surface) {
  378. surface->SetGpuAddr(gpu_addr);
  379. return surface;
  380. }
  381. // No reserved surface available, create a new one and reserve it
  382. auto new_surface{CreateSurface(gpu_addr, params)};
  383. return new_surface;
  384. }
  385. Core::System& system;
  386. const bool is_astc_supported;
  387. private:
  388. enum class RecycleStrategy : u32 {
  389. Ignore = 0,
  390. Flush = 1,
  391. BufferCopy = 3,
  392. };
  393. enum class DeductionType : u32 {
  394. DeductionComplete,
  395. DeductionIncomplete,
  396. DeductionFailed,
  397. };
  398. struct Deduction {
  399. DeductionType type{DeductionType::DeductionFailed};
  400. TSurface surface{};
  401. bool Failed() const {
  402. return type == DeductionType::DeductionFailed;
  403. }
  404. bool Incomplete() const {
  405. return type == DeductionType::DeductionIncomplete;
  406. }
  407. bool IsDepth() const {
  408. return surface->GetSurfaceParams().IsPixelFormatZeta();
  409. }
  410. };
  411. /**
  412. * Takes care of selecting a proper strategy to deal with a texture recycle.
  413. *
  414. * @param overlaps The overlapping surfaces registered in the cache.
  415. * @param params The parameters on the new surface.
  416. * @param gpu_addr The starting address of the new surface.
  417. * @param untopological Indicates to the recycler that the texture has no way
  418. * to match the overlaps due to topological reasons.
  419. **/
  420. RecycleStrategy PickStrategy(std::vector<TSurface>& overlaps, const SurfaceParams& params,
  421. const GPUVAddr gpu_addr, const MatchTopologyResult untopological) {
  422. if (Settings::IsGPULevelExtreme()) {
  423. return RecycleStrategy::Flush;
  424. }
  425. // 3D Textures decision
  426. if (params.block_depth > 1 || params.target == SurfaceTarget::Texture3D) {
  427. return RecycleStrategy::Flush;
  428. }
  429. for (const auto& s : overlaps) {
  430. const auto& s_params = s->GetSurfaceParams();
  431. if (s_params.block_depth > 1 || s_params.target == SurfaceTarget::Texture3D) {
  432. return RecycleStrategy::Flush;
  433. }
  434. }
  435. // Untopological decision
  436. if (untopological == MatchTopologyResult::CompressUnmatch) {
  437. return RecycleStrategy::Flush;
  438. }
  439. if (untopological == MatchTopologyResult::FullMatch && !params.is_tiled) {
  440. return RecycleStrategy::Flush;
  441. }
  442. return RecycleStrategy::Ignore;
  443. }
  444. /**
  445. * Used to decide what to do with textures we can't resolve in the cache It has 2 implemented
  446. * strategies: Ignore and Flush.
  447. *
  448. * - Ignore: Just unregisters all the overlaps and loads the new texture.
  449. * - Flush: Flushes all the overlaps into memory and loads the new surface from that data.
  450. *
  451. * @param overlaps The overlapping surfaces registered in the cache.
  452. * @param params The parameters for the new surface.
  453. * @param gpu_addr The starting address of the new surface.
  454. * @param untopological Indicates to the recycler that the texture has no way to match the
  455. * overlaps due to topological reasons.
  456. **/
  457. std::pair<TSurface, TView> RecycleSurface(std::vector<TSurface>& overlaps,
  458. const SurfaceParams& params, const GPUVAddr gpu_addr,
  459. const MatchTopologyResult untopological) {
  460. for (auto& surface : overlaps) {
  461. Unregister(surface);
  462. }
  463. switch (PickStrategy(overlaps, params, gpu_addr, untopological)) {
  464. case RecycleStrategy::Ignore: {
  465. return InitializeSurface(gpu_addr, params, Settings::IsGPULevelExtreme());
  466. }
  467. case RecycleStrategy::Flush: {
  468. std::sort(overlaps.begin(), overlaps.end(),
  469. [](const TSurface& a, const TSurface& b) -> bool {
  470. return a->GetModificationTick() < b->GetModificationTick();
  471. });
  472. for (auto& surface : overlaps) {
  473. FlushSurface(surface);
  474. }
  475. return InitializeSurface(gpu_addr, params);
  476. }
  477. case RecycleStrategy::BufferCopy: {
  478. auto new_surface = GetUncachedSurface(gpu_addr, params);
  479. BufferCopy(overlaps[0], new_surface);
  480. return {new_surface, new_surface->GetMainView()};
  481. }
  482. default: {
  483. UNIMPLEMENTED_MSG("Unimplemented Texture Cache Recycling Strategy!");
  484. return InitializeSurface(gpu_addr, params);
  485. }
  486. }
  487. }
  488. /**
  489. * Takes a single surface and recreates into another that may differ in
  490. * format, target or width alignment.
  491. *
  492. * @param current_surface The registered surface in the cache which we want to convert.
  493. * @param params The new surface params which we'll use to recreate the surface.
  494. * @param is_render Whether or not the surface is a render target.
  495. **/
  496. std::pair<TSurface, TView> RebuildSurface(TSurface current_surface, const SurfaceParams& params,
  497. bool is_render) {
  498. const auto gpu_addr = current_surface->GetGpuAddr();
  499. const auto& cr_params = current_surface->GetSurfaceParams();
  500. TSurface new_surface;
  501. if (cr_params.pixel_format != params.pixel_format && !is_render &&
  502. GetSiblingFormat(cr_params.pixel_format) == params.pixel_format) {
  503. SurfaceParams new_params = params;
  504. new_params.pixel_format = cr_params.pixel_format;
  505. new_params.type = cr_params.type;
  506. new_surface = GetUncachedSurface(gpu_addr, new_params);
  507. } else {
  508. new_surface = GetUncachedSurface(gpu_addr, params);
  509. }
  510. const auto& final_params = new_surface->GetSurfaceParams();
  511. if (cr_params.type != final_params.type) {
  512. if (Settings::IsGPULevelExtreme()) {
  513. BufferCopy(current_surface, new_surface);
  514. }
  515. } else {
  516. std::vector<CopyParams> bricks = current_surface->BreakDown(final_params);
  517. for (auto& brick : bricks) {
  518. ImageCopy(current_surface, new_surface, brick);
  519. }
  520. }
  521. Unregister(current_surface);
  522. Register(new_surface);
  523. new_surface->MarkAsModified(current_surface->IsModified(), Tick());
  524. return {new_surface, new_surface->GetMainView()};
  525. }
  526. /**
  527. * Takes a single surface and checks with the new surface's params if it's an exact
  528. * match, we return the main view of the registered surface. If its formats don't
  529. * match, we rebuild the surface. We call this last method a `Mirage`. If formats
  530. * match but the targets don't, we create an overview View of the registered surface.
  531. *
  532. * @param current_surface The registered surface in the cache which we want to convert.
  533. * @param params The new surface params which we want to check.
  534. * @param is_render Whether or not the surface is a render target.
  535. **/
  536. std::pair<TSurface, TView> ManageStructuralMatch(TSurface current_surface,
  537. const SurfaceParams& params, bool is_render) {
  538. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  539. const bool matches_target = current_surface->MatchTarget(params.target);
  540. const auto match_check = [&]() -> std::pair<TSurface, TView> {
  541. if (matches_target) {
  542. return {current_surface, current_surface->GetMainView()};
  543. }
  544. return {current_surface, current_surface->EmplaceOverview(params)};
  545. };
  546. if (!is_mirage) {
  547. return match_check();
  548. }
  549. if (!is_render && GetSiblingFormat(current_surface->GetFormat()) == params.pixel_format) {
  550. return match_check();
  551. }
  552. return RebuildSurface(current_surface, params, is_render);
  553. }
  554. /**
  555. * Unlike RebuildSurface where we know whether or not registered surfaces match the candidate
  556. * in some way, we have no guarantees here. We try to see if the overlaps are sublayers/mipmaps
  557. * of the new surface, if they all match we end up recreating a surface for them,
  558. * else we return nothing.
  559. *
  560. * @param overlaps The overlapping surfaces registered in the cache.
  561. * @param params The parameters on the new surface.
  562. * @param gpu_addr The starting address of the new surface.
  563. **/
  564. std::optional<std::pair<TSurface, TView>> TryReconstructSurface(std::vector<TSurface>& overlaps,
  565. const SurfaceParams& params,
  566. const GPUVAddr gpu_addr) {
  567. if (params.target == SurfaceTarget::Texture3D) {
  568. return {};
  569. }
  570. bool modified = false;
  571. TSurface new_surface = GetUncachedSurface(gpu_addr, params);
  572. u32 passed_tests = 0;
  573. for (auto& surface : overlaps) {
  574. const SurfaceParams& src_params = surface->GetSurfaceParams();
  575. if (src_params.is_layered || src_params.num_levels > 1) {
  576. // We send this cases to recycle as they are more complex to handle
  577. return {};
  578. }
  579. const std::size_t candidate_size = surface->GetSizeInBytes();
  580. auto mipmap_layer{new_surface->GetLayerMipmap(surface->GetGpuAddr())};
  581. if (!mipmap_layer) {
  582. continue;
  583. }
  584. const auto [layer, mipmap] = *mipmap_layer;
  585. if (new_surface->GetMipmapSize(mipmap) != candidate_size) {
  586. continue;
  587. }
  588. modified |= surface->IsModified();
  589. // Now we got all the data set up
  590. const u32 width = SurfaceParams::IntersectWidth(src_params, params, 0, mipmap);
  591. const u32 height = SurfaceParams::IntersectHeight(src_params, params, 0, mipmap);
  592. const CopyParams copy_params(0, 0, 0, 0, 0, layer, 0, mipmap, width, height, 1);
  593. passed_tests++;
  594. ImageCopy(surface, new_surface, copy_params);
  595. }
  596. if (passed_tests == 0) {
  597. return {};
  598. // In Accurate GPU all tests should pass, else we recycle
  599. } else if (Settings::IsGPULevelExtreme() && passed_tests != overlaps.size()) {
  600. return {};
  601. }
  602. for (const auto& surface : overlaps) {
  603. Unregister(surface);
  604. }
  605. new_surface->MarkAsModified(modified, Tick());
  606. Register(new_surface);
  607. return {{new_surface, new_surface->GetMainView()}};
  608. }
  609. /**
  610. * Takes care of managing 3D textures and its slices. Does HLE methods for reconstructing the 3D
  611. * textures within the GPU if possible. Falls back to LLE when it isn't possible to use any of
  612. * the HLE methods.
  613. *
  614. * @param overlaps The overlapping surfaces registered in the cache.
  615. * @param params The parameters on the new surface.
  616. * @param gpu_addr The starting address of the new surface.
  617. * @param cpu_addr The starting address of the new surface on physical memory.
  618. */
  619. std::optional<std::pair<TSurface, TView>> Manage3DSurfaces(std::vector<TSurface>& overlaps,
  620. const SurfaceParams& params,
  621. const GPUVAddr gpu_addr,
  622. const VAddr cpu_addr) {
  623. if (params.target == SurfaceTarget::Texture3D) {
  624. bool failed = false;
  625. if (params.num_levels > 1) {
  626. // We can't handle mipmaps in 3D textures yet, better fallback to LLE approach
  627. return std::nullopt;
  628. }
  629. TSurface new_surface = GetUncachedSurface(gpu_addr, params);
  630. bool modified = false;
  631. for (auto& surface : overlaps) {
  632. const SurfaceParams& src_params = surface->GetSurfaceParams();
  633. if (src_params.target != SurfaceTarget::Texture2D) {
  634. failed = true;
  635. break;
  636. }
  637. if (src_params.height != params.height) {
  638. failed = true;
  639. break;
  640. }
  641. if (src_params.block_depth != params.block_depth ||
  642. src_params.block_height != params.block_height) {
  643. failed = true;
  644. break;
  645. }
  646. const u32 offset = static_cast<u32>(surface->GetCpuAddr() - cpu_addr);
  647. const auto offsets = params.GetBlockOffsetXYZ(offset);
  648. const auto z = std::get<2>(offsets);
  649. modified |= surface->IsModified();
  650. const CopyParams copy_params(0, 0, 0, 0, 0, z, 0, 0, params.width, params.height,
  651. 1);
  652. ImageCopy(surface, new_surface, copy_params);
  653. }
  654. if (failed) {
  655. return std::nullopt;
  656. }
  657. for (const auto& surface : overlaps) {
  658. Unregister(surface);
  659. }
  660. new_surface->MarkAsModified(modified, Tick());
  661. Register(new_surface);
  662. auto view = new_surface->GetMainView();
  663. return {{std::move(new_surface), view}};
  664. } else {
  665. for (const auto& surface : overlaps) {
  666. if (!surface->MatchTarget(params.target)) {
  667. if (overlaps.size() == 1 && surface->GetCpuAddr() == cpu_addr) {
  668. if (Settings::IsGPULevelExtreme()) {
  669. return std::nullopt;
  670. }
  671. Unregister(surface);
  672. return InitializeSurface(gpu_addr, params);
  673. }
  674. return std::nullopt;
  675. }
  676. if (surface->GetCpuAddr() != cpu_addr) {
  677. continue;
  678. }
  679. if (surface->MatchesStructure(params) == MatchStructureResult::FullMatch) {
  680. return {{surface, surface->GetMainView()}};
  681. }
  682. }
  683. return InitializeSurface(gpu_addr, params);
  684. }
  685. }
  686. /**
  687. * Gets the starting address and parameters of a candidate surface and tries
  688. * to find a matching surface within the cache. This is done in 3 big steps:
  689. *
  690. * 1. Check the 1st Level Cache in order to find an exact match, if we fail, we move to step 2.
  691. *
  692. * 2. Check if there are any overlaps at all, if there are none, we just load the texture from
  693. * memory else we move to step 3.
  694. *
  695. * 3. Consists of figuring out the relationship between the candidate texture and the
  696. * overlaps. We divide the scenarios depending if there's 1 or many overlaps. If
  697. * there's many, we just try to reconstruct a new surface out of them based on the
  698. * candidate's parameters, if we fail, we recycle. When there's only 1 overlap then we
  699. * have to check if the candidate is a view (layer/mipmap) of the overlap or if the
  700. * registered surface is a mipmap/layer of the candidate. In this last case we reconstruct
  701. * a new surface.
  702. *
  703. * @param gpu_addr The starting address of the candidate surface.
  704. * @param params The parameters on the candidate surface.
  705. * @param is_render Whether or not the surface is a render target.
  706. **/
  707. std::pair<TSurface, TView> GetSurface(const GPUVAddr gpu_addr, const VAddr cpu_addr,
  708. const SurfaceParams& params, bool is_render) {
  709. // Step 1
  710. // Check Level 1 Cache for a fast structural match. If candidate surface
  711. // matches at certain level we are pretty much done.
  712. if (const auto iter = l1_cache.find(cpu_addr); iter != l1_cache.end()) {
  713. TSurface& current_surface = iter->second;
  714. const auto topological_result = current_surface->MatchesTopology(params);
  715. if (topological_result != MatchTopologyResult::FullMatch) {
  716. std::vector<TSurface> overlaps{current_surface};
  717. return RecycleSurface(overlaps, params, gpu_addr, topological_result);
  718. }
  719. const auto struct_result = current_surface->MatchesStructure(params);
  720. if (struct_result != MatchStructureResult::None) {
  721. const auto& old_params = current_surface->GetSurfaceParams();
  722. const bool not_3d = params.target != SurfaceTarget::Texture3D &&
  723. old_params.target != SurfaceTarget::Texture3D;
  724. if (not_3d || current_surface->MatchTarget(params.target)) {
  725. if (struct_result == MatchStructureResult::FullMatch) {
  726. return ManageStructuralMatch(current_surface, params, is_render);
  727. } else {
  728. return RebuildSurface(current_surface, params, is_render);
  729. }
  730. }
  731. }
  732. }
  733. // Step 2
  734. // Obtain all possible overlaps in the memory region
  735. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  736. auto overlaps{GetSurfacesInRegion(cpu_addr, candidate_size)};
  737. // If none are found, we are done. we just load the surface and create it.
  738. if (overlaps.empty()) {
  739. return InitializeSurface(gpu_addr, params);
  740. }
  741. // Step 3
  742. // Now we need to figure the relationship between the texture and its overlaps
  743. // we do a topological test to ensure we can find some relationship. If it fails
  744. // immediately recycle the texture
  745. for (const auto& surface : overlaps) {
  746. const auto topological_result = surface->MatchesTopology(params);
  747. if (topological_result != MatchTopologyResult::FullMatch) {
  748. return RecycleSurface(overlaps, params, gpu_addr, topological_result);
  749. }
  750. }
  751. // Check if it's a 3D texture
  752. if (params.block_depth > 0) {
  753. auto surface = Manage3DSurfaces(overlaps, params, gpu_addr, cpu_addr);
  754. if (surface) {
  755. return *surface;
  756. }
  757. }
  758. // Split cases between 1 overlap or many.
  759. if (overlaps.size() == 1) {
  760. TSurface current_surface = overlaps[0];
  761. // First check if the surface is within the overlap. If not, it means
  762. // two things either the candidate surface is a supertexture of the overlap
  763. // or they don't match in any known way.
  764. if (!current_surface->IsInside(gpu_addr, gpu_addr + candidate_size)) {
  765. if (current_surface->GetGpuAddr() == gpu_addr) {
  766. std::optional<std::pair<TSurface, TView>> view =
  767. TryReconstructSurface(overlaps, params, gpu_addr);
  768. if (view) {
  769. return *view;
  770. }
  771. }
  772. return RecycleSurface(overlaps, params, gpu_addr, MatchTopologyResult::FullMatch);
  773. }
  774. // Now we check if the candidate is a mipmap/layer of the overlap
  775. std::optional<TView> view =
  776. current_surface->EmplaceView(params, gpu_addr, candidate_size);
  777. if (view) {
  778. const bool is_mirage = !current_surface->MatchFormat(params.pixel_format);
  779. if (is_mirage) {
  780. // On a mirage view, we need to recreate the surface under this new view
  781. // and then obtain a view again.
  782. SurfaceParams new_params = current_surface->GetSurfaceParams();
  783. const u32 wh = SurfaceParams::ConvertWidth(
  784. new_params.width, new_params.pixel_format, params.pixel_format);
  785. const u32 hh = SurfaceParams::ConvertHeight(
  786. new_params.height, new_params.pixel_format, params.pixel_format);
  787. new_params.width = wh;
  788. new_params.height = hh;
  789. new_params.pixel_format = params.pixel_format;
  790. std::pair<TSurface, TView> pair =
  791. RebuildSurface(current_surface, new_params, is_render);
  792. std::optional<TView> mirage_view =
  793. pair.first->EmplaceView(params, gpu_addr, candidate_size);
  794. if (mirage_view)
  795. return {pair.first, *mirage_view};
  796. return RecycleSurface(overlaps, params, gpu_addr,
  797. MatchTopologyResult::FullMatch);
  798. }
  799. return {current_surface, *view};
  800. }
  801. } else {
  802. // If there are many overlaps, odds are they are subtextures of the candidate
  803. // surface. We try to construct a new surface based on the candidate parameters,
  804. // using the overlaps. If a single overlap fails, this will fail.
  805. std::optional<std::pair<TSurface, TView>> view =
  806. TryReconstructSurface(overlaps, params, gpu_addr);
  807. if (view) {
  808. return *view;
  809. }
  810. }
  811. // We failed all the tests, recycle the overlaps into a new texture.
  812. return RecycleSurface(overlaps, params, gpu_addr, MatchTopologyResult::FullMatch);
  813. }
  814. /**
  815. * Gets the starting address and parameters of a candidate surface and tries to find a
  816. * matching surface within the cache that's similar to it. If there are many textures
  817. * or the texture found if entirely incompatible, it will fail. If no texture is found, the
  818. * blit will be unsuccessful.
  819. *
  820. * @param gpu_addr The starting address of the candidate surface.
  821. * @param params The parameters on the candidate surface.
  822. **/
  823. Deduction DeduceSurface(const GPUVAddr gpu_addr, const SurfaceParams& params) {
  824. const std::optional<VAddr> cpu_addr =
  825. system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
  826. if (!cpu_addr) {
  827. Deduction result{};
  828. result.type = DeductionType::DeductionFailed;
  829. return result;
  830. }
  831. if (const auto iter = l1_cache.find(*cpu_addr); iter != l1_cache.end()) {
  832. TSurface& current_surface = iter->second;
  833. const auto topological_result = current_surface->MatchesTopology(params);
  834. if (topological_result != MatchTopologyResult::FullMatch) {
  835. Deduction result{};
  836. result.type = DeductionType::DeductionFailed;
  837. return result;
  838. }
  839. const auto struct_result = current_surface->MatchesStructure(params);
  840. if (struct_result != MatchStructureResult::None &&
  841. current_surface->MatchTarget(params.target)) {
  842. Deduction result{};
  843. result.type = DeductionType::DeductionComplete;
  844. result.surface = current_surface;
  845. return result;
  846. }
  847. }
  848. const std::size_t candidate_size = params.GetGuestSizeInBytes();
  849. auto overlaps{GetSurfacesInRegion(*cpu_addr, candidate_size)};
  850. if (overlaps.empty()) {
  851. Deduction result{};
  852. result.type = DeductionType::DeductionIncomplete;
  853. return result;
  854. }
  855. if (overlaps.size() > 1) {
  856. Deduction result{};
  857. result.type = DeductionType::DeductionFailed;
  858. return result;
  859. } else {
  860. Deduction result{};
  861. result.type = DeductionType::DeductionComplete;
  862. result.surface = overlaps[0];
  863. return result;
  864. }
  865. }
  866. /**
  867. * Gets a null surface based on a target texture.
  868. * @param target The target of the null surface.
  869. */
  870. TView GetNullSurface(SurfaceTarget target) {
  871. const u32 i_target = static_cast<u32>(target);
  872. if (const auto it = invalid_cache.find(i_target); it != invalid_cache.end()) {
  873. return it->second->GetMainView();
  874. }
  875. SurfaceParams params{};
  876. params.target = target;
  877. params.is_tiled = false;
  878. params.srgb_conversion = false;
  879. params.is_layered = false;
  880. params.block_width = 0;
  881. params.block_height = 0;
  882. params.block_depth = 0;
  883. params.tile_width_spacing = 1;
  884. params.width = 1;
  885. params.height = 1;
  886. params.depth = 1;
  887. if (target == SurfaceTarget::TextureCubemap || target == SurfaceTarget::TextureCubeArray) {
  888. params.depth = 6;
  889. }
  890. params.pitch = 4;
  891. params.num_levels = 1;
  892. params.emulated_levels = 1;
  893. params.pixel_format = VideoCore::Surface::PixelFormat::R8U;
  894. params.type = VideoCore::Surface::SurfaceType::ColorTexture;
  895. auto surface = CreateSurface(0ULL, params);
  896. invalid_memory.resize(surface->GetHostSizeInBytes(), 0U);
  897. surface->UploadTexture(invalid_memory);
  898. surface->MarkAsModified(false, Tick());
  899. invalid_cache.emplace(i_target, surface);
  900. return surface->GetMainView();
  901. }
  902. /**
  903. * Gets the a source and destination starting address and parameters,
  904. * and tries to deduce if they are supposed to be depth textures. If so, their
  905. * parameters are modified and fixed into so.
  906. *
  907. * @param src_params The parameters of the candidate surface.
  908. * @param dst_params The parameters of the destination surface.
  909. * @param src_gpu_addr The starting address of the candidate surface.
  910. * @param dst_gpu_addr The starting address of the destination surface.
  911. **/
  912. void DeduceBestBlit(SurfaceParams& src_params, SurfaceParams& dst_params,
  913. const GPUVAddr src_gpu_addr, const GPUVAddr dst_gpu_addr) {
  914. auto deduced_src = DeduceSurface(src_gpu_addr, src_params);
  915. auto deduced_dst = DeduceSurface(src_gpu_addr, src_params);
  916. if (deduced_src.Failed() || deduced_dst.Failed()) {
  917. return;
  918. }
  919. const bool incomplete_src = deduced_src.Incomplete();
  920. const bool incomplete_dst = deduced_dst.Incomplete();
  921. if (incomplete_src && incomplete_dst) {
  922. return;
  923. }
  924. const bool any_incomplete = incomplete_src || incomplete_dst;
  925. if (!any_incomplete) {
  926. if (!(deduced_src.IsDepth() && deduced_dst.IsDepth())) {
  927. return;
  928. }
  929. } else {
  930. if (incomplete_src && !(deduced_dst.IsDepth())) {
  931. return;
  932. }
  933. if (incomplete_dst && !(deduced_src.IsDepth())) {
  934. return;
  935. }
  936. }
  937. const auto inherit_format = [](SurfaceParams& to, TSurface from) {
  938. const SurfaceParams& params = from->GetSurfaceParams();
  939. to.pixel_format = params.pixel_format;
  940. to.type = params.type;
  941. };
  942. // Now we got the cases where one or both is Depth and the other is not known
  943. if (!incomplete_src) {
  944. inherit_format(src_params, deduced_src.surface);
  945. } else {
  946. inherit_format(src_params, deduced_dst.surface);
  947. }
  948. if (!incomplete_dst) {
  949. inherit_format(dst_params, deduced_dst.surface);
  950. } else {
  951. inherit_format(dst_params, deduced_src.surface);
  952. }
  953. }
  954. std::pair<TSurface, TView> InitializeSurface(GPUVAddr gpu_addr, const SurfaceParams& params,
  955. bool do_load = true) {
  956. auto new_surface{GetUncachedSurface(gpu_addr, params)};
  957. Register(new_surface);
  958. if (do_load) {
  959. LoadSurface(new_surface);
  960. }
  961. return {new_surface, new_surface->GetMainView()};
  962. }
  963. void LoadSurface(const TSurface& surface) {
  964. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  965. surface->LoadBuffer(system.GPU().MemoryManager(), staging_cache);
  966. surface->UploadTexture(staging_cache.GetBuffer(0));
  967. surface->MarkAsModified(false, Tick());
  968. }
  969. void FlushSurface(const TSurface& surface) {
  970. if (!surface->IsModified()) {
  971. return;
  972. }
  973. staging_cache.GetBuffer(0).resize(surface->GetHostSizeInBytes());
  974. surface->DownloadTexture(staging_cache.GetBuffer(0));
  975. surface->FlushBuffer(system.GPU().MemoryManager(), staging_cache);
  976. surface->MarkAsModified(false, Tick());
  977. }
  978. void RegisterInnerCache(TSurface& surface) {
  979. const VAddr cpu_addr = surface->GetCpuAddr();
  980. VAddr start = cpu_addr >> registry_page_bits;
  981. const VAddr end = (surface->GetCpuAddrEnd() - 1) >> registry_page_bits;
  982. l1_cache[cpu_addr] = surface;
  983. while (start <= end) {
  984. registry[start].push_back(surface);
  985. start++;
  986. }
  987. }
  988. void UnregisterInnerCache(TSurface& surface) {
  989. const VAddr cpu_addr = surface->GetCpuAddr();
  990. VAddr start = cpu_addr >> registry_page_bits;
  991. const VAddr end = (surface->GetCpuAddrEnd() - 1) >> registry_page_bits;
  992. l1_cache.erase(cpu_addr);
  993. while (start <= end) {
  994. auto& reg{registry[start]};
  995. reg.erase(std::find(reg.begin(), reg.end(), surface));
  996. start++;
  997. }
  998. }
  999. std::vector<TSurface> GetSurfacesInRegion(const VAddr cpu_addr, const std::size_t size) {
  1000. if (size == 0) {
  1001. return {};
  1002. }
  1003. const VAddr cpu_addr_end = cpu_addr + size;
  1004. VAddr start = cpu_addr >> registry_page_bits;
  1005. const VAddr end = (cpu_addr_end - 1) >> registry_page_bits;
  1006. std::vector<TSurface> surfaces;
  1007. while (start <= end) {
  1008. std::vector<TSurface>& list = registry[start];
  1009. for (auto& surface : list) {
  1010. if (!surface->IsPicked() && surface->Overlaps(cpu_addr, cpu_addr_end)) {
  1011. surface->MarkAsPicked(true);
  1012. surfaces.push_back(surface);
  1013. }
  1014. }
  1015. start++;
  1016. }
  1017. for (auto& surface : surfaces) {
  1018. surface->MarkAsPicked(false);
  1019. }
  1020. return surfaces;
  1021. }
  1022. void ReserveSurface(const SurfaceParams& params, TSurface surface) {
  1023. surface_reserve[params].push_back(std::move(surface));
  1024. }
  1025. TSurface TryGetReservedSurface(const SurfaceParams& params) {
  1026. auto search{surface_reserve.find(params)};
  1027. if (search == surface_reserve.end()) {
  1028. return {};
  1029. }
  1030. for (auto& surface : search->second) {
  1031. if (!surface->IsRegistered()) {
  1032. return surface;
  1033. }
  1034. }
  1035. return {};
  1036. }
  1037. constexpr PixelFormat GetSiblingFormat(PixelFormat format) const {
  1038. return siblings_table[static_cast<std::size_t>(format)];
  1039. }
  1040. /// Returns true the shader sampler entry is compatible with the TIC texture type.
  1041. static bool IsTypeCompatible(Tegra::Texture::TextureType tic_type,
  1042. const VideoCommon::Shader::Sampler& entry) {
  1043. const auto shader_type = entry.GetType();
  1044. switch (tic_type) {
  1045. case Tegra::Texture::TextureType::Texture1D:
  1046. case Tegra::Texture::TextureType::Texture1DArray:
  1047. return shader_type == Tegra::Shader::TextureType::Texture1D;
  1048. case Tegra::Texture::TextureType::Texture1DBuffer:
  1049. // TODO(Rodrigo): Assume as valid for now
  1050. return true;
  1051. case Tegra::Texture::TextureType::Texture2D:
  1052. case Tegra::Texture::TextureType::Texture2DNoMipmap:
  1053. return shader_type == Tegra::Shader::TextureType::Texture2D;
  1054. case Tegra::Texture::TextureType::Texture2DArray:
  1055. return shader_type == Tegra::Shader::TextureType::Texture2D ||
  1056. shader_type == Tegra::Shader::TextureType::TextureCube;
  1057. case Tegra::Texture::TextureType::Texture3D:
  1058. return shader_type == Tegra::Shader::TextureType::Texture3D;
  1059. case Tegra::Texture::TextureType::TextureCubeArray:
  1060. case Tegra::Texture::TextureType::TextureCubemap:
  1061. if (shader_type == Tegra::Shader::TextureType::TextureCube) {
  1062. return true;
  1063. }
  1064. return shader_type == Tegra::Shader::TextureType::Texture2D && entry.IsArray();
  1065. }
  1066. UNREACHABLE();
  1067. return true;
  1068. }
  1069. struct FramebufferTargetInfo {
  1070. TSurface target;
  1071. TView view;
  1072. };
  1073. void AsyncFlushSurface(TSurface& surface) {
  1074. if (!uncommited_flushes) {
  1075. uncommited_flushes = std::make_shared<std::list<TSurface>>();
  1076. }
  1077. uncommited_flushes->push_back(surface);
  1078. }
  1079. VideoCore::RasterizerInterface& rasterizer;
  1080. FormatLookupTable format_lookup_table;
  1081. u64 ticks{};
  1082. // Guards the cache for protection conflicts.
  1083. bool guard_render_targets{};
  1084. bool guard_samplers{};
  1085. // The siblings table is for formats that can inter exchange with one another
  1086. // without causing issues. This is only valid when a conflict occurs on a non
  1087. // rendering use.
  1088. std::array<PixelFormat, static_cast<std::size_t>(PixelFormat::Max)> siblings_table;
  1089. // The internal Cache is different for the Texture Cache. It's based on buckets
  1090. // of 1MB. This fits better for the purpose of this cache as textures are normaly
  1091. // large in size.
  1092. static constexpr u64 registry_page_bits{20};
  1093. static constexpr u64 registry_page_size{1 << registry_page_bits};
  1094. std::unordered_map<VAddr, std::vector<TSurface>> registry;
  1095. static constexpr u32 DEPTH_RT = 8;
  1096. static constexpr u32 NO_RT = 0xFFFFFFFF;
  1097. // The L1 Cache is used for fast texture lookup before checking the overlaps
  1098. // This avoids calculating size and other stuffs.
  1099. std::unordered_map<VAddr, TSurface> l1_cache;
  1100. /// The surface reserve is a "backup" cache, this is where we put unique surfaces that have
  1101. /// previously been used. This is to prevent surfaces from being constantly created and
  1102. /// destroyed when used with different surface parameters.
  1103. std::unordered_map<SurfaceParams, std::vector<TSurface>> surface_reserve;
  1104. std::array<FramebufferTargetInfo, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets>
  1105. render_targets;
  1106. FramebufferTargetInfo depth_buffer;
  1107. std::vector<TSurface> sampled_textures;
  1108. /// This cache stores null surfaces in order to be used as a placeholder
  1109. /// for invalid texture calls.
  1110. std::unordered_map<u32, TSurface> invalid_cache;
  1111. std::vector<u8> invalid_memory;
  1112. std::list<TSurface> marked_for_unregister;
  1113. std::shared_ptr<std::list<TSurface>> uncommited_flushes{};
  1114. std::list<std::shared_ptr<std::list<TSurface>>> commited_flushes;
  1115. StagingCache staging_cache;
  1116. std::recursive_mutex mutex;
  1117. };
  1118. } // namespace VideoCommon