texture_cache.h 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  1. // SPDX-FileCopyrightText: 2023 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-3.0-or-later
  3. #pragma once
  4. #include <unordered_set>
  5. #include <boost/container/small_vector.hpp>
  6. #include "common/alignment.h"
  7. #include "common/settings.h"
  8. #include "video_core/control/channel_state.h"
  9. #include "video_core/dirty_flags.h"
  10. #include "video_core/engines/kepler_compute.h"
  11. #include "video_core/guest_memory.h"
  12. #include "video_core/host1x/gpu_device_memory_manager.h"
  13. #include "video_core/texture_cache/image_view_base.h"
  14. #include "video_core/texture_cache/samples_helper.h"
  15. #include "video_core/texture_cache/texture_cache_base.h"
  16. #include "video_core/texture_cache/util.h"
  17. namespace VideoCommon {
  18. using Tegra::Texture::TICEntry;
  19. using Tegra::Texture::TSCEntry;
  20. using VideoCore::Surface::GetFormatType;
  21. using VideoCore::Surface::PixelFormat;
  22. using VideoCore::Surface::SurfaceType;
  23. using namespace Common::Literals;
  24. template <class P>
  25. TextureCache<P>::TextureCache(Runtime& runtime_, Tegra::MaxwellDeviceMemoryManager& device_memory_)
  26. : runtime{runtime_}, device_memory{device_memory_} {
  27. // Configure null sampler
  28. TSCEntry sampler_descriptor{};
  29. sampler_descriptor.min_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  30. sampler_descriptor.mag_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  31. sampler_descriptor.mipmap_filter.Assign(Tegra::Texture::TextureMipmapFilter::Linear);
  32. sampler_descriptor.cubemap_anisotropy.Assign(1);
  33. // These values were chosen based on typical peak swizzle data sizes seen in some titles
  34. static constexpr size_t SWIZZLE_DATA_BUFFER_INITIAL_CAPACITY = 8_MiB;
  35. static constexpr size_t UNSWIZZLE_DATA_BUFFER_INITIAL_CAPACITY = 1_MiB;
  36. swizzle_data_buffer.resize_destructive(SWIZZLE_DATA_BUFFER_INITIAL_CAPACITY);
  37. unswizzle_data_buffer.resize_destructive(UNSWIZZLE_DATA_BUFFER_INITIAL_CAPACITY);
  38. // Make sure the first index is reserved for the null resources
  39. // This way the null resource becomes a compile time constant
  40. void(slot_images.insert(NullImageParams{}));
  41. void(slot_image_views.insert(runtime, NullImageViewParams{}));
  42. void(slot_samplers.insert(runtime, sampler_descriptor));
  43. if constexpr (HAS_DEVICE_MEMORY_INFO) {
  44. const s64 device_local_memory = static_cast<s64>(runtime.GetDeviceLocalMemory());
  45. const s64 min_spacing_expected = device_local_memory - 1_GiB;
  46. const s64 min_spacing_critical = device_local_memory - 512_MiB;
  47. const s64 mem_threshold = std::min(device_local_memory, TARGET_THRESHOLD);
  48. const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
  49. const s64 min_vacancy_critical = (3 * mem_threshold) / 10;
  50. expected_memory = static_cast<u64>(
  51. std::max(std::min(device_local_memory - min_vacancy_expected, min_spacing_expected),
  52. DEFAULT_EXPECTED_MEMORY));
  53. critical_memory = static_cast<u64>(
  54. std::max(std::min(device_local_memory - min_vacancy_critical, min_spacing_critical),
  55. DEFAULT_CRITICAL_MEMORY));
  56. minimum_memory = static_cast<u64>((device_local_memory - mem_threshold) / 2);
  57. } else {
  58. expected_memory = DEFAULT_EXPECTED_MEMORY + 512_MiB;
  59. critical_memory = DEFAULT_CRITICAL_MEMORY + 1_GiB;
  60. minimum_memory = 0;
  61. }
  62. }
  63. template <class P>
  64. void TextureCache<P>::RunGarbageCollector() {
  65. bool high_priority_mode = total_used_memory >= expected_memory;
  66. bool aggressive_mode = total_used_memory >= critical_memory;
  67. const u64 ticks_to_destroy = aggressive_mode ? 10ULL : high_priority_mode ? 25ULL : 50ULL;
  68. size_t num_iterations = aggressive_mode ? 40 : (high_priority_mode ? 20 : 10);
  69. const auto clean_up = [this, &num_iterations, &high_priority_mode,
  70. &aggressive_mode](ImageId image_id) {
  71. if (num_iterations == 0) {
  72. return true;
  73. }
  74. --num_iterations;
  75. auto& image = slot_images[image_id];
  76. if (True(image.flags & ImageFlagBits::IsDecoding)) {
  77. // This image is still being decoded, deleting it will invalidate the slot
  78. // used by the async decoder thread.
  79. return false;
  80. }
  81. if (!aggressive_mode && True(image.flags & ImageFlagBits::CostlyLoad)) {
  82. return false;
  83. }
  84. const bool must_download =
  85. image.IsSafeDownload() && False(image.flags & ImageFlagBits::BadOverlap);
  86. if (!high_priority_mode && must_download) {
  87. return false;
  88. }
  89. if (must_download) {
  90. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  91. const auto copies = FullDownloadCopies(image.info);
  92. image.DownloadMemory(map, copies);
  93. runtime.Finish();
  94. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span,
  95. swizzle_data_buffer);
  96. }
  97. if (True(image.flags & ImageFlagBits::Tracked)) {
  98. UntrackImage(image, image_id);
  99. }
  100. UnregisterImage(image_id);
  101. DeleteImage(image_id, image.scale_tick > frame_tick + 5);
  102. if (total_used_memory < critical_memory) {
  103. if (aggressive_mode) {
  104. // Sink the aggresiveness.
  105. num_iterations >>= 2;
  106. aggressive_mode = false;
  107. return false;
  108. }
  109. if (high_priority_mode && total_used_memory < expected_memory) {
  110. num_iterations >>= 1;
  111. high_priority_mode = false;
  112. }
  113. }
  114. return false;
  115. };
  116. lru_cache.ForEachItemBelow(frame_tick - ticks_to_destroy, clean_up);
  117. }
  118. template <class P>
  119. void TextureCache<P>::TickFrame() {
  120. // If we can obtain the memory info, use it instead of the estimate.
  121. if (runtime.CanReportMemoryUsage()) {
  122. total_used_memory = runtime.GetDeviceMemoryUsage();
  123. }
  124. if (total_used_memory > minimum_memory) {
  125. RunGarbageCollector();
  126. }
  127. sentenced_images.Tick();
  128. sentenced_framebuffers.Tick();
  129. sentenced_image_view.Tick();
  130. TickAsyncDecode();
  131. runtime.TickFrame();
  132. ++frame_tick;
  133. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  134. for (auto& buffer : async_buffers_death_ring) {
  135. runtime.FreeDeferredStagingBuffer(buffer);
  136. }
  137. async_buffers_death_ring.clear();
  138. }
  139. }
  140. template <class P>
  141. const typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) const noexcept {
  142. return slot_image_views[id];
  143. }
  144. template <class P>
  145. typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) noexcept {
  146. return slot_image_views[id];
  147. }
  148. template <class P>
  149. typename P::ImageView& TextureCache<P>::GetImageView(u32 index) noexcept {
  150. const auto image_view_id = VisitImageView(channel_state->graphics_image_table,
  151. channel_state->graphics_image_view_ids, index);
  152. return slot_image_views[image_view_id];
  153. }
  154. template <class P>
  155. void TextureCache<P>::MarkModification(ImageId id) noexcept {
  156. MarkModification(slot_images[id]);
  157. }
  158. template <class P>
  159. template <bool has_blacklists>
  160. void TextureCache<P>::FillGraphicsImageViews(std::span<ImageViewInOut> views) {
  161. FillImageViews<has_blacklists>(channel_state->graphics_image_table,
  162. channel_state->graphics_image_view_ids, views);
  163. }
  164. template <class P>
  165. void TextureCache<P>::FillComputeImageViews(std::span<ImageViewInOut> views) {
  166. FillImageViews<true>(channel_state->compute_image_table, channel_state->compute_image_view_ids,
  167. views);
  168. }
  169. template <class P>
  170. void TextureCache<P>::CheckFeedbackLoop(std::span<const ImageViewInOut> views) {
  171. if (!Settings::values.barrier_feedback_loops.GetValue()) {
  172. return;
  173. }
  174. const bool requires_barrier = [&] {
  175. for (const auto& view : views) {
  176. if (!view.id) {
  177. continue;
  178. }
  179. auto& image_view = slot_image_views[view.id];
  180. // Check color targets
  181. for (const auto& ct_view_id : render_targets.color_buffer_ids) {
  182. if (ct_view_id) {
  183. auto& ct_view = slot_image_views[ct_view_id];
  184. if (image_view.image_id == ct_view.image_id) {
  185. return true;
  186. }
  187. }
  188. }
  189. // Check zeta target
  190. if (render_targets.depth_buffer_id) {
  191. auto& zt_view = slot_image_views[render_targets.depth_buffer_id];
  192. if (image_view.image_id == zt_view.image_id) {
  193. return true;
  194. }
  195. }
  196. }
  197. return false;
  198. }();
  199. if (requires_barrier) {
  200. runtime.BarrierFeedbackLoop();
  201. }
  202. }
  203. template <class P>
  204. typename P::Sampler* TextureCache<P>::GetGraphicsSampler(u32 index) {
  205. return &slot_samplers[GetGraphicsSamplerId(index)];
  206. }
  207. template <class P>
  208. typename P::Sampler* TextureCache<P>::GetComputeSampler(u32 index) {
  209. return &slot_samplers[GetComputeSamplerId(index)];
  210. }
  211. template <class P>
  212. SamplerId TextureCache<P>::GetGraphicsSamplerId(u32 index) {
  213. if (index > channel_state->graphics_sampler_table.Limit()) {
  214. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  215. return NULL_SAMPLER_ID;
  216. }
  217. const auto [descriptor, is_new] = channel_state->graphics_sampler_table.Read(index);
  218. SamplerId& id = channel_state->graphics_sampler_ids[index];
  219. if (is_new) {
  220. id = FindSampler(descriptor);
  221. }
  222. return id;
  223. }
  224. template <class P>
  225. SamplerId TextureCache<P>::GetComputeSamplerId(u32 index) {
  226. if (index > channel_state->compute_sampler_table.Limit()) {
  227. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  228. return NULL_SAMPLER_ID;
  229. }
  230. const auto [descriptor, is_new] = channel_state->compute_sampler_table.Read(index);
  231. SamplerId& id = channel_state->compute_sampler_ids[index];
  232. if (is_new) {
  233. id = FindSampler(descriptor);
  234. }
  235. return id;
  236. }
  237. template <class P>
  238. const typename P::Sampler& TextureCache<P>::GetSampler(SamplerId id) const noexcept {
  239. return slot_samplers[id];
  240. }
  241. template <class P>
  242. typename P::Sampler& TextureCache<P>::GetSampler(SamplerId id) noexcept {
  243. return slot_samplers[id];
  244. }
  245. template <class P>
  246. void TextureCache<P>::SynchronizeGraphicsDescriptors() {
  247. using SamplerBinding = Tegra::Engines::Maxwell3D::Regs::SamplerBinding;
  248. const bool linked_tsc = maxwell3d->regs.sampler_binding == SamplerBinding::ViaHeaderBinding;
  249. const u32 tic_limit = maxwell3d->regs.tex_header.limit;
  250. const u32 tsc_limit = linked_tsc ? tic_limit : maxwell3d->regs.tex_sampler.limit;
  251. if (channel_state->graphics_sampler_table.Synchronize(maxwell3d->regs.tex_sampler.Address(),
  252. tsc_limit)) {
  253. channel_state->graphics_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  254. }
  255. if (channel_state->graphics_image_table.Synchronize(maxwell3d->regs.tex_header.Address(),
  256. tic_limit)) {
  257. channel_state->graphics_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  258. }
  259. }
  260. template <class P>
  261. void TextureCache<P>::SynchronizeComputeDescriptors() {
  262. const bool linked_tsc = kepler_compute->launch_description.linked_tsc;
  263. const u32 tic_limit = kepler_compute->regs.tic.limit;
  264. const u32 tsc_limit = linked_tsc ? tic_limit : kepler_compute->regs.tsc.limit;
  265. const GPUVAddr tsc_gpu_addr = kepler_compute->regs.tsc.Address();
  266. if (channel_state->compute_sampler_table.Synchronize(tsc_gpu_addr, tsc_limit)) {
  267. channel_state->compute_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  268. }
  269. if (channel_state->compute_image_table.Synchronize(kepler_compute->regs.tic.Address(),
  270. tic_limit)) {
  271. channel_state->compute_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  272. }
  273. }
  274. template <class P>
  275. bool TextureCache<P>::RescaleRenderTargets() {
  276. auto& flags = maxwell3d->dirty.flags;
  277. u32 scale_rating = 0;
  278. bool rescaled = false;
  279. std::array<ImageId, NUM_RT> tmp_color_images{};
  280. ImageId tmp_depth_image{};
  281. do {
  282. flags[Dirty::RenderTargets] = false;
  283. has_deleted_images = false;
  284. // Render target control is used on all render targets, so force look ups when this one is
  285. // up
  286. const bool force = flags[Dirty::RenderTargetControl];
  287. flags[Dirty::RenderTargetControl] = false;
  288. scale_rating = 0;
  289. bool any_rescaled = false;
  290. bool can_rescale = true;
  291. const auto check_rescale = [&](ImageViewId view_id, ImageId& id_save) {
  292. if (view_id != NULL_IMAGE_VIEW_ID && view_id != ImageViewId{}) {
  293. const auto& view = slot_image_views[view_id];
  294. const auto image_id = view.image_id;
  295. id_save = image_id;
  296. auto& image = slot_images[image_id];
  297. can_rescale &= ImageCanRescale(image);
  298. any_rescaled |= True(image.flags & ImageFlagBits::Rescaled) ||
  299. GetFormatType(image.info.format) != SurfaceType::ColorTexture;
  300. scale_rating = std::max<u32>(scale_rating, image.scale_tick <= frame_tick
  301. ? image.scale_rating + 1U
  302. : image.scale_rating);
  303. } else {
  304. id_save = CORRUPT_ID;
  305. }
  306. };
  307. for (size_t index = 0; index < NUM_RT; ++index) {
  308. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  309. if (flags[Dirty::ColorBuffer0 + index] || force) {
  310. flags[Dirty::ColorBuffer0 + index] = false;
  311. BindRenderTarget(&color_buffer_id, FindColorBuffer(index));
  312. }
  313. check_rescale(color_buffer_id, tmp_color_images[index]);
  314. }
  315. if (flags[Dirty::ZetaBuffer] || force) {
  316. flags[Dirty::ZetaBuffer] = false;
  317. BindRenderTarget(&render_targets.depth_buffer_id, FindDepthBuffer());
  318. }
  319. check_rescale(render_targets.depth_buffer_id, tmp_depth_image);
  320. if (can_rescale) {
  321. rescaled = any_rescaled || scale_rating >= 2;
  322. const auto scale_up = [this](ImageId image_id) {
  323. if (image_id != CORRUPT_ID) {
  324. Image& image = slot_images[image_id];
  325. ScaleUp(image);
  326. }
  327. };
  328. if (rescaled) {
  329. for (size_t index = 0; index < NUM_RT; ++index) {
  330. scale_up(tmp_color_images[index]);
  331. }
  332. scale_up(tmp_depth_image);
  333. scale_rating = 2;
  334. }
  335. } else {
  336. rescaled = false;
  337. const auto scale_down = [this](ImageId image_id) {
  338. if (image_id != CORRUPT_ID) {
  339. Image& image = slot_images[image_id];
  340. ScaleDown(image);
  341. }
  342. };
  343. for (size_t index = 0; index < NUM_RT; ++index) {
  344. scale_down(tmp_color_images[index]);
  345. }
  346. scale_down(tmp_depth_image);
  347. scale_rating = 1;
  348. }
  349. } while (has_deleted_images);
  350. const auto set_rating = [this, scale_rating](ImageId image_id) {
  351. if (image_id != CORRUPT_ID) {
  352. Image& image = slot_images[image_id];
  353. image.scale_rating = scale_rating;
  354. if (image.scale_tick <= frame_tick) {
  355. image.scale_tick = frame_tick + 1;
  356. }
  357. }
  358. };
  359. for (size_t index = 0; index < NUM_RT; ++index) {
  360. set_rating(tmp_color_images[index]);
  361. }
  362. set_rating(tmp_depth_image);
  363. return rescaled;
  364. }
  365. template <class P>
  366. void TextureCache<P>::UpdateRenderTargets(bool is_clear) {
  367. using namespace VideoCommon::Dirty;
  368. auto& flags = maxwell3d->dirty.flags;
  369. if (!flags[Dirty::RenderTargets]) {
  370. for (size_t index = 0; index < NUM_RT; ++index) {
  371. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  372. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  373. }
  374. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  375. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  376. return;
  377. }
  378. const bool rescaled = RescaleRenderTargets();
  379. if (is_rescaling != rescaled) {
  380. flags[Dirty::RescaleViewports] = true;
  381. flags[Dirty::RescaleScissors] = true;
  382. is_rescaling = rescaled;
  383. }
  384. for (size_t index = 0; index < NUM_RT; ++index) {
  385. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  386. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  387. }
  388. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  389. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  390. for (size_t index = 0; index < NUM_RT; ++index) {
  391. render_targets.draw_buffers[index] = static_cast<u8>(maxwell3d->regs.rt_control.Map(index));
  392. }
  393. u32 up_scale = 1;
  394. u32 down_shift = 0;
  395. if (is_rescaling) {
  396. up_scale = Settings::values.resolution_info.up_scale;
  397. down_shift = Settings::values.resolution_info.down_shift;
  398. }
  399. render_targets.size = Extent2D{
  400. (maxwell3d->regs.surface_clip.width * up_scale) >> down_shift,
  401. (maxwell3d->regs.surface_clip.height * up_scale) >> down_shift,
  402. };
  403. render_targets.is_rescaled = is_rescaling;
  404. flags[Dirty::DepthBiasGlobal] = true;
  405. }
  406. template <class P>
  407. typename P::Framebuffer* TextureCache<P>::GetFramebuffer() {
  408. return &slot_framebuffers[GetFramebufferId(render_targets)];
  409. }
  410. template <class P>
  411. template <bool has_blacklists>
  412. void TextureCache<P>::FillImageViews(DescriptorTable<TICEntry>& table,
  413. std::span<ImageViewId> cached_image_view_ids,
  414. std::span<ImageViewInOut> views) {
  415. bool has_blacklisted = false;
  416. do {
  417. has_deleted_images = false;
  418. if constexpr (has_blacklists) {
  419. has_blacklisted = false;
  420. }
  421. for (ImageViewInOut& view : views) {
  422. view.id = VisitImageView(table, cached_image_view_ids, view.index);
  423. if constexpr (has_blacklists) {
  424. if (view.blacklist && view.id != NULL_IMAGE_VIEW_ID) {
  425. const ImageViewBase& image_view{slot_image_views[view.id]};
  426. auto& image = slot_images[image_view.image_id];
  427. has_blacklisted |= ScaleDown(image);
  428. image.scale_rating = 0;
  429. }
  430. }
  431. }
  432. } while (has_deleted_images || (has_blacklists && has_blacklisted));
  433. }
  434. template <class P>
  435. ImageViewId TextureCache<P>::VisitImageView(DescriptorTable<TICEntry>& table,
  436. std::span<ImageViewId> cached_image_view_ids,
  437. u32 index) {
  438. if (index > table.Limit()) {
  439. LOG_DEBUG(HW_GPU, "Invalid image view index={}", index);
  440. return NULL_IMAGE_VIEW_ID;
  441. }
  442. const auto [descriptor, is_new] = table.Read(index);
  443. ImageViewId& image_view_id = cached_image_view_ids[index];
  444. if (is_new) {
  445. image_view_id = FindImageView(descriptor);
  446. }
  447. if (image_view_id != NULL_IMAGE_VIEW_ID) {
  448. PrepareImageView(image_view_id, false, false);
  449. }
  450. return image_view_id;
  451. }
  452. template <class P>
  453. FramebufferId TextureCache<P>::GetFramebufferId(const RenderTargets& key) {
  454. const auto [pair, is_new] = framebuffers.try_emplace(key);
  455. FramebufferId& framebuffer_id = pair->second;
  456. if (!is_new) {
  457. return framebuffer_id;
  458. }
  459. std::array<ImageView*, NUM_RT> color_buffers;
  460. std::ranges::transform(key.color_buffer_ids, color_buffers.begin(),
  461. [this](ImageViewId id) { return id ? &slot_image_views[id] : nullptr; });
  462. ImageView* const depth_buffer =
  463. key.depth_buffer_id ? &slot_image_views[key.depth_buffer_id] : nullptr;
  464. framebuffer_id = slot_framebuffers.insert(runtime, color_buffers, depth_buffer, key);
  465. return framebuffer_id;
  466. }
  467. template <class P>
  468. void TextureCache<P>::WriteMemory(DAddr cpu_addr, size_t size) {
  469. ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) {
  470. if (True(image.flags & ImageFlagBits::CpuModified)) {
  471. return;
  472. }
  473. image.flags |= ImageFlagBits::CpuModified;
  474. if (True(image.flags & ImageFlagBits::Tracked)) {
  475. UntrackImage(image, image_id);
  476. }
  477. });
  478. }
  479. template <class P>
  480. void TextureCache<P>::DownloadMemory(DAddr cpu_addr, size_t size) {
  481. boost::container::small_vector<ImageId, 16> images;
  482. ForEachImageInRegion(cpu_addr, size, [&images](ImageId image_id, ImageBase& image) {
  483. if (!image.IsSafeDownload()) {
  484. return;
  485. }
  486. image.flags &= ~ImageFlagBits::GpuModified;
  487. images.push_back(image_id);
  488. });
  489. if (images.empty()) {
  490. return;
  491. }
  492. std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) {
  493. return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick;
  494. });
  495. for (const ImageId image_id : images) {
  496. Image& image = slot_images[image_id];
  497. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  498. const auto copies = FullDownloadCopies(image.info);
  499. image.DownloadMemory(map, copies);
  500. runtime.Finish();
  501. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span,
  502. swizzle_data_buffer);
  503. }
  504. }
  505. template <class P>
  506. std::optional<VideoCore::RasterizerDownloadArea> TextureCache<P>::GetFlushArea(DAddr cpu_addr,
  507. u64 size) {
  508. std::optional<VideoCore::RasterizerDownloadArea> area{};
  509. ForEachImageInRegion(cpu_addr, size, [&](ImageId, ImageBase& image) {
  510. if (False(image.flags & ImageFlagBits::GpuModified)) {
  511. return;
  512. }
  513. if (!area) {
  514. area.emplace();
  515. area->start_address = cpu_addr;
  516. area->end_address = cpu_addr + size;
  517. area->preemtive = true;
  518. }
  519. area->start_address = std::min(area->start_address, image.cpu_addr);
  520. area->end_address = std::max(area->end_address, image.cpu_addr_end);
  521. for (auto image_view_id : image.image_view_ids) {
  522. auto& image_view = slot_image_views[image_view_id];
  523. image_view.flags |= ImageViewFlagBits::PreemtiveDownload;
  524. }
  525. area->preemtive &= image.info.forced_flushed;
  526. image.info.forced_flushed = true;
  527. });
  528. return area;
  529. }
  530. template <class P>
  531. void TextureCache<P>::UnmapMemory(DAddr cpu_addr, size_t size) {
  532. boost::container::small_vector<ImageId, 16> deleted_images;
  533. ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); });
  534. for (const ImageId id : deleted_images) {
  535. Image& image = slot_images[id];
  536. if (True(image.flags & ImageFlagBits::Tracked)) {
  537. UntrackImage(image, id);
  538. }
  539. UnregisterImage(id);
  540. DeleteImage(id);
  541. }
  542. }
  543. template <class P>
  544. void TextureCache<P>::UnmapGPUMemory(size_t as_id, GPUVAddr gpu_addr, size_t size) {
  545. boost::container::small_vector<ImageId, 16> deleted_images;
  546. ForEachImageInRegionGPU(as_id, gpu_addr, size,
  547. [&](ImageId id, Image&) { deleted_images.push_back(id); });
  548. for (const ImageId id : deleted_images) {
  549. Image& image = slot_images[id];
  550. if (True(image.flags & ImageFlagBits::CpuModified)) {
  551. continue;
  552. }
  553. image.flags |= ImageFlagBits::CpuModified;
  554. if (True(image.flags & ImageFlagBits::Remapped)) {
  555. continue;
  556. }
  557. image.flags |= ImageFlagBits::Remapped;
  558. if (True(image.flags & ImageFlagBits::Tracked)) {
  559. UntrackImage(image, id);
  560. }
  561. }
  562. }
  563. template <class P>
  564. bool TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  565. const Tegra::Engines::Fermi2D::Surface& src,
  566. const Tegra::Engines::Fermi2D::Config& copy) {
  567. const auto result = GetBlitImages(dst, src, copy);
  568. if (!result) {
  569. return false;
  570. }
  571. const BlitImages images = *result;
  572. const ImageId dst_id = images.dst_id;
  573. const ImageId src_id = images.src_id;
  574. PrepareImage(src_id, false, false);
  575. PrepareImage(dst_id, true, false);
  576. Image& dst_image = slot_images[dst_id];
  577. Image& src_image = slot_images[src_id];
  578. bool is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  579. bool is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  580. const bool is_resolve = src_image.info.num_samples != 1 && dst_image.info.num_samples == 1;
  581. if (is_src_rescaled != is_dst_rescaled) {
  582. if (ImageCanRescale(src_image)) {
  583. ScaleUp(src_image);
  584. is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  585. if (is_resolve) {
  586. dst_image.info.rescaleable = true;
  587. for (const auto& alias : dst_image.aliased_images) {
  588. Image& other_image = slot_images[alias.id];
  589. other_image.info.rescaleable = true;
  590. }
  591. }
  592. }
  593. if (ImageCanRescale(dst_image)) {
  594. ScaleUp(dst_image);
  595. is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  596. }
  597. }
  598. if (is_resolve && (is_src_rescaled != is_dst_rescaled)) {
  599. // A resolve requires both images to be the same dimensions. Resize down if needed.
  600. ScaleDown(src_image);
  601. ScaleDown(dst_image);
  602. is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  603. is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  604. }
  605. const auto& resolution = Settings::values.resolution_info;
  606. const auto scale_region = [&](Region2D& region) {
  607. region.start.x = resolution.ScaleUp(region.start.x);
  608. region.start.y = resolution.ScaleUp(region.start.y);
  609. region.end.x = resolution.ScaleUp(region.end.x);
  610. region.end.y = resolution.ScaleUp(region.end.y);
  611. };
  612. // TODO: Deduplicate
  613. const std::optional src_base = src_image.TryFindBase(src.Address());
  614. const SubresourceRange src_range{.base = src_base.value(), .extent = {1, 1}};
  615. const ImageViewInfo src_view_info(ImageViewType::e2D, images.src_format, src_range);
  616. const auto [src_framebuffer_id, src_view_id] = RenderTargetFromImage(src_id, src_view_info);
  617. const auto [src_samples_x, src_samples_y] = SamplesLog2(src_image.info.num_samples);
  618. Region2D src_region{
  619. Offset2D{.x = copy.src_x0 >> src_samples_x, .y = copy.src_y0 >> src_samples_y},
  620. Offset2D{.x = copy.src_x1 >> src_samples_x, .y = copy.src_y1 >> src_samples_y},
  621. };
  622. if (is_src_rescaled) {
  623. scale_region(src_region);
  624. }
  625. const std::optional dst_base = dst_image.TryFindBase(dst.Address());
  626. const SubresourceRange dst_range{.base = dst_base.value(), .extent = {1, 1}};
  627. const ImageViewInfo dst_view_info(ImageViewType::e2D, images.dst_format, dst_range);
  628. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  629. const auto [dst_samples_x, dst_samples_y] = SamplesLog2(dst_image.info.num_samples);
  630. Region2D dst_region{
  631. Offset2D{.x = copy.dst_x0 >> dst_samples_x, .y = copy.dst_y0 >> dst_samples_y},
  632. Offset2D{.x = copy.dst_x1 >> dst_samples_x, .y = copy.dst_y1 >> dst_samples_y},
  633. };
  634. if (is_dst_rescaled) {
  635. scale_region(dst_region);
  636. }
  637. // Always call this after src_framebuffer_id was queried, as the address might be invalidated.
  638. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  639. if constexpr (FRAMEBUFFER_BLITS) {
  640. // OpenGL blits from framebuffers, not images
  641. Framebuffer* const src_framebuffer = &slot_framebuffers[src_framebuffer_id];
  642. runtime.BlitFramebuffer(dst_framebuffer, src_framebuffer, dst_region, src_region,
  643. copy.filter, copy.operation);
  644. } else {
  645. // Vulkan can blit images, but it lacks format reinterpretations
  646. // Provide a framebuffer in case it's necessary
  647. ImageView& dst_view = slot_image_views[dst_view_id];
  648. ImageView& src_view = slot_image_views[src_view_id];
  649. runtime.BlitImage(dst_framebuffer, dst_view, src_view, dst_region, src_region, copy.filter,
  650. copy.operation);
  651. }
  652. return true;
  653. }
  654. template <class P>
  655. std::pair<typename P::ImageView*, bool> TextureCache<P>::TryFindFramebufferImageView(
  656. const Tegra::FramebufferConfig& config, DAddr cpu_addr) {
  657. // TODO: Properly implement this
  658. const auto it = page_table.find(cpu_addr >> YUZU_PAGEBITS);
  659. if (it == page_table.end()) {
  660. return {};
  661. }
  662. const auto& image_map_ids = it->second;
  663. boost::container::small_vector<ImageId, 4> valid_image_ids;
  664. for (const ImageMapId map_id : image_map_ids) {
  665. const ImageMapView& map = slot_map_views[map_id];
  666. const ImageBase& image = slot_images[map.image_id];
  667. if (image.cpu_addr != cpu_addr) {
  668. continue;
  669. }
  670. if (image.image_view_ids.empty()) {
  671. continue;
  672. }
  673. valid_image_ids.push_back(map.image_id);
  674. }
  675. const auto view_format = [&]() {
  676. switch (config.pixel_format) {
  677. case Service::android::PixelFormat::Rgb565:
  678. return PixelFormat::R5G6B5_UNORM;
  679. case Service::android::PixelFormat::Bgra8888:
  680. return PixelFormat::B8G8R8A8_UNORM;
  681. default:
  682. return PixelFormat::A8B8G8R8_UNORM;
  683. }
  684. }();
  685. const auto GetImageViewForFramebuffer = [&](ImageId image_id) {
  686. ImageViewInfo info{ImageViewType::e2D, view_format};
  687. if (config.blending == Tegra::BlendMode::Opaque) {
  688. info.x_source = static_cast<u8>(SwizzleSource::R);
  689. info.y_source = static_cast<u8>(SwizzleSource::G);
  690. info.z_source = static_cast<u8>(SwizzleSource::B);
  691. info.w_source = static_cast<u8>(SwizzleSource::OneFloat);
  692. }
  693. return std::make_pair(&slot_image_views[FindOrEmplaceImageView(image_id, info)],
  694. slot_images[image_id].IsRescaled());
  695. };
  696. if (valid_image_ids.size() == 1) [[likely]] {
  697. return GetImageViewForFramebuffer(valid_image_ids.front());
  698. }
  699. if (valid_image_ids.size() > 0) [[unlikely]] {
  700. auto most_recent = std::ranges::max_element(valid_image_ids, [&](auto a, auto b) {
  701. return slot_images[a].modification_tick < slot_images[b].modification_tick;
  702. });
  703. return GetImageViewForFramebuffer(*most_recent);
  704. }
  705. return {};
  706. }
  707. template <class P>
  708. bool TextureCache<P>::HasUncommittedFlushes() const noexcept {
  709. return !uncommitted_downloads.empty();
  710. }
  711. template <class P>
  712. bool TextureCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  713. return !committed_downloads.empty() && !committed_downloads.front().empty();
  714. }
  715. template <class P>
  716. void TextureCache<P>::CommitAsyncFlushes() {
  717. // This is intentionally passing the value by copy
  718. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  719. auto& download_ids = uncommitted_downloads;
  720. if (download_ids.empty()) {
  721. committed_downloads.emplace_back(std::move(uncommitted_downloads));
  722. uncommitted_downloads.clear();
  723. async_buffers.emplace_back(std::move(uncommitted_async_buffers));
  724. uncommitted_async_buffers.clear();
  725. return;
  726. }
  727. size_t total_size_bytes = 0;
  728. size_t last_async_buffer_id = uncommitted_async_buffers.size();
  729. bool any_none_dma = false;
  730. for (PendingDownload& download_info : download_ids) {
  731. if (download_info.is_swizzle) {
  732. total_size_bytes +=
  733. Common::AlignUp(slot_images[download_info.object_id].unswizzled_size_bytes, 64);
  734. any_none_dma = true;
  735. download_info.async_buffer_id = last_async_buffer_id;
  736. }
  737. }
  738. if (any_none_dma) {
  739. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true);
  740. for (const PendingDownload& download_info : download_ids) {
  741. if (download_info.is_swizzle) {
  742. Image& image = slot_images[download_info.object_id];
  743. const auto copies = FullDownloadCopies(image.info);
  744. image.DownloadMemory(download_map, copies);
  745. download_map.offset += Common::AlignUp(image.unswizzled_size_bytes, 64);
  746. }
  747. }
  748. uncommitted_async_buffers.emplace_back(download_map);
  749. }
  750. async_buffers.emplace_back(std::move(uncommitted_async_buffers));
  751. uncommitted_async_buffers.clear();
  752. }
  753. committed_downloads.emplace_back(std::move(uncommitted_downloads));
  754. uncommitted_downloads.clear();
  755. }
  756. template <class P>
  757. void TextureCache<P>::PopAsyncFlushes() {
  758. if (committed_downloads.empty()) {
  759. return;
  760. }
  761. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  762. const auto& download_ids = committed_downloads.front();
  763. if (download_ids.empty()) {
  764. committed_downloads.pop_front();
  765. async_buffers.pop_front();
  766. return;
  767. }
  768. auto download_map = std::move(async_buffers.front());
  769. for (size_t i = download_ids.size(); i > 0; i--) {
  770. auto& download_info = download_ids[i - 1];
  771. auto& download_buffer = download_map[download_info.async_buffer_id];
  772. if (download_info.is_swizzle) {
  773. const ImageBase& image = slot_images[download_info.object_id];
  774. const auto copies = FullDownloadCopies(image.info);
  775. download_buffer.offset -= Common::AlignUp(image.unswizzled_size_bytes, 64);
  776. std::span<u8> download_span =
  777. download_buffer.mapped_span.subspan(download_buffer.offset);
  778. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, download_span,
  779. swizzle_data_buffer);
  780. } else {
  781. const BufferDownload& buffer_info = slot_buffer_downloads[download_info.object_id];
  782. std::span<u8> download_span =
  783. download_buffer.mapped_span.subspan(download_buffer.offset);
  784. gpu_memory->WriteBlockUnsafe(buffer_info.address, download_span.data(),
  785. buffer_info.size);
  786. slot_buffer_downloads.erase(download_info.object_id);
  787. }
  788. }
  789. for (auto& download_buffer : download_map) {
  790. async_buffers_death_ring.emplace_back(download_buffer);
  791. }
  792. committed_downloads.pop_front();
  793. async_buffers.pop_front();
  794. } else {
  795. const auto& download_ids = committed_downloads.front();
  796. if (download_ids.empty()) {
  797. committed_downloads.pop_front();
  798. return;
  799. }
  800. size_t total_size_bytes = 0;
  801. for (const PendingDownload& download_info : download_ids) {
  802. if (download_info.is_swizzle) {
  803. total_size_bytes += slot_images[download_info.object_id].unswizzled_size_bytes;
  804. }
  805. }
  806. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes);
  807. const size_t original_offset = download_map.offset;
  808. for (const PendingDownload& download_info : download_ids) {
  809. if (!download_info.is_swizzle) {
  810. continue;
  811. }
  812. Image& image = slot_images[download_info.object_id];
  813. const auto copies = FullDownloadCopies(image.info);
  814. image.DownloadMemory(download_map, copies);
  815. download_map.offset += image.unswizzled_size_bytes;
  816. }
  817. // Wait for downloads to finish
  818. runtime.Finish();
  819. download_map.offset = original_offset;
  820. std::span<u8> download_span = download_map.mapped_span;
  821. for (const PendingDownload& download_info : download_ids) {
  822. if (!download_info.is_swizzle) {
  823. continue;
  824. }
  825. const ImageBase& image = slot_images[download_info.object_id];
  826. const auto copies = FullDownloadCopies(image.info);
  827. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, download_span,
  828. swizzle_data_buffer);
  829. download_map.offset += image.unswizzled_size_bytes;
  830. download_span = download_span.subspan(image.unswizzled_size_bytes);
  831. }
  832. committed_downloads.pop_front();
  833. }
  834. }
  835. template <class P>
  836. ImageId TextureCache<P>::DmaImageId(const Tegra::DMA::ImageOperand& operand, bool is_upload) {
  837. const ImageInfo dst_info(operand);
  838. const ImageId dst_id = FindDMAImage(dst_info, operand.address);
  839. if (!dst_id) {
  840. return NULL_IMAGE_ID;
  841. }
  842. auto& image = slot_images[dst_id];
  843. if (False(image.flags & ImageFlagBits::GpuModified)) {
  844. // No need to waste time on an image that's synced with guest
  845. return NULL_IMAGE_ID;
  846. }
  847. if (image.info.type == ImageType::e3D) {
  848. // Don't accelerate 3D images.
  849. return NULL_IMAGE_ID;
  850. }
  851. if (!is_upload && !image.info.dma_downloaded) {
  852. // Force a full sync.
  853. image.info.dma_downloaded = true;
  854. return NULL_IMAGE_ID;
  855. }
  856. const auto base = image.TryFindBase(operand.address);
  857. if (!base) {
  858. return NULL_IMAGE_ID;
  859. }
  860. return dst_id;
  861. }
  862. template <class P>
  863. bool TextureCache<P>::IsRescaling() const noexcept {
  864. return is_rescaling;
  865. }
  866. template <class P>
  867. bool TextureCache<P>::IsRescaling(const ImageViewBase& image_view) const noexcept {
  868. if (image_view.type == ImageViewType::Buffer) {
  869. return false;
  870. }
  871. const ImageBase& image = slot_images[image_view.image_id];
  872. return True(image.flags & ImageFlagBits::Rescaled);
  873. }
  874. template <class P>
  875. bool TextureCache<P>::IsRegionGpuModified(DAddr addr, size_t size) {
  876. bool is_modified = false;
  877. ForEachImageInRegion(addr, size, [&is_modified](ImageId, ImageBase& image) {
  878. if (False(image.flags & ImageFlagBits::GpuModified)) {
  879. return false;
  880. }
  881. is_modified = true;
  882. return true;
  883. });
  884. return is_modified;
  885. }
  886. template <class P>
  887. std::pair<typename TextureCache<P>::Image*, BufferImageCopy> TextureCache<P>::DmaBufferImageCopy(
  888. const Tegra::DMA::ImageCopy& copy_info, const Tegra::DMA::BufferOperand& buffer_operand,
  889. const Tegra::DMA::ImageOperand& image_operand, ImageId image_id, bool modifies_image) {
  890. const auto [level, base] = PrepareDmaImage(image_id, image_operand.address, modifies_image);
  891. auto* image = &slot_images[image_id];
  892. const u32 buffer_size = static_cast<u32>(buffer_operand.pitch * buffer_operand.height);
  893. const u32 bpp = VideoCore::Surface::BytesPerBlock(image->info.format);
  894. const auto convert = [old_bpp = image_operand.bytes_per_pixel, bpp](u32 value) {
  895. return (old_bpp * value) / bpp;
  896. };
  897. const u32 base_x = convert(image_operand.params.origin.x.Value());
  898. const u32 base_y = image_operand.params.origin.y.Value();
  899. const u32 length_x = convert(copy_info.length_x);
  900. const u32 length_y = copy_info.length_y;
  901. const BufferImageCopy copy{
  902. .buffer_offset = 0,
  903. .buffer_size = buffer_size,
  904. .buffer_row_length = convert(buffer_operand.pitch),
  905. .buffer_image_height = buffer_operand.height,
  906. .image_subresource =
  907. {
  908. .base_level = static_cast<s32>(level),
  909. .base_layer = static_cast<s32>(base),
  910. .num_layers = 1,
  911. },
  912. .image_offset =
  913. {
  914. .x = static_cast<s32>(base_x),
  915. .y = static_cast<s32>(base_y),
  916. .z = 0,
  917. },
  918. .image_extent =
  919. {
  920. .width = length_x,
  921. .height = length_y,
  922. .depth = 1,
  923. },
  924. };
  925. return {image, copy};
  926. }
  927. template <class P>
  928. void TextureCache<P>::DownloadImageIntoBuffer(typename TextureCache<P>::Image* image,
  929. typename TextureCache<P>::BufferType buffer,
  930. size_t buffer_offset,
  931. std::span<const VideoCommon::BufferImageCopy> copies,
  932. GPUVAddr address, size_t size) {
  933. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  934. const BufferDownload new_buffer_download{address, size};
  935. auto slot = slot_buffer_downloads.insert(new_buffer_download);
  936. const PendingDownload new_download{false, uncommitted_async_buffers.size(), slot};
  937. uncommitted_downloads.emplace_back(new_download);
  938. auto download_map = runtime.DownloadStagingBuffer(size, true);
  939. uncommitted_async_buffers.emplace_back(download_map);
  940. std::array buffers{
  941. buffer,
  942. download_map.buffer,
  943. };
  944. std::array<size_t, 2> buffer_offsets{
  945. buffer_offset,
  946. download_map.offset,
  947. };
  948. image->DownloadMemory(buffers, buffer_offsets, copies);
  949. } else {
  950. image->DownloadMemory(buffer, buffer_offset, copies);
  951. }
  952. }
  953. template <class P>
  954. void TextureCache<P>::RefreshContents(Image& image, ImageId image_id) {
  955. if (False(image.flags & ImageFlagBits::CpuModified)) {
  956. // Only upload modified images
  957. return;
  958. }
  959. image.flags &= ~ImageFlagBits::CpuModified;
  960. TrackImage(image, image_id);
  961. if (image.info.num_samples > 1 && !runtime.CanUploadMSAA()) {
  962. LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
  963. runtime.TransitionImageLayout(image);
  964. return;
  965. }
  966. if (True(image.flags & ImageFlagBits::AsynchronousDecode)) {
  967. QueueAsyncDecode(image, image_id);
  968. return;
  969. }
  970. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  971. UploadImageContents(image, staging);
  972. runtime.InsertUploadMemoryBarrier();
  973. }
  974. template <class P>
  975. template <typename StagingBuffer>
  976. void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging) {
  977. const std::span<u8> mapped_span = staging.mapped_span;
  978. const GPUVAddr gpu_addr = image.gpu_addr;
  979. if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
  980. gpu_memory->ReadBlock(gpu_addr, mapped_span.data(), mapped_span.size_bytes(),
  981. VideoCommon::CacheType::NoTextureCache);
  982. const auto uploads = FullUploadSwizzles(image.info);
  983. runtime.AccelerateImageUpload(image, staging, uploads);
  984. return;
  985. }
  986. Tegra::Memory::GpuGuestMemory<u8, Tegra::Memory::GuestMemoryFlags::UnsafeRead> swizzle_data(
  987. *gpu_memory, gpu_addr, image.guest_size_bytes, &swizzle_data_buffer);
  988. if (True(image.flags & ImageFlagBits::Converted)) {
  989. unswizzle_data_buffer.resize_destructive(image.unswizzled_size_bytes);
  990. auto copies =
  991. UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data, unswizzle_data_buffer);
  992. ConvertImage(unswizzle_data_buffer, image.info, mapped_span, copies);
  993. image.UploadMemory(staging, copies);
  994. } else {
  995. const auto copies =
  996. UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data, mapped_span);
  997. image.UploadMemory(staging, copies);
  998. }
  999. }
  1000. template <class P>
  1001. ImageViewId TextureCache<P>::FindImageView(const TICEntry& config) {
  1002. if (!IsValidEntry(*gpu_memory, config)) {
  1003. return NULL_IMAGE_VIEW_ID;
  1004. }
  1005. const auto [pair, is_new] = channel_state->image_views.try_emplace(config);
  1006. ImageViewId& image_view_id = pair->second;
  1007. if (is_new) {
  1008. image_view_id = CreateImageView(config);
  1009. }
  1010. return image_view_id;
  1011. }
  1012. template <class P>
  1013. ImageViewId TextureCache<P>::CreateImageView(const TICEntry& config) {
  1014. const ImageInfo info(config);
  1015. if (info.type == ImageType::Buffer) {
  1016. const ImageViewInfo view_info(config, 0);
  1017. return slot_image_views.insert(runtime, info, view_info, config.Address());
  1018. }
  1019. const u32 layer_offset = config.BaseLayer() * info.layer_stride;
  1020. const GPUVAddr image_gpu_addr = config.Address() - layer_offset;
  1021. const ImageId image_id = FindOrInsertImage(info, image_gpu_addr);
  1022. if (!image_id) {
  1023. return NULL_IMAGE_VIEW_ID;
  1024. }
  1025. ImageBase& image = slot_images[image_id];
  1026. const SubresourceBase base = image.TryFindBase(config.Address()).value();
  1027. ASSERT(base.level == 0);
  1028. const ImageViewInfo view_info(config, base.layer);
  1029. const ImageViewId image_view_id = FindOrEmplaceImageView(image_id, view_info);
  1030. ImageViewBase& image_view = slot_image_views[image_view_id];
  1031. image_view.flags |= ImageViewFlagBits::Strong;
  1032. image.flags |= ImageFlagBits::Strong;
  1033. return image_view_id;
  1034. }
  1035. template <class P>
  1036. ImageId TextureCache<P>::FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  1037. RelaxedOptions options) {
  1038. if (const ImageId image_id = FindImage(info, gpu_addr, options); image_id) {
  1039. return image_id;
  1040. }
  1041. return InsertImage(info, gpu_addr, options);
  1042. }
  1043. template <class P>
  1044. ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  1045. RelaxedOptions options) {
  1046. std::optional<DAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1047. if (!cpu_addr) {
  1048. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  1049. if (!cpu_addr) {
  1050. return ImageId{};
  1051. }
  1052. }
  1053. const bool broken_views =
  1054. runtime.HasBrokenTextureViewFormats() || True(options & RelaxedOptions::ForceBrokenViews);
  1055. const bool native_bgr = runtime.HasNativeBgr();
  1056. const bool flexible_formats = True(options & RelaxedOptions::Format);
  1057. ImageId image_id{};
  1058. boost::container::small_vector<ImageId, 8> image_ids;
  1059. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  1060. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  1061. return false;
  1062. }
  1063. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear)
  1064. [[unlikely]] {
  1065. const bool strict_size = False(options & RelaxedOptions::Size) &&
  1066. True(existing_image.flags & ImageFlagBits::Strong);
  1067. const ImageInfo& existing = existing_image.info;
  1068. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  1069. existing.pitch == info.pitch &&
  1070. IsPitchLinearSameSize(existing, info, strict_size) &&
  1071. IsViewCompatible(existing.format, info.format, broken_views, native_bgr)) {
  1072. image_id = existing_image_id;
  1073. image_ids.push_back(existing_image_id);
  1074. return !flexible_formats && existing.format == info.format;
  1075. }
  1076. } else if (IsSubresource(info, existing_image, gpu_addr, options, broken_views,
  1077. native_bgr)) {
  1078. image_id = existing_image_id;
  1079. image_ids.push_back(existing_image_id);
  1080. return !flexible_formats && existing_image.info.format == info.format;
  1081. }
  1082. return false;
  1083. };
  1084. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  1085. if (image_ids.size() <= 1) [[likely]] {
  1086. return image_id;
  1087. }
  1088. auto image_ids_compare = [this](ImageId a, ImageId b) {
  1089. auto& image_a = slot_images[a];
  1090. auto& image_b = slot_images[b];
  1091. return image_a.modification_tick < image_b.modification_tick;
  1092. };
  1093. return *std::ranges::max_element(image_ids, image_ids_compare);
  1094. }
  1095. template <class P>
  1096. bool TextureCache<P>::ImageCanRescale(ImageBase& image) {
  1097. if (!image.info.rescaleable) {
  1098. return false;
  1099. }
  1100. if (Settings::values.resolution_info.downscale && !image.info.downscaleable) {
  1101. return false;
  1102. }
  1103. if (True(image.flags & (ImageFlagBits::Rescaled | ImageFlagBits::CheckingRescalable))) {
  1104. return true;
  1105. }
  1106. if (True(image.flags & ImageFlagBits::IsRescalable)) {
  1107. return true;
  1108. }
  1109. image.flags |= ImageFlagBits::CheckingRescalable;
  1110. for (const auto& alias : image.aliased_images) {
  1111. Image& other_image = slot_images[alias.id];
  1112. if (!ImageCanRescale(other_image)) {
  1113. image.flags &= ~ImageFlagBits::CheckingRescalable;
  1114. return false;
  1115. }
  1116. }
  1117. image.flags &= ~ImageFlagBits::CheckingRescalable;
  1118. image.flags |= ImageFlagBits::IsRescalable;
  1119. return true;
  1120. }
  1121. template <class P>
  1122. void TextureCache<P>::InvalidateScale(Image& image) {
  1123. if (image.scale_tick <= frame_tick) {
  1124. image.scale_tick = frame_tick + 1;
  1125. }
  1126. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  1127. auto& dirty = maxwell3d->dirty.flags;
  1128. dirty[Dirty::RenderTargets] = true;
  1129. dirty[Dirty::ZetaBuffer] = true;
  1130. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  1131. dirty[Dirty::ColorBuffer0 + rt] = true;
  1132. }
  1133. for (const ImageViewId image_view_id : image_view_ids) {
  1134. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  1135. if (render_targets.depth_buffer_id == image_view_id) {
  1136. render_targets.depth_buffer_id = ImageViewId{};
  1137. }
  1138. }
  1139. RemoveImageViewReferences(image_view_ids);
  1140. RemoveFramebuffers(image_view_ids);
  1141. for (const ImageViewId image_view_id : image_view_ids) {
  1142. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  1143. slot_image_views.erase(image_view_id);
  1144. }
  1145. image.image_view_ids.clear();
  1146. image.image_view_infos.clear();
  1147. for (size_t c : active_channel_ids) {
  1148. auto& channel_info = channel_storage[c];
  1149. if constexpr (ENABLE_VALIDATION) {
  1150. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  1151. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  1152. }
  1153. channel_info.graphics_image_table.Invalidate();
  1154. channel_info.compute_image_table.Invalidate();
  1155. }
  1156. has_deleted_images = true;
  1157. }
  1158. template <class P>
  1159. u64 TextureCache<P>::GetScaledImageSizeBytes(const ImageBase& image) {
  1160. const u64 scale_up = static_cast<u64>(Settings::values.resolution_info.up_scale *
  1161. Settings::values.resolution_info.up_scale);
  1162. const u64 down_shift = static_cast<u64>(Settings::values.resolution_info.down_shift +
  1163. Settings::values.resolution_info.down_shift);
  1164. const u64 image_size_bytes =
  1165. static_cast<u64>(std::max(image.guest_size_bytes, image.unswizzled_size_bytes));
  1166. const u64 tentative_size = (image_size_bytes * scale_up) >> down_shift;
  1167. const u64 fitted_size = Common::AlignUp(tentative_size, 1024);
  1168. return fitted_size;
  1169. }
  1170. template <class P>
  1171. void TextureCache<P>::QueueAsyncDecode(Image& image, ImageId image_id) {
  1172. UNIMPLEMENTED_IF(False(image.flags & ImageFlagBits::Converted));
  1173. LOG_INFO(HW_GPU, "Queuing async texture decode");
  1174. image.flags |= ImageFlagBits::IsDecoding;
  1175. auto decode = std::make_unique<AsyncDecodeContext>();
  1176. auto* decode_ptr = decode.get();
  1177. decode->image_id = image_id;
  1178. async_decodes.push_back(std::move(decode));
  1179. static Common::ScratchBuffer<u8> local_unswizzle_data_buffer;
  1180. local_unswizzle_data_buffer.resize_destructive(image.unswizzled_size_bytes);
  1181. Tegra::Memory::GpuGuestMemory<u8, Tegra::Memory::GuestMemoryFlags::UnsafeRead> swizzle_data(
  1182. *gpu_memory, image.gpu_addr, image.guest_size_bytes, &swizzle_data_buffer);
  1183. auto copies = UnswizzleImage(*gpu_memory, image.gpu_addr, image.info, swizzle_data,
  1184. local_unswizzle_data_buffer);
  1185. const size_t out_size = MapSizeBytes(image);
  1186. auto func = [out_size, copies, info = image.info,
  1187. input = std::move(local_unswizzle_data_buffer),
  1188. async_decode = decode_ptr]() mutable {
  1189. async_decode->decoded_data.resize_destructive(out_size);
  1190. std::span copies_span{copies.data(), copies.size()};
  1191. ConvertImage(input, info, async_decode->decoded_data, copies_span);
  1192. // TODO: Do we need this lock?
  1193. std::unique_lock lock{async_decode->mutex};
  1194. async_decode->copies = std::move(copies);
  1195. async_decode->complete = true;
  1196. };
  1197. texture_decode_worker.QueueWork(std::move(func));
  1198. }
  1199. template <class P>
  1200. void TextureCache<P>::TickAsyncDecode() {
  1201. bool has_uploads{};
  1202. auto i = async_decodes.begin();
  1203. while (i != async_decodes.end()) {
  1204. auto* async_decode = i->get();
  1205. std::unique_lock lock{async_decode->mutex};
  1206. if (!async_decode->complete) {
  1207. ++i;
  1208. continue;
  1209. }
  1210. Image& image = slot_images[async_decode->image_id];
  1211. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  1212. std::memcpy(staging.mapped_span.data(), async_decode->decoded_data.data(),
  1213. async_decode->decoded_data.size());
  1214. image.UploadMemory(staging, async_decode->copies);
  1215. image.flags &= ~ImageFlagBits::IsDecoding;
  1216. has_uploads = true;
  1217. i = async_decodes.erase(i);
  1218. }
  1219. if (has_uploads) {
  1220. runtime.InsertUploadMemoryBarrier();
  1221. }
  1222. }
  1223. template <class P>
  1224. bool TextureCache<P>::ScaleUp(Image& image) {
  1225. const bool has_copy = image.HasScaled();
  1226. const bool rescaled = image.ScaleUp();
  1227. if (!rescaled) {
  1228. return false;
  1229. }
  1230. if (!has_copy) {
  1231. total_used_memory += GetScaledImageSizeBytes(image);
  1232. }
  1233. InvalidateScale(image);
  1234. return true;
  1235. }
  1236. template <class P>
  1237. bool TextureCache<P>::ScaleDown(Image& image) {
  1238. const bool rescaled = image.ScaleDown();
  1239. if (!rescaled) {
  1240. return false;
  1241. }
  1242. InvalidateScale(image);
  1243. return true;
  1244. }
  1245. template <class P>
  1246. ImageId TextureCache<P>::InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  1247. RelaxedOptions options) {
  1248. std::optional<DAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1249. if (!cpu_addr) {
  1250. const auto size = CalculateGuestSizeInBytes(info);
  1251. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, size);
  1252. if (!cpu_addr) {
  1253. const DAddr fake_addr = ~(1ULL << 40ULL) + virtual_invalid_space;
  1254. virtual_invalid_space += Common::AlignUp(size, 32);
  1255. cpu_addr = std::optional<DAddr>(fake_addr);
  1256. }
  1257. }
  1258. ASSERT_MSG(cpu_addr, "Tried to insert an image to an invalid gpu_addr=0x{:x}", gpu_addr);
  1259. const ImageId image_id = JoinImages(info, gpu_addr, *cpu_addr);
  1260. const Image& image = slot_images[image_id];
  1261. // Using "image.gpu_addr" instead of "gpu_addr" is important because it might be different
  1262. const auto [it, is_new] = image_allocs_table.try_emplace(image.gpu_addr);
  1263. if (is_new) {
  1264. it->second = slot_image_allocs.insert();
  1265. }
  1266. slot_image_allocs[it->second].images.push_back(image_id);
  1267. return image_id;
  1268. }
  1269. template <class P>
  1270. ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, DAddr cpu_addr) {
  1271. ImageInfo new_info = info;
  1272. const size_t size_bytes = CalculateGuestSizeInBytes(new_info);
  1273. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  1274. const bool native_bgr = runtime.HasNativeBgr();
  1275. join_overlap_ids.clear();
  1276. join_overlaps_found.clear();
  1277. join_left_aliased_ids.clear();
  1278. join_right_aliased_ids.clear();
  1279. join_ignore_textures.clear();
  1280. join_bad_overlap_ids.clear();
  1281. join_copies_to_do.clear();
  1282. join_alias_indices.clear();
  1283. const bool this_is_linear = info.type == ImageType::Linear;
  1284. const auto region_check = [&](ImageId overlap_id, ImageBase& overlap) {
  1285. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1286. join_ignore_textures.insert(overlap_id);
  1287. return;
  1288. }
  1289. const bool overlap_is_linear = overlap.info.type == ImageType::Linear;
  1290. if (this_is_linear != overlap_is_linear) {
  1291. return;
  1292. }
  1293. if (this_is_linear && overlap_is_linear) {
  1294. if (info.pitch == overlap.info.pitch && gpu_addr == overlap.gpu_addr) {
  1295. // Alias linear images with the same pitch
  1296. join_left_aliased_ids.push_back(overlap_id);
  1297. }
  1298. return;
  1299. }
  1300. join_overlaps_found.insert(overlap_id);
  1301. static constexpr bool strict_size = true;
  1302. const std::optional<OverlapResult> solution = ResolveOverlap(
  1303. new_info, gpu_addr, cpu_addr, overlap, strict_size, broken_views, native_bgr);
  1304. if (solution) {
  1305. gpu_addr = solution->gpu_addr;
  1306. cpu_addr = solution->cpu_addr;
  1307. new_info.resources = solution->resources;
  1308. join_overlap_ids.push_back(overlap_id);
  1309. join_copies_to_do.emplace_back(JoinCopy{false, overlap_id});
  1310. return;
  1311. }
  1312. static constexpr auto options = RelaxedOptions::Size | RelaxedOptions::Format;
  1313. const ImageBase new_image_base(new_info, gpu_addr, cpu_addr);
  1314. if (IsSubresource(new_info, overlap, gpu_addr, options, broken_views, native_bgr)) {
  1315. join_left_aliased_ids.push_back(overlap_id);
  1316. overlap.flags |= ImageFlagBits::Alias;
  1317. join_copies_to_do.emplace_back(JoinCopy{true, overlap_id});
  1318. } else if (IsSubresource(overlap.info, new_image_base, overlap.gpu_addr, options,
  1319. broken_views, native_bgr)) {
  1320. join_right_aliased_ids.push_back(overlap_id);
  1321. overlap.flags |= ImageFlagBits::Alias;
  1322. join_copies_to_do.emplace_back(JoinCopy{true, overlap_id});
  1323. } else {
  1324. join_bad_overlap_ids.push_back(overlap_id);
  1325. }
  1326. };
  1327. ForEachImageInRegion(cpu_addr, size_bytes, region_check);
  1328. const auto region_check_gpu = [&](ImageId overlap_id, ImageBase& overlap) {
  1329. if (!join_overlaps_found.contains(overlap_id)) {
  1330. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1331. join_ignore_textures.insert(overlap_id);
  1332. }
  1333. if (overlap.gpu_addr == gpu_addr && overlap.guest_size_bytes == size_bytes) {
  1334. join_ignore_textures.insert(overlap_id);
  1335. }
  1336. }
  1337. };
  1338. ForEachSparseImageInRegion(channel_state->gpu_memory.GetID(), gpu_addr, size_bytes,
  1339. region_check_gpu);
  1340. bool can_rescale = info.rescaleable;
  1341. bool any_rescaled = false;
  1342. for (const auto& copy : join_copies_to_do) {
  1343. if (!can_rescale) {
  1344. break;
  1345. }
  1346. Image& sibling = slot_images[copy.id];
  1347. can_rescale &= ImageCanRescale(sibling);
  1348. any_rescaled |= True(sibling.flags & ImageFlagBits::Rescaled);
  1349. }
  1350. can_rescale &= any_rescaled;
  1351. if (can_rescale) {
  1352. for (const auto& copy : join_copies_to_do) {
  1353. Image& sibling = slot_images[copy.id];
  1354. ScaleUp(sibling);
  1355. }
  1356. } else {
  1357. for (const auto& copy : join_copies_to_do) {
  1358. Image& sibling = slot_images[copy.id];
  1359. ScaleDown(sibling);
  1360. }
  1361. }
  1362. const ImageId new_image_id = slot_images.insert(runtime, new_info, gpu_addr, cpu_addr);
  1363. Image& new_image = slot_images[new_image_id];
  1364. if (!gpu_memory->IsContinuousRange(new_image.gpu_addr, new_image.guest_size_bytes)) {
  1365. new_image.flags |= ImageFlagBits::Sparse;
  1366. }
  1367. for (const ImageId overlap_id : join_ignore_textures) {
  1368. Image& overlap = slot_images[overlap_id];
  1369. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1370. UNIMPLEMENTED();
  1371. }
  1372. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1373. UntrackImage(overlap, overlap_id);
  1374. }
  1375. UnregisterImage(overlap_id);
  1376. DeleteImage(overlap_id);
  1377. }
  1378. // TODO: Only upload what we need
  1379. RefreshContents(new_image, new_image_id);
  1380. if (can_rescale) {
  1381. ScaleUp(new_image);
  1382. } else {
  1383. ScaleDown(new_image);
  1384. }
  1385. std::ranges::sort(join_copies_to_do, [this](const JoinCopy& lhs, const JoinCopy& rhs) {
  1386. const ImageBase& lhs_image = slot_images[lhs.id];
  1387. const ImageBase& rhs_image = slot_images[rhs.id];
  1388. return lhs_image.modification_tick < rhs_image.modification_tick;
  1389. });
  1390. ImageBase& new_image_base = new_image;
  1391. for (const ImageId aliased_id : join_right_aliased_ids) {
  1392. ImageBase& aliased = slot_images[aliased_id];
  1393. size_t alias_index = new_image_base.aliased_images.size();
  1394. if (!AddImageAlias(new_image_base, aliased, new_image_id, aliased_id)) {
  1395. continue;
  1396. }
  1397. join_alias_indices.emplace(aliased_id, alias_index);
  1398. new_image.flags |= ImageFlagBits::Alias;
  1399. }
  1400. for (const ImageId aliased_id : join_left_aliased_ids) {
  1401. ImageBase& aliased = slot_images[aliased_id];
  1402. size_t alias_index = new_image_base.aliased_images.size();
  1403. if (!AddImageAlias(aliased, new_image_base, aliased_id, new_image_id)) {
  1404. continue;
  1405. }
  1406. join_alias_indices.emplace(aliased_id, alias_index);
  1407. new_image.flags |= ImageFlagBits::Alias;
  1408. }
  1409. for (const ImageId aliased_id : join_bad_overlap_ids) {
  1410. ImageBase& aliased = slot_images[aliased_id];
  1411. aliased.overlapping_images.push_back(new_image_id);
  1412. new_image.overlapping_images.push_back(aliased_id);
  1413. if (aliased.info.resources.levels == 1 && aliased.info.block.depth == 0 &&
  1414. aliased.overlapping_images.size() > 1) {
  1415. aliased.flags |= ImageFlagBits::BadOverlap;
  1416. }
  1417. if (new_image.info.resources.levels == 1 && new_image.info.block.depth == 0 &&
  1418. new_image.overlapping_images.size() > 1) {
  1419. new_image.flags |= ImageFlagBits::BadOverlap;
  1420. }
  1421. }
  1422. for (const auto& copy_object : join_copies_to_do) {
  1423. Image& overlap = slot_images[copy_object.id];
  1424. if (copy_object.is_alias) {
  1425. if (!overlap.IsSafeDownload()) {
  1426. continue;
  1427. }
  1428. const auto alias_pointer = join_alias_indices.find(copy_object.id);
  1429. if (alias_pointer == join_alias_indices.end()) {
  1430. continue;
  1431. }
  1432. const AliasedImage& aliased = new_image.aliased_images[alias_pointer->second];
  1433. CopyImage(new_image_id, aliased.id, aliased.copies);
  1434. new_image.modification_tick = overlap.modification_tick;
  1435. continue;
  1436. }
  1437. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1438. new_image.flags |= ImageFlagBits::GpuModified;
  1439. const auto& resolution = Settings::values.resolution_info;
  1440. const SubresourceBase base = new_image.TryFindBase(overlap.gpu_addr).value();
  1441. const u32 up_scale = can_rescale ? resolution.up_scale : 1;
  1442. const u32 down_shift = can_rescale ? resolution.down_shift : 0;
  1443. auto copies = MakeShrinkImageCopies(new_info, overlap.info, base, up_scale, down_shift);
  1444. if (overlap.info.num_samples != new_image.info.num_samples) {
  1445. runtime.CopyImageMSAA(new_image, overlap, std::move(copies));
  1446. } else {
  1447. runtime.CopyImage(new_image, overlap, std::move(copies));
  1448. }
  1449. new_image.modification_tick = overlap.modification_tick;
  1450. }
  1451. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1452. UntrackImage(overlap, copy_object.id);
  1453. }
  1454. UnregisterImage(copy_object.id);
  1455. DeleteImage(copy_object.id);
  1456. }
  1457. RegisterImage(new_image_id);
  1458. return new_image_id;
  1459. }
  1460. template <class P>
  1461. std::optional<typename TextureCache<P>::BlitImages> TextureCache<P>::GetBlitImages(
  1462. const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src,
  1463. const Tegra::Engines::Fermi2D::Config& copy) {
  1464. static constexpr auto FIND_OPTIONS = RelaxedOptions::Samples;
  1465. const GPUVAddr dst_addr = dst.Address();
  1466. const GPUVAddr src_addr = src.Address();
  1467. ImageInfo dst_info(dst);
  1468. ImageInfo src_info(src);
  1469. const bool can_be_depth_blit =
  1470. dst_info.format == src_info.format && copy.filter == Tegra::Engines::Fermi2D::Filter::Point;
  1471. ImageId dst_id;
  1472. ImageId src_id;
  1473. RelaxedOptions try_options = FIND_OPTIONS;
  1474. if (can_be_depth_blit) {
  1475. try_options |= RelaxedOptions::Format;
  1476. }
  1477. do {
  1478. has_deleted_images = false;
  1479. src_id = FindImage(src_info, src_addr, try_options);
  1480. dst_id = FindImage(dst_info, dst_addr, try_options);
  1481. if (!copy.must_accelerate) {
  1482. do {
  1483. if (!src_id && !dst_id) {
  1484. return std::nullopt;
  1485. }
  1486. if (src_id && True(slot_images[src_id].flags & ImageFlagBits::GpuModified)) {
  1487. break;
  1488. }
  1489. if (dst_id && True(slot_images[dst_id].flags & ImageFlagBits::GpuModified)) {
  1490. break;
  1491. }
  1492. return std::nullopt;
  1493. } while (false);
  1494. }
  1495. const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
  1496. if (src_image && src_image->info.num_samples > 1) {
  1497. RelaxedOptions find_options{FIND_OPTIONS | RelaxedOptions::ForceBrokenViews};
  1498. src_id = FindOrInsertImage(src_info, src_addr, find_options);
  1499. dst_id = FindOrInsertImage(dst_info, dst_addr, find_options);
  1500. if (has_deleted_images) {
  1501. continue;
  1502. }
  1503. break;
  1504. }
  1505. if (can_be_depth_blit) {
  1506. const ImageBase* const dst_image = dst_id ? &slot_images[dst_id] : nullptr;
  1507. DeduceBlitImages(dst_info, src_info, dst_image, src_image);
  1508. if (GetFormatType(dst_info.format) != GetFormatType(src_info.format)) {
  1509. continue;
  1510. }
  1511. }
  1512. if (!src_id) {
  1513. src_id = InsertImage(src_info, src_addr, RelaxedOptions{});
  1514. }
  1515. if (!dst_id) {
  1516. dst_id = InsertImage(dst_info, dst_addr, RelaxedOptions{});
  1517. }
  1518. } while (has_deleted_images);
  1519. const ImageBase& src_image = slot_images[src_id];
  1520. const ImageBase& dst_image = slot_images[dst_id];
  1521. const bool native_bgr = runtime.HasNativeBgr();
  1522. if (GetFormatType(dst_info.format) != GetFormatType(dst_image.info.format) ||
  1523. GetFormatType(src_info.format) != GetFormatType(src_image.info.format) ||
  1524. !VideoCore::Surface::IsViewCompatible(dst_info.format, dst_image.info.format, false,
  1525. native_bgr) ||
  1526. !VideoCore::Surface::IsViewCompatible(src_info.format, src_image.info.format, false,
  1527. native_bgr)) {
  1528. // Make sure the images match the expected format.
  1529. do {
  1530. has_deleted_images = false;
  1531. src_id = FindOrInsertImage(src_info, src_addr, RelaxedOptions{});
  1532. dst_id = FindOrInsertImage(dst_info, dst_addr, RelaxedOptions{});
  1533. } while (has_deleted_images);
  1534. }
  1535. return {BlitImages{
  1536. .dst_id = dst_id,
  1537. .src_id = src_id,
  1538. .dst_format = dst_info.format,
  1539. .src_format = src_info.format,
  1540. }};
  1541. }
  1542. template <class P>
  1543. ImageId TextureCache<P>::FindDMAImage(const ImageInfo& info, GPUVAddr gpu_addr) {
  1544. std::optional<DAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1545. if (!cpu_addr) {
  1546. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  1547. if (!cpu_addr) {
  1548. return ImageId{};
  1549. }
  1550. }
  1551. ImageId image_id{};
  1552. boost::container::small_vector<ImageId, 8> image_ids;
  1553. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  1554. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  1555. return false;
  1556. }
  1557. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear)
  1558. [[unlikely]] {
  1559. const bool strict_size = True(existing_image.flags & ImageFlagBits::Strong);
  1560. const ImageInfo& existing = existing_image.info;
  1561. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  1562. existing.pitch == info.pitch &&
  1563. IsPitchLinearSameSize(existing, info, strict_size) &&
  1564. IsViewCompatible(existing.format, info.format, false, true)) {
  1565. image_id = existing_image_id;
  1566. image_ids.push_back(existing_image_id);
  1567. return true;
  1568. }
  1569. } else if (IsSubCopy(info, existing_image, gpu_addr)) {
  1570. image_id = existing_image_id;
  1571. image_ids.push_back(existing_image_id);
  1572. return true;
  1573. }
  1574. return false;
  1575. };
  1576. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  1577. if (image_ids.size() <= 1) [[likely]] {
  1578. return image_id;
  1579. }
  1580. auto image_ids_compare = [this](ImageId a, ImageId b) {
  1581. auto& image_a = slot_images[a];
  1582. auto& image_b = slot_images[b];
  1583. return image_a.modification_tick < image_b.modification_tick;
  1584. };
  1585. return *std::ranges::max_element(image_ids, image_ids_compare);
  1586. }
  1587. template <class P>
  1588. std::pair<u32, u32> TextureCache<P>::PrepareDmaImage(ImageId dst_id, GPUVAddr base_addr,
  1589. bool mark_as_modified) {
  1590. const auto& image = slot_images[dst_id];
  1591. const auto base = image.TryFindBase(base_addr);
  1592. PrepareImage(dst_id, mark_as_modified, false);
  1593. const auto& new_image = slot_images[dst_id];
  1594. lru_cache.Touch(new_image.lru_index, frame_tick);
  1595. return std::make_pair(base->level, base->layer);
  1596. }
  1597. template <class P>
  1598. SamplerId TextureCache<P>::FindSampler(const TSCEntry& config) {
  1599. if (std::ranges::all_of(config.raw, [](u64 value) { return value == 0; })) {
  1600. return NULL_SAMPLER_ID;
  1601. }
  1602. const auto [pair, is_new] = channel_state->samplers.try_emplace(config);
  1603. if (is_new) {
  1604. pair->second = slot_samplers.insert(runtime, config);
  1605. }
  1606. return pair->second;
  1607. }
  1608. template <class P>
  1609. ImageViewId TextureCache<P>::FindColorBuffer(size_t index) {
  1610. const auto& regs = maxwell3d->regs;
  1611. if (index >= regs.rt_control.count) {
  1612. return ImageViewId{};
  1613. }
  1614. const auto& rt = regs.rt[index];
  1615. const GPUVAddr gpu_addr = rt.Address();
  1616. if (gpu_addr == 0) {
  1617. return ImageViewId{};
  1618. }
  1619. if (rt.format == Tegra::RenderTargetFormat::NONE) {
  1620. return ImageViewId{};
  1621. }
  1622. const ImageInfo info(regs.rt[index], regs.anti_alias_samples_mode);
  1623. return FindRenderTargetView(info, gpu_addr);
  1624. }
  1625. template <class P>
  1626. ImageViewId TextureCache<P>::FindDepthBuffer() {
  1627. const auto& regs = maxwell3d->regs;
  1628. if (!regs.zeta_enable) {
  1629. return ImageViewId{};
  1630. }
  1631. const GPUVAddr gpu_addr = regs.zeta.Address();
  1632. if (gpu_addr == 0) {
  1633. return ImageViewId{};
  1634. }
  1635. const ImageInfo info(regs.zeta, regs.zeta_size, regs.anti_alias_samples_mode);
  1636. return FindRenderTargetView(info, gpu_addr);
  1637. }
  1638. template <class P>
  1639. ImageViewId TextureCache<P>::FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr) {
  1640. ImageId image_id{};
  1641. bool delete_state = has_deleted_images;
  1642. do {
  1643. has_deleted_images = false;
  1644. image_id = FindOrInsertImage(info, gpu_addr);
  1645. delete_state |= has_deleted_images;
  1646. } while (has_deleted_images);
  1647. has_deleted_images = delete_state;
  1648. if (!image_id) {
  1649. return NULL_IMAGE_VIEW_ID;
  1650. }
  1651. Image& image = slot_images[image_id];
  1652. const ImageViewType view_type = RenderTargetImageViewType(info);
  1653. SubresourceBase base;
  1654. if (image.info.type == ImageType::Linear) {
  1655. base = SubresourceBase{.level = 0, .layer = 0};
  1656. } else {
  1657. base = image.TryFindBase(gpu_addr).value();
  1658. }
  1659. const s32 layers = image.info.type == ImageType::e3D ? info.size.depth : info.resources.layers;
  1660. const SubresourceRange range{
  1661. .base = base,
  1662. .extent = {.levels = 1, .layers = layers},
  1663. };
  1664. return FindOrEmplaceImageView(image_id, ImageViewInfo(view_type, info.format, range));
  1665. }
  1666. template <class P>
  1667. template <typename Func>
  1668. void TextureCache<P>::ForEachImageInRegion(DAddr cpu_addr, size_t size, Func&& func) {
  1669. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1670. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1671. boost::container::small_vector<ImageId, 32> images;
  1672. boost::container::small_vector<ImageMapId, 32> maps;
  1673. ForEachCPUPage(cpu_addr, size, [this, &images, &maps, cpu_addr, size, func](u64 page) {
  1674. const auto it = page_table.find(page);
  1675. if (it == page_table.end()) {
  1676. if constexpr (BOOL_BREAK) {
  1677. return false;
  1678. } else {
  1679. return;
  1680. }
  1681. }
  1682. for (const ImageMapId map_id : it->second) {
  1683. ImageMapView& map = slot_map_views[map_id];
  1684. if (map.picked) {
  1685. continue;
  1686. }
  1687. if (!map.Overlaps(cpu_addr, size)) {
  1688. continue;
  1689. }
  1690. map.picked = true;
  1691. maps.push_back(map_id);
  1692. Image& image = slot_images[map.image_id];
  1693. if (True(image.flags & ImageFlagBits::Picked)) {
  1694. continue;
  1695. }
  1696. image.flags |= ImageFlagBits::Picked;
  1697. images.push_back(map.image_id);
  1698. if constexpr (BOOL_BREAK) {
  1699. if (func(map.image_id, image)) {
  1700. return true;
  1701. }
  1702. } else {
  1703. func(map.image_id, image);
  1704. }
  1705. }
  1706. if constexpr (BOOL_BREAK) {
  1707. return false;
  1708. }
  1709. });
  1710. for (const ImageId image_id : images) {
  1711. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1712. }
  1713. for (const ImageMapId map_id : maps) {
  1714. slot_map_views[map_id].picked = false;
  1715. }
  1716. }
  1717. template <class P>
  1718. template <typename Func>
  1719. void TextureCache<P>::ForEachImageInRegionGPU(size_t as_id, GPUVAddr gpu_addr, size_t size,
  1720. Func&& func) {
  1721. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1722. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1723. boost::container::small_vector<ImageId, 8> images;
  1724. auto storage_id = getStorageID(as_id);
  1725. if (!storage_id) {
  1726. return;
  1727. }
  1728. auto& gpu_page_table = gpu_page_table_storage[*storage_id * 2];
  1729. ForEachGPUPage(gpu_addr, size,
  1730. [this, &gpu_page_table, &images, gpu_addr, size, func](u64 page) {
  1731. const auto it = gpu_page_table.find(page);
  1732. if (it == gpu_page_table.end()) {
  1733. if constexpr (BOOL_BREAK) {
  1734. return false;
  1735. } else {
  1736. return;
  1737. }
  1738. }
  1739. for (const ImageId image_id : it->second) {
  1740. Image& image = slot_images[image_id];
  1741. if (True(image.flags & ImageFlagBits::Picked)) {
  1742. continue;
  1743. }
  1744. if (!image.OverlapsGPU(gpu_addr, size)) {
  1745. continue;
  1746. }
  1747. image.flags |= ImageFlagBits::Picked;
  1748. images.push_back(image_id);
  1749. if constexpr (BOOL_BREAK) {
  1750. if (func(image_id, image)) {
  1751. return true;
  1752. }
  1753. } else {
  1754. func(image_id, image);
  1755. }
  1756. }
  1757. if constexpr (BOOL_BREAK) {
  1758. return false;
  1759. }
  1760. });
  1761. for (const ImageId image_id : images) {
  1762. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1763. }
  1764. }
  1765. template <class P>
  1766. template <typename Func>
  1767. void TextureCache<P>::ForEachSparseImageInRegion(size_t as_id, GPUVAddr gpu_addr, size_t size,
  1768. Func&& func) {
  1769. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1770. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1771. boost::container::small_vector<ImageId, 8> images;
  1772. auto storage_id = getStorageID(as_id);
  1773. if (!storage_id) {
  1774. return;
  1775. }
  1776. auto& sparse_page_table = gpu_page_table_storage[*storage_id * 2 + 1];
  1777. ForEachGPUPage(gpu_addr, size,
  1778. [this, &sparse_page_table, &images, gpu_addr, size, func](u64 page) {
  1779. const auto it = sparse_page_table.find(page);
  1780. if (it == sparse_page_table.end()) {
  1781. if constexpr (BOOL_BREAK) {
  1782. return false;
  1783. } else {
  1784. return;
  1785. }
  1786. }
  1787. for (const ImageId image_id : it->second) {
  1788. Image& image = slot_images[image_id];
  1789. if (True(image.flags & ImageFlagBits::Picked)) {
  1790. continue;
  1791. }
  1792. if (!image.OverlapsGPU(gpu_addr, size)) {
  1793. continue;
  1794. }
  1795. image.flags |= ImageFlagBits::Picked;
  1796. images.push_back(image_id);
  1797. if constexpr (BOOL_BREAK) {
  1798. if (func(image_id, image)) {
  1799. return true;
  1800. }
  1801. } else {
  1802. func(image_id, image);
  1803. }
  1804. }
  1805. if constexpr (BOOL_BREAK) {
  1806. return false;
  1807. }
  1808. });
  1809. for (const ImageId image_id : images) {
  1810. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1811. }
  1812. }
  1813. template <class P>
  1814. template <typename Func>
  1815. void TextureCache<P>::ForEachSparseSegment(ImageBase& image, Func&& func) {
  1816. using FuncReturn = typename std::invoke_result<Func, GPUVAddr, DAddr, size_t>::type;
  1817. static constexpr bool RETURNS_BOOL = std::is_same_v<FuncReturn, bool>;
  1818. const auto segments = gpu_memory->GetSubmappedRange(image.gpu_addr, image.guest_size_bytes);
  1819. for (const auto& [gpu_addr, size] : segments) {
  1820. std::optional<DAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1821. ASSERT(cpu_addr);
  1822. if constexpr (RETURNS_BOOL) {
  1823. if (func(gpu_addr, *cpu_addr, size)) {
  1824. break;
  1825. }
  1826. } else {
  1827. func(gpu_addr, *cpu_addr, size);
  1828. }
  1829. }
  1830. }
  1831. template <class P>
  1832. ImageViewId TextureCache<P>::FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info) {
  1833. Image& image = slot_images[image_id];
  1834. if (const ImageViewId image_view_id = image.FindView(info); image_view_id) {
  1835. return image_view_id;
  1836. }
  1837. const ImageViewId image_view_id =
  1838. slot_image_views.insert(runtime, info, image_id, image, slot_images);
  1839. image.InsertView(info, image_view_id);
  1840. return image_view_id;
  1841. }
  1842. template <class P>
  1843. void TextureCache<P>::RegisterImage(ImageId image_id) {
  1844. ImageBase& image = slot_images[image_id];
  1845. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered),
  1846. "Trying to register an already registered image");
  1847. image.flags |= ImageFlagBits::Registered;
  1848. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1849. if ((IsPixelFormatASTC(image.info.format) &&
  1850. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1851. True(image.flags & ImageFlagBits::Converted)) {
  1852. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1853. }
  1854. total_used_memory += Common::AlignUp(tentative_size, 1024);
  1855. image.lru_index = lru_cache.Insert(image_id, frame_tick);
  1856. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, image_id](u64 page) {
  1857. (*channel_state->gpu_page_table)[page].push_back(image_id);
  1858. });
  1859. if (False(image.flags & ImageFlagBits::Sparse)) {
  1860. auto map_id =
  1861. slot_map_views.insert(image.gpu_addr, image.cpu_addr, image.guest_size_bytes, image_id);
  1862. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes,
  1863. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1864. image.map_view_id = map_id;
  1865. return;
  1866. }
  1867. boost::container::small_vector<ImageViewId, 16> sparse_maps;
  1868. ForEachSparseSegment(
  1869. image, [this, image_id, &sparse_maps](GPUVAddr gpu_addr, DAddr cpu_addr, size_t size) {
  1870. auto map_id = slot_map_views.insert(gpu_addr, cpu_addr, size, image_id);
  1871. ForEachCPUPage(cpu_addr, size,
  1872. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1873. sparse_maps.push_back(map_id);
  1874. });
  1875. sparse_views.emplace(image_id, std::move(sparse_maps));
  1876. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, image_id](u64 page) {
  1877. (*channel_state->sparse_page_table)[page].push_back(image_id);
  1878. });
  1879. }
  1880. template <class P>
  1881. void TextureCache<P>::UnregisterImage(ImageId image_id) {
  1882. Image& image = slot_images[image_id];
  1883. ASSERT_MSG(True(image.flags & ImageFlagBits::Registered),
  1884. "Trying to unregister an already registered image");
  1885. image.flags &= ~ImageFlagBits::Registered;
  1886. image.flags &= ~ImageFlagBits::BadOverlap;
  1887. lru_cache.Free(image.lru_index);
  1888. const auto& clear_page_table =
  1889. [image_id](u64 page,
  1890. std::unordered_map<u64, std::vector<ImageId>, Common::IdentityHash<u64>>&
  1891. selected_page_table) {
  1892. const auto page_it = selected_page_table.find(page);
  1893. if (page_it == selected_page_table.end()) {
  1894. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1895. return;
  1896. }
  1897. std::vector<ImageId>& image_ids = page_it->second;
  1898. const auto vector_it = std::ranges::find(image_ids, image_id);
  1899. if (vector_it == image_ids.end()) {
  1900. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1901. page << YUZU_PAGEBITS);
  1902. return;
  1903. }
  1904. image_ids.erase(vector_it);
  1905. };
  1906. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1907. clear_page_table(page, (*channel_state->gpu_page_table));
  1908. });
  1909. if (False(image.flags & ImageFlagBits::Sparse)) {
  1910. const auto map_id = image.map_view_id;
  1911. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes, [this, map_id](u64 page) {
  1912. const auto page_it = page_table.find(page);
  1913. if (page_it == page_table.end()) {
  1914. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1915. return;
  1916. }
  1917. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1918. const auto vector_it = std::ranges::find(image_map_ids, map_id);
  1919. if (vector_it == image_map_ids.end()) {
  1920. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1921. page << YUZU_PAGEBITS);
  1922. return;
  1923. }
  1924. image_map_ids.erase(vector_it);
  1925. });
  1926. slot_map_views.erase(map_id);
  1927. return;
  1928. }
  1929. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1930. clear_page_table(page, (*channel_state->sparse_page_table));
  1931. });
  1932. auto it = sparse_views.find(image_id);
  1933. ASSERT(it != sparse_views.end());
  1934. auto& sparse_maps = it->second;
  1935. for (auto& map_view_id : sparse_maps) {
  1936. const auto& map_range = slot_map_views[map_view_id];
  1937. const DAddr cpu_addr = map_range.cpu_addr;
  1938. const std::size_t size = map_range.size;
  1939. ForEachCPUPage(cpu_addr, size, [this, image_id](u64 page) {
  1940. const auto page_it = page_table.find(page);
  1941. if (page_it == page_table.end()) {
  1942. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1943. return;
  1944. }
  1945. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1946. auto vector_it = image_map_ids.begin();
  1947. while (vector_it != image_map_ids.end()) {
  1948. ImageMapView& map = slot_map_views[*vector_it];
  1949. if (map.image_id != image_id) {
  1950. vector_it++;
  1951. continue;
  1952. }
  1953. if (!map.picked) {
  1954. map.picked = true;
  1955. }
  1956. vector_it = image_map_ids.erase(vector_it);
  1957. }
  1958. });
  1959. slot_map_views.erase(map_view_id);
  1960. }
  1961. sparse_views.erase(it);
  1962. }
  1963. template <class P>
  1964. void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) {
  1965. ASSERT(False(image.flags & ImageFlagBits::Tracked));
  1966. image.flags |= ImageFlagBits::Tracked;
  1967. if (False(image.flags & ImageFlagBits::Sparse)) {
  1968. device_memory.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1);
  1969. return;
  1970. }
  1971. if (True(image.flags & ImageFlagBits::Registered)) {
  1972. auto it = sparse_views.find(image_id);
  1973. ASSERT(it != sparse_views.end());
  1974. auto& sparse_maps = it->second;
  1975. for (auto& map_view_id : sparse_maps) {
  1976. const auto& map = slot_map_views[map_view_id];
  1977. const DAddr cpu_addr = map.cpu_addr;
  1978. const std::size_t size = map.size;
  1979. device_memory.UpdatePagesCachedCount(cpu_addr, size, 1);
  1980. }
  1981. return;
  1982. }
  1983. ForEachSparseSegment(image,
  1984. [this]([[maybe_unused]] GPUVAddr gpu_addr, DAddr cpu_addr, size_t size) {
  1985. device_memory.UpdatePagesCachedCount(cpu_addr, size, 1);
  1986. });
  1987. }
  1988. template <class P>
  1989. void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) {
  1990. ASSERT(True(image.flags & ImageFlagBits::Tracked));
  1991. image.flags &= ~ImageFlagBits::Tracked;
  1992. if (False(image.flags & ImageFlagBits::Sparse)) {
  1993. device_memory.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1);
  1994. return;
  1995. }
  1996. ASSERT(True(image.flags & ImageFlagBits::Registered));
  1997. auto it = sparse_views.find(image_id);
  1998. ASSERT(it != sparse_views.end());
  1999. auto& sparse_maps = it->second;
  2000. for (auto& map_view_id : sparse_maps) {
  2001. const auto& map = slot_map_views[map_view_id];
  2002. const DAddr cpu_addr = map.cpu_addr;
  2003. const std::size_t size = map.size;
  2004. device_memory.UpdatePagesCachedCount(cpu_addr, size, -1);
  2005. }
  2006. }
  2007. template <class P>
  2008. void TextureCache<P>::DeleteImage(ImageId image_id, bool immediate_delete) {
  2009. ImageBase& image = slot_images[image_id];
  2010. if (image.HasScaled()) {
  2011. total_used_memory -= GetScaledImageSizeBytes(image);
  2012. }
  2013. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  2014. if ((IsPixelFormatASTC(image.info.format) &&
  2015. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  2016. True(image.flags & ImageFlagBits::Converted)) {
  2017. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  2018. }
  2019. total_used_memory -= Common::AlignUp(tentative_size, 1024);
  2020. const GPUVAddr gpu_addr = image.gpu_addr;
  2021. const auto alloc_it = image_allocs_table.find(gpu_addr);
  2022. if (alloc_it == image_allocs_table.end()) {
  2023. ASSERT_MSG(false, "Trying to delete an image alloc that does not exist in address 0x{:x}",
  2024. gpu_addr);
  2025. return;
  2026. }
  2027. const ImageAllocId alloc_id = alloc_it->second;
  2028. std::vector<ImageId>& alloc_images = slot_image_allocs[alloc_id].images;
  2029. const auto alloc_image_it = std::ranges::find(alloc_images, image_id);
  2030. if (alloc_image_it == alloc_images.end()) {
  2031. ASSERT_MSG(false, "Trying to delete an image that does not exist");
  2032. return;
  2033. }
  2034. ASSERT_MSG(False(image.flags & ImageFlagBits::Tracked), "Image was not untracked");
  2035. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered), "Image was not unregistered");
  2036. // Mark render targets as dirty
  2037. auto& dirty = maxwell3d->dirty.flags;
  2038. dirty[Dirty::RenderTargets] = true;
  2039. dirty[Dirty::ZetaBuffer] = true;
  2040. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  2041. dirty[Dirty::ColorBuffer0 + rt] = true;
  2042. }
  2043. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  2044. for (const ImageViewId image_view_id : image_view_ids) {
  2045. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  2046. if (render_targets.depth_buffer_id == image_view_id) {
  2047. render_targets.depth_buffer_id = ImageViewId{};
  2048. }
  2049. }
  2050. RemoveImageViewReferences(image_view_ids);
  2051. RemoveFramebuffers(image_view_ids);
  2052. for (const AliasedImage& alias : image.aliased_images) {
  2053. ImageBase& other_image = slot_images[alias.id];
  2054. [[maybe_unused]] const size_t num_removed_aliases =
  2055. std::erase_if(other_image.aliased_images, [image_id](const AliasedImage& other_alias) {
  2056. return other_alias.id == image_id;
  2057. });
  2058. other_image.CheckAliasState();
  2059. ASSERT_MSG(num_removed_aliases == 1, "Invalid number of removed aliases: {}",
  2060. num_removed_aliases);
  2061. }
  2062. for (const ImageId overlap_id : image.overlapping_images) {
  2063. ImageBase& other_image = slot_images[overlap_id];
  2064. [[maybe_unused]] const size_t num_removed_overlaps = std::erase_if(
  2065. other_image.overlapping_images,
  2066. [image_id](const ImageId other_overlap_id) { return other_overlap_id == image_id; });
  2067. other_image.CheckBadOverlapState();
  2068. ASSERT_MSG(num_removed_overlaps == 1, "Invalid number of removed overlapps: {}",
  2069. num_removed_overlaps);
  2070. }
  2071. for (const ImageViewId image_view_id : image_view_ids) {
  2072. if (!immediate_delete) {
  2073. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  2074. }
  2075. slot_image_views.erase(image_view_id);
  2076. }
  2077. if (!immediate_delete) {
  2078. sentenced_images.Push(std::move(slot_images[image_id]));
  2079. }
  2080. slot_images.erase(image_id);
  2081. alloc_images.erase(alloc_image_it);
  2082. if (alloc_images.empty()) {
  2083. image_allocs_table.erase(alloc_it);
  2084. }
  2085. for (size_t c : active_channel_ids) {
  2086. auto& channel_info = channel_storage[c];
  2087. if constexpr (ENABLE_VALIDATION) {
  2088. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  2089. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  2090. }
  2091. channel_info.graphics_image_table.Invalidate();
  2092. channel_info.compute_image_table.Invalidate();
  2093. }
  2094. has_deleted_images = true;
  2095. }
  2096. template <class P>
  2097. void TextureCache<P>::RemoveImageViewReferences(std::span<const ImageViewId> removed_views) {
  2098. for (size_t c : active_channel_ids) {
  2099. auto& channel_info = channel_storage[c];
  2100. auto it = channel_info.image_views.begin();
  2101. while (it != channel_info.image_views.end()) {
  2102. const auto found = std::ranges::find(removed_views, it->second);
  2103. if (found != removed_views.end()) {
  2104. it = channel_info.image_views.erase(it);
  2105. } else {
  2106. ++it;
  2107. }
  2108. }
  2109. }
  2110. }
  2111. template <class P>
  2112. void TextureCache<P>::RemoveFramebuffers(std::span<const ImageViewId> removed_views) {
  2113. auto it = framebuffers.begin();
  2114. while (it != framebuffers.end()) {
  2115. if (it->first.Contains(removed_views)) {
  2116. auto framebuffer_id = it->second;
  2117. ASSERT(framebuffer_id);
  2118. sentenced_framebuffers.Push(std::move(slot_framebuffers[framebuffer_id]));
  2119. it = framebuffers.erase(it);
  2120. } else {
  2121. ++it;
  2122. }
  2123. }
  2124. }
  2125. template <class P>
  2126. void TextureCache<P>::MarkModification(ImageBase& image) noexcept {
  2127. image.flags |= ImageFlagBits::GpuModified;
  2128. image.modification_tick = ++modification_tick;
  2129. }
  2130. template <class P>
  2131. void TextureCache<P>::SynchronizeAliases(ImageId image_id) {
  2132. boost::container::small_vector<const AliasedImage*, 8> aliased_images;
  2133. Image& image = slot_images[image_id];
  2134. bool any_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  2135. bool any_modified = True(image.flags & ImageFlagBits::GpuModified);
  2136. u64 most_recent_tick = image.modification_tick;
  2137. for (const AliasedImage& aliased : image.aliased_images) {
  2138. ImageBase& aliased_image = slot_images[aliased.id];
  2139. if (image.modification_tick < aliased_image.modification_tick) {
  2140. most_recent_tick = std::max(most_recent_tick, aliased_image.modification_tick);
  2141. aliased_images.push_back(&aliased);
  2142. any_rescaled |= True(aliased_image.flags & ImageFlagBits::Rescaled);
  2143. any_modified |= True(aliased_image.flags & ImageFlagBits::GpuModified);
  2144. }
  2145. }
  2146. if (aliased_images.empty()) {
  2147. return;
  2148. }
  2149. const bool can_rescale = ImageCanRescale(image);
  2150. if (any_rescaled) {
  2151. if (can_rescale) {
  2152. ScaleUp(image);
  2153. } else {
  2154. ScaleDown(image);
  2155. }
  2156. }
  2157. image.modification_tick = most_recent_tick;
  2158. if (any_modified) {
  2159. image.flags |= ImageFlagBits::GpuModified;
  2160. }
  2161. std::ranges::sort(aliased_images, [this](const AliasedImage* lhs, const AliasedImage* rhs) {
  2162. const ImageBase& lhs_image = slot_images[lhs->id];
  2163. const ImageBase& rhs_image = slot_images[rhs->id];
  2164. return lhs_image.modification_tick < rhs_image.modification_tick;
  2165. });
  2166. const auto& resolution = Settings::values.resolution_info;
  2167. for (const AliasedImage* const aliased : aliased_images) {
  2168. if (!resolution.active || !any_rescaled) {
  2169. CopyImage(image_id, aliased->id, aliased->copies);
  2170. continue;
  2171. }
  2172. Image& aliased_image = slot_images[aliased->id];
  2173. if (!can_rescale) {
  2174. ScaleDown(aliased_image);
  2175. CopyImage(image_id, aliased->id, aliased->copies);
  2176. continue;
  2177. }
  2178. ScaleUp(aliased_image);
  2179. CopyImage(image_id, aliased->id, aliased->copies);
  2180. }
  2181. }
  2182. template <class P>
  2183. void TextureCache<P>::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) {
  2184. Image& image = slot_images[image_id];
  2185. if (invalidate) {
  2186. image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified);
  2187. if (False(image.flags & ImageFlagBits::Tracked)) {
  2188. TrackImage(image, image_id);
  2189. }
  2190. } else {
  2191. RefreshContents(image, image_id);
  2192. SynchronizeAliases(image_id);
  2193. }
  2194. if (is_modification) {
  2195. MarkModification(image);
  2196. }
  2197. lru_cache.Touch(image.lru_index, frame_tick);
  2198. }
  2199. template <class P>
  2200. void TextureCache<P>::PrepareImageView(ImageViewId image_view_id, bool is_modification,
  2201. bool invalidate) {
  2202. if (!image_view_id) {
  2203. return;
  2204. }
  2205. const ImageViewBase& image_view = slot_image_views[image_view_id];
  2206. if (image_view.IsBuffer()) {
  2207. return;
  2208. }
  2209. PrepareImage(image_view.image_id, is_modification, invalidate);
  2210. }
  2211. template <class P>
  2212. void TextureCache<P>::CopyImage(ImageId dst_id, ImageId src_id, std::vector<ImageCopy> copies) {
  2213. Image& dst = slot_images[dst_id];
  2214. Image& src = slot_images[src_id];
  2215. const bool is_rescaled = True(src.flags & ImageFlagBits::Rescaled);
  2216. if (is_rescaled) {
  2217. ASSERT(True(dst.flags & ImageFlagBits::Rescaled));
  2218. const bool both_2d{src.info.type == ImageType::e2D && dst.info.type == ImageType::e2D};
  2219. const auto& resolution = Settings::values.resolution_info;
  2220. for (auto& copy : copies) {
  2221. copy.src_offset.x = resolution.ScaleUp(copy.src_offset.x);
  2222. copy.dst_offset.x = resolution.ScaleUp(copy.dst_offset.x);
  2223. copy.extent.width = resolution.ScaleUp(copy.extent.width);
  2224. if (both_2d) {
  2225. copy.src_offset.y = resolution.ScaleUp(copy.src_offset.y);
  2226. copy.dst_offset.y = resolution.ScaleUp(copy.dst_offset.y);
  2227. copy.extent.height = resolution.ScaleUp(copy.extent.height);
  2228. }
  2229. }
  2230. }
  2231. const auto dst_format_type = GetFormatType(dst.info.format);
  2232. const auto src_format_type = GetFormatType(src.info.format);
  2233. if (src_format_type == dst_format_type) {
  2234. if constexpr (HAS_EMULATED_COPIES) {
  2235. if (!runtime.CanImageBeCopied(dst, src)) {
  2236. return runtime.EmulateCopyImage(dst, src, copies);
  2237. }
  2238. }
  2239. return runtime.CopyImage(dst, src, copies);
  2240. }
  2241. UNIMPLEMENTED_IF(dst.info.type != ImageType::e2D);
  2242. UNIMPLEMENTED_IF(src.info.type != ImageType::e2D);
  2243. if (runtime.ShouldReinterpret(dst, src)) {
  2244. return runtime.ReinterpretImage(dst, src, copies);
  2245. }
  2246. for (const ImageCopy& copy : copies) {
  2247. UNIMPLEMENTED_IF(copy.dst_subresource.num_layers != 1);
  2248. UNIMPLEMENTED_IF(copy.src_subresource.num_layers != 1);
  2249. UNIMPLEMENTED_IF(copy.src_offset != Offset3D{});
  2250. UNIMPLEMENTED_IF(copy.dst_offset != Offset3D{});
  2251. const SubresourceBase dst_base{
  2252. .level = copy.dst_subresource.base_level,
  2253. .layer = copy.dst_subresource.base_layer,
  2254. };
  2255. const SubresourceBase src_base{
  2256. .level = copy.src_subresource.base_level,
  2257. .layer = copy.src_subresource.base_layer,
  2258. };
  2259. const SubresourceExtent dst_extent{.levels = 1, .layers = 1};
  2260. const SubresourceExtent src_extent{.levels = 1, .layers = 1};
  2261. const SubresourceRange dst_range{.base = dst_base, .extent = dst_extent};
  2262. const SubresourceRange src_range{.base = src_base, .extent = src_extent};
  2263. PixelFormat dst_format = dst.info.format;
  2264. if (GetFormatType(src.info.format) == SurfaceType::DepthStencil &&
  2265. GetFormatType(dst_format) == SurfaceType::ColorTexture &&
  2266. BytesPerBlock(dst_format) == 4) {
  2267. dst_format = PixelFormat::A8B8G8R8_UNORM;
  2268. }
  2269. const ImageViewInfo dst_view_info(ImageViewType::e2D, dst_format, dst_range);
  2270. const ImageViewInfo src_view_info(ImageViewType::e2D, src.info.format, src_range);
  2271. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  2272. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  2273. const ImageViewId src_view_id = FindOrEmplaceImageView(src_id, src_view_info);
  2274. ImageView& dst_view = slot_image_views[dst_view_id];
  2275. ImageView& src_view = slot_image_views[src_view_id];
  2276. [[maybe_unused]] const Extent3D expected_size{
  2277. .width = std::min(dst_view.size.width, src_view.size.width),
  2278. .height = std::min(dst_view.size.height, src_view.size.height),
  2279. .depth = std::min(dst_view.size.depth, src_view.size.depth),
  2280. };
  2281. const Extent3D scaled_extent = [is_rescaled, expected_size]() {
  2282. if (!is_rescaled) {
  2283. return expected_size;
  2284. }
  2285. const auto& resolution = Settings::values.resolution_info;
  2286. return Extent3D{
  2287. .width = resolution.ScaleUp(expected_size.width),
  2288. .height = resolution.ScaleUp(expected_size.height),
  2289. .depth = expected_size.depth,
  2290. };
  2291. }();
  2292. UNIMPLEMENTED_IF(copy.extent != scaled_extent);
  2293. runtime.ConvertImage(dst_framebuffer, dst_view, src_view);
  2294. }
  2295. }
  2296. template <class P>
  2297. void TextureCache<P>::BindRenderTarget(ImageViewId* old_id, ImageViewId new_id) {
  2298. if (*old_id == new_id) {
  2299. return;
  2300. }
  2301. if (new_id) {
  2302. const ImageViewBase& old_view = slot_image_views[new_id];
  2303. if (True(old_view.flags & ImageViewFlagBits::PreemtiveDownload)) {
  2304. const PendingDownload new_download{true, 0, old_view.image_id};
  2305. uncommitted_downloads.emplace_back(new_download);
  2306. }
  2307. }
  2308. *old_id = new_id;
  2309. }
  2310. template <class P>
  2311. std::pair<FramebufferId, ImageViewId> TextureCache<P>::RenderTargetFromImage(
  2312. ImageId image_id, const ImageViewInfo& view_info) {
  2313. const ImageViewId view_id = FindOrEmplaceImageView(image_id, view_info);
  2314. const ImageBase& image = slot_images[image_id];
  2315. const bool is_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  2316. const bool is_color = GetFormatType(image.info.format) == SurfaceType::ColorTexture;
  2317. const ImageViewId color_view_id = is_color ? view_id : ImageViewId{};
  2318. const ImageViewId depth_view_id = is_color ? ImageViewId{} : view_id;
  2319. Extent3D extent = MipSize(image.info.size, view_info.range.base.level);
  2320. if (is_rescaled) {
  2321. const auto& resolution = Settings::values.resolution_info;
  2322. extent.width = resolution.ScaleUp(extent.width);
  2323. if (image.info.type == ImageType::e2D) {
  2324. extent.height = resolution.ScaleUp(extent.height);
  2325. }
  2326. }
  2327. const u32 num_samples = image.info.num_samples;
  2328. const auto [samples_x, samples_y] = SamplesLog2(num_samples);
  2329. const FramebufferId framebuffer_id = GetFramebufferId(RenderTargets{
  2330. .color_buffer_ids = {color_view_id},
  2331. .depth_buffer_id = depth_view_id,
  2332. .size = {extent.width >> samples_x, extent.height >> samples_y},
  2333. .is_rescaled = is_rescaled,
  2334. });
  2335. return {framebuffer_id, view_id};
  2336. }
  2337. template <class P>
  2338. bool TextureCache<P>::IsFullClear(ImageViewId id) {
  2339. if (!id) {
  2340. return true;
  2341. }
  2342. const ImageViewBase& image_view = slot_image_views[id];
  2343. const ImageBase& image = slot_images[image_view.image_id];
  2344. const Extent3D size = image_view.size;
  2345. const auto& regs = maxwell3d->regs;
  2346. const auto& scissor = regs.scissor_test[0];
  2347. if (image.info.resources.levels > 1 || image.info.resources.layers > 1) {
  2348. // Images with multiple resources can't be cleared in a single call
  2349. return false;
  2350. }
  2351. if (regs.clear_control.use_scissor == 0) {
  2352. // If scissor testing is disabled, the clear is always full
  2353. return true;
  2354. }
  2355. // Make sure the clear covers all texels in the subresource
  2356. return scissor.min_x == 0 && scissor.min_y == 0 && scissor.max_x >= size.width &&
  2357. scissor.max_y >= size.height;
  2358. }
  2359. template <class P>
  2360. void TextureCache<P>::CreateChannel(struct Tegra::Control::ChannelState& channel) {
  2361. VideoCommon::ChannelSetupCaches<TextureCacheChannelInfo>::CreateChannel(channel);
  2362. const auto it = channel_map.find(channel.bind_id);
  2363. auto* this_state = &channel_storage[it->second];
  2364. const auto& this_as_ref = address_spaces[channel.memory_manager->GetID()];
  2365. this_state->gpu_page_table = &gpu_page_table_storage[this_as_ref.storage_id * 2];
  2366. this_state->sparse_page_table = &gpu_page_table_storage[this_as_ref.storage_id * 2 + 1];
  2367. }
  2368. /// Bind a channel for execution.
  2369. template <class P>
  2370. void TextureCache<P>::OnGPUASRegister([[maybe_unused]] size_t map_id) {
  2371. gpu_page_table_storage.emplace_back();
  2372. gpu_page_table_storage.emplace_back();
  2373. }
  2374. } // namespace VideoCommon