Texture.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Memory;
  4. using Ryujinx.Graphics.Texture;
  5. using Ryujinx.Graphics.Texture.Astc;
  6. using Ryujinx.Memory;
  7. using Ryujinx.Memory.Range;
  8. using System;
  9. using System.Buffers;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.Linq;
  13. using System.Numerics;
  14. namespace Ryujinx.Graphics.Gpu.Image
  15. {
  16. /// <summary>
  17. /// Represents a cached GPU texture.
  18. /// </summary>
  19. class Texture : IMultiRangeItem, IDisposable
  20. {
  21. // How many updates we need before switching to the byte-by-byte comparison
  22. // modification check method.
  23. // This method uses much more memory so we want to avoid it if possible.
  24. private const int ByteComparisonSwitchThreshold = 4;
  25. // Tuning for blacklisting textures from scaling when their data is updated from CPU.
  26. // Each write adds the weight, each GPU modification subtracts 1.
  27. // Exceeding the threshold blacklists the texture.
  28. private const int ScaledSetWeight = 10;
  29. private const int ScaledSetThreshold = 30;
  30. private const int MinLevelsForForceAnisotropy = 5;
  31. private struct TexturePoolOwner
  32. {
  33. public TexturePool Pool;
  34. public int ID;
  35. public ulong GpuAddress;
  36. }
  37. private GpuContext _context;
  38. private PhysicalMemory _physicalMemory;
  39. private SizeInfo _sizeInfo;
  40. /// <summary>
  41. /// Texture format.
  42. /// </summary>
  43. public Format Format => Info.FormatInfo.Format;
  44. /// <summary>
  45. /// Texture target.
  46. /// </summary>
  47. public Target Target { get; private set; }
  48. /// <summary>
  49. /// Texture width.
  50. /// </summary>
  51. public int Width { get; private set; }
  52. /// <summary>
  53. /// Texture height.
  54. /// </summary>
  55. public int Height { get; private set; }
  56. /// <summary>
  57. /// Texture information.
  58. /// </summary>
  59. public TextureInfo Info { get; private set; }
  60. /// <summary>
  61. /// Set when anisotropic filtering can be forced on the given texture.
  62. /// </summary>
  63. public bool CanForceAnisotropy { get; private set; }
  64. /// <summary>
  65. /// Host scale factor.
  66. /// </summary>
  67. public float ScaleFactor { get; private set; }
  68. /// <summary>
  69. /// Upscaling mode. Informs if a texture is scaled, or is eligible for scaling.
  70. /// </summary>
  71. public TextureScaleMode ScaleMode { get; private set; }
  72. /// <summary>
  73. /// Group that this texture belongs to. Manages read/write memory tracking.
  74. /// </summary>
  75. public TextureGroup Group { get; private set; }
  76. /// <summary>
  77. /// Set when a texture's GPU VA has ever been partially or fully unmapped.
  78. /// This indicates that the range must be fully checked when matching the texture.
  79. /// </summary>
  80. public bool ChangedMapping { get; private set; }
  81. /// <summary>
  82. /// True if the data for this texture must always be flushed when an overlap appears.
  83. /// This is useful if SetData is called directly on this texture, but the data is meant for a future texture.
  84. /// </summary>
  85. public bool AlwaysFlushOnOverlap { get; private set; }
  86. /// <summary>
  87. /// Increments when the host texture is swapped, or when the texture is removed from all pools.
  88. /// </summary>
  89. public int InvalidatedSequence { get; private set; }
  90. private int _depth;
  91. private int _layers;
  92. public int FirstLayer { get; private set; }
  93. public int FirstLevel { get; private set; }
  94. private bool _hasData;
  95. private bool _dirty = true;
  96. private int _updateCount;
  97. private byte[] _currentData;
  98. private bool _modifiedStale = true;
  99. private ITexture _arrayViewTexture;
  100. private Target _arrayViewTarget;
  101. private ITexture _flushHostTexture;
  102. private ITexture _setHostTexture;
  103. private int _scaledSetScore;
  104. private Texture _viewStorage;
  105. private List<Texture> _views;
  106. /// <summary>
  107. /// Host texture.
  108. /// </summary>
  109. public ITexture HostTexture { get; private set; }
  110. /// <summary>
  111. /// Intrusive linked list node used on the auto deletion texture cache.
  112. /// </summary>
  113. public LinkedListNode<Texture> CacheNode { get; set; }
  114. /// <summary>
  115. /// Entry for this texture in the short duration cache, if present.
  116. /// </summary>
  117. public ShortTextureCacheEntry ShortCacheEntry { get; set; }
  118. /// <summary>
  119. /// Whether this texture has ever been referenced by a pool.
  120. /// </summary>
  121. public bool HadPoolOwner { get; private set; }
  122. /// <summary>
  123. /// Physical memory ranges where the texture data is located.
  124. /// </summary>
  125. public MultiRange Range { get; private set; }
  126. /// <summary>
  127. /// Layer size in bytes.
  128. /// </summary>
  129. public int LayerSize => _sizeInfo.LayerSize;
  130. /// <summary>
  131. /// Texture size in bytes.
  132. /// </summary>
  133. public ulong Size => (ulong)_sizeInfo.TotalSize;
  134. /// <summary>
  135. /// Whether or not the texture belongs is a view.
  136. /// </summary>
  137. public bool IsView => _viewStorage != this;
  138. /// <summary>
  139. /// Whether or not this texture has views.
  140. /// </summary>
  141. public bool HasViews => _views.Count > 0;
  142. private int _referenceCount;
  143. private List<TexturePoolOwner> _poolOwners;
  144. /// <summary>
  145. /// Constructs a new instance of the cached GPU texture.
  146. /// </summary>
  147. /// <param name="context">GPU context that the texture belongs to</param>
  148. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  149. /// <param name="info">Texture information</param>
  150. /// <param name="sizeInfo">Size information of the texture</param>
  151. /// <param name="range">Physical memory ranges where the texture data is located</param>
  152. /// <param name="firstLayer">The first layer of the texture, or 0 if the texture has no parent</param>
  153. /// <param name="firstLevel">The first mipmap level of the texture, or 0 if the texture has no parent</param>
  154. /// <param name="scaleFactor">The floating point scale factor to initialize with</param>
  155. /// <param name="scaleMode">The scale mode to initialize with</param>
  156. private Texture(
  157. GpuContext context,
  158. PhysicalMemory physicalMemory,
  159. TextureInfo info,
  160. SizeInfo sizeInfo,
  161. MultiRange range,
  162. int firstLayer,
  163. int firstLevel,
  164. float scaleFactor,
  165. TextureScaleMode scaleMode)
  166. {
  167. InitializeTexture(context, physicalMemory, info, sizeInfo, range);
  168. FirstLayer = firstLayer;
  169. FirstLevel = firstLevel;
  170. ScaleFactor = scaleFactor;
  171. ScaleMode = scaleMode;
  172. InitializeData(true);
  173. }
  174. /// <summary>
  175. /// Constructs a new instance of the cached GPU texture.
  176. /// </summary>
  177. /// <param name="context">GPU context that the texture belongs to</param>
  178. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  179. /// <param name="info">Texture information</param>
  180. /// <param name="sizeInfo">Size information of the texture</param>
  181. /// <param name="range">Physical memory ranges where the texture data is located</param>
  182. /// <param name="scaleMode">The scale mode to initialize with. If scaled, the texture's data is loaded immediately and scaled up</param>
  183. public Texture(
  184. GpuContext context,
  185. PhysicalMemory physicalMemory,
  186. TextureInfo info,
  187. SizeInfo sizeInfo,
  188. MultiRange range,
  189. TextureScaleMode scaleMode)
  190. {
  191. ScaleFactor = 1f; // Texture is first loaded at scale 1x.
  192. ScaleMode = scaleMode;
  193. InitializeTexture(context, physicalMemory, info, sizeInfo, range);
  194. }
  195. /// <summary>
  196. /// Common texture initialization method.
  197. /// This sets the context, info and sizeInfo fields.
  198. /// Other fields are initialized with their default values.
  199. /// </summary>
  200. /// <param name="context">GPU context that the texture belongs to</param>
  201. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  202. /// <param name="info">Texture information</param>
  203. /// <param name="sizeInfo">Size information of the texture</param>
  204. /// <param name="range">Physical memory ranges where the texture data is located</param>
  205. private void InitializeTexture(
  206. GpuContext context,
  207. PhysicalMemory physicalMemory,
  208. TextureInfo info,
  209. SizeInfo sizeInfo,
  210. MultiRange range)
  211. {
  212. _context = context;
  213. _physicalMemory = physicalMemory;
  214. _sizeInfo = sizeInfo;
  215. Range = range;
  216. SetInfo(info);
  217. _viewStorage = this;
  218. _views = new List<Texture>();
  219. _poolOwners = new List<TexturePoolOwner>();
  220. }
  221. /// <summary>
  222. /// Initializes the data for a texture. Can optionally initialize the texture with or without data.
  223. /// If the texture is a view, it will initialize memory tracking to be non-dirty.
  224. /// </summary>
  225. /// <param name="isView">True if the texture is a view, false otherwise</param>
  226. /// <param name="withData">True if the texture is to be initialized with data</param>
  227. public void InitializeData(bool isView, bool withData = false)
  228. {
  229. withData |= Group != null && Group.FlushIncompatibleOverlapsIfNeeded();
  230. if (withData)
  231. {
  232. Debug.Assert(!isView);
  233. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  234. HostTexture = _context.Renderer.CreateTexture(createInfo);
  235. SynchronizeMemory(); // Load the data.
  236. if (ScaleMode == TextureScaleMode.Scaled)
  237. {
  238. SetScale(GraphicsConfig.ResScale); // Scale the data up.
  239. }
  240. }
  241. else
  242. {
  243. _hasData = true;
  244. if (!isView)
  245. {
  246. // Don't update this texture the next time we synchronize.
  247. CheckModified(true);
  248. if (ScaleMode == TextureScaleMode.Scaled)
  249. {
  250. // Don't need to start at 1x as there is no data to scale, just go straight to the target scale.
  251. ScaleFactor = GraphicsConfig.ResScale;
  252. }
  253. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  254. HostTexture = _context.Renderer.CreateTexture(createInfo);
  255. }
  256. }
  257. }
  258. /// <summary>
  259. /// Initialize a new texture group with this texture as storage.
  260. /// </summary>
  261. /// <param name="hasLayerViews">True if the texture will have layer views</param>
  262. /// <param name="hasMipViews">True if the texture will have mip views</param>
  263. /// <param name="incompatibleOverlaps">Groups that overlap with this one but are incompatible</param>
  264. public void InitializeGroup(bool hasLayerViews, bool hasMipViews, List<TextureIncompatibleOverlap> incompatibleOverlaps)
  265. {
  266. Group = new TextureGroup(_context, _physicalMemory, this, incompatibleOverlaps);
  267. Group.Initialize(ref _sizeInfo, hasLayerViews, hasMipViews);
  268. }
  269. /// <summary>
  270. /// Create a texture view from this texture.
  271. /// A texture view is defined as a child texture, from a sub-range of their parent texture.
  272. /// For example, the initial layer and mipmap level of the view can be defined, so the texture
  273. /// will start at the given layer/level of the parent texture.
  274. /// </summary>
  275. /// <param name="info">Child texture information</param>
  276. /// <param name="sizeInfo">Child texture size information</param>
  277. /// <param name="range">Physical memory ranges where the texture data is located</param>
  278. /// <param name="firstLayer">Start layer of the child texture on the parent texture</param>
  279. /// <param name="firstLevel">Start mipmap level of the child texture on the parent texture</param>
  280. /// <returns>The child texture</returns>
  281. public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, MultiRange range, int firstLayer, int firstLevel)
  282. {
  283. Texture texture = new(
  284. _context,
  285. _physicalMemory,
  286. info,
  287. sizeInfo,
  288. range,
  289. FirstLayer + firstLayer,
  290. FirstLevel + firstLevel,
  291. ScaleFactor,
  292. ScaleMode);
  293. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(info, _context.Capabilities, ScaleFactor);
  294. texture.HostTexture = HostTexture.CreateView(createInfo, firstLayer, firstLevel);
  295. _viewStorage.AddView(texture);
  296. return texture;
  297. }
  298. /// <summary>
  299. /// Adds a child texture to this texture.
  300. /// </summary>
  301. /// <param name="texture">The child texture</param>
  302. private void AddView(Texture texture)
  303. {
  304. IncrementReferenceCount();
  305. _views.Add(texture);
  306. texture._viewStorage = this;
  307. Group.UpdateViews(_views, texture);
  308. if (texture.Group != null && texture.Group != Group)
  309. {
  310. if (texture.Group.Storage == texture)
  311. {
  312. // This texture's group is no longer used.
  313. Group.Inherit(texture.Group);
  314. texture.Group.Dispose();
  315. }
  316. }
  317. texture.Group = Group;
  318. }
  319. /// <summary>
  320. /// Removes a child texture from this texture.
  321. /// </summary>
  322. /// <param name="texture">The child texture</param>
  323. private void RemoveView(Texture texture)
  324. {
  325. _views.Remove(texture);
  326. Group.RemoveView(texture);
  327. texture._viewStorage = texture;
  328. DecrementReferenceCount();
  329. }
  330. /// <summary>
  331. /// Replaces the texture's physical memory range. This forces tracking to regenerate.
  332. /// </summary>
  333. /// <param name="range">New physical memory range backing the texture</param>
  334. public void ReplaceRange(MultiRange range)
  335. {
  336. Range = range;
  337. Group.RangeChanged();
  338. }
  339. /// <summary>
  340. /// Create a copy dependency to a texture that is view compatible with this one.
  341. /// When either texture is modified, the texture data will be copied to the other to keep them in sync.
  342. /// This is essentially an emulated view, useful for handling multiple view parents or format incompatibility.
  343. /// This also forces a copy on creation, to or from the given texture to get them in sync immediately.
  344. /// </summary>
  345. /// <param name="contained">The view compatible texture to create a dependency to</param>
  346. /// <param name="layer">The base layer of the given texture relative to this one</param>
  347. /// <param name="level">The base level of the given texture relative to this one</param>
  348. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  349. public void CreateCopyDependency(Texture contained, int layer, int level, bool copyTo)
  350. {
  351. if (contained.Group == Group)
  352. {
  353. return;
  354. }
  355. Group.CreateCopyDependency(contained, FirstLayer + layer, FirstLevel + level, copyTo);
  356. }
  357. /// <summary>
  358. /// Registers when a texture has had its data set after being scaled, and
  359. /// determines if it should be blacklisted from scaling to improve performance.
  360. /// </summary>
  361. /// <returns>True if setting data for a scaled texture is allowed, false if the texture has been blacklisted</returns>
  362. private bool AllowScaledSetData()
  363. {
  364. _scaledSetScore += ScaledSetWeight;
  365. if (_scaledSetScore >= ScaledSetThreshold)
  366. {
  367. BlacklistScale();
  368. return false;
  369. }
  370. return true;
  371. }
  372. /// <summary>
  373. /// Blacklists this texture from being scaled. Resets its scale to 1 if needed.
  374. /// </summary>
  375. public void BlacklistScale()
  376. {
  377. ScaleMode = TextureScaleMode.Blacklisted;
  378. SetScale(1f);
  379. }
  380. /// <summary>
  381. /// Propagates the scale between this texture and another to ensure they have the same scale.
  382. /// If one texture is blacklisted from scaling, the other will become blacklisted too.
  383. /// </summary>
  384. /// <param name="other">The other texture</param>
  385. public void PropagateScale(Texture other)
  386. {
  387. if (other.ScaleMode == TextureScaleMode.Blacklisted || ScaleMode == TextureScaleMode.Blacklisted)
  388. {
  389. BlacklistScale();
  390. other.BlacklistScale();
  391. }
  392. else
  393. {
  394. // Prefer the configured scale if present. If not, prefer the max.
  395. float targetScale = GraphicsConfig.ResScale;
  396. float sharedScale = (ScaleFactor == targetScale || other.ScaleFactor == targetScale) ? targetScale : Math.Max(ScaleFactor, other.ScaleFactor);
  397. SetScale(sharedScale);
  398. other.SetScale(sharedScale);
  399. }
  400. }
  401. /// <summary>
  402. /// Copy the host texture to a scaled one. If a texture is not provided, create it with the given scale.
  403. /// </summary>
  404. /// <param name="scale">Scale factor</param>
  405. /// <param name="copy">True if the data should be copied to the texture, false otherwise</param>
  406. /// <param name="storage">Texture to use instead of creating one</param>
  407. /// <returns>A host texture containing a scaled version of this texture</returns>
  408. private ITexture GetScaledHostTexture(float scale, bool copy, ITexture storage = null)
  409. {
  410. if (storage == null)
  411. {
  412. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, scale);
  413. storage = _context.Renderer.CreateTexture(createInfo);
  414. }
  415. if (copy)
  416. {
  417. HostTexture.CopyTo(storage, new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), new Extents2D(0, 0, storage.Width, storage.Height), true);
  418. }
  419. return storage;
  420. }
  421. /// <summary>
  422. /// Sets the Scale Factor on this texture, and immediately recreates it at the correct size.
  423. /// When a texture is resized, a scaled copy is performed from the old texture to the new one, to ensure no data is lost.
  424. /// If scale is equivalent, this only propagates the blacklisted/scaled mode.
  425. /// If called on a view, its storage is resized instead.
  426. /// When resizing storage, all texture views are recreated.
  427. /// </summary>
  428. /// <param name="scale">The new scale factor for this texture</param>
  429. public void SetScale(float scale)
  430. {
  431. bool unscaled = ScaleMode == TextureScaleMode.Blacklisted || (ScaleMode == TextureScaleMode.Undesired && scale == 1);
  432. TextureScaleMode newScaleMode = unscaled ? ScaleMode : TextureScaleMode.Scaled;
  433. if (_viewStorage != this)
  434. {
  435. _viewStorage.ScaleMode = newScaleMode;
  436. _viewStorage.SetScale(scale);
  437. return;
  438. }
  439. if (ScaleFactor != scale)
  440. {
  441. Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format} to ({ScaleFactor} to {scale}). ");
  442. ScaleFactor = scale;
  443. ITexture newStorage = GetScaledHostTexture(ScaleFactor, true);
  444. Logger.Debug?.Print(LogClass.Gpu, $" Copy performed: {HostTexture.Width}x{HostTexture.Height} to {newStorage.Width}x{newStorage.Height}");
  445. ReplaceStorage(newStorage);
  446. // All views must be recreated against the new storage.
  447. foreach (var view in _views)
  448. {
  449. Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format}.");
  450. view.ScaleFactor = scale;
  451. TextureCreateInfo viewCreateInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, scale);
  452. ITexture newView = HostTexture.CreateView(viewCreateInfo, view.FirstLayer - FirstLayer, view.FirstLevel - FirstLevel);
  453. view.ReplaceStorage(newView);
  454. view.ScaleMode = newScaleMode;
  455. }
  456. }
  457. if (ScaleMode != newScaleMode)
  458. {
  459. ScaleMode = newScaleMode;
  460. foreach (var view in _views)
  461. {
  462. view.ScaleMode = newScaleMode;
  463. }
  464. }
  465. }
  466. /// <summary>
  467. /// Checks if the memory for this texture was modified, and returns true if it was.
  468. /// The modified flags are optionally consumed as a result.
  469. /// </summary>
  470. /// <param name="consume">True to consume the dirty flags and reprotect, false to leave them as is</param>
  471. /// <returns>True if the texture was modified, false otherwise.</returns>
  472. public bool CheckModified(bool consume)
  473. {
  474. return Group.CheckDirty(this, consume);
  475. }
  476. /// <summary>
  477. /// Discards all data for this texture.
  478. /// This clears all dirty flags and pending copies from other textures.
  479. /// It should be used if the texture data will be fully overwritten by the next use.
  480. /// </summary>
  481. public void DiscardData()
  482. {
  483. Group.DiscardData(this);
  484. _dirty = false;
  485. }
  486. /// <summary>
  487. /// Synchronizes guest and host memory.
  488. /// This will overwrite the texture data with the texture data on the guest memory, if a CPU
  489. /// modification is detected.
  490. /// Be aware that this can cause texture data written by the GPU to be lost, this is just a
  491. /// one way copy (from CPU owned to GPU owned memory).
  492. /// </summary>
  493. public void SynchronizeMemory()
  494. {
  495. if (Target == Target.TextureBuffer)
  496. {
  497. return;
  498. }
  499. if (!_dirty)
  500. {
  501. return;
  502. }
  503. _dirty = false;
  504. if (_hasData)
  505. {
  506. Group.SynchronizeMemory(this);
  507. }
  508. else
  509. {
  510. Group.CheckDirty(this, true);
  511. SynchronizeFull();
  512. }
  513. }
  514. /// <summary>
  515. /// Signal that this texture is dirty, indicating that the texture group must be checked.
  516. /// </summary>
  517. public void SignalGroupDirty()
  518. {
  519. _dirty = true;
  520. }
  521. /// <summary>
  522. /// Signal that the modified state is dirty, indicating that the texture group should be notified when it changes.
  523. /// </summary>
  524. public void SignalModifiedDirty()
  525. {
  526. _modifiedStale = true;
  527. }
  528. /// <summary>
  529. /// Fully synchronizes guest and host memory.
  530. /// This will replace the entire texture with the data present in guest memory.
  531. /// </summary>
  532. public void SynchronizeFull()
  533. {
  534. ReadOnlySpan<byte> data = _physicalMemory.GetSpan(Range);
  535. // If the host does not support ASTC compression, we need to do the decompression.
  536. // The decompression is slow, so we want to avoid it as much as possible.
  537. // This does a byte-by-byte check and skips the update if the data is equal in this case.
  538. // This improves the speed on applications that overwrites ASTC data without changing anything.
  539. if (Info.FormatInfo.Format.IsAstc() && !_context.Capabilities.SupportsAstcCompression)
  540. {
  541. if (_updateCount < ByteComparisonSwitchThreshold)
  542. {
  543. _updateCount++;
  544. }
  545. else
  546. {
  547. bool dataMatches = _currentData != null && data.SequenceEqual(_currentData);
  548. if (dataMatches)
  549. {
  550. return;
  551. }
  552. _currentData = data.ToArray();
  553. }
  554. }
  555. IMemoryOwner<byte> result = ConvertToHostCompatibleFormat(data);
  556. if (ScaleFactor != 1f && AllowScaledSetData())
  557. {
  558. // If needed, create a texture to load from 1x scale.
  559. ITexture texture = _setHostTexture = GetScaledHostTexture(1f, false, _setHostTexture);
  560. texture.SetData(result);
  561. texture.CopyTo(HostTexture, new Extents2D(0, 0, texture.Width, texture.Height), new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), true);
  562. }
  563. else
  564. {
  565. HostTexture.SetData(result);
  566. }
  567. _hasData = true;
  568. }
  569. /// <summary>
  570. /// Uploads new texture data to the host GPU.
  571. /// </summary>
  572. /// <param name="data">New data</param>
  573. public void SetData(IMemoryOwner<byte> data)
  574. {
  575. BlacklistScale();
  576. Group.CheckDirty(this, true);
  577. AlwaysFlushOnOverlap = true;
  578. HostTexture.SetData(data);
  579. _hasData = true;
  580. }
  581. /// <summary>
  582. /// Uploads new texture data to the host GPU for a specific layer/level.
  583. /// </summary>
  584. /// <param name="data">New data</param>
  585. /// <param name="layer">Target layer</param>
  586. /// <param name="level">Target level</param>
  587. public void SetData(IMemoryOwner<byte> data, int layer, int level)
  588. {
  589. BlacklistScale();
  590. HostTexture.SetData(data, layer, level);
  591. _currentData = null;
  592. _hasData = true;
  593. }
  594. /// <summary>
  595. /// Uploads new texture data to the host GPU for a specific layer/level and 2D sub-region.
  596. /// </summary>
  597. /// <param name="data">New data</param>
  598. /// <param name="layer">Target layer</param>
  599. /// <param name="level">Target level</param>
  600. /// <param name="region">Target sub-region of the texture to update</param>
  601. public void SetData(IMemoryOwner<byte> data, int layer, int level, Rectangle<int> region)
  602. {
  603. BlacklistScale();
  604. HostTexture.SetData(data, layer, level, region);
  605. _currentData = null;
  606. _hasData = true;
  607. }
  608. /// <summary>
  609. /// Converts texture data to a format and layout that is supported by the host GPU.
  610. /// </summary>
  611. /// <param name="data">Data to be converted</param>
  612. /// <param name="level">Mip level to convert</param>
  613. /// <param name="single">True to convert a single slice</param>
  614. /// <returns>Converted data</returns>
  615. public IMemoryOwner<byte> ConvertToHostCompatibleFormat(ReadOnlySpan<byte> data, int level = 0, bool single = false)
  616. {
  617. int width = Info.Width;
  618. int height = Info.Height;
  619. int depth = _depth;
  620. int layers = single ? 1 : _layers;
  621. int levels = single ? 1 : (Info.Levels - level);
  622. width = Math.Max(width >> level, 1);
  623. height = Math.Max(height >> level, 1);
  624. depth = Math.Max(depth >> level, 1);
  625. int sliceDepth = single ? 1 : depth;
  626. IMemoryOwner<byte> linear;
  627. if (Info.IsLinear)
  628. {
  629. linear = LayoutConverter.ConvertLinearStridedToLinear(
  630. width,
  631. height,
  632. Info.FormatInfo.BlockWidth,
  633. Info.FormatInfo.BlockHeight,
  634. Info.Stride,
  635. Info.Stride,
  636. Info.FormatInfo.BytesPerPixel,
  637. data);
  638. }
  639. else
  640. {
  641. linear = LayoutConverter.ConvertBlockLinearToLinear(
  642. width,
  643. height,
  644. depth,
  645. sliceDepth,
  646. levels,
  647. layers,
  648. Info.FormatInfo.BlockWidth,
  649. Info.FormatInfo.BlockHeight,
  650. Info.FormatInfo.BytesPerPixel,
  651. Info.GobBlocksInY,
  652. Info.GobBlocksInZ,
  653. Info.GobBlocksInTileX,
  654. _sizeInfo,
  655. data);
  656. }
  657. IMemoryOwner<byte> result = linear;
  658. // Handle compressed cases not supported by the host:
  659. // - ASTC is usually not supported on desktop cards.
  660. // - BC4/BC5 is not supported on 3D textures.
  661. if (!_context.Capabilities.SupportsAstcCompression && Format.IsAstc())
  662. {
  663. using (result)
  664. {
  665. if (!AstcDecoder.TryDecodeToRgba8P(
  666. result.Memory,
  667. Info.FormatInfo.BlockWidth,
  668. Info.FormatInfo.BlockHeight,
  669. width,
  670. height,
  671. sliceDepth,
  672. levels,
  673. layers,
  674. out IMemoryOwner<byte> decoded))
  675. {
  676. string texInfo = $"{Info.Target} {Info.FormatInfo.Format} {Info.Width}x{Info.Height}x{Info.DepthOrLayers} levels {Info.Levels}";
  677. Logger.Debug?.Print(LogClass.Gpu, $"Invalid ASTC texture at 0x{Info.GpuAddress:X} ({texInfo}).");
  678. }
  679. if (GraphicsConfig.EnableTextureRecompression)
  680. {
  681. using (decoded)
  682. {
  683. return BCnEncoder.EncodeBC7(decoded.Memory, width, height, sliceDepth, levels, layers);
  684. }
  685. }
  686. return decoded;
  687. }
  688. }
  689. else if (!_context.Capabilities.SupportsEtc2Compression && Format.IsEtc2())
  690. {
  691. switch (Format)
  692. {
  693. case Format.Etc2RgbaSrgb:
  694. case Format.Etc2RgbaUnorm:
  695. using (result)
  696. {
  697. return ETC2Decoder.DecodeRgba(result.Memory.Span, width, height, sliceDepth, levels, layers);
  698. }
  699. case Format.Etc2RgbPtaSrgb:
  700. case Format.Etc2RgbPtaUnorm:
  701. using (result)
  702. {
  703. return ETC2Decoder.DecodePta(result.Memory.Span, width, height, sliceDepth, levels, layers);
  704. }
  705. case Format.Etc2RgbSrgb:
  706. case Format.Etc2RgbUnorm:
  707. using (result)
  708. {
  709. return ETC2Decoder.DecodeRgb(result.Memory.Span, width, height, sliceDepth, levels, layers);
  710. }
  711. }
  712. }
  713. else if (!TextureCompatibility.HostSupportsBcFormat(Format, Target, _context.Capabilities))
  714. {
  715. switch (Format)
  716. {
  717. case Format.Bc1RgbaSrgb:
  718. case Format.Bc1RgbaUnorm:
  719. using (result)
  720. {
  721. return BCnDecoder.DecodeBC1(result.Memory.Span, width, height, sliceDepth, levels, layers);
  722. }
  723. case Format.Bc2Srgb:
  724. case Format.Bc2Unorm:
  725. using (result)
  726. {
  727. return BCnDecoder.DecodeBC2(result.Memory.Span, width, height, sliceDepth, levels, layers);
  728. }
  729. case Format.Bc3Srgb:
  730. case Format.Bc3Unorm:
  731. using (result)
  732. {
  733. return BCnDecoder.DecodeBC3(result.Memory.Span, width, height, sliceDepth, levels, layers);
  734. }
  735. case Format.Bc4Snorm:
  736. case Format.Bc4Unorm:
  737. using (result)
  738. {
  739. return BCnDecoder.DecodeBC4(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc4Snorm);
  740. }
  741. case Format.Bc5Snorm:
  742. case Format.Bc5Unorm:
  743. using (result)
  744. {
  745. return BCnDecoder.DecodeBC5(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc5Snorm);
  746. }
  747. case Format.Bc6HSfloat:
  748. case Format.Bc6HUfloat:
  749. using (result)
  750. {
  751. return BCnDecoder.DecodeBC6(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc6HSfloat);
  752. }
  753. case Format.Bc7Srgb:
  754. case Format.Bc7Unorm:
  755. using (result)
  756. {
  757. return BCnDecoder.DecodeBC7(result.Memory.Span, width, height, sliceDepth, levels, layers);
  758. }
  759. }
  760. }
  761. else if (!_context.Capabilities.SupportsR4G4Format && Format == Format.R4G4Unorm)
  762. {
  763. using (result)
  764. {
  765. var converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Memory.Span, width);
  766. if (_context.Capabilities.SupportsR4G4B4A4Format)
  767. {
  768. return converted;
  769. }
  770. else
  771. {
  772. using (converted)
  773. {
  774. return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(converted.Memory.Span, width);
  775. }
  776. }
  777. }
  778. }
  779. else if (Format == Format.R4G4B4A4Unorm)
  780. {
  781. if (!_context.Capabilities.SupportsR4G4B4A4Format)
  782. {
  783. using (result)
  784. {
  785. return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result.Memory.Span, width);
  786. }
  787. }
  788. }
  789. else if (!_context.Capabilities.Supports5BitComponentFormat && Format.Is16BitPacked())
  790. {
  791. switch (Format)
  792. {
  793. case Format.B5G6R5Unorm:
  794. case Format.R5G6B5Unorm:
  795. using (result)
  796. {
  797. return PixelConverter.ConvertR5G6B5ToR8G8B8A8(result.Memory.Span, width);
  798. }
  799. case Format.B5G5R5A1Unorm:
  800. case Format.R5G5B5X1Unorm:
  801. case Format.R5G5B5A1Unorm:
  802. using (result)
  803. {
  804. return PixelConverter.ConvertR5G5B5ToR8G8B8A8(result.Memory.Span, width, Format == Format.R5G5B5X1Unorm);
  805. }
  806. case Format.A1B5G5R5Unorm:
  807. using (result)
  808. {
  809. return PixelConverter.ConvertA1B5G5R5ToR8G8B8A8(result.Memory.Span, width);
  810. }
  811. case Format.R4G4B4A4Unorm:
  812. using (result)
  813. {
  814. return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result.Memory.Span, width);
  815. }
  816. }
  817. }
  818. return result;
  819. }
  820. /// <summary>
  821. /// Converts texture data from a format and layout that is supported by the host GPU, back into the intended format on the guest GPU.
  822. /// </summary>
  823. /// <param name="output">Optional output span to convert into</param>
  824. /// <param name="data">Data to be converted</param>
  825. /// <param name="level">Mip level to convert</param>
  826. /// <param name="single">True to convert a single slice</param>
  827. /// <returns>Converted data</returns>
  828. public ReadOnlySpan<byte> ConvertFromHostCompatibleFormat(Span<byte> output, ReadOnlySpan<byte> data, int level = 0, bool single = false)
  829. {
  830. if (Target != Target.TextureBuffer)
  831. {
  832. int width = Info.Width;
  833. int height = Info.Height;
  834. int depth = _depth;
  835. int layers = single ? 1 : _layers;
  836. int levels = single ? 1 : (Info.Levels - level);
  837. width = Math.Max(width >> level, 1);
  838. height = Math.Max(height >> level, 1);
  839. depth = Math.Max(depth >> level, 1);
  840. if (Info.IsLinear)
  841. {
  842. data = LayoutConverter.ConvertLinearToLinearStrided(
  843. output,
  844. Info.Width,
  845. Info.Height,
  846. Info.FormatInfo.BlockWidth,
  847. Info.FormatInfo.BlockHeight,
  848. Info.Stride,
  849. Info.FormatInfo.BytesPerPixel,
  850. data);
  851. }
  852. else
  853. {
  854. data = LayoutConverter.ConvertLinearToBlockLinear(
  855. output,
  856. width,
  857. height,
  858. depth,
  859. single ? 1 : depth,
  860. levels,
  861. layers,
  862. Info.FormatInfo.BlockWidth,
  863. Info.FormatInfo.BlockHeight,
  864. Info.FormatInfo.BytesPerPixel,
  865. Info.GobBlocksInY,
  866. Info.GobBlocksInZ,
  867. Info.GobBlocksInTileX,
  868. _sizeInfo,
  869. data);
  870. }
  871. }
  872. return data;
  873. }
  874. /// <summary>
  875. /// Flushes the texture data.
  876. /// This causes the texture data to be written back to guest memory.
  877. /// If the texture was written by the GPU, this includes all modification made by the GPU
  878. /// up to this point.
  879. /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
  880. /// This may cause data corruption if the memory is already being used for something else on the CPU side.
  881. /// </summary>
  882. /// <param name="tracked">Whether or not the flush triggers write tracking. If it doesn't, the texture will not be blacklisted for scaling either.</param>
  883. /// <returns>True if data was flushed, false otherwise</returns>
  884. public bool FlushModified(bool tracked = true)
  885. {
  886. return TextureCompatibility.CanTextureFlush(Info, _context.Capabilities) && Group.FlushModified(this, tracked);
  887. }
  888. /// <summary>
  889. /// Flushes the texture data.
  890. /// This causes the texture data to be written back to guest memory.
  891. /// If the texture was written by the GPU, this includes all modification made by the GPU
  892. /// up to this point.
  893. /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
  894. /// This may cause data corruption if the memory is already being used for something else on the CPU side.
  895. /// </summary>
  896. /// <param name="tracked">Whether or not the flush triggers write tracking. If it doesn't, the texture will not be blacklisted for scaling either.</param>
  897. public void Flush(bool tracked)
  898. {
  899. if (TextureCompatibility.CanTextureFlush(Info, _context.Capabilities))
  900. {
  901. FlushTextureDataToGuest(tracked);
  902. }
  903. }
  904. /// <summary>
  905. /// Gets a host texture to use for flushing the texture, at 1x resolution.
  906. /// If the HostTexture is already at 1x resolution, it is returned directly.
  907. /// </summary>
  908. /// <returns>The host texture to flush</returns>
  909. public ITexture GetFlushTexture()
  910. {
  911. ITexture texture = HostTexture;
  912. if (ScaleFactor != 1f)
  913. {
  914. // If needed, create a texture to flush back to host at 1x scale.
  915. texture = _flushHostTexture = GetScaledHostTexture(1f, true, _flushHostTexture);
  916. }
  917. return texture;
  918. }
  919. /// <summary>
  920. /// Gets data from the host GPU, and flushes it all to guest memory.
  921. /// </summary>
  922. /// <remarks>
  923. /// This method should be used to retrieve data that was modified by the host GPU.
  924. /// This is not cheap, avoid doing that unless strictly needed.
  925. /// When possible, the data is written directly into guest memory, rather than copied.
  926. /// </remarks>
  927. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  928. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  929. public void FlushTextureDataToGuest(bool tracked, ITexture texture = null)
  930. {
  931. using WritableRegion region = _physicalMemory.GetWritableRegion(Range, tracked);
  932. GetTextureDataFromGpu(region.Memory.Span, tracked, texture);
  933. }
  934. /// <summary>
  935. /// Gets data from the host GPU.
  936. /// </summary>
  937. /// <remarks>
  938. /// This method should be used to retrieve data that was modified by the host GPU.
  939. /// This is not cheap, avoid doing that unless strictly needed.
  940. /// </remarks>
  941. /// <param name="output">An output span to place the texture data into</param>
  942. /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
  943. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  944. private void GetTextureDataFromGpu(Span<byte> output, bool blacklist, ITexture texture = null)
  945. {
  946. PinnedSpan<byte> data;
  947. if (texture != null)
  948. {
  949. data = texture.GetData();
  950. }
  951. else
  952. {
  953. if (blacklist)
  954. {
  955. BlacklistScale();
  956. data = HostTexture.GetData();
  957. }
  958. else if (ScaleFactor != 1f)
  959. {
  960. float scale = ScaleFactor;
  961. SetScale(1f);
  962. data = HostTexture.GetData();
  963. SetScale(scale);
  964. }
  965. else
  966. {
  967. data = HostTexture.GetData();
  968. }
  969. }
  970. ConvertFromHostCompatibleFormat(output, data.Get());
  971. data.Dispose();
  972. }
  973. /// <summary>
  974. /// Gets data from the host GPU for a single slice.
  975. /// </summary>
  976. /// <remarks>
  977. /// This method should be used to retrieve data that was modified by the host GPU.
  978. /// This is not cheap, avoid doing that unless strictly needed.
  979. /// </remarks>
  980. /// <param name="output">An output span to place the texture data into. If empty, one is generated</param>
  981. /// <param name="layer">The layer of the texture to flush</param>
  982. /// <param name="level">The level of the texture to flush</param>
  983. /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
  984. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  985. public void GetTextureDataSliceFromGpu(Span<byte> output, int layer, int level, bool blacklist, ITexture texture = null)
  986. {
  987. PinnedSpan<byte> data;
  988. if (texture != null)
  989. {
  990. data = texture.GetData(layer, level);
  991. }
  992. else
  993. {
  994. if (blacklist)
  995. {
  996. BlacklistScale();
  997. data = HostTexture.GetData(layer, level);
  998. }
  999. else if (ScaleFactor != 1f)
  1000. {
  1001. float scale = ScaleFactor;
  1002. SetScale(1f);
  1003. data = HostTexture.GetData(layer, level);
  1004. SetScale(scale);
  1005. }
  1006. else
  1007. {
  1008. data = HostTexture.GetData(layer, level);
  1009. }
  1010. }
  1011. ConvertFromHostCompatibleFormat(output, data.Get(), level, true);
  1012. data.Dispose();
  1013. }
  1014. /// <summary>
  1015. /// This performs a strict comparison, used to check if this texture is equal to the one supplied.
  1016. /// </summary>
  1017. /// <param name="info">Texture information to compare against</param>
  1018. /// <param name="flags">Comparison flags</param>
  1019. /// <returns>A value indicating how well this texture matches the given info</returns>
  1020. public TextureMatchQuality IsExactMatch(TextureInfo info, TextureSearchFlags flags)
  1021. {
  1022. bool forSampler = (flags & TextureSearchFlags.ForSampler) != 0;
  1023. TextureMatchQuality matchQuality = TextureCompatibility.FormatMatches(Info, info, forSampler, (flags & TextureSearchFlags.DepthAlias) != 0);
  1024. if (matchQuality == TextureMatchQuality.NoMatch)
  1025. {
  1026. return matchQuality;
  1027. }
  1028. if (!TextureCompatibility.LayoutMatches(Info, info))
  1029. {
  1030. return TextureMatchQuality.NoMatch;
  1031. }
  1032. if (!TextureCompatibility.SizeMatches(Info, info, forSampler))
  1033. {
  1034. return TextureMatchQuality.NoMatch;
  1035. }
  1036. if ((flags & TextureSearchFlags.ForSampler) != 0)
  1037. {
  1038. if (!TextureCompatibility.SamplerParamsMatches(Info, info))
  1039. {
  1040. return TextureMatchQuality.NoMatch;
  1041. }
  1042. }
  1043. if ((flags & TextureSearchFlags.ForCopy) != 0)
  1044. {
  1045. bool msTargetCompatible = Info.Target == Target.Texture2DMultisample && info.Target == Target.Texture2D;
  1046. if (!msTargetCompatible && !TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  1047. {
  1048. return TextureMatchQuality.NoMatch;
  1049. }
  1050. }
  1051. else if (!TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  1052. {
  1053. return TextureMatchQuality.NoMatch;
  1054. }
  1055. return Info.Levels == info.Levels ? matchQuality : TextureMatchQuality.NoMatch;
  1056. }
  1057. /// <summary>
  1058. /// Check if it's possible to create a view, with the given parameters, from this texture.
  1059. /// </summary>
  1060. /// <param name="info">Texture view information</param>
  1061. /// <param name="range">Texture view physical memory ranges</param>
  1062. /// <param name="exactSize">Indicates if the texture sizes must be exactly equal, or width is allowed to differ</param>
  1063. /// <param name="layerSize">Layer size on the given texture</param>
  1064. /// <param name="caps">Host GPU capabilities</param>
  1065. /// <param name="firstLayer">Texture view initial layer on this texture</param>
  1066. /// <param name="firstLevel">Texture view first mipmap level on this texture</param>
  1067. /// <param name="flags">Texture search flags</param>
  1068. /// <returns>The level of compatiblilty a view with the given parameters created from this texture has</returns>
  1069. public TextureViewCompatibility IsViewCompatible(
  1070. TextureInfo info,
  1071. MultiRange range,
  1072. bool exactSize,
  1073. int layerSize,
  1074. Capabilities caps,
  1075. out int firstLayer,
  1076. out int firstLevel,
  1077. TextureSearchFlags flags = TextureSearchFlags.None)
  1078. {
  1079. TextureViewCompatibility result = TextureViewCompatibility.Full;
  1080. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewFormatCompatible(Info, info, caps, flags));
  1081. if (result != TextureViewCompatibility.Incompatible)
  1082. {
  1083. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewTargetCompatible(Info, info, ref caps));
  1084. bool bothMs = Info.Target.IsMultisample() && info.Target.IsMultisample();
  1085. if (bothMs && (Info.SamplesInX != info.SamplesInX || Info.SamplesInY != info.SamplesInY))
  1086. {
  1087. result = TextureViewCompatibility.Incompatible;
  1088. }
  1089. if (result == TextureViewCompatibility.Full && Info.FormatInfo.Format != info.FormatInfo.Format && !_context.Capabilities.SupportsMismatchingViewFormat)
  1090. {
  1091. // AMD and Intel have a bug where the view format is always ignored;
  1092. // they use the parent format instead.
  1093. // Create a copy dependency to avoid this issue.
  1094. result = TextureViewCompatibility.CopyOnly;
  1095. }
  1096. }
  1097. firstLayer = 0;
  1098. firstLevel = 0;
  1099. if (result == TextureViewCompatibility.Incompatible)
  1100. {
  1101. return TextureViewCompatibility.Incompatible;
  1102. }
  1103. int offset = Range.FindOffset(range);
  1104. if (offset < 0 || !_sizeInfo.FindView(offset, out firstLayer, out firstLevel))
  1105. {
  1106. return TextureViewCompatibility.LayoutIncompatible;
  1107. }
  1108. if (!TextureCompatibility.ViewLayoutCompatible(Info, info, firstLevel))
  1109. {
  1110. return TextureViewCompatibility.LayoutIncompatible;
  1111. }
  1112. if (info.GetSlices() > 1 && LayerSize != layerSize)
  1113. {
  1114. return TextureViewCompatibility.LayoutIncompatible;
  1115. }
  1116. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSizeMatches(Info, info, exactSize, firstLevel));
  1117. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSubImagesInBounds(Info, info, firstLayer, firstLevel));
  1118. return result;
  1119. }
  1120. /// <summary>
  1121. /// Gets a texture of the specified target type from this texture.
  1122. /// This can be used to get an array texture from a non-array texture and vice-versa.
  1123. /// If this texture and the requested targets are equal, then this texture Host texture is returned directly.
  1124. /// </summary>
  1125. /// <param name="target">The desired target type</param>
  1126. /// <returns>A view of this texture with the requested target, or null if the target is invalid for this texture</returns>
  1127. public ITexture GetTargetTexture(Target target)
  1128. {
  1129. if (target == Target)
  1130. {
  1131. return HostTexture;
  1132. }
  1133. if (_arrayViewTexture == null && IsSameDimensionsTarget(target))
  1134. {
  1135. FormatInfo formatInfo = TextureCompatibility.ToHostCompatibleFormat(Info, _context.Capabilities);
  1136. TextureCreateInfo createInfo = new(
  1137. Info.Width,
  1138. Info.Height,
  1139. target == Target.CubemapArray ? 6 : 1,
  1140. Info.Levels,
  1141. Info.Samples,
  1142. formatInfo.BlockWidth,
  1143. formatInfo.BlockHeight,
  1144. formatInfo.BytesPerPixel,
  1145. formatInfo.Format,
  1146. Info.DepthStencilMode,
  1147. target,
  1148. Info.SwizzleR,
  1149. Info.SwizzleG,
  1150. Info.SwizzleB,
  1151. Info.SwizzleA);
  1152. ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0);
  1153. _arrayViewTexture = viewTexture;
  1154. _arrayViewTarget = target;
  1155. return viewTexture;
  1156. }
  1157. else if (_arrayViewTarget == target)
  1158. {
  1159. return _arrayViewTexture;
  1160. }
  1161. return null;
  1162. }
  1163. /// <summary>
  1164. /// Determine if this texture can have anisotropic filtering forced.
  1165. /// Filtered textures that we might want to force anisotropy on should have a lot of mip levels.
  1166. /// </summary>
  1167. /// <returns>True if anisotropic filtering can be forced, false otherwise</returns>
  1168. private bool CanTextureForceAnisotropy()
  1169. {
  1170. if (!(Target == Target.Texture2D || Target == Target.Texture2DArray))
  1171. {
  1172. return false;
  1173. }
  1174. int maxSize = Math.Max(Info.Width, Info.Height);
  1175. int maxLevels = BitOperations.Log2((uint)maxSize) + 1;
  1176. return Info.Levels >= Math.Min(MinLevelsForForceAnisotropy, maxLevels);
  1177. }
  1178. /// <summary>
  1179. /// Check if this texture and the specified target have the same number of dimensions.
  1180. /// For the purposes of this comparison, 2D and 2D Multisample textures are not considered to have
  1181. /// the same number of dimensions. Same for Cubemap and 3D textures.
  1182. /// </summary>
  1183. /// <param name="target">The target to compare with</param>
  1184. /// <returns>True if both targets have the same number of dimensions, false otherwise</returns>
  1185. private bool IsSameDimensionsTarget(Target target)
  1186. {
  1187. switch (Info.Target)
  1188. {
  1189. case Target.Texture1D:
  1190. case Target.Texture1DArray:
  1191. return target == Target.Texture1D || target == Target.Texture1DArray;
  1192. case Target.Texture2D:
  1193. case Target.Texture2DArray:
  1194. return target == Target.Texture2D || target == Target.Texture2DArray;
  1195. case Target.Cubemap:
  1196. case Target.CubemapArray:
  1197. return target == Target.Cubemap || target == Target.CubemapArray;
  1198. case Target.Texture2DMultisample:
  1199. case Target.Texture2DMultisampleArray:
  1200. return target == Target.Texture2DMultisample || target == Target.Texture2DMultisampleArray;
  1201. case Target.Texture3D:
  1202. return target == Target.Texture3D;
  1203. default:
  1204. return false;
  1205. }
  1206. }
  1207. /// <summary>
  1208. /// Replaces view texture information.
  1209. /// This should only be used for child textures with a parent.
  1210. /// </summary>
  1211. /// <param name="parent">The parent texture</param>
  1212. /// <param name="info">The new view texture information</param>
  1213. /// <param name="hostTexture">The new host texture</param>
  1214. /// <param name="firstLayer">The first layer of the view</param>
  1215. /// <param name="firstLevel">The first level of the view</param>
  1216. public void ReplaceView(Texture parent, TextureInfo info, ITexture hostTexture, int firstLayer, int firstLevel)
  1217. {
  1218. IncrementReferenceCount();
  1219. parent._viewStorage.SynchronizeMemory();
  1220. // If this texture has views, they must be given to the new parent.
  1221. if (_views.Count > 0)
  1222. {
  1223. Texture[] viewCopy = _views.ToArray();
  1224. foreach (Texture view in viewCopy)
  1225. {
  1226. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, ScaleFactor);
  1227. ITexture newView = parent.HostTexture.CreateView(createInfo, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);
  1228. view.ReplaceView(parent, view.Info, newView, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);
  1229. }
  1230. }
  1231. ReplaceStorage(hostTexture);
  1232. if (_viewStorage != this)
  1233. {
  1234. _viewStorage.RemoveView(this);
  1235. }
  1236. FirstLayer = parent.FirstLayer + firstLayer;
  1237. FirstLevel = parent.FirstLevel + firstLevel;
  1238. parent._viewStorage.AddView(this);
  1239. SetInfo(info);
  1240. DecrementReferenceCount();
  1241. }
  1242. /// <summary>
  1243. /// Sets the internal texture information structure.
  1244. /// </summary>
  1245. /// <param name="info">The new texture information</param>
  1246. private void SetInfo(TextureInfo info)
  1247. {
  1248. Info = info;
  1249. Target = info.Target;
  1250. Width = info.Width;
  1251. Height = info.Height;
  1252. CanForceAnisotropy = CanTextureForceAnisotropy();
  1253. _depth = info.GetDepth();
  1254. _layers = info.GetLayers();
  1255. }
  1256. /// <summary>
  1257. /// Signals that the texture has been modified.
  1258. /// </summary>
  1259. public void SignalModified()
  1260. {
  1261. _scaledSetScore = Math.Max(0, _scaledSetScore - 1);
  1262. if (_modifiedStale || Group.HasCopyDependencies)
  1263. {
  1264. _modifiedStale = false;
  1265. Group.SignalModified(this);
  1266. }
  1267. _physicalMemory.TextureCache.Lift(this);
  1268. }
  1269. /// <summary>
  1270. /// Signals that a texture has been bound, or has been unbound.
  1271. /// During this time, lazy copies will not clear the dirty flag.
  1272. /// </summary>
  1273. /// <param name="bound">True if the texture has been bound, false if it has been unbound</param>
  1274. public void SignalModifying(bool bound)
  1275. {
  1276. if (bound)
  1277. {
  1278. _scaledSetScore = Math.Max(0, _scaledSetScore - 1);
  1279. }
  1280. if (_modifiedStale || Group.HasCopyDependencies || Group.HasFlushBuffer)
  1281. {
  1282. _modifiedStale = false;
  1283. Group.SignalModifying(this, bound);
  1284. }
  1285. _physicalMemory.TextureCache.Lift(this);
  1286. if (bound)
  1287. {
  1288. IncrementReferenceCount();
  1289. }
  1290. else
  1291. {
  1292. DecrementReferenceCount();
  1293. }
  1294. }
  1295. /// <summary>
  1296. /// Replaces the host texture, while disposing of the old one if needed.
  1297. /// </summary>
  1298. /// <param name="hostTexture">The new host texture</param>
  1299. private void ReplaceStorage(ITexture hostTexture)
  1300. {
  1301. DisposeTextures();
  1302. HostTexture = hostTexture;
  1303. }
  1304. /// <summary>
  1305. /// Determine if any of this texture's data overlaps with another.
  1306. /// </summary>
  1307. /// <param name="texture">The texture to check against</param>
  1308. /// <param name="compatibility">The view compatibility of the two textures</param>
  1309. /// <returns>True if any slice of the textures overlap, false otherwise</returns>
  1310. public bool DataOverlaps(Texture texture, TextureViewCompatibility compatibility)
  1311. {
  1312. if (compatibility == TextureViewCompatibility.LayoutIncompatible && Info.GobBlocksInZ > 1 && Info.GobBlocksInZ == texture.Info.GobBlocksInZ)
  1313. {
  1314. // Allow overlapping slices of layout compatible 3D textures with matching GobBlocksInZ, as they are interleaved.
  1315. return false;
  1316. }
  1317. if (texture._sizeInfo.AllOffsets.Length == 1 && _sizeInfo.AllOffsets.Length == 1)
  1318. {
  1319. return Range.OverlapsWith(texture.Range);
  1320. }
  1321. MultiRange otherRange = texture.Range;
  1322. IEnumerable<MultiRange> regions = _sizeInfo.AllRegions().Select((region) => Range.Slice((ulong)region.Offset, (ulong)region.Size));
  1323. IEnumerable<MultiRange> otherRegions = texture._sizeInfo.AllRegions().Select((region) => otherRange.Slice((ulong)region.Offset, (ulong)region.Size));
  1324. foreach (MultiRange region in regions)
  1325. {
  1326. foreach (MultiRange otherRegion in otherRegions)
  1327. {
  1328. if (region.OverlapsWith(otherRegion))
  1329. {
  1330. return true;
  1331. }
  1332. }
  1333. }
  1334. return false;
  1335. }
  1336. /// <summary>
  1337. /// Increments the texture reference count.
  1338. /// </summary>
  1339. public void IncrementReferenceCount()
  1340. {
  1341. _referenceCount++;
  1342. }
  1343. /// <summary>
  1344. /// Increments the reference count and records the given texture pool and ID as a pool owner.
  1345. /// </summary>
  1346. /// <param name="pool">The texture pool this texture has been added to</param>
  1347. /// <param name="id">The ID of the reference to this texture in the pool</param>
  1348. /// <param name="gpuVa">GPU VA of the pool reference</param>
  1349. public void IncrementReferenceCount(TexturePool pool, int id, ulong gpuVa)
  1350. {
  1351. HadPoolOwner = true;
  1352. lock (_poolOwners)
  1353. {
  1354. _poolOwners.Add(new TexturePoolOwner { Pool = pool, ID = id, GpuAddress = gpuVa });
  1355. }
  1356. _referenceCount++;
  1357. if (ShortCacheEntry != null)
  1358. {
  1359. _physicalMemory.TextureCache.RemoveShortCache(this);
  1360. }
  1361. }
  1362. /// <summary>
  1363. /// Indicates that the texture has one reference left, and will delete on reference decrement.
  1364. /// </summary>
  1365. /// <returns>True if there is one reference remaining, false otherwise</returns>
  1366. public bool HasOneReference()
  1367. {
  1368. return _referenceCount == 1;
  1369. }
  1370. /// <summary>
  1371. /// Decrements the texture reference count.
  1372. /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
  1373. /// </summary>
  1374. /// <returns>True if the texture is now referenceless, false otherwise</returns>
  1375. public bool DecrementReferenceCount()
  1376. {
  1377. int newRefCount = --_referenceCount;
  1378. if (newRefCount == 0)
  1379. {
  1380. if (_viewStorage != this)
  1381. {
  1382. _viewStorage.RemoveView(this);
  1383. }
  1384. _physicalMemory.TextureCache.RemoveTextureFromCache(this);
  1385. }
  1386. Debug.Assert(newRefCount >= 0);
  1387. DeleteIfNotUsed();
  1388. return newRefCount <= 0;
  1389. }
  1390. /// <summary>
  1391. /// Decrements the texture reference count, also removing an associated pool owner reference.
  1392. /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
  1393. /// </summary>
  1394. /// <param name="pool">The texture pool this texture is being removed from</param>
  1395. /// <param name="id">The ID of the reference to this texture in the pool</param>
  1396. /// <returns>True if the texture is now referenceless, false otherwise</returns>
  1397. public bool DecrementReferenceCount(TexturePool pool, int id = -1)
  1398. {
  1399. lock (_poolOwners)
  1400. {
  1401. int references = _poolOwners.RemoveAll(entry => entry.Pool == pool && entry.ID == id || id == -1);
  1402. if (references == 0)
  1403. {
  1404. // This reference has already been removed.
  1405. return _referenceCount <= 0;
  1406. }
  1407. Debug.Assert(references == 1);
  1408. }
  1409. return DecrementReferenceCount();
  1410. }
  1411. /// <summary>
  1412. /// Forcibly remove this texture from all pools that reference it.
  1413. /// </summary>
  1414. /// <param name="deferred">Indicates if the removal is being done from another thread.</param>
  1415. public void RemoveFromPools(bool deferred)
  1416. {
  1417. lock (_poolOwners)
  1418. {
  1419. foreach (var owner in _poolOwners)
  1420. {
  1421. owner.Pool.ForceRemove(this, owner.ID, deferred);
  1422. }
  1423. _poolOwners.Clear();
  1424. }
  1425. if (ShortCacheEntry != null && !ShortCacheEntry.IsAutoDelete && _context.IsGpuThread())
  1426. {
  1427. // If this is called from another thread (unmapped), the short cache will
  1428. // have to remove this texture on a future tick.
  1429. _physicalMemory.TextureCache.RemoveShortCache(this);
  1430. }
  1431. InvalidatedSequence++;
  1432. }
  1433. /// <summary>
  1434. /// Queue updating texture mappings on the pool. Happens from another thread.
  1435. /// </summary>
  1436. public void UpdatePoolMappings()
  1437. {
  1438. ChangedMapping = true;
  1439. lock (_poolOwners)
  1440. {
  1441. ulong address = 0;
  1442. foreach (var owner in _poolOwners)
  1443. {
  1444. if (address == 0 || address == owner.GpuAddress)
  1445. {
  1446. address = owner.GpuAddress;
  1447. owner.Pool.QueueUpdateMapping(this, owner.ID);
  1448. }
  1449. else
  1450. {
  1451. // If there is a different GPU VA mapping, prefer the first and delete the others.
  1452. owner.Pool.ForceRemove(this, owner.ID, true);
  1453. }
  1454. }
  1455. _poolOwners.Clear();
  1456. }
  1457. InvalidatedSequence++;
  1458. }
  1459. /// <summary>
  1460. /// Delete the texture if it is not used anymore.
  1461. /// The texture is considered unused when the reference count is zero,
  1462. /// and it has no child views.
  1463. /// </summary>
  1464. private void DeleteIfNotUsed()
  1465. {
  1466. // We can delete the texture as long it is not being used
  1467. // in any cache (the reference count is 0 in this case), and
  1468. // also all views that may be created from this texture were
  1469. // already deleted (views count is 0).
  1470. if (_referenceCount == 0 && _views.Count == 0)
  1471. {
  1472. Dispose();
  1473. }
  1474. }
  1475. /// <summary>
  1476. /// Performs texture disposal, deleting the texture.
  1477. /// </summary>
  1478. private void DisposeTextures()
  1479. {
  1480. InvalidatedSequence++;
  1481. _currentData = null;
  1482. HostTexture.Release();
  1483. _arrayViewTexture?.Release();
  1484. _arrayViewTexture = null;
  1485. _flushHostTexture?.Release();
  1486. _flushHostTexture = null;
  1487. _setHostTexture?.Release();
  1488. _setHostTexture = null;
  1489. }
  1490. /// <summary>
  1491. /// Called when the memory for this texture has been unmapped.
  1492. /// Calls are from non-gpu threads.
  1493. /// </summary>
  1494. /// <param name="unmapRange">The range of memory being unmapped</param>
  1495. public void Unmapped(MultiRange unmapRange)
  1496. {
  1497. ChangedMapping = true;
  1498. if (Group.Storage == this)
  1499. {
  1500. Group.Unmapped();
  1501. Group.ClearModified(unmapRange);
  1502. }
  1503. }
  1504. /// <summary>
  1505. /// Performs texture disposal, deleting the texture.
  1506. /// </summary>
  1507. public void Dispose()
  1508. {
  1509. DisposeTextures();
  1510. if (Group.Storage == this)
  1511. {
  1512. Group.Dispose();
  1513. }
  1514. }
  1515. }
  1516. }