aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Graphics.Gpu/Image/Texture.cs
blob: dde28dbd77238006dceb96f0e0b17e25391bcc40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
using Ryujinx.Common.Logging;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu.Memory;
using Ryujinx.Graphics.Texture;
using Ryujinx.Graphics.Texture.Astc;
using Ryujinx.Memory;
using Ryujinx.Memory.Range;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;

namespace Ryujinx.Graphics.Gpu.Image
{
    /// <summary>
    /// Represents a cached GPU texture.
    /// </summary>
    class Texture : IMultiRangeItem, IDisposable
    {
        // How many updates we need before switching to the byte-by-byte comparison
        // modification check method.
        // This method uses much more memory so we want to avoid it if possible.
        private const int ByteComparisonSwitchThreshold = 4;

        // Tuning for blacklisting textures from scaling when their data is updated from CPU.
        // Each write adds the weight, each GPU modification subtracts 1.
        // Exceeding the threshold blacklists the texture.
        private const int ScaledSetWeight = 10;
        private const int ScaledSetThreshold = 30;

        private const int MinLevelsForForceAnisotropy = 5;

        private struct TexturePoolOwner
        {
            public TexturePool Pool;
            public int ID;
            public ulong GpuAddress;
        }

        private GpuContext _context;
        private PhysicalMemory _physicalMemory;

        private SizeInfo _sizeInfo;

        /// <summary>
        /// Texture format.
        /// </summary>
        public Format Format => Info.FormatInfo.Format;

        /// <summary>
        /// Texture target.
        /// </summary>
        public Target Target { get; private set; }

        /// <summary>
        /// Texture width.
        /// </summary>
        public int Width { get; private set; }

        /// <summary>
        /// Texture height.
        /// </summary>
        public int Height { get; private set; }

        /// <summary>
        /// Texture information.
        /// </summary>
        public TextureInfo Info { get; private set; }

        /// <summary>
        /// Set when anisotropic filtering can be forced on the given texture.
        /// </summary>
        public bool CanForceAnisotropy { get; private set; }

        /// <summary>
        /// Host scale factor.
        /// </summary>
        public float ScaleFactor { get; private set; }

        /// <summary>
        /// Upscaling mode. Informs if a texture is scaled, or is eligible for scaling.
        /// </summary>
        public TextureScaleMode ScaleMode { get; private set; }

        /// <summary>
        /// Group that this texture belongs to. Manages read/write memory tracking.
        /// </summary>
        public TextureGroup Group { get; private set; }

        /// <summary>
        /// Set when a texture's GPU VA has ever been partially or fully unmapped.
        /// This indicates that the range must be fully checked when matching the texture.
        /// </summary>
        public bool ChangedMapping { get; private set; }

        /// <summary>
        /// True if the data for this texture must always be flushed when an overlap appears.
        /// This is useful if SetData is called directly on this texture, but the data is meant for a future texture.
        /// </summary>
        public bool AlwaysFlushOnOverlap { get; private set; }

        /// <summary>
        /// Increments when the host texture is swapped, or when the texture is removed from all pools.
        /// </summary>
        public int InvalidatedSequence { get; private set; }

        private int _depth;
        private int _layers;
        public int FirstLayer { get; private set; }
        public int FirstLevel { get; private set; }

        private bool _hasData;
        private bool _dirty = true;
        private int _updateCount;
        private byte[] _currentData;

        private bool _modifiedStale = true;

        private ITexture _arrayViewTexture;
        private Target _arrayViewTarget;

        private ITexture _flushHostTexture;
        private ITexture _setHostTexture;
        private int _scaledSetScore;

        private Texture _viewStorage;

        private List<Texture> _views;

        /// <summary>
        /// Host texture.
        /// </summary>
        public ITexture HostTexture { get; private set; }

        /// <summary>
        /// Intrusive linked list node used on the auto deletion texture cache.
        /// </summary>
        public LinkedListNode<Texture> CacheNode { get; set; }

        /// <summary>
        /// Entry for this texture in the short duration cache, if present.
        /// </summary>
        public ShortTextureCacheEntry ShortCacheEntry { get; set; }

        /// <summary>
        /// Whether this texture has ever been referenced by a pool.
        /// </summary>
        public bool HadPoolOwner { get; private set; }

        /// <summary>
        /// Physical memory ranges where the texture data is located.
        /// </summary>
        public MultiRange Range { get; private set; }

        /// <summary>
        /// Layer size in bytes.
        /// </summary>
        public int LayerSize => _sizeInfo.LayerSize;

        /// <summary>
        /// Texture size in bytes.
        /// </summary>
        public ulong Size => (ulong)_sizeInfo.TotalSize;

        /// <summary>
        /// Whether or not the texture belongs is a view.
        /// </summary>
        public bool IsView => _viewStorage != this;

        /// <summary>
        /// Whether or not this texture has views.
        /// </summary>
        public bool HasViews => _views.Count > 0;

        private int _referenceCount;
        private List<TexturePoolOwner> _poolOwners;

        /// <summary>
        /// Constructs a new instance of the cached GPU texture.
        /// </summary>
        /// <param name="context">GPU context that the texture belongs to</param>
        /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
        /// <param name="info">Texture information</param>
        /// <param name="sizeInfo">Size information of the texture</param>
        /// <param name="range">Physical memory ranges where the texture data is located</param>
        /// <param name="firstLayer">The first layer of the texture, or 0 if the texture has no parent</param>
        /// <param name="firstLevel">The first mipmap level of the texture, or 0 if the texture has no parent</param>
        /// <param name="scaleFactor">The floating point scale factor to initialize with</param>
        /// <param name="scaleMode">The scale mode to initialize with</param>
        private Texture(
            GpuContext context,
            PhysicalMemory physicalMemory,
            TextureInfo info,
            SizeInfo sizeInfo,
            MultiRange range,
            int firstLayer,
            int firstLevel,
            float scaleFactor,
            TextureScaleMode scaleMode)
        {
            InitializeTexture(context, physicalMemory, info, sizeInfo, range);

            FirstLayer = firstLayer;
            FirstLevel = firstLevel;

            ScaleFactor = scaleFactor;
            ScaleMode = scaleMode;

            InitializeData(true);
        }

        /// <summary>
        /// Constructs a new instance of the cached GPU texture.
        /// </summary>
        /// <param name="context">GPU context that the texture belongs to</param>
        /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
        /// <param name="info">Texture information</param>
        /// <param name="sizeInfo">Size information of the texture</param>
        /// <param name="range">Physical memory ranges where the texture data is located</param>
        /// <param name="scaleMode">The scale mode to initialize with. If scaled, the texture's data is loaded immediately and scaled up</param>
        public Texture(
            GpuContext context,
            PhysicalMemory physicalMemory,
            TextureInfo info,
            SizeInfo sizeInfo,
            MultiRange range,
            TextureScaleMode scaleMode)
        {
            ScaleFactor = 1f; // Texture is first loaded at scale 1x.
            ScaleMode = scaleMode;

            InitializeTexture(context, physicalMemory, info, sizeInfo, range);
        }

        /// <summary>
        /// Common texture initialization method.
        /// This sets the context, info and sizeInfo fields.
        /// Other fields are initialized with their default values.
        /// </summary>
        /// <param name="context">GPU context that the texture belongs to</param>
        /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
        /// <param name="info">Texture information</param>
        /// <param name="sizeInfo">Size information of the texture</param>
        /// <param name="range">Physical memory ranges where the texture data is located</param>
        private void InitializeTexture(
            GpuContext context,
            PhysicalMemory physicalMemory,
            TextureInfo info,
            SizeInfo sizeInfo,
            MultiRange range)
        {
            _context = context;
            _physicalMemory = physicalMemory;
            _sizeInfo = sizeInfo;
            Range = range;

            SetInfo(info);

            _viewStorage = this;

            _views = new List<Texture>();
            _poolOwners = new List<TexturePoolOwner>();
        }

        /// <summary>
        /// Initializes the data for a texture. Can optionally initialize the texture with or without data.
        /// If the texture is a view, it will initialize memory tracking to be non-dirty.
        /// </summary>
        /// <param name="isView">True if the texture is a view, false otherwise</param>
        /// <param name="withData">True if the texture is to be initialized with data</param>
        public void InitializeData(bool isView, bool withData = false)
        {
            withData |= Group != null && Group.FlushIncompatibleOverlapsIfNeeded();

            if (withData)
            {
                Debug.Assert(!isView);

                TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
                HostTexture = _context.Renderer.CreateTexture(createInfo);

                SynchronizeMemory(); // Load the data.
                if (ScaleMode == TextureScaleMode.Scaled)
                {
                    SetScale(GraphicsConfig.ResScale); // Scale the data up.
                }
            }
            else
            {
                _hasData = true;

                if (!isView)
                {
                    // Don't update this texture the next time we synchronize.
                    CheckModified(true);

                    if (ScaleMode == TextureScaleMode.Scaled)
                    {
                        // Don't need to start at 1x as there is no data to scale, just go straight to the target scale.
                        ScaleFactor = GraphicsConfig.ResScale;
                    }

                    TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
                    HostTexture = _context.Renderer.CreateTexture(createInfo);
                }
            }
        }

        /// <summary>
        /// Initialize a new texture group with this texture as storage.
        /// </summary>
        /// <param name="hasLayerViews">True if the texture will have layer views</param>
        /// <param name="hasMipViews">True if the texture will have mip views</param>
        /// <param name="incompatibleOverlaps">Groups that overlap with this one but are incompatible</param>
        public void InitializeGroup(bool hasLayerViews, bool hasMipViews, List<TextureIncompatibleOverlap> incompatibleOverlaps)
        {
            Group = new TextureGroup(_context, _physicalMemory, this, incompatibleOverlaps);

            Group.Initialize(ref _sizeInfo, hasLayerViews, hasMipViews);
        }

        /// <summary>
        /// Create a texture view from this texture.
        /// A texture view is defined as a child texture, from a sub-range of their parent texture.
        /// For example, the initial layer and mipmap level of the view can be defined, so the texture
        /// will start at the given layer/level of the parent texture.
        /// </summary>
        /// <param name="info">Child texture information</param>
        /// <param name="sizeInfo">Child texture size information</param>
        /// <param name="range">Physical memory ranges where the texture data is located</param>
        /// <param name="firstLayer">Start layer of the child texture on the parent texture</param>
        /// <param name="firstLevel">Start mipmap level of the child texture on the parent texture</param>
        /// <returns>The child texture</returns>
        public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, MultiRange range, int firstLayer, int firstLevel)
        {
            Texture texture = new(
                _context,
                _physicalMemory,
                info,
                sizeInfo,
                range,
                FirstLayer + firstLayer,
                FirstLevel + firstLevel,
                ScaleFactor,
                ScaleMode);

            TextureCreateInfo createInfo = TextureCache.GetCreateInfo(info, _context.Capabilities, ScaleFactor);
            texture.HostTexture = HostTexture.CreateView(createInfo, firstLayer, firstLevel);

            _viewStorage.AddView(texture);

            return texture;
        }

        /// <summary>
        /// Adds a child texture to this texture.
        /// </summary>
        /// <param name="texture">The child texture</param>
        private void AddView(Texture texture)
        {
            IncrementReferenceCount();

            _views.Add(texture);

            texture._viewStorage = this;

            Group.UpdateViews(_views, texture);

            if (texture.Group != null && texture.Group != Group)
            {
                if (texture.Group.Storage == texture)
                {
                    // This texture's group is no longer used.
                    Group.Inherit(texture.Group);

                    texture.Group.Dispose();
                }
            }

            texture.Group = Group;
        }

        /// <summary>
        /// Removes a child texture from this texture.
        /// </summary>
        /// <param name="texture">The child texture</param>
        private void RemoveView(Texture texture)
        {
            _views.Remove(texture);

            Group.RemoveView(_views, texture);

            texture._viewStorage = texture;

            DecrementReferenceCount();
        }

        /// <summary>
        /// Replaces the texture's physical memory range. This forces tracking to regenerate.
        /// </summary>
        /// <param name="range">New physical memory range backing the texture</param>
        public void ReplaceRange(MultiRange range)
        {
            Range = range;

            Group.RangeChanged();
        }

        /// <summary>
        /// Create a copy dependency to a texture that is view compatible with this one.
        /// When either texture is modified, the texture data will be copied to the other to keep them in sync.
        /// This is essentially an emulated view, useful for handling multiple view parents or format incompatibility.
        /// This also forces a copy on creation, to or from the given texture to get them in sync immediately.
        /// </summary>
        /// <param name="contained">The view compatible texture to create a dependency to</param>
        /// <param name="layer">The base layer of the given texture relative to this one</param>
        /// <param name="level">The base level of the given texture relative to this one</param>
        /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
        public void CreateCopyDependency(Texture contained, int layer, int level, bool copyTo)
        {
            if (contained.Group == Group)
            {
                return;
            }

            Group.CreateCopyDependency(contained, FirstLayer + layer, FirstLevel + level, copyTo);
        }

        /// <summary>
        /// Registers when a texture has had its data set after being scaled, and
        /// determines if it should be blacklisted from scaling to improve performance.
        /// </summary>
        /// <returns>True if setting data for a scaled texture is allowed, false if the texture has been blacklisted</returns>
        private bool AllowScaledSetData()
        {
            _scaledSetScore += ScaledSetWeight;

            if (_scaledSetScore >= ScaledSetThreshold)
            {
                BlacklistScale();

                return false;
            }

            return true;
        }

        /// <summary>
        /// Blacklists this texture from being scaled. Resets its scale to 1 if needed.
        /// </summary>
        public void BlacklistScale()
        {
            ScaleMode = TextureScaleMode.Blacklisted;
            SetScale(1f);
        }

        /// <summary>
        /// Propagates the scale between this texture and another to ensure they have the same scale.
        /// If one texture is blacklisted from scaling, the other will become blacklisted too.
        /// </summary>
        /// <param name="other">The other texture</param>
        public void PropagateScale(Texture other)
        {
            if (other.ScaleMode == TextureScaleMode.Blacklisted || ScaleMode == TextureScaleMode.Blacklisted)
            {
                BlacklistScale();
                other.BlacklistScale();
            }
            else
            {
                // Prefer the configured scale if present. If not, prefer the max.
                float targetScale = GraphicsConfig.ResScale;
                float sharedScale = (ScaleFactor == targetScale || other.ScaleFactor == targetScale) ? targetScale : Math.Max(ScaleFactor, other.ScaleFactor);

                SetScale(sharedScale);
                other.SetScale(sharedScale);
            }
        }

        /// <summary>
        /// Copy the host texture to a scaled one. If a texture is not provided, create it with the given scale.
        /// </summary>
        /// <param name="scale">Scale factor</param>
        /// <param name="copy">True if the data should be copied to the texture, false otherwise</param>
        /// <param name="storage">Texture to use instead of creating one</param>
        /// <returns>A host texture containing a scaled version of this texture</returns>
        private ITexture GetScaledHostTexture(float scale, bool copy, ITexture storage = null)
        {
            if (storage == null)
            {
                TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, scale);
                storage = _context.Renderer.CreateTexture(createInfo);
            }

            if (copy)
            {
                HostTexture.CopyTo(storage, new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), new Extents2D(0, 0, storage.Width, storage.Height), true);
            }

            return storage;
        }

        /// <summary>
        /// Sets the Scale Factor on this texture, and immediately recreates it at the correct size.
        /// When a texture is resized, a scaled copy is performed from the old texture to the new one, to ensure no data is lost.
        /// If scale is equivalent, this only propagates the blacklisted/scaled mode.
        /// If called on a view, its storage is resized instead.
        /// When resizing storage, all texture views are recreated.
        /// </summary>
        /// <param name="scale">The new scale factor for this texture</param>
        public void SetScale(float scale)
        {
            bool unscaled = ScaleMode == TextureScaleMode.Blacklisted || (ScaleMode == TextureScaleMode.Undesired && scale == 1);
            TextureScaleMode newScaleMode = unscaled ? ScaleMode : TextureScaleMode.Scaled;

            if (_viewStorage != this)
            {
                _viewStorage.ScaleMode = newScaleMode;
                _viewStorage.SetScale(scale);
                return;
            }

            if (ScaleFactor != scale)
            {
                Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format} to ({ScaleFactor} to {scale}). ");

                ScaleFactor = scale;

                ITexture newStorage = GetScaledHostTexture(ScaleFactor, true);

                Logger.Debug?.Print(LogClass.Gpu, $"  Copy performed: {HostTexture.Width}x{HostTexture.Height} to {newStorage.Width}x{newStorage.Height}");

                ReplaceStorage(newStorage);

                // All views must be recreated against the new storage.

                foreach (var view in _views)
                {
                    Logger.Debug?.Print(LogClass.Gpu, $"  Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format}.");
                    view.ScaleFactor = scale;

                    TextureCreateInfo viewCreateInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, scale);
                    ITexture newView = HostTexture.CreateView(viewCreateInfo, view.FirstLayer - FirstLayer, view.FirstLevel - FirstLevel);

                    view.ReplaceStorage(newView);
                    view.ScaleMode = newScaleMode;
                }
            }

            if (ScaleMode != newScaleMode)
            {
                ScaleMode = newScaleMode;

                foreach (var view in _views)
                {
                    view.ScaleMode = newScaleMode;
                }
            }
        }

        /// <summary>
        /// Checks if the memory for this texture was modified, and returns true if it was.
        /// The modified flags are optionally consumed as a result.
        /// </summary>
        /// <param name="consume">True to consume the dirty flags and reprotect, false to leave them as is</param>
        /// <returns>True if the texture was modified, false otherwise.</returns>
        public bool CheckModified(bool consume)
        {
            return Group.CheckDirty(this, consume);
        }

        /// <summary>
        /// Discards all data for this texture.
        /// This clears all dirty flags and pending copies from other textures.
        /// It should be used if the texture data will be fully overwritten by the next use.
        /// </summary>
        public void DiscardData()
        {
            Group.DiscardData(this);

            _dirty = false;
        }

        /// <summary>
        /// Synchronizes guest and host memory.
        /// This will overwrite the texture data with the texture data on the guest memory, if a CPU
        /// modification is detected.
        /// Be aware that this can cause texture data written by the GPU to be lost, this is just a
        /// one way copy (from CPU owned to GPU owned memory).
        /// </summary>
        public void SynchronizeMemory()
        {
            if (Target == Target.TextureBuffer)
            {
                return;
            }

            if (!_dirty)
            {
                return;
            }

            _dirty = false;

            if (_hasData)
            {
                Group.SynchronizeMemory(this);
            }
            else
            {
                Group.CheckDirty(this, true);
                SynchronizeFull();
            }
        }

        /// <summary>
        /// Signal that this texture is dirty, indicating that the texture group must be checked.
        /// </summary>
        public void SignalGroupDirty()
        {
            _dirty = true;
        }

        /// <summary>
        /// Signal that the modified state is dirty, indicating that the texture group should be notified when it changes.
        /// </summary>
        public void SignalModifiedDirty()
        {
            _modifiedStale = true;
        }

        /// <summary>
        /// Fully synchronizes guest and host memory.
        /// This will replace the entire texture with the data present in guest memory.
        /// </summary>
        public void SynchronizeFull()
        {
            ReadOnlySpan<byte> data = _physicalMemory.GetSpan(Range);

            // If the host does not support ASTC compression, we need to do the decompression.
            // The decompression is slow, so we want to avoid it as much as possible.
            // This does a byte-by-byte check and skips the update if the data is equal in this case.
            // This improves the speed on applications that overwrites ASTC data without changing anything.
            if (Info.FormatInfo.Format.IsAstc() && !_context.Capabilities.SupportsAstcCompression)
            {
                if (_updateCount < ByteComparisonSwitchThreshold)
                {
                    _updateCount++;
                }
                else
                {
                    bool dataMatches = _currentData != null && data.SequenceEqual(_currentData);
                    if (dataMatches)
                    {
                        return;
                    }

                    _currentData = data.ToArray();
                }
            }

            IMemoryOwner<byte> result = ConvertToHostCompatibleFormat(data);

            if (ScaleFactor != 1f && AllowScaledSetData())
            {
                // If needed, create a texture to load from 1x scale.
                ITexture texture = _setHostTexture = GetScaledHostTexture(1f, false, _setHostTexture);

                texture.SetData(result);

                texture.CopyTo(HostTexture, new Extents2D(0, 0, texture.Width, texture.Height), new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), true);
            }
            else
            {
                HostTexture.SetData(result);
            }

            _hasData = true;
        }

        /// <summary>
        /// Uploads new texture data to the host GPU.
        /// </summary>
        /// <param name="data">New data</param>
        public void SetData(IMemoryOwner<byte> data)
        {
            BlacklistScale();

            Group.CheckDirty(this, true);

            AlwaysFlushOnOverlap = true;

            HostTexture.SetData(data);

            _hasData = true;
        }

        /// <summary>
        /// Uploads new texture data to the host GPU for a specific layer/level.
        /// </summary>
        /// <param name="data">New data</param>
        /// <param name="layer">Target layer</param>
        /// <param name="level">Target level</param>
        public void SetData(IMemoryOwner<byte> data, int layer, int level)
        {
            BlacklistScale();

            HostTexture.SetData(data, layer, level);

            _currentData = null;

            _hasData = true;
        }

        /// <summary>
        /// Uploads new texture data to the host GPU for a specific layer/level and 2D sub-region.
        /// </summary>
        /// <param name="data">New data</param>
        /// <param name="layer">Target layer</param>
        /// <param name="level">Target level</param>
        /// <param name="region">Target sub-region of the texture to update</param>
        public void SetData(IMemoryOwner<byte> data, int layer, int level, Rectangle<int> region)
        {
            BlacklistScale();

            HostTexture.SetData(data, layer, level, region);

            _currentData = null;

            _hasData = true;
        }

        /// <summary>
        /// Converts texture data to a format and layout that is supported by the host GPU.
        /// </summary>
        /// <param name="data">Data to be converted</param>
        /// <param name="level">Mip level to convert</param>
        /// <param name="single">True to convert a single slice</param>
        /// <returns>Converted data</returns>
        public IMemoryOwner<byte> ConvertToHostCompatibleFormat(ReadOnlySpan<byte> data, int level = 0, bool single = false)
        {
            int width = Info.Width;
            int height = Info.Height;

            int depth = _depth;
            int layers = single ? 1 : _layers;
            int levels = single ? 1 : (Info.Levels - level);

            width = Math.Max(width >> level, 1);
            height = Math.Max(height >> level, 1);
            depth = Math.Max(depth >> level, 1);

            int sliceDepth = single ? 1 : depth;

            IMemoryOwner<byte> linear;

            if (Info.IsLinear)
            {
                linear = LayoutConverter.ConvertLinearStridedToLinear(
                    width,
                    height,
                    Info.FormatInfo.BlockWidth,
                    Info.FormatInfo.BlockHeight,
                    Info.Stride,
                    Info.Stride,
                    Info.FormatInfo.BytesPerPixel,
                    data);
            }
            else
            {
                linear = LayoutConverter.ConvertBlockLinearToLinear(
                    width,
                    height,
                    depth,
                    sliceDepth,
                    levels,
                    layers,
                    Info.FormatInfo.BlockWidth,
                    Info.FormatInfo.BlockHeight,
                    Info.FormatInfo.BytesPerPixel,
                    Info.GobBlocksInY,
                    Info.GobBlocksInZ,
                    Info.GobBlocksInTileX,
                    _sizeInfo,
                    data);
            }

            IMemoryOwner<byte> result = linear;

            // Handle compressed cases not supported by the host:
            // - ASTC is usually not supported on desktop cards.
            // - BC4/BC5 is not supported on 3D textures.
            if (!_context.Capabilities.SupportsAstcCompression && Format.IsAstc())
            {
                using (result)
                {
                    if (!AstcDecoder.TryDecodeToRgba8P(
                        result.Memory,
                        Info.FormatInfo.BlockWidth,
                        Info.FormatInfo.BlockHeight,
                        width,
                        height,
                        sliceDepth,
                        levels,
                        layers,
                        out IMemoryOwner<byte> decoded))
                    {
                        string texInfo = $"{Info.Target} {Info.FormatInfo.Format} {Info.Width}x{Info.Height}x{Info.DepthOrLayers} levels {Info.Levels}";

                        Logger.Debug?.Print(LogClass.Gpu, $"Invalid ASTC texture at 0x{Info.GpuAddress:X} ({texInfo}).");
                    }

                    if (GraphicsConfig.EnableTextureRecompression)
                    {
                        using (decoded)
                        {
                            return BCnEncoder.EncodeBC7(decoded.Memory, width, height, sliceDepth, levels, layers);
                        }
                    }

                    return decoded;
                }
            }
            else if (!_context.Capabilities.SupportsEtc2Compression && Format.IsEtc2())
            {
                switch (Format)
                {
                    case Format.Etc2RgbaSrgb:
                    case Format.Etc2RgbaUnorm:
                        using (result)
                        {
                            return ETC2Decoder.DecodeRgba(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                    case Format.Etc2RgbPtaSrgb:
                    case Format.Etc2RgbPtaUnorm:
                        using (result)
                        {
                            return ETC2Decoder.DecodePta(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                    case Format.Etc2RgbSrgb:
                    case Format.Etc2RgbUnorm:
                        using (result)
                        {
                            return ETC2Decoder.DecodeRgb(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                }
            }
            else if (!TextureCompatibility.HostSupportsBcFormat(Format, Target, _context.Capabilities))
            {
                switch (Format)
                {
                    case Format.Bc1RgbaSrgb:
                    case Format.Bc1RgbaUnorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC1(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                    case Format.Bc2Srgb:
                    case Format.Bc2Unorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC2(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                    case Format.Bc3Srgb:
                    case Format.Bc3Unorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC3(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                    case Format.Bc4Snorm:
                    case Format.Bc4Unorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC4(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc4Snorm);
                        }
                    case Format.Bc5Snorm:
                    case Format.Bc5Unorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC5(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc5Snorm);
                        }
                    case Format.Bc6HSfloat:
                    case Format.Bc6HUfloat:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC6(result.Memory.Span, width, height, sliceDepth, levels, layers, Format == Format.Bc6HSfloat);
                        }
                    case Format.Bc7Srgb:
                    case Format.Bc7Unorm:
                        using (result)
                        {
                            return BCnDecoder.DecodeBC7(result.Memory.Span, width, height, sliceDepth, levels, layers);
                        }
                }
            }
            else if (!_context.Capabilities.SupportsR4G4Format && Format == Format.R4G4Unorm)
            {
                using (result)
                {
                    var converted = PixelConverter.ConvertR4G4ToR4G4B4A4(result.Memory.Span, width);

                    if (_context.Capabilities.SupportsR4G4B4A4Format)
                    {
                        return converted;
                    }
                    else
                    {
                        using (converted)
                        {
                            return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(converted.Memory.Span, width);
                        }
                    }
                }
            }
            else if (Format == Format.R4G4B4A4Unorm)
            {
                if (!_context.Capabilities.SupportsR4G4B4A4Format)
                {
                    using (result)
                    {
                        return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result.Memory.Span, width);
                    }
                }
            }
            else if (!_context.Capabilities.Supports5BitComponentFormat && Format.Is16BitPacked())
            {
                switch (Format)
                {
                    case Format.B5G6R5Unorm:
                    case Format.R5G6B5Unorm:
                        using (result)
                        {
                            return PixelConverter.ConvertR5G6B5ToR8G8B8A8(result.Memory.Span, width);
                        }
                    case Format.B5G5R5A1Unorm:
                    case Format.R5G5B5X1Unorm:
                    case Format.R5G5B5A1Unorm:
                        using (result)
                        {
                            return PixelConverter.ConvertR5G5B5ToR8G8B8A8(result.Memory.Span, width, Format == Format.R5G5B5X1Unorm);
                        }
                    case Format.A1B5G5R5Unorm:
                        using (result)
                        {
                            return PixelConverter.ConvertA1B5G5R5ToR8G8B8A8(result.Memory.Span, width);
                        }
                    case Format.R4G4B4A4Unorm:
                        using (result)
                        {
                            return PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result.Memory.Span, width);
                        }
                }
            }

            return result;
        }

        /// <summary>
        /// Converts texture data from a format and layout that is supported by the host GPU, back into the intended format on the guest GPU.
        /// </summary>
        /// <param name="output">Optional output span to convert into</param>
        /// <param name="data">Data to be converted</param>
        /// <param name="level">Mip level to convert</param>
        /// <param name="single">True to convert a single slice</param>
        /// <returns>Converted data</returns>
        public ReadOnlySpan<byte> ConvertFromHostCompatibleFormat(Span<byte> output, ReadOnlySpan<byte> data, int level = 0, bool single = false)
        {
            if (Target != Target.TextureBuffer)
            {
                int width = Info.Width;
                int height = Info.Height;

                int depth = _depth;
                int layers = single ? 1 : _layers;
                int levels = single ? 1 : (Info.Levels - level);

                width = Math.Max(width >> level, 1);
                height = Math.Max(height >> level, 1);
                depth = Math.Max(depth >> level, 1);

                if (Info.IsLinear)
                {
                    data = LayoutConverter.ConvertLinearToLinearStrided(
                        output,
                        Info.Width,
                        Info.Height,
                        Info.FormatInfo.BlockWidth,
                        Info.FormatInfo.BlockHeight,
                        Info.Stride,
                        Info.FormatInfo.BytesPerPixel,
                        data);
                }
                else
                {
                    data = LayoutConverter.ConvertLinearToBlockLinear(
                        output,
                        width,
                        height,
                        depth,
                        single ? 1 : depth,
                        levels,
                        layers,
                        Info.FormatInfo.BlockWidth,
                        Info.FormatInfo.BlockHeight,
                        Info.FormatInfo.BytesPerPixel,
                        Info.GobBlocksInY,
                        Info.GobBlocksInZ,
                        Info.GobBlocksInTileX,
                        _sizeInfo,
                        data);
                }
            }

            return data;
        }

        /// <summary>
        /// Flushes the texture data.
        /// This causes the texture data to be written back to guest memory.
        /// If the texture was written by the GPU, this includes all modification made by the GPU
        /// up to this point.
        /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
        /// This may cause data corruption if the memory is already being used for something else on the CPU side.
        /// </summary>
        /// <param name="tracked">Whether or not the flush triggers write tracking. If it doesn't, the texture will not be blacklisted for scaling either.</param>
        /// <returns>True if data was flushed, false otherwise</returns>
        public bool FlushModified(bool tracked = true)
        {
            return TextureCompatibility.CanTextureFlush(Info, _context.Capabilities) && Group.FlushModified(this, tracked);
        }

        /// <summary>
        /// Flushes the texture data.
        /// This causes the texture data to be written back to guest memory.
        /// If the texture was written by the GPU, this includes all modification made by the GPU
        /// up to this point.
        /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
        /// This may cause data corruption if the memory is already being used for something else on the CPU side.
        /// </summary>
        /// <param name="tracked">Whether or not the flush triggers write tracking. If it doesn't, the texture will not be blacklisted for scaling either.</param>
        public void Flush(bool tracked)
        {
            if (TextureCompatibility.CanTextureFlush(Info, _context.Capabilities))
            {
                FlushTextureDataToGuest(tracked);
            }
        }

        /// <summary>
        /// Gets a host texture to use for flushing the texture, at 1x resolution.
        /// If the HostTexture is already at 1x resolution, it is returned directly.
        /// </summary>
        /// <returns>The host texture to flush</returns>
        public ITexture GetFlushTexture()
        {
            ITexture texture = HostTexture;
            if (ScaleFactor != 1f)
            {
                // If needed, create a texture to flush back to host at 1x scale.
                texture = _flushHostTexture = GetScaledHostTexture(1f, true, _flushHostTexture);
            }

            return texture;
        }

        /// <summary>
        /// Gets data from the host GPU, and flushes it all to guest memory.
        /// </summary>
        /// <remarks>
        /// This method should be used to retrieve data that was modified by the host GPU.
        /// This is not cheap, avoid doing that unless strictly needed.
        /// When possible, the data is written directly into guest memory, rather than copied.
        /// </remarks>
        /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
        /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
        public void FlushTextureDataToGuest(bool tracked, ITexture texture = null)
        {
            using WritableRegion region = _physicalMemory.GetWritableRegion(Range, tracked);

            GetTextureDataFromGpu(region.Memory.Span, tracked, texture);
        }

        /// <summary>
        /// Gets data from the host GPU.
        /// </summary>
        /// <remarks>
        /// This method should be used to retrieve data that was modified by the host GPU.
        /// This is not cheap, avoid doing that unless strictly needed.
        /// </remarks>
        /// <param name="output">An output span to place the texture data into</param>
        /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
        /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
        private void GetTextureDataFromGpu(Span<byte> output, bool blacklist, ITexture texture = null)
        {
            PinnedSpan<byte> data;

            if (texture != null)
            {
                data = texture.GetData();
            }
            else
            {
                if (blacklist)
                {
                    BlacklistScale();
                    data = HostTexture.GetData();
                }
                else if (ScaleFactor != 1f)
                {
                    float scale = ScaleFactor;
                    SetScale(1f);
                    data = HostTexture.GetData();
                    SetScale(scale);
                }
                else
                {
                    data = HostTexture.GetData();
                }
            }

            ConvertFromHostCompatibleFormat(output, data.Get());

            data.Dispose();
        }

        /// <summary>
        /// Gets data from the host GPU for a single slice.
        /// </summary>
        /// <remarks>
        /// This method should be used to retrieve data that was modified by the host GPU.
        /// This is not cheap, avoid doing that unless strictly needed.
        /// </remarks>
        /// <param name="output">An output span to place the texture data into. If empty, one is generated</param>
        /// <param name="layer">The layer of the texture to flush</param>
        /// <param name="level">The level of the texture to flush</param>
        /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
        /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
        public void GetTextureDataSliceFromGpu(Span<byte> output, int layer, int level, bool blacklist, ITexture texture = null)
        {
            PinnedSpan<byte> data;

            if (texture != null)
            {
                data = texture.GetData(layer, level);
            }
            else
            {
                if (blacklist)
                {
                    BlacklistScale();
                    data = HostTexture.GetData(layer, level);
                }
                else if (ScaleFactor != 1f)
                {
                    float scale = ScaleFactor;
                    SetScale(1f);
                    data = HostTexture.GetData(layer, level);
                    SetScale(scale);
                }
                else
                {
                    data = HostTexture.GetData(layer, level);
                }
            }

            ConvertFromHostCompatibleFormat(output, data.Get(), level, true);

            data.Dispose();
        }

        /// <summary>
        /// This performs a strict comparison, used to check if this texture is equal to the one supplied.
        /// </summary>
        /// <param name="info">Texture information to compare against</param>
        /// <param name="flags">Comparison flags</param>
        /// <returns>A value indicating how well this texture matches the given info</returns>
        public TextureMatchQuality IsExactMatch(TextureInfo info, TextureSearchFlags flags)
        {
            bool forSampler = (flags & TextureSearchFlags.ForSampler) != 0;

            TextureMatchQuality matchQuality = TextureCompatibility.FormatMatches(Info, info, forSampler, (flags & TextureSearchFlags.DepthAlias) != 0);

            if (matchQuality == TextureMatchQuality.NoMatch)
            {
                return matchQuality;
            }

            if (!TextureCompatibility.LayoutMatches(Info, info))
            {
                return TextureMatchQuality.NoMatch;
            }

            if (!TextureCompatibility.SizeMatches(Info, info, forSampler))
            {
                return TextureMatchQuality.NoMatch;
            }

            if ((flags & TextureSearchFlags.ForSampler) != 0)
            {
                if (!TextureCompatibility.SamplerParamsMatches(Info, info))
                {
                    return TextureMatchQuality.NoMatch;
                }
            }

            if ((flags & TextureSearchFlags.ForCopy) != 0)
            {
                bool msTargetCompatible = Info.Target == Target.Texture2DMultisample && info.Target == Target.Texture2D;

                if (!msTargetCompatible && !TextureCompatibility.TargetAndSamplesCompatible(Info, info))
                {
                    return TextureMatchQuality.NoMatch;
                }
            }
            else if (!TextureCompatibility.TargetAndSamplesCompatible(Info, info))
            {
                return TextureMatchQuality.NoMatch;
            }

            return Info.Levels == info.Levels ? matchQuality : TextureMatchQuality.NoMatch;
        }

        /// <summary>
        /// Check if it's possible to create a view, with the given parameters, from this texture.
        /// </summary>
        /// <param name="info">Texture view information</param>
        /// <param name="range">Texture view physical memory ranges</param>
        /// <param name="exactSize">Indicates if the texture sizes must be exactly equal, or width is allowed to differ</param>
        /// <param name="layerSize">Layer size on the given texture</param>
        /// <param name="caps">Host GPU capabilities</param>
        /// <param name="firstLayer">Texture view initial layer on this texture</param>
        /// <param name="firstLevel">Texture view first mipmap level on this texture</param>
        /// <param name="flags">Texture search flags</param>
        /// <returns>The level of compatiblilty a view with the given parameters created from this texture has</returns>
        public TextureViewCompatibility IsViewCompatible(
            TextureInfo info,
            MultiRange range,
            bool exactSize,
            int layerSize,
            Capabilities caps,
            out int firstLayer,
            out int firstLevel,
            TextureSearchFlags flags = TextureSearchFlags.None)
        {
            TextureViewCompatibility result = TextureViewCompatibility.Full;

            result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewFormatCompatible(Info, info, caps, flags));
            if (result != TextureViewCompatibility.Incompatible)
            {
                result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewTargetCompatible(Info, info, ref caps));

                bool bothMs = Info.Target.IsMultisample() && info.Target.IsMultisample();
                if (bothMs && (Info.SamplesInX != info.SamplesInX || Info.SamplesInY != info.SamplesInY))
                {
                    result = TextureViewCompatibility.Incompatible;
                }

                if (result == TextureViewCompatibility.Full && Info.FormatInfo.Format != info.FormatInfo.Format && !_context.Capabilities.SupportsMismatchingViewFormat)
                {
                    // AMD and Intel have a bug where the view format is always ignored;
                    // they use the parent format instead.
                    // Create a copy dependency to avoid this issue.

                    result = TextureViewCompatibility.CopyOnly;
                }
            }

            firstLayer = 0;
            firstLevel = 0;

            if (result == TextureViewCompatibility.Incompatible)
            {
                return TextureViewCompatibility.Incompatible;
            }

            int offset = Range.FindOffset(range);

            if (offset < 0 || !_sizeInfo.FindView(offset, out firstLayer, out firstLevel))
            {
                return TextureViewCompatibility.LayoutIncompatible;
            }

            if (!TextureCompatibility.ViewLayoutCompatible(Info, info, firstLevel))
            {
                return TextureViewCompatibility.LayoutIncompatible;
            }

            if (info.GetSlices() > 1 && LayerSize != layerSize)
            {
                return TextureViewCompatibility.LayoutIncompatible;
            }

            result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSizeMatches(Info, info, exactSize, firstLevel));
            result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSubImagesInBounds(Info, info, firstLayer, firstLevel));

            return result;
        }

        /// <summary>
        /// Gets a texture of the specified target type from this texture.
        /// This can be used to get an array texture from a non-array texture and vice-versa.
        /// If this texture and the requested targets are equal, then this texture Host texture is returned directly.
        /// </summary>
        /// <param name="target">The desired target type</param>
        /// <returns>A view of this texture with the requested target, or null if the target is invalid for this texture</returns>
        public ITexture GetTargetTexture(Target target)
        {
            if (target == Target)
            {
                return HostTexture;
            }

            if (_arrayViewTexture == null && IsSameDimensionsTarget(target))
            {
                FormatInfo formatInfo = TextureCompatibility.ToHostCompatibleFormat(Info, _context.Capabilities);

                TextureCreateInfo createInfo = new(
                    Info.Width,
                    Info.Height,
                    target == Target.CubemapArray ? 6 : 1,
                    Info.Levels,
                    Info.Samples,
                    formatInfo.BlockWidth,
                    formatInfo.BlockHeight,
                    formatInfo.BytesPerPixel,
                    formatInfo.Format,
                    Info.DepthStencilMode,
                    target,
                    Info.SwizzleR,
                    Info.SwizzleG,
                    Info.SwizzleB,
                    Info.SwizzleA);

                ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0);

                _arrayViewTexture = viewTexture;
                _arrayViewTarget = target;

                return viewTexture;
            }
            else if (_arrayViewTarget == target)
            {
                return _arrayViewTexture;
            }

            return null;
        }

        /// <summary>
        /// Determine if this texture can have anisotropic filtering forced.
        /// Filtered textures that we might want to force anisotropy on should have a lot of mip levels.
        /// </summary>
        /// <returns>True if anisotropic filtering can be forced, false otherwise</returns>
        private bool CanTextureForceAnisotropy()
        {
            if (!(Target == Target.Texture2D || Target == Target.Texture2DArray))
            {
                return false;
            }

            int maxSize = Math.Max(Info.Width, Info.Height);
            int maxLevels = BitOperations.Log2((uint)maxSize) + 1;

            return Info.Levels >= Math.Min(MinLevelsForForceAnisotropy, maxLevels);
        }

        /// <summary>
        /// Check if this texture and the specified target have the same number of dimensions.
        /// For the purposes of this comparison, 2D and 2D Multisample textures are not considered to have
        /// the same number of dimensions. Same for Cubemap and 3D textures.
        /// </summary>
        /// <param name="target">The target to compare with</param>
        /// <returns>True if both targets have the same number of dimensions, false otherwise</returns>
        private bool IsSameDimensionsTarget(Target target)
        {
            switch (Info.Target)
            {
                case Target.Texture1D:
                case Target.Texture1DArray:
                    return target == Target.Texture1D || target == Target.Texture1DArray;
                case Target.Texture2D:
                case Target.Texture2DArray:
                    return target == Target.Texture2D || target == Target.Texture2DArray;
                case Target.Cubemap:
                case Target.CubemapArray:
                    return target == Target.Cubemap || target == Target.CubemapArray;
                case Target.Texture2DMultisample:
                case Target.Texture2DMultisampleArray:
                    return target == Target.Texture2DMultisample || target == Target.Texture2DMultisampleArray;
                case Target.Texture3D:
                    return target == Target.Texture3D;
                default:
                    return false;
            }
        }

        /// <summary>
        /// Replaces view texture information.
        /// This should only be used for child textures with a parent.
        /// </summary>
        /// <param name="parent">The parent texture</param>
        /// <param name="info">The new view texture information</param>
        /// <param name="hostTexture">The new host texture</param>
        /// <param name="firstLayer">The first layer of the view</param>
        /// <param name="firstLevel">The first level of the view</param>
        public void ReplaceView(Texture parent, TextureInfo info, ITexture hostTexture, int firstLayer, int firstLevel)
        {
            IncrementReferenceCount();
            parent._viewStorage.SynchronizeMemory();

            // If this texture has views, they must be given to the new parent.
            if (_views.Count > 0)
            {
                Texture[] viewCopy = _views.ToArray();

                foreach (Texture view in viewCopy)
                {
                    TextureCreateInfo createInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, ScaleFactor);

                    ITexture newView = parent.HostTexture.CreateView(createInfo, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);

                    view.ReplaceView(parent, view.Info, newView, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);
                }
            }

            ReplaceStorage(hostTexture);

            if (_viewStorage != this)
            {
                _viewStorage.RemoveView(this);
            }

            FirstLayer = parent.FirstLayer + firstLayer;
            FirstLevel = parent.FirstLevel + firstLevel;
            parent._viewStorage.AddView(this);

            SetInfo(info);
            DecrementReferenceCount();
        }

        /// <summary>
        /// Sets the internal texture information structure.
        /// </summary>
        /// <param name="info">The new texture information</param>
        private void SetInfo(TextureInfo info)
        {
            Info = info;
            Target = info.Target;
            Width = info.Width;
            Height = info.Height;
            CanForceAnisotropy = CanTextureForceAnisotropy();

            _depth = info.GetDepth();
            _layers = info.GetLayers();
        }

        /// <summary>
        /// Signals that the texture has been modified.
        /// </summary>
        public void SignalModified()
        {
            _scaledSetScore = Math.Max(0, _scaledSetScore - 1);

            if (_modifiedStale || Group.HasCopyDependencies)
            {
                _modifiedStale = false;
                Group.SignalModified(this);
            }

            _physicalMemory.TextureCache.Lift(this);
        }

        /// <summary>
        /// Signals that a texture has been bound, or has been unbound.
        /// During this time, lazy copies will not clear the dirty flag.
        /// </summary>
        /// <param name="bound">True if the texture has been bound, false if it has been unbound</param>
        public void SignalModifying(bool bound)
        {
            if (bound)
            {
                _scaledSetScore = Math.Max(0, _scaledSetScore - 1);
            }

            if (_modifiedStale || Group.HasCopyDependencies || Group.HasFlushBuffer)
            {
                _modifiedStale = false;
                Group.SignalModifying(this, bound);
            }

            _physicalMemory.TextureCache.Lift(this);

            if (bound)
            {
                IncrementReferenceCount();
            }
            else
            {
                DecrementReferenceCount();
            }
        }

        /// <summary>
        /// Replaces the host texture, while disposing of the old one if needed.
        /// </summary>
        /// <param name="hostTexture">The new host texture</param>
        private void ReplaceStorage(ITexture hostTexture)
        {
            DisposeTextures();

            HostTexture = hostTexture;
        }

        /// <summary>
        /// Determine if any of this texture's data overlaps with another.
        /// </summary>
        /// <param name="texture">The texture to check against</param>
        /// <param name="compatibility">The view compatibility of the two textures</param>
        /// <returns>True if any slice of the textures overlap, false otherwise</returns>
        public bool DataOverlaps(Texture texture, TextureViewCompatibility compatibility)
        {
            if (compatibility == TextureViewCompatibility.LayoutIncompatible && Info.GobBlocksInZ > 1 && Info.GobBlocksInZ == texture.Info.GobBlocksInZ)
            {
                // Allow overlapping slices of layout compatible 3D textures with matching GobBlocksInZ, as they are interleaved.
                return false;
            }

            if (texture._sizeInfo.AllOffsets.Length == 1 && _sizeInfo.AllOffsets.Length == 1)
            {
                return Range.OverlapsWith(texture.Range);
            }

            MultiRange otherRange = texture.Range;

            IEnumerable<MultiRange> regions = _sizeInfo.AllRegions().Select((region) => Range.Slice((ulong)region.Offset, (ulong)region.Size));
            IEnumerable<MultiRange> otherRegions = texture._sizeInfo.AllRegions().Select((region) => otherRange.Slice((ulong)region.Offset, (ulong)region.Size));

            foreach (MultiRange region in regions)
            {
                foreach (MultiRange otherRegion in otherRegions)
                {
                    if (region.OverlapsWith(otherRegion))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Increments the texture reference count.
        /// </summary>
        public void IncrementReferenceCount()
        {
            _referenceCount++;
        }

        /// <summary>
        /// Increments the reference count and records the given texture pool and ID as a pool owner.
        /// </summary>
        /// <param name="pool">The texture pool this texture has been added to</param>
        /// <param name="id">The ID of the reference to this texture in the pool</param>
        /// <param name="gpuVa">GPU VA of the pool reference</param>
        public void IncrementReferenceCount(TexturePool pool, int id, ulong gpuVa)
        {
            HadPoolOwner = true;

            lock (_poolOwners)
            {
                _poolOwners.Add(new TexturePoolOwner { Pool = pool, ID = id, GpuAddress = gpuVa });
            }

            _referenceCount++;

            if (ShortCacheEntry != null)
            {
                _physicalMemory.TextureCache.RemoveShortCache(this);
            }
        }

        /// <summary>
        /// Indicates that the texture has one reference left, and will delete on reference decrement.
        /// </summary>
        /// <returns>True if there is one reference remaining, false otherwise</returns>
        public bool HasOneReference()
        {
            return _referenceCount == 1;
        }

        /// <summary>
        /// Decrements the texture reference count.
        /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
        /// </summary>
        /// <returns>True if the texture is now referenceless, false otherwise</returns>
        public bool DecrementReferenceCount()
        {
            int newRefCount = --_referenceCount;

            if (newRefCount == 0)
            {
                if (_viewStorage != this)
                {
                    _viewStorage.RemoveView(this);
                }

                _physicalMemory.TextureCache.RemoveTextureFromCache(this);
            }

            Debug.Assert(newRefCount >= 0);

            DeleteIfNotUsed();

            return newRefCount <= 0;
        }

        /// <summary>
        /// Decrements the texture reference count, also removing an associated pool owner reference.
        /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
        /// </summary>
        /// <param name="pool">The texture pool this texture is being removed from</param>
        /// <param name="id">The ID of the reference to this texture in the pool</param>
        /// <returns>True if the texture is now referenceless, false otherwise</returns>
        public bool DecrementReferenceCount(TexturePool pool, int id = -1)
        {
            lock (_poolOwners)
            {
                int references = _poolOwners.RemoveAll(entry => entry.Pool == pool && entry.ID == id || id == -1);

                if (references == 0)
                {
                    // This reference has already been removed.
                    return _referenceCount <= 0;
                }

                Debug.Assert(references == 1);
            }

            return DecrementReferenceCount();
        }

        /// <summary>
        /// Forcibly remove this texture from all pools that reference it.
        /// </summary>
        /// <param name="deferred">Indicates if the removal is being done from another thread.</param>
        public void RemoveFromPools(bool deferred)
        {
            lock (_poolOwners)
            {
                foreach (var owner in _poolOwners)
                {
                    owner.Pool.ForceRemove(this, owner.ID, deferred);
                }

                _poolOwners.Clear();
            }

            if (ShortCacheEntry != null && !ShortCacheEntry.IsAutoDelete && _context.IsGpuThread())
            {
                // If this is called from another thread (unmapped), the short cache will
                // have to remove this texture on a future tick.

                _physicalMemory.TextureCache.RemoveShortCache(this);
            }

            InvalidatedSequence++;
        }

        /// <summary>
        /// Queue updating texture mappings on the pool. Happens from another thread.
        /// </summary>
        public void UpdatePoolMappings()
        {
            ChangedMapping = true;

            lock (_poolOwners)
            {
                ulong address = 0;

                foreach (var owner in _poolOwners)
                {
                    if (address == 0 || address == owner.GpuAddress)
                    {
                        address = owner.GpuAddress;

                        owner.Pool.QueueUpdateMapping(this, owner.ID);
                    }
                    else
                    {
                        // If there is a different GPU VA mapping, prefer the first and delete the others.
                        owner.Pool.ForceRemove(this, owner.ID, true);
                    }
                }

                _poolOwners.Clear();
            }

            InvalidatedSequence++;
        }

        /// <summary>
        /// Delete the texture if it is not used anymore.
        /// The texture is considered unused when the reference count is zero,
        /// and it has no child views.
        /// </summary>
        private void DeleteIfNotUsed()
        {
            // We can delete the texture as long it is not being used
            // in any cache (the reference count is 0 in this case), and
            // also all views that may be created from this texture were
            // already deleted (views count is 0).
            if (_referenceCount == 0 && _views.Count == 0)
            {
                Dispose();
            }
        }

        /// <summary>
        /// Performs texture disposal, deleting the texture.
        /// </summary>
        private void DisposeTextures()
        {
            InvalidatedSequence++;

            _currentData = null;
            HostTexture.Release();

            _arrayViewTexture?.Release();
            _arrayViewTexture = null;

            _flushHostTexture?.Release();
            _flushHostTexture = null;

            _setHostTexture?.Release();
            _setHostTexture = null;
        }

        /// <summary>
        /// Called when the memory for this texture has been unmapped.
        /// Calls are from non-gpu threads.
        /// </summary>
        /// <param name="unmapRange">The range of memory being unmapped</param>
        public void Unmapped(MultiRange unmapRange)
        {
            ChangedMapping = true;

            if (Group.Storage == this)
            {
                Group.Unmapped();
                Group.ClearModified(unmapRange);
            }
        }

        /// <summary>
        /// Performs texture disposal, deleting the texture.
        /// </summary>
        public void Dispose()
        {
            DisposeTextures();

            if (Group.Storage == this)
            {
                Group.Dispose();
            }
        }
    }
}