TextureGroup.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. using Ryujinx.Common.Memory;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Texture;
  6. using Ryujinx.Memory;
  7. using Ryujinx.Memory.Range;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Runtime.CompilerServices;
  11. namespace Ryujinx.Graphics.Gpu.Image
  12. {
  13. /// <summary>
  14. /// An overlapping texture group with a given view compatibility.
  15. /// </summary>
  16. readonly struct TextureIncompatibleOverlap
  17. {
  18. public readonly TextureGroup Group;
  19. public readonly TextureViewCompatibility Compatibility;
  20. /// <summary>
  21. /// Create a new texture incompatible overlap.
  22. /// </summary>
  23. /// <param name="group">The group that is incompatible</param>
  24. /// <param name="compatibility">The view compatibility for the group</param>
  25. public TextureIncompatibleOverlap(TextureGroup group, TextureViewCompatibility compatibility)
  26. {
  27. Group = group;
  28. Compatibility = compatibility;
  29. }
  30. }
  31. /// <summary>
  32. /// A texture group represents a group of textures that belong to the same storage.
  33. /// When views are created, this class will track memory accesses for them separately.
  34. /// The group iteratively adds more granular tracking as views of different kinds are added.
  35. /// Note that a texture group can be absorbed into another when it becomes a view parent.
  36. /// </summary>
  37. class TextureGroup : IDisposable
  38. {
  39. private delegate void HandlesCallbackDelegate(int baseHandle, int regionCount, bool split = false);
  40. /// <summary>
  41. /// The storage texture associated with this group.
  42. /// </summary>
  43. public Texture Storage { get; }
  44. /// <summary>
  45. /// Indicates if the texture has copy dependencies. If true, then all modifications
  46. /// must be signalled to the group, rather than skipping ones still to be flushed.
  47. /// </summary>
  48. public bool HasCopyDependencies { get; set; }
  49. /// <summary>
  50. /// Indicates if this texture has any incompatible overlaps alive.
  51. /// </summary>
  52. public bool HasIncompatibleOverlaps => _incompatibleOverlaps.Count > 0;
  53. private readonly GpuContext _context;
  54. private readonly PhysicalMemory _physicalMemory;
  55. private int[] _allOffsets;
  56. private int[] _sliceSizes;
  57. private bool _is3D;
  58. private bool _hasMipViews;
  59. private bool _hasLayerViews;
  60. private int _layers;
  61. private int _levels;
  62. private MultiRange TextureRange => Storage.Range;
  63. /// <summary>
  64. /// The views list from the storage texture.
  65. /// </summary>
  66. private List<Texture> _views;
  67. private TextureGroupHandle[] _handles;
  68. private bool[] _loadNeeded;
  69. /// <summary>
  70. /// Other texture groups that have incompatible overlaps with this one.
  71. /// </summary>
  72. private List<TextureIncompatibleOverlap> _incompatibleOverlaps;
  73. private bool _incompatibleOverlapsDirty = true;
  74. private bool _flushIncompatibleOverlaps;
  75. /// <summary>
  76. /// Create a new texture group.
  77. /// </summary>
  78. /// <param name="context">GPU context that the texture group belongs to</param>
  79. /// <param name="physicalMemory">Physical memory where the <paramref name="storage"/> texture is mapped</param>
  80. /// <param name="storage">The storage texture for this group</param>
  81. /// <param name="incompatibleOverlaps">Groups that overlap with this one but are incompatible</param>
  82. public TextureGroup(GpuContext context, PhysicalMemory physicalMemory, Texture storage, List<TextureIncompatibleOverlap> incompatibleOverlaps)
  83. {
  84. Storage = storage;
  85. _context = context;
  86. _physicalMemory = physicalMemory;
  87. _is3D = storage.Info.Target == Target.Texture3D;
  88. _layers = storage.Info.GetSlices();
  89. _levels = storage.Info.Levels;
  90. _incompatibleOverlaps = incompatibleOverlaps;
  91. _flushIncompatibleOverlaps = TextureCompatibility.IsFormatHostIncompatible(storage.Info, context.Capabilities);
  92. }
  93. /// <summary>
  94. /// Initialize a new texture group's dirty regions and offsets.
  95. /// </summary>
  96. /// <param name="size">Size info for the storage texture</param>
  97. /// <param name="hasLayerViews">True if the storage will have layer views</param>
  98. /// <param name="hasMipViews">True if the storage will have mip views</param>
  99. public void Initialize(ref SizeInfo size, bool hasLayerViews, bool hasMipViews)
  100. {
  101. _allOffsets = size.AllOffsets;
  102. _sliceSizes = size.SliceSizes;
  103. (_hasLayerViews, _hasMipViews) = PropagateGranularity(hasLayerViews, hasMipViews);
  104. RecalculateHandleRegions();
  105. }
  106. /// <summary>
  107. /// Initialize all incompatible overlaps in the list, registering them with the other texture groups
  108. /// and creating copy dependencies when partially compatible.
  109. /// </summary>
  110. public void InitializeOverlaps()
  111. {
  112. foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps)
  113. {
  114. if (overlap.Compatibility == TextureViewCompatibility.LayoutIncompatible)
  115. {
  116. CreateCopyDependency(overlap.Group, false);
  117. }
  118. overlap.Group._incompatibleOverlaps.Add(new TextureIncompatibleOverlap(this, overlap.Compatibility));
  119. overlap.Group._incompatibleOverlapsDirty = true;
  120. }
  121. if (_incompatibleOverlaps.Count > 0)
  122. {
  123. SignalIncompatibleOverlapModified();
  124. }
  125. }
  126. /// <summary>
  127. /// Signal that the group is dirty to all views and the storage.
  128. /// </summary>
  129. private void SignalAllDirty()
  130. {
  131. Storage.SignalGroupDirty();
  132. if (_views != null)
  133. {
  134. foreach (Texture texture in _views)
  135. {
  136. texture.SignalGroupDirty();
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Signal that an incompatible overlap has been modified.
  142. /// If this group must flush incompatible overlaps, the group is signalled as dirty too.
  143. /// </summary>
  144. private void SignalIncompatibleOverlapModified()
  145. {
  146. _incompatibleOverlapsDirty = true;
  147. if (_flushIncompatibleOverlaps)
  148. {
  149. SignalAllDirty();
  150. }
  151. }
  152. /// <summary>
  153. /// Flushes incompatible overlaps if the storage format requires it, and they have been modified.
  154. /// This allows unsupported host formats to accept data written to format aliased textures.
  155. /// </summary>
  156. /// <returns>True if data was flushed, false otherwise</returns>
  157. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  158. public bool FlushIncompatibleOverlapsIfNeeded()
  159. {
  160. if (_flushIncompatibleOverlaps && _incompatibleOverlapsDirty)
  161. {
  162. bool flushed = false;
  163. foreach (var overlap in _incompatibleOverlaps)
  164. {
  165. flushed |= overlap.Group.Storage.FlushModified(true);
  166. }
  167. _incompatibleOverlapsDirty = false;
  168. return flushed;
  169. }
  170. else
  171. {
  172. return false;
  173. }
  174. }
  175. /// <summary>
  176. /// Check and optionally consume the dirty flags for a given texture.
  177. /// The state is shared between views of the same layers and levels.
  178. /// </summary>
  179. /// <param name="texture">The texture being used</param>
  180. /// <param name="consume">True to consume the dirty flags and reprotect, false to leave them as is</param>
  181. /// <returns>True if a flag was dirty, false otherwise</returns>
  182. public bool CheckDirty(Texture texture, bool consume)
  183. {
  184. bool dirty = false;
  185. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  186. {
  187. for (int i = 0; i < regionCount; i++)
  188. {
  189. TextureGroupHandle group = _handles[baseHandle + i];
  190. foreach (CpuRegionHandle handle in group.Handles)
  191. {
  192. if (handle.Dirty)
  193. {
  194. if (consume)
  195. {
  196. handle.Reprotect();
  197. }
  198. dirty = true;
  199. }
  200. }
  201. }
  202. });
  203. return dirty;
  204. }
  205. /// <summary>
  206. /// Synchronize memory for a given texture.
  207. /// If overlapping tracking handles are dirty, fully or partially synchronize the texture data.
  208. /// </summary>
  209. /// <param name="texture">The texture being used</param>
  210. public void SynchronizeMemory(Texture texture)
  211. {
  212. FlushIncompatibleOverlapsIfNeeded();
  213. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  214. {
  215. bool dirty = false;
  216. bool anyModified = false;
  217. bool anyUnmapped = false;
  218. for (int i = 0; i < regionCount; i++)
  219. {
  220. TextureGroupHandle group = _handles[baseHandle + i];
  221. bool modified = group.Modified;
  222. bool handleDirty = false;
  223. bool handleUnmapped = false;
  224. foreach (CpuRegionHandle handle in group.Handles)
  225. {
  226. if (handle.Dirty)
  227. {
  228. handle.Reprotect();
  229. handleDirty = true;
  230. }
  231. else
  232. {
  233. handleUnmapped |= handle.Unmapped;
  234. }
  235. }
  236. // If the modified flag is still present, prefer the data written from gpu.
  237. // A write from CPU will do a flush before writing its data, which should unset this.
  238. if (modified)
  239. {
  240. handleDirty = false;
  241. }
  242. // Evaluate if any copy dependencies need to be fulfilled. A few rules:
  243. // If the copy handle needs to be synchronized, prefer our own state.
  244. // If we need to be synchronized and there is a copy present, prefer the copy.
  245. if (group.NeedsCopy && group.Copy(_context))
  246. {
  247. anyModified |= true; // The copy target has been modified.
  248. handleDirty = false;
  249. }
  250. else
  251. {
  252. anyModified |= modified;
  253. dirty |= handleDirty;
  254. }
  255. anyUnmapped |= handleUnmapped;
  256. if (group.NeedsCopy)
  257. {
  258. // The texture we copied from is still being written to. Copy from it again the next time this texture is used.
  259. texture.SignalGroupDirty();
  260. }
  261. _loadNeeded[baseHandle + i] = handleDirty && !handleUnmapped;
  262. }
  263. if (dirty)
  264. {
  265. if (anyUnmapped || (_handles.Length > 1 && (anyModified || split)))
  266. {
  267. // Partial texture invalidation. Only update the layers/levels with dirty flags of the storage.
  268. SynchronizePartial(baseHandle, regionCount);
  269. }
  270. else
  271. {
  272. // Full texture invalidation.
  273. texture.SynchronizeFull();
  274. }
  275. }
  276. });
  277. }
  278. /// <summary>
  279. /// Synchronize part of the storage texture, represented by a given range of handles.
  280. /// Only handles marked by the _loadNeeded array will be synchronized.
  281. /// </summary>
  282. /// <param name="baseHandle">The base index of the range of handles</param>
  283. /// <param name="regionCount">The number of handles to synchronize</param>
  284. private void SynchronizePartial(int baseHandle, int regionCount)
  285. {
  286. for (int i = 0; i < regionCount; i++)
  287. {
  288. if (_loadNeeded[baseHandle + i])
  289. {
  290. var info = GetHandleInformation(baseHandle + i);
  291. int offsetIndex = info.Index;
  292. // Only one of these will be greater than 1, as partial sync is only called when there are sub-image views.
  293. for (int layer = 0; layer < info.Layers; layer++)
  294. {
  295. for (int level = 0; level < info.Levels; level++)
  296. {
  297. int offset = _allOffsets[offsetIndex];
  298. int endOffset = Math.Min(offset + _sliceSizes[info.BaseLevel + level], (int)Storage.Size);
  299. int size = endOffset - offset;
  300. ReadOnlySpan<byte> data = _physicalMemory.GetSpan(Storage.Range.GetSlice((ulong)offset, (ulong)size));
  301. SpanOrArray<byte> result = Storage.ConvertToHostCompatibleFormat(data, info.BaseLevel, true);
  302. Storage.SetData(result, info.BaseLayer, info.BaseLevel);
  303. offsetIndex++;
  304. }
  305. }
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// Synchronize dependent textures, if any of them have deferred a copy from the given texture.
  311. /// </summary>
  312. /// <param name="texture">The texture to synchronize dependents of</param>
  313. public void SynchronizeDependents(Texture texture)
  314. {
  315. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  316. {
  317. for (int i = 0; i < regionCount; i++)
  318. {
  319. TextureGroupHandle group = _handles[baseHandle + i];
  320. group.SynchronizeDependents();
  321. }
  322. });
  323. }
  324. /// <summary>
  325. /// Determines whether flushes in this texture group should be tracked.
  326. /// Incompatible overlaps may need data from this texture to flush tracked for it to be visible to them.
  327. /// </summary>
  328. /// <returns>True if flushes should be tracked, false otherwise</returns>
  329. private bool ShouldFlushTriggerTracking()
  330. {
  331. foreach (var overlap in _incompatibleOverlaps)
  332. {
  333. if (overlap.Group._flushIncompatibleOverlaps)
  334. {
  335. return true;
  336. }
  337. }
  338. return false;
  339. }
  340. /// <summary>
  341. /// Gets data from the host GPU, and flushes a slice to guest memory.
  342. /// </summary>
  343. /// <remarks>
  344. /// This method should be used to retrieve data that was modified by the host GPU.
  345. /// This is not cheap, avoid doing that unless strictly needed.
  346. /// When possible, the data is written directly into guest memory, rather than copied.
  347. /// </remarks>
  348. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  349. /// <param name="sliceIndex">The index of the slice to flush</param>
  350. /// <param name="texture">The specific host texture to flush. Defaults to the storage texture</param>
  351. private void FlushTextureDataSliceToGuest(bool tracked, int sliceIndex, ITexture texture = null)
  352. {
  353. (int layer, int level) = GetLayerLevelForView(sliceIndex);
  354. int offset = _allOffsets[sliceIndex];
  355. int endOffset = Math.Min(offset + _sliceSizes[level], (int)Storage.Size);
  356. int size = endOffset - offset;
  357. using WritableRegion region = _physicalMemory.GetWritableRegion(Storage.Range.GetSlice((ulong)offset, (ulong)size), tracked);
  358. Storage.GetTextureDataSliceFromGpu(region.Memory.Span, layer, level, tracked, texture);
  359. }
  360. /// <summary>
  361. /// Gets and flushes a number of slices of the storage texture to guest memory.
  362. /// </summary>
  363. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  364. /// <param name="sliceStart">The first slice to flush</param>
  365. /// <param name="sliceEnd">The slice to finish flushing on (exclusive)</param>
  366. /// <param name="texture">The specific host texture to flush. Defaults to the storage texture</param>
  367. private void FlushSliceRange(bool tracked, int sliceStart, int sliceEnd, ITexture texture = null)
  368. {
  369. for (int i = sliceStart; i < sliceEnd; i++)
  370. {
  371. FlushTextureDataSliceToGuest(tracked, i, texture);
  372. }
  373. }
  374. /// <summary>
  375. /// Flush modified ranges for a given texture.
  376. /// </summary>
  377. /// <param name="texture">The texture being used</param>
  378. /// <param name="tracked">True if the flush writes should be tracked, false otherwise</param>
  379. /// <returns>True if data was flushed, false otherwise</returns>
  380. public bool FlushModified(Texture texture, bool tracked)
  381. {
  382. tracked = tracked || ShouldFlushTriggerTracking();
  383. bool flushed = false;
  384. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  385. {
  386. int startSlice = 0;
  387. int endSlice = 0;
  388. bool allModified = true;
  389. for (int i = 0; i < regionCount; i++)
  390. {
  391. TextureGroupHandle group = _handles[baseHandle + i];
  392. if (group.Modified)
  393. {
  394. if (endSlice < group.BaseSlice)
  395. {
  396. if (endSlice > startSlice)
  397. {
  398. FlushSliceRange(tracked, startSlice, endSlice);
  399. flushed = true;
  400. }
  401. startSlice = group.BaseSlice;
  402. }
  403. endSlice = group.BaseSlice + group.SliceCount;
  404. if (tracked)
  405. {
  406. group.Modified = false;
  407. foreach (Texture texture in group.Overlaps)
  408. {
  409. texture.SignalModifiedDirty();
  410. }
  411. }
  412. }
  413. else
  414. {
  415. allModified = false;
  416. }
  417. }
  418. if (endSlice > startSlice)
  419. {
  420. if (allModified && !split)
  421. {
  422. texture.Flush(tracked);
  423. }
  424. else
  425. {
  426. FlushSliceRange(tracked, startSlice, endSlice);
  427. }
  428. flushed = true;
  429. }
  430. });
  431. Storage.SignalModifiedDirty();
  432. return flushed;
  433. }
  434. /// <summary>
  435. /// Clears competing modified flags for all incompatible ranges, if they have possibly been modified.
  436. /// </summary>
  437. /// <param name="texture">The texture that has been modified</param>
  438. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  439. private void ClearIncompatibleOverlaps(Texture texture)
  440. {
  441. if (_incompatibleOverlapsDirty)
  442. {
  443. foreach (TextureIncompatibleOverlap incompatible in _incompatibleOverlaps)
  444. {
  445. incompatible.Group.ClearModified(texture.Range, this);
  446. incompatible.Group.SignalIncompatibleOverlapModified();
  447. }
  448. _incompatibleOverlapsDirty = false;
  449. }
  450. }
  451. /// <summary>
  452. /// Signal that a texture in the group has been modified by the GPU.
  453. /// </summary>
  454. /// <param name="texture">The texture that has been modified</param>
  455. public void SignalModified(Texture texture)
  456. {
  457. ClearIncompatibleOverlaps(texture);
  458. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  459. {
  460. for (int i = 0; i < regionCount; i++)
  461. {
  462. TextureGroupHandle group = _handles[baseHandle + i];
  463. group.SignalModified(_context);
  464. }
  465. });
  466. }
  467. /// <summary>
  468. /// Signal that a texture in the group is actively bound, or has been unbound by the GPU.
  469. /// </summary>
  470. /// <param name="texture">The texture that has been modified</param>
  471. /// <param name="bound">True if this texture is being bound, false if unbound</param>
  472. public void SignalModifying(Texture texture, bool bound)
  473. {
  474. ClearIncompatibleOverlaps(texture);
  475. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  476. {
  477. for (int i = 0; i < regionCount; i++)
  478. {
  479. TextureGroupHandle group = _handles[baseHandle + i];
  480. group.SignalModifying(bound, _context);
  481. }
  482. });
  483. }
  484. /// <summary>
  485. /// Register a read/write action to flush for a texture group.
  486. /// </summary>
  487. /// <param name="group">The group to register an action for</param>
  488. public void RegisterAction(TextureGroupHandle group)
  489. {
  490. foreach (CpuRegionHandle handle in group.Handles)
  491. {
  492. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  493. }
  494. }
  495. /// <summary>
  496. /// Propagates the mip/layer view flags depending on the texture type.
  497. /// When the most granular type of subresource has views, the other type of subresource must be segmented granularly too.
  498. /// </summary>
  499. /// <param name="hasLayerViews">True if the storage has layer views</param>
  500. /// <param name="hasMipViews">True if the storage has mip views</param>
  501. /// <returns>The input values after propagation</returns>
  502. private (bool HasLayerViews, bool HasMipViews) PropagateGranularity(bool hasLayerViews, bool hasMipViews)
  503. {
  504. if (_is3D)
  505. {
  506. hasMipViews |= hasLayerViews;
  507. }
  508. else
  509. {
  510. hasLayerViews |= hasMipViews;
  511. }
  512. return (hasLayerViews, hasMipViews);
  513. }
  514. /// <summary>
  515. /// Evaluate the range of tracking handles which a view texture overlaps with.
  516. /// </summary>
  517. /// <param name="texture">The texture to get handles for</param>
  518. /// <param name="callback">
  519. /// A function to be called with the base index of the range of handles for the given texture, and the number of handles it covers.
  520. /// This can be called for multiple disjoint ranges, if required.
  521. /// </param>
  522. private void EvaluateRelevantHandles(Texture texture, HandlesCallbackDelegate callback)
  523. {
  524. if (texture == Storage || !(_hasMipViews || _hasLayerViews))
  525. {
  526. callback(0, _handles.Length);
  527. return;
  528. }
  529. EvaluateRelevantHandles(texture.FirstLayer, texture.FirstLevel, texture.Info.GetSlices(), texture.Info.Levels, callback);
  530. }
  531. /// <summary>
  532. /// Evaluate the range of tracking handles which a view texture overlaps with,
  533. /// using the view's position and slice/level counts.
  534. /// </summary>
  535. /// <param name="firstLayer">The first layer of the texture</param>
  536. /// <param name="firstLevel">The first level of the texture</param>
  537. /// <param name="slices">The slice count of the texture</param>
  538. /// <param name="levels">The level count of the texture</param>
  539. /// <param name="callback">
  540. /// A function to be called with the base index of the range of handles for the given texture, and the number of handles it covers.
  541. /// This can be called for multiple disjoint ranges, if required.
  542. /// </param>
  543. private void EvaluateRelevantHandles(int firstLayer, int firstLevel, int slices, int levels, HandlesCallbackDelegate callback)
  544. {
  545. int targetLayerHandles = _hasLayerViews ? slices : 1;
  546. int targetLevelHandles = _hasMipViews ? levels : 1;
  547. if (_is3D)
  548. {
  549. // Future mip levels come after all layers of the last mip level. Each mipmap has less layers (depth) than the last.
  550. if (!_hasLayerViews)
  551. {
  552. // When there are no layer views, the mips are at a consistent offset.
  553. callback(firstLevel, targetLevelHandles);
  554. }
  555. else
  556. {
  557. (int levelIndex, int layerCount) = Get3DLevelRange(firstLevel);
  558. if (levels > 1 && slices < _layers)
  559. {
  560. // The given texture only covers some of the depth of multiple mips. (a "depth slice")
  561. // Callback with each mip's range separately.
  562. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  563. while (levels-- > 1)
  564. {
  565. callback(firstLayer + levelIndex, slices);
  566. levelIndex += layerCount;
  567. layerCount = Math.Max(layerCount >> 1, 1);
  568. slices = Math.Max(layerCount >> 1, 1);
  569. }
  570. }
  571. else
  572. {
  573. int totalSize = Math.Min(layerCount, slices);
  574. while (levels-- > 1)
  575. {
  576. layerCount = Math.Max(layerCount >> 1, 1);
  577. totalSize += layerCount;
  578. }
  579. callback(firstLayer + levelIndex, totalSize);
  580. }
  581. }
  582. }
  583. else
  584. {
  585. // Future layers come after all mipmaps of the last.
  586. int levelHandles = _hasMipViews ? _levels : 1;
  587. if (slices > 1 && levels < _levels)
  588. {
  589. // The given texture only covers some of the mipmaps of multiple slices. (a "mip slice")
  590. // Callback with each layer's range separately.
  591. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  592. for (int i = 0; i < slices; i++)
  593. {
  594. callback(firstLevel + (firstLayer + i) * levelHandles, targetLevelHandles, true);
  595. }
  596. }
  597. else
  598. {
  599. callback(firstLevel + firstLayer * levelHandles, targetLevelHandles + (targetLayerHandles - 1) * levelHandles);
  600. }
  601. }
  602. }
  603. /// <summary>
  604. /// Get the range of offsets for a given mip level of a 3D texture.
  605. /// </summary>
  606. /// <param name="level">The level to return</param>
  607. /// <returns>Start index and count of offsets for the given level</returns>
  608. private (int Index, int Count) Get3DLevelRange(int level)
  609. {
  610. int index = 0;
  611. int count = _layers; // Depth. Halves with each mip level.
  612. while (level-- > 0)
  613. {
  614. index += count;
  615. count = Math.Max(count >> 1, 1);
  616. }
  617. return (index, count);
  618. }
  619. /// <summary>
  620. /// Get view information for a single tracking handle.
  621. /// </summary>
  622. /// <param name="handleIndex">The index of the handle</param>
  623. /// <returns>The layers and levels that the handle covers, and its index in the offsets array</returns>
  624. private (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) GetHandleInformation(int handleIndex)
  625. {
  626. int baseLayer;
  627. int baseLevel;
  628. int levels = _hasMipViews ? 1 : _levels;
  629. int layers = _hasLayerViews ? 1 : _layers;
  630. int index;
  631. if (_is3D)
  632. {
  633. if (_hasLayerViews)
  634. {
  635. // NOTE: Will also have mip views, or only one level in storage.
  636. index = handleIndex;
  637. baseLevel = 0;
  638. int levelLayers = _layers;
  639. while (handleIndex >= levelLayers)
  640. {
  641. handleIndex -= levelLayers;
  642. baseLevel++;
  643. levelLayers = Math.Max(levelLayers >> 1, 1);
  644. }
  645. baseLayer = handleIndex;
  646. }
  647. else
  648. {
  649. baseLayer = 0;
  650. baseLevel = handleIndex;
  651. (index, _) = Get3DLevelRange(baseLevel);
  652. }
  653. }
  654. else
  655. {
  656. baseLevel = _hasMipViews ? handleIndex % _levels : 0;
  657. baseLayer = _hasMipViews ? handleIndex / _levels : handleIndex;
  658. index = baseLevel + baseLayer * _levels;
  659. }
  660. return (baseLayer, baseLevel, levels, layers, index);
  661. }
  662. /// <summary>
  663. /// Gets the layer and level for a given view.
  664. /// </summary>
  665. /// <param name="index">The index of the view</param>
  666. /// <returns>The layer and level of the specified view</returns>
  667. private (int BaseLayer, int BaseLevel) GetLayerLevelForView(int index)
  668. {
  669. if (_is3D)
  670. {
  671. int baseLevel = 0;
  672. int levelLayers = _layers;
  673. while (index >= levelLayers)
  674. {
  675. index -= levelLayers;
  676. baseLevel++;
  677. levelLayers = Math.Max(levelLayers >> 1, 1);
  678. }
  679. return (index, baseLevel);
  680. }
  681. else
  682. {
  683. return (index / _levels, index % _levels);
  684. }
  685. }
  686. /// <summary>
  687. /// Find the byte offset of a given texture relative to the storage.
  688. /// </summary>
  689. /// <param name="texture">The texture to locate</param>
  690. /// <returns>The offset of the texture in bytes</returns>
  691. public int FindOffset(Texture texture)
  692. {
  693. return _allOffsets[GetOffsetIndex(texture.FirstLayer, texture.FirstLevel)];
  694. }
  695. /// <summary>
  696. /// Find the offset index of a given layer and level.
  697. /// </summary>
  698. /// <param name="layer">The view layer</param>
  699. /// <param name="level">The view level</param>
  700. /// <returns>The offset index of the given layer and level</returns>
  701. public int GetOffsetIndex(int layer, int level)
  702. {
  703. if (_is3D)
  704. {
  705. return layer + Get3DLevelRange(level).Index;
  706. }
  707. else
  708. {
  709. return level + layer * _levels;
  710. }
  711. }
  712. /// <summary>
  713. /// The action to perform when a memory tracking handle is flipped to dirty.
  714. /// This notifies overlapping textures that the memory needs to be synchronized.
  715. /// </summary>
  716. /// <param name="groupHandle">The handle that a dirty flag was set on</param>
  717. private void DirtyAction(TextureGroupHandle groupHandle)
  718. {
  719. // Notify all textures that belong to this handle.
  720. Storage.SignalGroupDirty();
  721. lock (groupHandle.Overlaps)
  722. {
  723. foreach (Texture overlap in groupHandle.Overlaps)
  724. {
  725. overlap.SignalGroupDirty();
  726. }
  727. }
  728. }
  729. /// <summary>
  730. /// Generate a CpuRegionHandle for a given address and size range in CPU VA.
  731. /// </summary>
  732. /// <param name="address">The start address of the tracked region</param>
  733. /// <param name="size">The size of the tracked region</param>
  734. /// <returns>A CpuRegionHandle covering the given range</returns>
  735. private CpuRegionHandle GenerateHandle(ulong address, ulong size)
  736. {
  737. return _physicalMemory.BeginTracking(address, size);
  738. }
  739. /// <summary>
  740. /// Generate a TextureGroupHandle covering a specified range of views.
  741. /// </summary>
  742. /// <param name="viewStart">The start view of the handle</param>
  743. /// <param name="views">The number of views to cover</param>
  744. /// <returns>A TextureGroupHandle covering the given views</returns>
  745. private TextureGroupHandle GenerateHandles(int viewStart, int views)
  746. {
  747. int offset = _allOffsets[viewStart];
  748. int endOffset = (viewStart + views == _allOffsets.Length) ? (int)Storage.Size : _allOffsets[viewStart + views];
  749. int size = endOffset - offset;
  750. var result = new List<CpuRegionHandle>();
  751. for (int i = 0; i < TextureRange.Count; i++)
  752. {
  753. MemoryRange item = TextureRange.GetSubRange(i);
  754. int subRangeSize = (int)item.Size;
  755. int sliceStart = Math.Clamp(offset, 0, subRangeSize);
  756. int sliceEnd = Math.Clamp(endOffset, 0, subRangeSize);
  757. if (sliceStart != sliceEnd && item.Address != MemoryManager.PteUnmapped)
  758. {
  759. result.Add(GenerateHandle(item.Address + (ulong)sliceStart, (ulong)(sliceEnd - sliceStart)));
  760. }
  761. offset -= subRangeSize;
  762. endOffset -= subRangeSize;
  763. if (endOffset <= 0)
  764. {
  765. break;
  766. }
  767. }
  768. (int firstLayer, int firstLevel) = GetLayerLevelForView(viewStart);
  769. if (_hasLayerViews && _hasMipViews)
  770. {
  771. size = _sliceSizes[firstLevel];
  772. }
  773. offset = _allOffsets[viewStart];
  774. ulong maxSize = Storage.Size - (ulong)offset;
  775. var groupHandle = new TextureGroupHandle(
  776. this,
  777. offset,
  778. Math.Min(maxSize, (ulong)size),
  779. _views,
  780. firstLayer,
  781. firstLevel,
  782. viewStart,
  783. views,
  784. result.ToArray());
  785. foreach (CpuRegionHandle handle in result)
  786. {
  787. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  788. }
  789. return groupHandle;
  790. }
  791. /// <summary>
  792. /// Update the views in this texture group, rebuilding the memory tracking if required.
  793. /// </summary>
  794. /// <param name="views">The views list of the storage texture</param>
  795. public void UpdateViews(List<Texture> views)
  796. {
  797. // This is saved to calculate overlapping views for each handle.
  798. _views = views;
  799. bool layerViews = _hasLayerViews;
  800. bool mipViews = _hasMipViews;
  801. bool regionsRebuilt = false;
  802. if (!(layerViews && mipViews))
  803. {
  804. foreach (Texture view in views)
  805. {
  806. if (view.Info.GetSlices() < _layers)
  807. {
  808. layerViews = true;
  809. }
  810. if (view.Info.Levels < _levels)
  811. {
  812. mipViews = true;
  813. }
  814. }
  815. (layerViews, mipViews) = PropagateGranularity(layerViews, mipViews);
  816. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  817. {
  818. _hasLayerViews = layerViews;
  819. _hasMipViews = mipViews;
  820. RecalculateHandleRegions();
  821. regionsRebuilt = true;
  822. }
  823. }
  824. if (!regionsRebuilt)
  825. {
  826. // Must update the overlapping views on all handles, but only if they were not just recreated.
  827. foreach (TextureGroupHandle handle in _handles)
  828. {
  829. handle.RecalculateOverlaps(this, views);
  830. }
  831. }
  832. SignalAllDirty();
  833. }
  834. /// <summary>
  835. /// Inherit handle state from an old set of handles, such as modified and dirty flags.
  836. /// </summary>
  837. /// <param name="oldHandles">The set of handles to inherit state from</param>
  838. /// <param name="handles">The set of handles inheriting the state</param>
  839. /// <param name="relativeOffset">The offset of the old handles in relation to the new ones</param>
  840. private void InheritHandles(TextureGroupHandle[] oldHandles, TextureGroupHandle[] handles, int relativeOffset)
  841. {
  842. foreach (var group in handles)
  843. {
  844. foreach (var handle in group.Handles)
  845. {
  846. bool dirty = false;
  847. foreach (var oldGroup in oldHandles)
  848. {
  849. if (group.OverlapsWith(oldGroup.Offset + relativeOffset, oldGroup.Size))
  850. {
  851. foreach (var oldHandle in oldGroup.Handles)
  852. {
  853. if (handle.OverlapsWith(oldHandle.Address, oldHandle.Size))
  854. {
  855. dirty |= oldHandle.Dirty;
  856. }
  857. }
  858. group.Inherit(oldGroup, group.Offset == oldGroup.Offset + relativeOffset);
  859. }
  860. }
  861. if (dirty && !handle.Dirty)
  862. {
  863. handle.Reprotect(true);
  864. }
  865. if (group.Modified)
  866. {
  867. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  868. }
  869. }
  870. }
  871. foreach (var oldGroup in oldHandles)
  872. {
  873. oldGroup.Modified = false;
  874. }
  875. }
  876. /// <summary>
  877. /// Inherit state from another texture group.
  878. /// </summary>
  879. /// <param name="other">The texture group to inherit from</param>
  880. public void Inherit(TextureGroup other)
  881. {
  882. bool layerViews = _hasLayerViews || other._hasLayerViews;
  883. bool mipViews = _hasMipViews || other._hasMipViews;
  884. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  885. {
  886. _hasLayerViews = layerViews;
  887. _hasMipViews = mipViews;
  888. RecalculateHandleRegions();
  889. }
  890. foreach (TextureIncompatibleOverlap incompatible in other._incompatibleOverlaps)
  891. {
  892. RegisterIncompatibleOverlap(incompatible, false);
  893. incompatible.Group._incompatibleOverlaps.RemoveAll(overlap => overlap.Group == other);
  894. }
  895. int relativeOffset = Storage.Range.FindOffset(other.Storage.Range);
  896. InheritHandles(other._handles, _handles, relativeOffset);
  897. }
  898. /// <summary>
  899. /// Replace the current handles with the new handles. It is assumed that the new handles start dirty.
  900. /// The dirty flags from the previous handles will be kept.
  901. /// </summary>
  902. /// <param name="handles">The handles to replace the current handles with</param>
  903. private void ReplaceHandles(TextureGroupHandle[] handles)
  904. {
  905. if (_handles != null)
  906. {
  907. // When replacing handles, they should start as non-dirty.
  908. foreach (TextureGroupHandle groupHandle in handles)
  909. {
  910. foreach (CpuRegionHandle handle in groupHandle.Handles)
  911. {
  912. handle.Reprotect();
  913. }
  914. }
  915. InheritHandles(_handles, handles, 0);
  916. foreach (var oldGroup in _handles)
  917. {
  918. foreach (var oldHandle in oldGroup.Handles)
  919. {
  920. oldHandle.Dispose();
  921. }
  922. }
  923. }
  924. _handles = handles;
  925. _loadNeeded = new bool[_handles.Length];
  926. }
  927. /// <summary>
  928. /// Recalculate handle regions for this texture group, and inherit existing state into the new handles.
  929. /// </summary>
  930. private void RecalculateHandleRegions()
  931. {
  932. TextureGroupHandle[] handles;
  933. if (!(_hasMipViews || _hasLayerViews))
  934. {
  935. // Single dirty region.
  936. var cpuRegionHandles = new CpuRegionHandle[TextureRange.Count];
  937. int count = 0;
  938. for (int i = 0; i < TextureRange.Count; i++)
  939. {
  940. var currentRange = TextureRange.GetSubRange(i);
  941. if (currentRange.Address != MemoryManager.PteUnmapped)
  942. {
  943. cpuRegionHandles[count++] = GenerateHandle(currentRange.Address, currentRange.Size);
  944. }
  945. }
  946. if (count != TextureRange.Count)
  947. {
  948. Array.Resize(ref cpuRegionHandles, count);
  949. }
  950. var groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles);
  951. foreach (CpuRegionHandle handle in cpuRegionHandles)
  952. {
  953. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  954. }
  955. handles = new TextureGroupHandle[] { groupHandle };
  956. }
  957. else
  958. {
  959. // Get views for the host texture.
  960. // It's worth noting that either the texture has layer views or mip views when getting to this point, which simplifies the logic a little.
  961. // Depending on if the texture is 3d, either the mip views imply that layer views are present (2d) or the other way around (3d).
  962. // This is enforced by the way the texture matched as a view, so we don't need to check.
  963. int layerHandles = _hasLayerViews ? _layers : 1;
  964. int levelHandles = _hasMipViews ? _levels : 1;
  965. int handleIndex = 0;
  966. if (_is3D)
  967. {
  968. var handlesList = new List<TextureGroupHandle>();
  969. for (int i = 0; i < levelHandles; i++)
  970. {
  971. for (int j = 0; j < layerHandles; j++)
  972. {
  973. (int viewStart, int views) = Get3DLevelRange(i);
  974. viewStart += j;
  975. views = _hasLayerViews ? 1 : views; // A layer view is also a mip view.
  976. handlesList.Add(GenerateHandles(viewStart, views));
  977. }
  978. layerHandles = Math.Max(1, layerHandles >> 1);
  979. }
  980. handles = handlesList.ToArray();
  981. }
  982. else
  983. {
  984. handles = new TextureGroupHandle[layerHandles * levelHandles];
  985. for (int i = 0; i < layerHandles; i++)
  986. {
  987. for (int j = 0; j < levelHandles; j++)
  988. {
  989. int viewStart = j + i * _levels;
  990. int views = _hasMipViews ? 1 : _levels; // A mip view is also a layer view.
  991. handles[handleIndex++] = GenerateHandles(viewStart, views);
  992. }
  993. }
  994. }
  995. }
  996. ReplaceHandles(handles);
  997. }
  998. /// <summary>
  999. /// Ensure that there is a handle for each potential texture view. Required for copy dependencies to work.
  1000. /// </summary>
  1001. private void EnsureFullSubdivision()
  1002. {
  1003. if (!(_hasLayerViews && _hasMipViews))
  1004. {
  1005. _hasLayerViews = true;
  1006. _hasMipViews = true;
  1007. RecalculateHandleRegions();
  1008. }
  1009. }
  1010. /// <summary>
  1011. /// Create a copy dependency between this texture group, and a texture at a given layer/level offset.
  1012. /// </summary>
  1013. /// <param name="other">The view compatible texture to create a dependency to</param>
  1014. /// <param name="firstLayer">The base layer of the given texture relative to the storage</param>
  1015. /// <param name="firstLevel">The base level of the given texture relative to the storage</param>
  1016. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  1017. public void CreateCopyDependency(Texture other, int firstLayer, int firstLevel, bool copyTo)
  1018. {
  1019. TextureGroup otherGroup = other.Group;
  1020. EnsureFullSubdivision();
  1021. otherGroup.EnsureFullSubdivision();
  1022. // Get the location of each texture within its storage, so we can find the handles to apply the dependency to.
  1023. // This can consist of multiple disjoint regions, for example if this is a mip slice of an array texture.
  1024. var targetRange = new List<(int BaseHandle, int RegionCount)>();
  1025. var otherRange = new List<(int BaseHandle, int RegionCount)>();
  1026. EvaluateRelevantHandles(firstLayer, firstLevel, other.Info.GetSlices(), other.Info.Levels, (baseHandle, regionCount, split) => targetRange.Add((baseHandle, regionCount)));
  1027. otherGroup.EvaluateRelevantHandles(other, (baseHandle, regionCount, split) => otherRange.Add((baseHandle, regionCount)));
  1028. int targetIndex = 0;
  1029. int otherIndex = 0;
  1030. (int Handle, int RegionCount) targetRegion = (0, 0);
  1031. (int Handle, int RegionCount) otherRegion = (0, 0);
  1032. while (true)
  1033. {
  1034. if (targetRegion.RegionCount == 0)
  1035. {
  1036. if (targetIndex >= targetRange.Count)
  1037. {
  1038. break;
  1039. }
  1040. targetRegion = targetRange[targetIndex++];
  1041. }
  1042. if (otherRegion.RegionCount == 0)
  1043. {
  1044. if (otherIndex >= otherRange.Count)
  1045. {
  1046. break;
  1047. }
  1048. otherRegion = otherRange[otherIndex++];
  1049. }
  1050. TextureGroupHandle handle = _handles[targetRegion.Handle++];
  1051. TextureGroupHandle otherHandle = other.Group._handles[otherRegion.Handle++];
  1052. targetRegion.RegionCount--;
  1053. otherRegion.RegionCount--;
  1054. handle.CreateCopyDependency(otherHandle, copyTo);
  1055. // If "copyTo" is true, this texture must copy to the other.
  1056. // Otherwise, it must copy to this texture.
  1057. if (copyTo)
  1058. {
  1059. otherHandle.Copy(_context, handle);
  1060. }
  1061. else
  1062. {
  1063. handle.Copy(_context, otherHandle);
  1064. }
  1065. }
  1066. }
  1067. /// <summary>
  1068. /// Creates a copy dependency to another texture group, where handles overlap.
  1069. /// Scans through all handles to find compatible patches in the other group.
  1070. /// </summary>
  1071. /// <param name="other">The texture group that overlaps this one</param>
  1072. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  1073. public void CreateCopyDependency(TextureGroup other, bool copyTo)
  1074. {
  1075. for (int i = 0; i < _allOffsets.Length; i++)
  1076. {
  1077. (int layer, int level) = GetLayerLevelForView(i);
  1078. MultiRange handleRange = Storage.Range.GetSlice((ulong)_allOffsets[i], 1);
  1079. ulong handleBase = handleRange.GetSubRange(0).Address;
  1080. for (int j = 0; j < other._handles.Length; j++)
  1081. {
  1082. (int otherLayer, int otherLevel) = other.GetLayerLevelForView(j);
  1083. MultiRange otherHandleRange = other.Storage.Range.GetSlice((ulong)other._allOffsets[j], 1);
  1084. ulong otherHandleBase = otherHandleRange.GetSubRange(0).Address;
  1085. if (handleBase == otherHandleBase)
  1086. {
  1087. // Check if the two sizes are compatible.
  1088. TextureInfo info = Storage.Info;
  1089. TextureInfo otherInfo = other.Storage.Info;
  1090. if (TextureCompatibility.ViewLayoutCompatible(info, otherInfo, level, otherLevel) &&
  1091. TextureCompatibility.CopySizeMatches(info, otherInfo, level, otherLevel))
  1092. {
  1093. // These textures are copy compatible. Create the dependency.
  1094. EnsureFullSubdivision();
  1095. other.EnsureFullSubdivision();
  1096. TextureGroupHandle handle = _handles[i];
  1097. TextureGroupHandle otherHandle = other._handles[j];
  1098. handle.CreateCopyDependency(otherHandle, copyTo);
  1099. // If "copyTo" is true, this texture must copy to the other.
  1100. // Otherwise, it must copy to this texture.
  1101. if (copyTo)
  1102. {
  1103. otherHandle.Copy(_context, handle);
  1104. }
  1105. else
  1106. {
  1107. handle.Copy(_context, otherHandle);
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. /// <summary>
  1115. /// Registers another texture group as an incompatible overlap, if not already registered.
  1116. /// </summary>
  1117. /// <param name="other">The texture group to add to the incompatible overlaps list</param>
  1118. /// <param name="copy">True if the overlap should register copy dependencies</param>
  1119. public void RegisterIncompatibleOverlap(TextureIncompatibleOverlap other, bool copy)
  1120. {
  1121. if (!_incompatibleOverlaps.Exists(overlap => overlap.Group == other.Group))
  1122. {
  1123. if (copy && other.Compatibility == TextureViewCompatibility.LayoutIncompatible)
  1124. {
  1125. // Any of the group's views may share compatibility, even if the parents do not fully.
  1126. CreateCopyDependency(other.Group, false);
  1127. }
  1128. _incompatibleOverlaps.Add(other);
  1129. other.Group._incompatibleOverlaps.Add(new TextureIncompatibleOverlap(this, other.Compatibility));
  1130. }
  1131. other.Group.SignalIncompatibleOverlapModified();
  1132. SignalIncompatibleOverlapModified();
  1133. }
  1134. /// <summary>
  1135. /// Clear modified flags in the given range.
  1136. /// This will stop any GPU written data from flushing or copying to dependent textures.
  1137. /// </summary>
  1138. /// <param name="range">The range to clear modified flags in</param>
  1139. /// <param name="ignore">Ignore handles that have a copy dependency to the specified group</param>
  1140. public void ClearModified(MultiRange range, TextureGroup ignore = null)
  1141. {
  1142. TextureGroupHandle[] handles = _handles;
  1143. foreach (TextureGroupHandle handle in handles)
  1144. {
  1145. // Handles list is not modified by another thread, only replaced, so this is thread safe.
  1146. // Remove modified flags from all overlapping handles, so that the textures don't flush to unmapped/remapped GPU memory.
  1147. MultiRange subRange = Storage.Range.GetSlice((ulong)handle.Offset, (ulong)handle.Size);
  1148. if (range.OverlapsWith(subRange))
  1149. {
  1150. if ((ignore == null || !handle.HasDependencyTo(ignore)) && handle.Modified)
  1151. {
  1152. handle.Modified = false;
  1153. Storage.SignalModifiedDirty();
  1154. lock (handle.Overlaps)
  1155. {
  1156. foreach (Texture texture in handle.Overlaps)
  1157. {
  1158. texture.SignalModifiedDirty();
  1159. }
  1160. }
  1161. }
  1162. }
  1163. }
  1164. Storage.SignalModifiedDirty();
  1165. if (_views != null)
  1166. {
  1167. foreach (Texture texture in _views)
  1168. {
  1169. texture.SignalModifiedDirty();
  1170. }
  1171. }
  1172. }
  1173. /// <summary>
  1174. /// A flush has been requested on a tracked region. Flush texture data for the given handle.
  1175. /// </summary>
  1176. /// <param name="handle">The handle this flush action is for</param>
  1177. /// <param name="address">The address of the flushing memory access</param>
  1178. /// <param name="size">The size of the flushing memory access</param>
  1179. public void FlushAction(TextureGroupHandle handle, ulong address, ulong size)
  1180. {
  1181. // There is a small gap here where the action is removed but _actionRegistered is still 1.
  1182. // In this case it will skip registering the action, but here we are already handling it,
  1183. // so there shouldn't be any issue as it's the same handler for all actions.
  1184. handle.ClearActionRegistered();
  1185. if (!handle.Modified)
  1186. {
  1187. return;
  1188. }
  1189. _context.Renderer.BackgroundContextAction(() =>
  1190. {
  1191. handle.Sync(_context);
  1192. Storage.SignalModifiedDirty();
  1193. lock (handle.Overlaps)
  1194. {
  1195. foreach (Texture texture in handle.Overlaps)
  1196. {
  1197. texture.SignalModifiedDirty();
  1198. }
  1199. }
  1200. if (TextureCompatibility.CanTextureFlush(Storage.Info, _context.Capabilities))
  1201. {
  1202. FlushSliceRange(false, handle.BaseSlice, handle.BaseSlice + handle.SliceCount, Storage.GetFlushTexture());
  1203. }
  1204. });
  1205. }
  1206. /// <summary>
  1207. /// Dispose this texture group, disposing all related memory tracking handles.
  1208. /// </summary>
  1209. public void Dispose()
  1210. {
  1211. foreach (TextureGroupHandle group in _handles)
  1212. {
  1213. group.Dispose();
  1214. }
  1215. foreach (TextureIncompatibleOverlap incompatible in _incompatibleOverlaps)
  1216. {
  1217. incompatible.Group._incompatibleOverlaps.RemoveAll(overlap => overlap.Group == this);
  1218. }
  1219. }
  1220. }
  1221. }