TextureGroup.cs 61 KB

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