texture_cache.h 50 KB

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