TextureGroupHandle.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using Ryujinx.Cpu.Tracking;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. namespace Ryujinx.Graphics.Gpu.Image
  7. {
  8. /// <summary>
  9. /// A tracking handle for a texture group, which represents a range of views in a storage texture.
  10. /// Retains a list of overlapping texture views, a modified flag, and tracking for each
  11. /// CPU VA range that the views cover.
  12. /// Also tracks copy dependencies for the handle - references to other handles that must be kept
  13. /// in sync with this one before use.
  14. /// </summary>
  15. class TextureGroupHandle : IDisposable
  16. {
  17. private TextureGroup _group;
  18. private int _bindCount;
  19. private int _firstLevel;
  20. private int _firstLayer;
  21. // Sync state for texture flush.
  22. /// <summary>
  23. /// The sync number last registered.
  24. /// </summary>
  25. private ulong _registeredSync;
  26. /// <summary>
  27. /// The sync number when the texture was last modified by GPU.
  28. /// </summary>
  29. private ulong _modifiedSync;
  30. /// <summary>
  31. /// Whether a tracking action is currently registered or not. (0/1)
  32. /// </summary>
  33. private int _actionRegistered;
  34. /// <summary>
  35. /// Whether a sync action is currently registered or not.
  36. /// </summary>
  37. private bool _syncActionRegistered;
  38. /// <summary>
  39. /// The byte offset from the start of the storage of this handle.
  40. /// </summary>
  41. public int Offset { get; }
  42. /// <summary>
  43. /// The size in bytes covered by this handle.
  44. /// </summary>
  45. public int Size { get; }
  46. /// <summary>
  47. /// The base slice index for this handle.
  48. /// </summary>
  49. public int BaseSlice { get; }
  50. /// <summary>
  51. /// The number of slices covered by this handle.
  52. /// </summary>
  53. public int SliceCount { get; }
  54. /// <summary>
  55. /// The textures which this handle overlaps with.
  56. /// </summary>
  57. public List<Texture> Overlaps { get; }
  58. /// <summary>
  59. /// The CPU memory tracking handles that cover this handle.
  60. /// </summary>
  61. public CpuRegionHandle[] Handles { get; }
  62. /// <summary>
  63. /// True if a texture overlapping this handle has been modified. Is set false when the flush action is called.
  64. /// </summary>
  65. public bool Modified { get; set; }
  66. /// <summary>
  67. /// Dependencies to handles from other texture groups.
  68. /// </summary>
  69. public List<TextureDependency> Dependencies { get; }
  70. /// <summary>
  71. /// A flag indicating that a copy is required from one of the dependencies.
  72. /// </summary>
  73. public bool NeedsCopy => DeferredCopy != null;
  74. /// <summary>
  75. /// A data copy that must be acknowledged the next time this handle is used.
  76. /// </summary>
  77. public TextureGroupHandle DeferredCopy { get; set; }
  78. /// <summary>
  79. /// Create a new texture group handle, representing a range of views in a storage texture.
  80. /// </summary>
  81. /// <param name="group">The TextureGroup that the handle belongs to</param>
  82. /// <param name="offset">The byte offset from the start of the storage of the handle</param>
  83. /// <param name="size">The size in bytes covered by the handle</param>
  84. /// <param name="views">All views of the storage texture, used to calculate overlaps</param>
  85. /// <param name="firstLayer">The first layer of this handle in the storage texture</param>
  86. /// <param name="firstLevel">The first level of this handle in the storage texture</param>
  87. /// <param name="baseSlice">The base slice index of this handle</param>
  88. /// <param name="sliceCount">The number of slices this handle covers</param>
  89. /// <param name="handles">The memory tracking handles that cover this handle</param>
  90. public TextureGroupHandle(TextureGroup group,
  91. int offset,
  92. ulong size,
  93. List<Texture> views,
  94. int firstLayer,
  95. int firstLevel,
  96. int baseSlice,
  97. int sliceCount,
  98. CpuRegionHandle[] handles)
  99. {
  100. _group = group;
  101. _firstLayer = firstLayer;
  102. _firstLevel = firstLevel;
  103. Offset = offset;
  104. Size = (int)size;
  105. Overlaps = new List<Texture>();
  106. Dependencies = new List<TextureDependency>();
  107. BaseSlice = baseSlice;
  108. SliceCount = sliceCount;
  109. if (views != null)
  110. {
  111. RecalculateOverlaps(group, views);
  112. }
  113. Handles = handles;
  114. }
  115. /// <summary>
  116. /// Calculate a list of which views overlap this handle.
  117. /// </summary>
  118. /// <param name="group">The parent texture group, used to find a view's base CPU VA offset</param>
  119. /// <param name="views">The list of views to search for overlaps</param>
  120. public void RecalculateOverlaps(TextureGroup group, List<Texture> views)
  121. {
  122. // Overlaps can be accessed from the memory tracking signal handler, so access must be atomic.
  123. lock (Overlaps)
  124. {
  125. int endOffset = Offset + Size;
  126. Overlaps.Clear();
  127. foreach (Texture view in views)
  128. {
  129. int viewOffset = group.FindOffset(view);
  130. if (viewOffset < endOffset && Offset < viewOffset + (int)view.Size)
  131. {
  132. Overlaps.Add(view);
  133. }
  134. }
  135. }
  136. }
  137. /// <summary>
  138. /// Adds a single texture view as an overlap if its range overlaps.
  139. /// </summary>
  140. /// <param name="offset">The offset of the view in the group</param>
  141. /// <param name="view">The texture to add as an overlap</param>
  142. public void AddOverlap(int offset, Texture view)
  143. {
  144. // Overlaps can be accessed from the memory tracking signal handler, so access must be atomic.
  145. if (OverlapsWith(offset, (int)view.Size))
  146. {
  147. lock (Overlaps)
  148. {
  149. Overlaps.Add(view);
  150. }
  151. }
  152. }
  153. /// <summary>
  154. /// Removes a single texture view as an overlap if its range overlaps.
  155. /// </summary>
  156. /// <param name="offset">The offset of the view in the group</param>
  157. /// <param name="view">The texture to add as an overlap</param>
  158. public void RemoveOverlap(int offset, Texture view)
  159. {
  160. // Overlaps can be accessed from the memory tracking signal handler, so access must be atomic.
  161. if (OverlapsWith(offset, (int)view.Size))
  162. {
  163. lock (Overlaps)
  164. {
  165. Overlaps.Remove(view);
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// Registers a sync action to happen for this handle, and an interim flush action on the tracking handle.
  171. /// </summary>
  172. /// <param name="context">The GPU context to register a sync action on</param>
  173. private void RegisterSync(GpuContext context)
  174. {
  175. if (!_syncActionRegistered)
  176. {
  177. _modifiedSync = context.SyncNumber;
  178. context.RegisterSyncAction(SyncAction, true);
  179. _syncActionRegistered = true;
  180. }
  181. if (Interlocked.Exchange(ref _actionRegistered, 1) == 0)
  182. {
  183. _group.RegisterAction(this);
  184. }
  185. }
  186. /// <summary>
  187. /// Signal that this handle has been modified to any existing dependencies, and set the modified flag.
  188. /// </summary>
  189. /// <param name="context">The GPU context to register a sync action on</param>
  190. public void SignalModified(GpuContext context)
  191. {
  192. Modified = true;
  193. // If this handle has any copy dependencies, notify the other handle that a copy needs to be performed.
  194. foreach (TextureDependency dependency in Dependencies)
  195. {
  196. dependency.SignalModified();
  197. }
  198. RegisterSync(context);
  199. }
  200. /// <summary>
  201. /// Signal that this handle has either started or ended being modified.
  202. /// </summary>
  203. /// <param name="bound">True if this handle is being bound, false if unbound</param>
  204. /// <param name="context">The GPU context to register a sync action on</param>
  205. public void SignalModifying(bool bound, GpuContext context)
  206. {
  207. SignalModified(context);
  208. // Note: Bind count currently resets to 0 on inherit for safety, as the handle <-> view relationship can change.
  209. _bindCount = Math.Max(0, _bindCount + (bound ? 1 : -1));
  210. }
  211. /// <summary>
  212. /// Synchronize dependent textures, if any of them have deferred a copy from this texture.
  213. /// </summary>
  214. public void SynchronizeDependents()
  215. {
  216. foreach (TextureDependency dependency in Dependencies)
  217. {
  218. TextureGroupHandle otherHandle = dependency.Other.Handle;
  219. if (otherHandle.DeferredCopy == this)
  220. {
  221. otherHandle._group.Storage.SynchronizeMemory();
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Wait for the latest sync number that the texture handle was written to,
  227. /// removing the modified flag if it was reached, or leaving it set if it has not yet been created.
  228. /// </summary>
  229. /// <param name="context">The GPU context used to wait for sync</param>
  230. public void Sync(GpuContext context)
  231. {
  232. ulong registeredSync = _registeredSync;
  233. long diff = (long)(context.SyncNumber - registeredSync);
  234. if (diff > 0)
  235. {
  236. context.Renderer.WaitSync(registeredSync);
  237. if ((long)(_modifiedSync - registeredSync) > 0)
  238. {
  239. // Flush the data in a previous state. Do not remove the modified flag - it will be removed to ignore following writes.
  240. return;
  241. }
  242. Modified = false;
  243. }
  244. // If the difference is <= 0, no data is not ready yet. Flush any data we can without waiting or removing modified flag.
  245. }
  246. /// <summary>
  247. /// Clears the action registered variable, indicating that the tracking action should be
  248. /// re-registered on the next modification.
  249. /// </summary>
  250. public void ClearActionRegistered()
  251. {
  252. Interlocked.Exchange(ref _actionRegistered, 0);
  253. }
  254. /// <summary>
  255. /// Action to perform when a sync number is registered after modification.
  256. /// This action will register a read tracking action on the memory tracking handle so that a flush from CPU can happen.
  257. /// </summary>
  258. private void SyncAction()
  259. {
  260. // The storage will need to signal modified again to update the sync number in future.
  261. _group.Storage.SignalModifiedDirty();
  262. lock (Overlaps)
  263. {
  264. foreach (Texture texture in Overlaps)
  265. {
  266. texture.SignalModifiedDirty();
  267. }
  268. }
  269. // Register region tracking for CPU? (again)
  270. _registeredSync = _modifiedSync;
  271. _syncActionRegistered = false;
  272. if (Interlocked.Exchange(ref _actionRegistered, 1) == 0)
  273. {
  274. _group.RegisterAction(this);
  275. }
  276. }
  277. /// <summary>
  278. /// Signal that a copy dependent texture has been modified, and must have its data copied to this one.
  279. /// </summary>
  280. /// <param name="copyFrom">The texture handle that must defer a copy to this one</param>
  281. public void DeferCopy(TextureGroupHandle copyFrom)
  282. {
  283. Modified = false;
  284. DeferredCopy = copyFrom;
  285. _group.Storage.SignalGroupDirty();
  286. foreach (Texture overlap in Overlaps)
  287. {
  288. overlap.SignalGroupDirty();
  289. }
  290. }
  291. /// <summary>
  292. /// Create a copy dependency between this handle, and another.
  293. /// </summary>
  294. /// <param name="other">The handle to create a copy dependency to</param>
  295. /// <param name="copyToOther">True if a copy should be deferred to all of the other handle's dependencies</param>
  296. public void CreateCopyDependency(TextureGroupHandle other, bool copyToOther = false)
  297. {
  298. // Does this dependency already exist?
  299. foreach (TextureDependency existing in Dependencies)
  300. {
  301. if (existing.Other.Handle == other)
  302. {
  303. // Do not need to create it again. May need to set the dirty flag.
  304. return;
  305. }
  306. }
  307. _group.HasCopyDependencies = true;
  308. other._group.HasCopyDependencies = true;
  309. TextureDependency dependency = new TextureDependency(this);
  310. TextureDependency otherDependency = new TextureDependency(other);
  311. dependency.Other = otherDependency;
  312. otherDependency.Other = dependency;
  313. Dependencies.Add(dependency);
  314. other.Dependencies.Add(otherDependency);
  315. // Recursively create dependency:
  316. // All of this handle's dependencies must depend on the other.
  317. foreach (TextureDependency existing in Dependencies.ToArray())
  318. {
  319. if (existing != dependency && existing.Other.Handle != other)
  320. {
  321. existing.Other.Handle.CreateCopyDependency(other);
  322. }
  323. }
  324. // All of the other handle's dependencies must depend on this.
  325. foreach (TextureDependency existing in other.Dependencies.ToArray())
  326. {
  327. if (existing != otherDependency && existing.Other.Handle != this)
  328. {
  329. existing.Other.Handle.CreateCopyDependency(this);
  330. if (copyToOther)
  331. {
  332. existing.Other.Handle.DeferCopy(this);
  333. }
  334. }
  335. }
  336. }
  337. /// <summary>
  338. /// Remove a dependency from this handle's dependency list.
  339. /// </summary>
  340. /// <param name="dependency">The dependency to remove</param>
  341. public void RemoveDependency(TextureDependency dependency)
  342. {
  343. Dependencies.Remove(dependency);
  344. }
  345. /// <summary>
  346. /// Check if any of this handle's memory tracking handles are dirty.
  347. /// </summary>
  348. /// <returns>True if at least one of the handles is dirty</returns>
  349. private bool CheckDirty()
  350. {
  351. return Handles.Any(handle => handle.Dirty);
  352. }
  353. /// <summary>
  354. /// Perform a copy from the provided handle to this one, or perform a deferred copy if none is provided.
  355. /// </summary>
  356. /// <param name="context">GPU context to register sync for modified handles</param>
  357. /// <param name="fromHandle">The handle to copy from. If not provided, this method will copy from and clear the deferred copy instead</param>
  358. /// <returns>True if the copy was performed, false otherwise</returns>
  359. public bool Copy(GpuContext context, TextureGroupHandle fromHandle = null)
  360. {
  361. bool result = false;
  362. bool shouldCopy = false;
  363. if (fromHandle == null)
  364. {
  365. fromHandle = DeferredCopy;
  366. if (fromHandle != null)
  367. {
  368. // Only copy if the copy texture is still modified.
  369. // It will be set as unmodified if new data is written from CPU, as the data previously in the texture will flush.
  370. // It will also set as unmodified if a copy is deferred to it.
  371. shouldCopy = fromHandle.Modified;
  372. if (fromHandle._bindCount == 0)
  373. {
  374. // Repeat the copy in future if the bind count is greater than 0.
  375. DeferredCopy = null;
  376. }
  377. }
  378. }
  379. else
  380. {
  381. // Copies happen directly when initializing a copy dependency.
  382. // If dirty, do not copy. Its data no longer matters, and this handle should also be dirty.
  383. // Also, only direct copy if the data in this handle is not already modified (can be set by copies from modified handles).
  384. shouldCopy = !fromHandle.CheckDirty() && (fromHandle.Modified || !Modified);
  385. }
  386. if (shouldCopy)
  387. {
  388. Texture from = fromHandle._group.Storage;
  389. Texture to = _group.Storage;
  390. if (from.ScaleFactor != to.ScaleFactor)
  391. {
  392. to.PropagateScale(from);
  393. }
  394. from.HostTexture.CopyTo(
  395. to.HostTexture,
  396. fromHandle._firstLayer,
  397. _firstLayer,
  398. fromHandle._firstLevel,
  399. _firstLevel);
  400. if (fromHandle.Modified)
  401. {
  402. Modified = true;
  403. RegisterSync(context);
  404. }
  405. result = true;
  406. }
  407. return result;
  408. }
  409. /// <summary>
  410. /// Check if this handle has a dependency to a given texture group.
  411. /// </summary>
  412. /// <param name="group">The texture group to check for</param>
  413. /// <returns>True if there is a dependency, false otherwise</returns>
  414. public bool HasDependencyTo(TextureGroup group)
  415. {
  416. foreach (TextureDependency dep in Dependencies)
  417. {
  418. if (dep.Other.Handle._group == group)
  419. {
  420. return true;
  421. }
  422. }
  423. return false;
  424. }
  425. /// <summary>
  426. /// Inherit modified flags and dependencies from another texture handle.
  427. /// </summary>
  428. /// <param name="old">The texture handle to inherit from</param>
  429. /// <param name="withCopies">Whether the handle should inherit copy dependencies or not</param>
  430. public void Inherit(TextureGroupHandle old, bool withCopies)
  431. {
  432. Modified |= old.Modified;
  433. if (withCopies)
  434. {
  435. foreach (TextureDependency dependency in old.Dependencies.ToArray())
  436. {
  437. CreateCopyDependency(dependency.Other.Handle);
  438. if (dependency.Other.Handle.DeferredCopy == old)
  439. {
  440. dependency.Other.Handle.DeferredCopy = this;
  441. }
  442. }
  443. DeferredCopy = old.DeferredCopy;
  444. }
  445. }
  446. /// <summary>
  447. /// Check if this region overlaps with another.
  448. /// </summary>
  449. /// <param name="address">Base address</param>
  450. /// <param name="size">Size of the region</param>
  451. /// <returns>True if overlapping, false otherwise</returns>
  452. public bool OverlapsWith(int offset, int size)
  453. {
  454. return Offset < offset + size && offset < Offset + Size;
  455. }
  456. /// <summary>
  457. /// Dispose this texture group handle, removing all its dependencies and disposing its memory tracking handles.
  458. /// </summary>
  459. public void Dispose()
  460. {
  461. foreach (CpuRegionHandle handle in Handles)
  462. {
  463. handle.Dispose();
  464. }
  465. foreach (TextureDependency dependency in Dependencies.ToArray())
  466. {
  467. dependency.Other.Handle.RemoveDependency(dependency.Other);
  468. }
  469. }
  470. }
  471. }