aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Graphics.Gpu/Engine/Threed/StateUpdater.cs
blob: d51077dc7f3a1d4c52fc21f3be632118aa5595a2 (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
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu.Engine.Types;
using Ryujinx.Graphics.Gpu.Image;
using Ryujinx.Graphics.Gpu.Shader;
using Ryujinx.Graphics.Shader;
using Ryujinx.Graphics.Texture;
using System;
using System.Runtime.CompilerServices;

namespace Ryujinx.Graphics.Gpu.Engine.Threed
{
    /// <summary>
    /// GPU state updater.
    /// </summary>
    class StateUpdater
    {
        public const int ShaderStateIndex = 16;
        public const int RasterizerStateIndex = 15;
        public const int ScissorStateIndex = 18;
        public const int VertexBufferStateIndex = 0;
        public const int PrimitiveRestartStateIndex = 12;

        private readonly GpuContext _context;
        private readonly GpuChannel _channel;
        private readonly DeviceStateWithShadow<ThreedClassState> _state;
        private readonly DrawState _drawState;

        private readonly StateUpdateTracker<ThreedClassState> _updateTracker;

        private readonly ShaderProgramInfo[] _currentProgramInfo;
        private ShaderSpecializationState _shaderSpecState;

        private ProgramPipelineState _pipeline;

        private bool _vsUsesDrawParameters;
        private bool _vtgWritesRtLayer;
        private byte _vsClipDistancesWritten;

        private bool _prevDrawIndexed;
        private bool _prevDrawIndirect;
        private IndexType _prevIndexType;
        private uint _prevFirstVertex;
        private bool _prevTfEnable;

        private uint _prevRtNoAlphaMask;

        /// <summary>
        /// Creates a new instance of the state updater.
        /// </summary>
        /// <param name="context">GPU context</param>
        /// <param name="channel">GPU channel</param>
        /// <param name="state">3D engine state</param>
        /// <param name="drawState">Draw state</param>
        public StateUpdater(GpuContext context, GpuChannel channel, DeviceStateWithShadow<ThreedClassState> state, DrawState drawState)
        {
            _context = context;
            _channel = channel;
            _state = state;
            _drawState = drawState;
            _currentProgramInfo = new ShaderProgramInfo[Constants.ShaderStages];

            // ShaderState must be updated after other state updates, as pipeline state is sent to the backend when compiling new shaders.
            // Render target state must appear after shader state as it depends on information from the currently bound shader.
            // Rasterizer and scissor states are checked by render target clear, their indexes
            // must be updated on the constants "RasterizerStateIndex" and "ScissorStateIndex" if modified.
            // The vertex buffer state may be forced dirty when a indexed draw starts, the "VertexBufferStateIndex"
            // constant must be updated if modified.
            // The order of the other state updates doesn't matter.
            _updateTracker = new StateUpdateTracker<ThreedClassState>(new[]
            {
                new StateUpdateCallbackEntry(UpdateVertexBufferState,
                    nameof(ThreedClassState.VertexBufferDrawState),
                    nameof(ThreedClassState.VertexBufferInstanced),
                    nameof(ThreedClassState.VertexBufferState),
                    nameof(ThreedClassState.VertexBufferEndAddress)),

                new StateUpdateCallbackEntry(UpdateVertexAttribState, nameof(ThreedClassState.VertexAttribState)),

                new StateUpdateCallbackEntry(UpdateBlendState,
                    nameof(ThreedClassState.BlendIndependent),
                    nameof(ThreedClassState.BlendConstant),
                    nameof(ThreedClassState.BlendStateCommon),
                    nameof(ThreedClassState.BlendEnableCommon),
                    nameof(ThreedClassState.BlendEnable),
                    nameof(ThreedClassState.BlendState)),

                new StateUpdateCallbackEntry(UpdateFaceState, nameof(ThreedClassState.FaceState)),

                new StateUpdateCallbackEntry(UpdateStencilTestState,
                    nameof(ThreedClassState.StencilBackMasks),
                    nameof(ThreedClassState.StencilTestState),
                    nameof(ThreedClassState.StencilBackTestState)),

                new StateUpdateCallbackEntry(UpdateDepthTestState,
                    nameof(ThreedClassState.DepthTestEnable),
                    nameof(ThreedClassState.DepthWriteEnable),
                    nameof(ThreedClassState.DepthTestFunc)),

                new StateUpdateCallbackEntry(UpdateTessellationState,
                    nameof(ThreedClassState.TessOuterLevel),
                    nameof(ThreedClassState.TessInnerLevel),
                    nameof(ThreedClassState.PatchVertices)),

                new StateUpdateCallbackEntry(UpdateViewportTransform,
                    nameof(ThreedClassState.DepthMode),
                    nameof(ThreedClassState.ViewportTransform),
                    nameof(ThreedClassState.ViewportExtents),
                    nameof(ThreedClassState.YControl),
                    nameof(ThreedClassState.ViewportTransformEnable)),

                new StateUpdateCallbackEntry(UpdateLogicOpState, nameof(ThreedClassState.LogicOpState)),

                new StateUpdateCallbackEntry(UpdateDepthClampState, nameof(ThreedClassState.ViewVolumeClipControl)),

                new StateUpdateCallbackEntry(UpdatePolygonMode,
                    nameof(ThreedClassState.PolygonModeFront),
                    nameof(ThreedClassState.PolygonModeBack)),

                new StateUpdateCallbackEntry(UpdateDepthBiasState,
                    nameof(ThreedClassState.DepthBiasState),
                    nameof(ThreedClassState.DepthBiasFactor),
                    nameof(ThreedClassState.DepthBiasUnits),
                    nameof(ThreedClassState.DepthBiasClamp)),

                new StateUpdateCallbackEntry(UpdatePrimitiveRestartState, nameof(ThreedClassState.PrimitiveRestartState)),

                new StateUpdateCallbackEntry(UpdateLineState,
                    nameof(ThreedClassState.LineWidthSmooth),
                    nameof(ThreedClassState.LineSmoothEnable)),

                new StateUpdateCallbackEntry(UpdateRtColorMask,
                    nameof(ThreedClassState.RtColorMaskShared),
                    nameof(ThreedClassState.RtColorMask)),

                new StateUpdateCallbackEntry(UpdateRasterizerState, nameof(ThreedClassState.RasterizeEnable)),

                new StateUpdateCallbackEntry(UpdateShaderState,
                    nameof(ThreedClassState.ShaderBaseAddress),
                    nameof(ThreedClassState.ShaderState)),

                new StateUpdateCallbackEntry(UpdateRenderTargetState,
                    nameof(ThreedClassState.RtColorState),
                    nameof(ThreedClassState.RtDepthStencilState),
                    nameof(ThreedClassState.RtControl),
                    nameof(ThreedClassState.RtDepthStencilSize),
                    nameof(ThreedClassState.RtDepthStencilEnable)),

                new StateUpdateCallbackEntry(UpdateScissorState,
                    nameof(ThreedClassState.ScissorState),
                    nameof(ThreedClassState.ScreenScissorState)),

                new StateUpdateCallbackEntry(UpdateTfBufferState, nameof(ThreedClassState.TfBufferState)),
                new StateUpdateCallbackEntry(UpdateUserClipState, nameof(ThreedClassState.ClipDistanceEnable)),

                new StateUpdateCallbackEntry(UpdateAlphaTestState,
                    nameof(ThreedClassState.AlphaTestEnable),
                    nameof(ThreedClassState.AlphaTestRef),
                    nameof(ThreedClassState.AlphaTestFunc)),

                new StateUpdateCallbackEntry(UpdateSamplerPoolState,
                    nameof(ThreedClassState.SamplerPoolState),
                    nameof(ThreedClassState.SamplerIndex)),

                new StateUpdateCallbackEntry(UpdateTexturePoolState, nameof(ThreedClassState.TexturePoolState)),

                new StateUpdateCallbackEntry(UpdatePointState,
                    nameof(ThreedClassState.PointSize),
                    nameof(ThreedClassState.VertexProgramPointSize),
                    nameof(ThreedClassState.PointSpriteEnable),
                    nameof(ThreedClassState.PointCoordReplace)),

                new StateUpdateCallbackEntry(UpdateIndexBufferState,
                    nameof(ThreedClassState.IndexBufferState),
                    nameof(ThreedClassState.IndexBufferCount)),

                new StateUpdateCallbackEntry(UpdateMultisampleState,
                    nameof(ThreedClassState.AlphaToCoverageDitherEnable),
                    nameof(ThreedClassState.MultisampleControl))
            });
        }

        /// <summary>
        /// Sets a register at a specific offset as dirty.
        /// This must be called if the register value was modified.
        /// </summary>
        /// <param name="offset">Register offset</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void SetDirty(int offset)
        {
            _updateTracker.SetDirty(offset);
        }

        /// <summary>
        /// Force all the guest state to be marked as dirty.
        /// The next call to <see cref="Update"/> will update all the host state.
        /// </summary>
        public void SetAllDirty()
        {
            _updateTracker.SetAllDirty();
        }

        /// <summary>
        /// Updates host state for any modified guest state, since the last time this function was called.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update()
        {
            // If any state that the shader depends on changed,
            // then we may need to compile/bind a different version
            // of the shader for the new state.
            if (_shaderSpecState != null)
            {
                if (!_shaderSpecState.MatchesGraphics(_channel, GetPoolState(), GetGraphicsState(), _vsUsesDrawParameters, false))
                {
                    ForceShaderUpdate();
                }
            }

            // The vertex buffer size is calculated using a different
            // method when doing indexed draws, so we need to make sure
            // to update the vertex buffers if we are doing a regular
            // draw after a indexed one and vice-versa.
            if (_drawState.DrawIndexed != _prevDrawIndexed)
            {
                _updateTracker.ForceDirty(VertexBufferStateIndex);

                // If PrimitiveRestartDrawArrays is false and this is a non-indexed draw, we need to ensure primitive restart is disabled.
                // If PrimitiveRestartDrawArrays is false and this is a indexed draw, we need to ensure primitive restart enable matches GPU state.
                // If PrimitiveRestartDrawArrays is true, then primitive restart enable should always match GPU state.
                // That is because "PrimitiveRestartDrawArrays" is not configurable on the backend, it is always
                // true on OpenGL and always false on Vulkan.
                if (!_state.State.PrimitiveRestartDrawArrays && _state.State.PrimitiveRestartState.Enable)
                {
                    _updateTracker.ForceDirty(PrimitiveRestartStateIndex);
                }

                _prevDrawIndexed = _drawState.DrawIndexed;
            }

            // Some draw parameters are used to restrict the vertex buffer size,
            // but they can't be used on indirect draws because their values are unknown in this case.
            // When switching between indirect and non-indirect draw, we need to
            // make sure the vertex buffer sizes are still correct.
            if (_drawState.DrawIndirect != _prevDrawIndirect)
            {
                _updateTracker.ForceDirty(VertexBufferStateIndex);
            }

            // In some cases, the index type is also used to guess the
            // vertex buffer size, so we must update it if the type changed too.
            if (_drawState.DrawIndexed &&
                (_prevIndexType != _state.State.IndexBufferState.Type ||
                 _prevFirstVertex != _state.State.FirstVertex))
            {
                _updateTracker.ForceDirty(VertexBufferStateIndex);
                _prevIndexType = _state.State.IndexBufferState.Type;
                _prevFirstVertex = _state.State.FirstVertex;
            }

            bool tfEnable = _state.State.TfEnable;

            if (!tfEnable && _prevTfEnable)
            {
                _context.Renderer.Pipeline.EndTransformFeedback();
                _prevTfEnable = false;
            }

            _updateTracker.Update(ulong.MaxValue);

            CommitBindings();

            if (tfEnable && !_prevTfEnable)
            {
                _context.Renderer.Pipeline.BeginTransformFeedback(_drawState.Topology);
                _prevTfEnable = true;
            }
        }

        /// <summary>
        /// Updates the host state for any modified guest state group with the respective bit set on <paramref name="mask"/>.
        /// </summary>
        /// <param name="mask">Mask, where each bit set corresponds to a group index that should be checked and updated</param>
        public void Update(ulong mask)
        {
            _updateTracker.Update(mask);
        }

        /// <summary>
        /// Ensures that the bindings are visible to the host GPU.
        /// Note: this actually performs the binding using the host graphics API.
        /// </summary>
        private void CommitBindings()
        {
            var buffers = _channel.BufferManager;
            var hasUnaligned = buffers.HasUnalignedStorageBuffers;

            UpdateStorageBuffers();

            if (!_channel.TextureManager.CommitGraphicsBindings(_shaderSpecState) || (buffers.HasUnalignedStorageBuffers != hasUnaligned))
            {
                // Shader must be reloaded.
                UpdateShaderState();
            }

            _channel.BufferManager.CommitGraphicsBindings();
        }

        /// <summary>
        /// Updates storage buffer bindings.
        /// </summary>
        private void UpdateStorageBuffers()
        {
            for (int stage = 0; stage < Constants.ShaderStages; stage++)
            {
                ShaderProgramInfo info = _currentProgramInfo[stage];

                if (info == null)
                {
                    continue;
                }

                for (int index = 0; index < info.SBuffers.Count; index++)
                {
                    BufferDescriptor sb = info.SBuffers[index];

                    ulong sbDescAddress = _channel.BufferManager.GetGraphicsUniformBufferAddress(stage, 0);

                    int sbDescOffset = 0x110 + stage * 0x100 + sb.Slot * 0x10;

                    sbDescAddress += (ulong)sbDescOffset;

                    SbDescriptor sbDescriptor = _channel.MemoryManager.Physical.Read<SbDescriptor>(sbDescAddress);

                    _channel.BufferManager.SetGraphicsStorageBuffer(stage, sb.Slot, sbDescriptor.PackAddress(), (uint)sbDescriptor.Size, sb.Flags);
                }
            }
        }

        /// <summary>
        /// Updates tessellation state based on the guest GPU state.
        /// </summary>
        private void UpdateTessellationState()
        {
            _pipeline.PatchControlPoints = (uint)_state.State.PatchVertices;

            _context.Renderer.Pipeline.SetPatchParameters(
                _state.State.PatchVertices,
                _state.State.TessOuterLevel.AsSpan(),
                _state.State.TessInnerLevel.AsSpan());
        }

        /// <summary>
        /// Updates transform feedback buffer state based on the guest GPU state.
        /// </summary>
        private void UpdateTfBufferState()
        {
            for (int index = 0; index < Constants.TotalTransformFeedbackBuffers; index++)
            {
                TfBufferState tfb = _state.State.TfBufferState[index];

                if (!tfb.Enable)
                {
                    _channel.BufferManager.SetTransformFeedbackBuffer(index, 0, 0);

                    continue;
                }

                _channel.BufferManager.SetTransformFeedbackBuffer(index, tfb.Address.Pack(), (uint)tfb.Size);
            }
        }

        /// <summary>
        /// Updates Rasterizer primitive discard state based on guest gpu state.
        /// </summary>
        private void UpdateRasterizerState()
        {
            bool enable = _state.State.RasterizeEnable;
            _pipeline.RasterizerDiscard = !enable;
            _context.Renderer.Pipeline.SetRasterizerDiscard(!enable);
        }

        /// <summary>
        /// Updates render targets (color and depth-stencil buffers) based on current render target state.
        /// </summary>
        private void UpdateRenderTargetState()
        {
            UpdateRenderTargetState(true);
        }

        /// <summary>
        /// Updates render targets (color and depth-stencil buffers) based on current render target state.
        /// </summary>
        /// <param name="useControl">Use draw buffers information from render target control register</param>
        /// <param name="layered">Indicates if the texture is layered</param>
        /// <param name="singleUse">If this is not -1, it indicates that only the given indexed target will be used.</param>
        public void UpdateRenderTargetState(bool useControl, bool layered = false, int singleUse = -1)
        {
            var memoryManager = _channel.MemoryManager;
            var rtControl = _state.State.RtControl;

            int count = useControl ? rtControl.UnpackCount() : Constants.TotalRenderTargets;

            var msaaMode = _state.State.RtMsaaMode;

            int samplesInX = msaaMode.SamplesInX();
            int samplesInY = msaaMode.SamplesInY();

            var scissor = _state.State.ScreenScissorState;
            Size sizeHint = new Size(scissor.X + scissor.Width, scissor.Y + scissor.Height, 1);

            int clipRegionWidth = int.MaxValue;
            int clipRegionHeight = int.MaxValue;

            bool changedScale = false;
            uint rtNoAlphaMask = 0;

            for (int index = 0; index < Constants.TotalRenderTargets; index++)
            {
                int rtIndex = useControl ? rtControl.UnpackPermutationIndex(index) : index;

                var colorState = _state.State.RtColorState[rtIndex];

                if (index >= count || !IsRtEnabled(colorState))
                {
                    changedScale |= _channel.TextureManager.SetRenderTargetColor(index, null);

                    continue;
                }

                if (colorState.Format.NoAlpha())
                {
                    rtNoAlphaMask |= 1u << index;
                }

                Image.Texture color = memoryManager.Physical.TextureCache.FindOrCreateTexture(
                    memoryManager,
                    colorState,
                    _vtgWritesRtLayer || layered,
                    samplesInX,
                    samplesInY,
                    sizeHint);

                changedScale |= _channel.TextureManager.SetRenderTargetColor(index, color);

                if (color != null)
                {
                    if (clipRegionWidth > color.Width / samplesInX)
                    {
                        clipRegionWidth = color.Width / samplesInX;
                    }

                    if (clipRegionHeight > color.Height / samplesInY)
                    {
                        clipRegionHeight = color.Height / samplesInY;
                    }
                }
            }

            bool dsEnable = _state.State.RtDepthStencilEnable;

            Image.Texture depthStencil = null;

            if (dsEnable)
            {
                var dsState = _state.State.RtDepthStencilState;
                var dsSize = _state.State.RtDepthStencilSize;

                depthStencil = memoryManager.Physical.TextureCache.FindOrCreateTexture(
                    memoryManager,
                    dsState,
                    dsSize,
                    _vtgWritesRtLayer || layered,
                    samplesInX,
                    samplesInY,
                    sizeHint);

                if (depthStencil != null)
                {
                    if (clipRegionWidth > depthStencil.Width / samplesInX)
                    {
                        clipRegionWidth = depthStencil.Width / samplesInX;
                    }

                    if (clipRegionHeight > depthStencil.Height / samplesInY)
                    {
                        clipRegionHeight = depthStencil.Height / samplesInY;
                    }
                }
            }

            changedScale |= _channel.TextureManager.SetRenderTargetDepthStencil(depthStencil);

            if (changedScale)
            {
                float oldScale = _channel.TextureManager.RenderTargetScale;
                _channel.TextureManager.UpdateRenderTargetScale(singleUse);

                if (oldScale != _channel.TextureManager.RenderTargetScale)
                {
                    _context.Renderer.Pipeline.SetRenderTargetScale(_channel.TextureManager.RenderTargetScale);

                    UpdateViewportTransform();
                    UpdateScissorState();
                }
            }

            _channel.TextureManager.SetClipRegion(clipRegionWidth, clipRegionHeight);

            if (useControl && _prevRtNoAlphaMask != rtNoAlphaMask)
            {
                _prevRtNoAlphaMask = rtNoAlphaMask;

                UpdateBlendState();
            }
        }

        /// <summary>
        /// Checks if a render target color buffer is used.
        /// </summary>
        /// <param name="colorState">Color buffer information</param>
        /// <returns>True if the specified buffer is enabled/used, false otherwise</returns>
        private static bool IsRtEnabled(RtColorState colorState)
        {
            // Colors are disabled by writing 0 to the format.
            return colorState.Format != 0 && colorState.WidthOrStride != 0;
        }

        /// <summary>
        /// Updates host scissor test state based on current GPU state.
        /// </summary>
        public void UpdateScissorState()
        {
            const int MinX = 0;
            const int MinY = 0;
            const int MaxW = 0xffff;
            const int MaxH = 0xffff;

            Span<Rectangle<int>> regions = stackalloc Rectangle<int>[Constants.TotalViewports];

            for (int index = 0; index < Constants.TotalViewports; index++)
            {
                ScissorState scissor = _state.State.ScissorState[index];

                bool enable = scissor.Enable && (scissor.X1 != MinX ||
                                                 scissor.Y1 != MinY ||
                                                 scissor.X2 != MaxW ||
                                                 scissor.Y2 != MaxH);

                if (enable)
                {
                    int x = scissor.X1;
                    int y = scissor.Y1;
                    int width = scissor.X2 - x;
                    int height = scissor.Y2 - y;

                    if (_state.State.YControl.HasFlag(YControl.NegateY))
                    {
                        ref var screenScissor = ref _state.State.ScreenScissorState;
                        y = screenScissor.Height - height - y;

                        if (y < 0)
                        {
                            height += y;
                            y = 0;
                        }
                    }

                    float scale = _channel.TextureManager.RenderTargetScale;
                    if (scale != 1f)
                    {
                        x = (int)(x * scale);
                        y = (int)(y * scale);
                        width = (int)MathF.Ceiling(width * scale);
                        height = (int)MathF.Ceiling(height * scale);
                    }

                    regions[index] = new Rectangle<int>(x, y, width, height);
                }
                else
                {
                    regions[index] = new Rectangle<int>(MinX, MinY, MaxW, MaxH);
                }
            }

            _context.Renderer.Pipeline.SetScissors(regions);
        }

        /// <summary>
        /// Updates host depth clamp state based on current GPU state.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        private void UpdateDepthClampState()
        {
            ViewVolumeClipControl clip = _state.State.ViewVolumeClipControl;
            bool clamp = (clip & ViewVolumeClipControl.DepthClampDisabled) == 0;

            _pipeline.DepthClampEnable = clamp;
            _context.Renderer.Pipeline.SetDepthClamp(clamp);
        }

        /// <summary>
        /// Updates host alpha test state based on current GPU state.
        /// </summary>
        private void UpdateAlphaTestState()
        {
            _context.Renderer.Pipeline.SetAlphaTest(
                _state.State.AlphaTestEnable,
                _state.State.AlphaTestRef,
                _state.State.AlphaTestFunc);
        }

        /// <summary>
        /// Updates host depth test state based on current GPU state.
        /// </summary>
        private void UpdateDepthTestState()
        {
            DepthTestDescriptor descriptor = new DepthTestDescriptor(
                _state.State.DepthTestEnable,
                _state.State.DepthWriteEnable,
                _state.State.DepthTestFunc);

            _pipeline.DepthTest = descriptor;
            _context.Renderer.Pipeline.SetDepthTest(descriptor);
        }

        /// <summary>
        /// Updates host viewport transform and clipping state based on current GPU state.
        /// </summary>
        private void UpdateViewportTransform()
        {
            var yControl = _state.State.YControl;
            var face = _state.State.FaceState;

            bool disableTransform = _state.State.ViewportTransformEnable == 0;

            UpdateFrontFace(yControl, face.FrontFace);
            UpdateDepthMode();

            bool flipY = yControl.HasFlag(YControl.NegateY);

            Span<Viewport> viewports = stackalloc Viewport[Constants.TotalViewports];

            for (int index = 0; index < Constants.TotalViewports; index++)
            {
                if (disableTransform)
                {
                    ref var scissor = ref _state.State.ScreenScissorState;

                    float rScale = _channel.TextureManager.RenderTargetScale;
                    var scissorRect = new Rectangle<float>(0, 0, (scissor.X + scissor.Width) * rScale, (scissor.Y + scissor.Height) * rScale);

                    viewports[index] = new Viewport(scissorRect, ViewportSwizzle.PositiveX, ViewportSwizzle.PositiveY, ViewportSwizzle.PositiveZ, ViewportSwizzle.PositiveW, 0, 1);
                    continue;
                }

                ref var transform = ref _state.State.ViewportTransform[index];
                ref var extents = ref _state.State.ViewportExtents[index];

                float scaleX = MathF.Abs(transform.ScaleX);
                float scaleY = transform.ScaleY;

                if (flipY)
                {
                    scaleY = -scaleY;
                }

                if (!_context.Capabilities.SupportsViewportSwizzle && transform.UnpackSwizzleY() == ViewportSwizzle.NegativeY)
                {
                    scaleY = -scaleY;
                }

                float x = transform.TranslateX - scaleX;
                float y = transform.TranslateY - scaleY;

                float width = scaleX * 2;
                float height = scaleY * 2;

                float scale = _channel.TextureManager.RenderTargetScale;
                if (scale != 1f)
                {
                    x *= scale;
                    y *= scale;
                    width *= scale;
                    height *= scale;
                }

                Rectangle<float> region = new Rectangle<float>(x, y, width, height);

                ViewportSwizzle swizzleX = transform.UnpackSwizzleX();
                ViewportSwizzle swizzleY = transform.UnpackSwizzleY();
                ViewportSwizzle swizzleZ = transform.UnpackSwizzleZ();
                ViewportSwizzle swizzleW = transform.UnpackSwizzleW();

                float depthNear = extents.DepthNear;
                float depthFar = extents.DepthFar;

                if (transform.ScaleZ < 0)
                {
                    float temp = depthNear;
                    depthNear = depthFar;
                    depthFar = temp;
                }

                viewports[index] = new Viewport(region, swizzleX, swizzleY, swizzleZ, swizzleW, depthNear, depthFar);
            }

            _context.Renderer.Pipeline.SetDepthMode(GetDepthMode());
            _context.Renderer.Pipeline.SetViewports(viewports, disableTransform);
        }

        /// <summary>
        /// Updates the depth mode (0 to 1 or -1 to 1) based on the current viewport and depth mode register state.
        /// </summary>
        private void UpdateDepthMode()
        {
            _context.Renderer.Pipeline.SetDepthMode(GetDepthMode());
        }

        /// <summary>
        /// Updates polygon mode state based on current GPU state.
        /// </summary>
        private void UpdatePolygonMode()
        {
            _context.Renderer.Pipeline.SetPolygonMode(_state.State.PolygonModeFront, _state.State.PolygonModeBack);
        }

        /// <summary>
        /// Updates host depth bias (also called polygon offset) state based on current GPU state.
        /// </summary>
        private void UpdateDepthBiasState()
        {
            var depthBias = _state.State.DepthBiasState;

            float factor = _state.State.DepthBiasFactor;
            float units = _state.State.DepthBiasUnits;
            float clamp = _state.State.DepthBiasClamp;

            PolygonModeMask enables;

            enables = (depthBias.PointEnable ? PolygonModeMask.Point : 0);
            enables |= (depthBias.LineEnable ? PolygonModeMask.Line : 0);
            enables |= (depthBias.FillEnable ? PolygonModeMask.Fill : 0);

            _pipeline.BiasEnable = enables;
            _context.Renderer.Pipeline.SetDepthBias(enables, factor, units / 2f, clamp);
        }

        /// <summary>
        /// Updates host stencil test state based on current GPU state.
        /// </summary>
        private void UpdateStencilTestState()
        {
            var backMasks = _state.State.StencilBackMasks;
            var test = _state.State.StencilTestState;
            var backTest = _state.State.StencilBackTestState;

            CompareOp backFunc;
            StencilOp backSFail;
            StencilOp backDpPass;
            StencilOp backDpFail;
            int backFuncRef;
            int backFuncMask;
            int backMask;

            if (backTest.TwoSided)
            {
                backFunc = backTest.BackFunc;
                backSFail = backTest.BackSFail;
                backDpPass = backTest.BackDpPass;
                backDpFail = backTest.BackDpFail;
                backFuncRef = backMasks.FuncRef;
                backFuncMask = backMasks.FuncMask;
                backMask = backMasks.Mask;
            }
            else
            {
                backFunc = test.FrontFunc;
                backSFail = test.FrontSFail;
                backDpPass = test.FrontDpPass;
                backDpFail = test.FrontDpFail;
                backFuncRef = test.FrontFuncRef;
                backFuncMask = test.FrontFuncMask;
                backMask = test.FrontMask;
            }

            StencilTestDescriptor descriptor = new StencilTestDescriptor(
                test.Enable,
                test.FrontFunc,
                test.FrontSFail,
                test.FrontDpPass,
                test.FrontDpFail,
                test.FrontFuncRef,
                test.FrontFuncMask,
                test.FrontMask,
                backFunc,
                backSFail,
                backDpPass,
                backDpFail,
                backFuncRef,
                backFuncMask,
                backMask);

            _pipeline.StencilTest = descriptor;
            _context.Renderer.Pipeline.SetStencilTest(descriptor);
        }

        /// <summary>
        /// Updates user-defined clipping based on the guest GPU state.
        /// </summary>
        private void UpdateUserClipState()
        {
            uint clipMask = _state.State.ClipDistanceEnable & _vsClipDistancesWritten;

            for (int i = 0; i < Constants.TotalClipDistances; ++i)
            {
                _context.Renderer.Pipeline.SetUserClipDistance(i, (clipMask & (1 << i)) != 0);
            }
        }

        /// <summary>
        /// Updates current sampler pool address and size based on guest GPU state.
        /// </summary>
        private void UpdateSamplerPoolState()
        {
            var texturePool = _state.State.TexturePoolState;
            var samplerPool = _state.State.SamplerPoolState;

            var samplerIndex = _state.State.SamplerIndex;

            int maximumId = samplerIndex == SamplerIndex.ViaHeaderIndex
                ? texturePool.MaximumId
                : samplerPool.MaximumId;

            _channel.TextureManager.SetGraphicsSamplerPool(samplerPool.Address.Pack(), maximumId, samplerIndex);
        }

        /// <summary>
        /// Updates current texture pool address and size based on guest GPU state.
        /// </summary>
        private void UpdateTexturePoolState()
        {
            var texturePool = _state.State.TexturePoolState;

            _channel.TextureManager.SetGraphicsTexturePool(texturePool.Address.Pack(), texturePool.MaximumId);
            _channel.TextureManager.SetGraphicsTextureBufferIndex((int)_state.State.TextureBufferIndex);
        }

        /// <summary>
        /// Updates host vertex attributes based on guest GPU state.
        /// </summary>
        private void UpdateVertexAttribState()
        {
            Span<VertexAttribDescriptor> vertexAttribs = stackalloc VertexAttribDescriptor[Constants.TotalVertexAttribs];

            for (int index = 0; index < Constants.TotalVertexAttribs; index++)
            {
                var vertexAttrib = _state.State.VertexAttribState[index];

                if (!FormatTable.TryGetAttribFormat(vertexAttrib.UnpackFormat(), out Format format))
                {
                    Logger.Debug?.Print(LogClass.Gpu, $"Invalid attribute format 0x{vertexAttrib.UnpackFormat():X}.");

                    format = Format.R32G32B32A32Float;
                }

                vertexAttribs[index] = new VertexAttribDescriptor(
                    vertexAttrib.UnpackBufferIndex(),
                    vertexAttrib.UnpackOffset(),
                    vertexAttrib.UnpackIsConstant(),
                    format);
            }

            _pipeline.SetVertexAttribs(vertexAttribs);
            _context.Renderer.Pipeline.SetVertexAttribs(vertexAttribs);
        }

        /// <summary>
        /// Updates host line width based on guest GPU state.
        /// </summary>
        private void UpdateLineState()
        {
            float width = _state.State.LineWidthSmooth;
            bool smooth = _state.State.LineSmoothEnable;

            _pipeline.LineWidth = width;
            _context.Renderer.Pipeline.SetLineParameters(width, smooth);
        }

        /// <summary>
        /// Updates host point size based on guest GPU state.
        /// </summary>
        private void UpdatePointState()
        {
            float size = _state.State.PointSize;
            bool isProgramPointSize = _state.State.VertexProgramPointSize;
            bool enablePointSprite = _state.State.PointSpriteEnable;

            // TODO: Need to figure out a way to map PointCoordReplace enable bit.
            Origin origin = (_state.State.PointCoordReplace & 4) == 0 ? Origin.LowerLeft : Origin.UpperLeft;

            _context.Renderer.Pipeline.SetPointParameters(size, isProgramPointSize, enablePointSprite, origin);
        }

        /// <summary>
        /// Updates host primitive restart based on guest GPU state.
        /// </summary>
        private void UpdatePrimitiveRestartState()
        {
            PrimitiveRestartState primitiveRestart = _state.State.PrimitiveRestartState;
            bool enable = primitiveRestart.Enable && (_drawState.DrawIndexed || _state.State.PrimitiveRestartDrawArrays);

            _pipeline.PrimitiveRestartEnable = enable;
            _context.Renderer.Pipeline.SetPrimitiveRestart(enable, primitiveRestart.Index);
        }

        /// <summary>
        /// Updates host index buffer binding based on guest GPU state.
        /// </summary>
        private void UpdateIndexBufferState()
        {
            var indexBuffer = _state.State.IndexBufferState;

            if (_drawState.IndexCount == 0)
            {
                return;
            }

            ulong gpuVa = indexBuffer.Address.Pack();

            // Do not use the end address to calculate the size, because
            // the result may be much larger than the real size of the index buffer.
            ulong size = (ulong)(_drawState.FirstIndex + _drawState.IndexCount);

            switch (indexBuffer.Type)
            {
                case IndexType.UShort: size *= 2; break;
                case IndexType.UInt: size *= 4; break;
            }

            _channel.BufferManager.SetIndexBuffer(gpuVa, size, indexBuffer.Type);
        }

        /// <summary>
        /// Updates host vertex buffer bindings based on guest GPU state.
        /// </summary>
        private void UpdateVertexBufferState()
        {
            IndexType indexType = _state.State.IndexBufferState.Type;
            bool indexTypeSmall = indexType == IndexType.UByte || indexType == IndexType.UShort;

            _drawState.IsAnyVbInstanced = false;

            bool drawIndexed = _drawState.DrawIndexed;
            bool drawIndirect = _drawState.DrawIndirect;

            for (int index = 0; index < Constants.TotalVertexBuffers; index++)
            {
                var vertexBuffer = _state.State.VertexBufferState[index];

                if (!vertexBuffer.UnpackEnable())
                {
                    _pipeline.VertexBuffers[index] = new BufferPipelineDescriptor(false, 0, 0);
                    _channel.BufferManager.SetVertexBuffer(index, 0, 0, 0, 0);

                    continue;
                }

                GpuVa endAddress = _state.State.VertexBufferEndAddress[index];

                ulong address = vertexBuffer.Address.Pack();

                int stride = vertexBuffer.UnpackStride();

                bool instanced = _state.State.VertexBufferInstanced[index];

                int divisor = instanced ? vertexBuffer.Divisor : 0;

                _drawState.IsAnyVbInstanced |= divisor != 0;

                ulong vbSize = endAddress.Pack() - address + 1;
                ulong size;

                if (_drawState.IbStreamer.HasInlineIndexData || drawIndexed || stride == 0 || instanced)
                {
                    // This size may be (much) larger than the real vertex buffer size.
                    // Avoid calculating it this way, unless we don't have any other option.

                    size = vbSize;

                    if (stride > 0 && indexTypeSmall && drawIndexed && !drawIndirect && !instanced)
                    {
                        // If the index type is a small integer type, then we might be still able
                        // to reduce the vertex buffer size based on the maximum possible index value.

                        ulong maxVertexBufferSize = indexType == IndexType.UByte ? 0x100UL : 0x10000UL;

                        maxVertexBufferSize += _state.State.FirstVertex;
                        maxVertexBufferSize *= (uint)stride;

                        size = Math.Min(size, maxVertexBufferSize);
                    }
                }
                else
                {
                    // For non-indexed draws, we can guess the size from the vertex count
                    // and stride.

                    int firstInstance = (int)_state.State.FirstInstance;

                    var drawState = _state.State.VertexBufferDrawState;

                    size = Math.Min(vbSize, (ulong)((firstInstance + drawState.First + drawState.Count) * stride));
                }

                _pipeline.VertexBuffers[index] = new BufferPipelineDescriptor(_channel.MemoryManager.IsMapped(address), stride, divisor);
                _channel.BufferManager.SetVertexBuffer(index, address, size, stride, divisor);
            }
        }

        /// <summary>
        /// Updates host face culling and orientation based on guest GPU state.
        /// </summary>
        private void UpdateFaceState()
        {
            var yControl = _state.State.YControl;
            var face = _state.State.FaceState;

            _pipeline.CullEnable = face.CullEnable;
            _pipeline.CullMode = face.CullFace;
            _context.Renderer.Pipeline.SetFaceCulling(face.CullEnable, face.CullFace);

            UpdateFrontFace(yControl, face.FrontFace);
        }

        /// <summary>
        /// Updates the front face based on the current front face and the origin.
        /// </summary>
        /// <param name="yControl">Y control register value, where the origin is located</param>
        /// <param name="frontFace">Front face</param>
        private void UpdateFrontFace(YControl yControl, FrontFace frontFace)
        {
            bool isUpperLeftOrigin = !yControl.HasFlag(YControl.TriangleRastFlip);

            if (isUpperLeftOrigin)
            {
                frontFace = frontFace == FrontFace.CounterClockwise ? FrontFace.Clockwise : FrontFace.CounterClockwise;
            }

            _pipeline.FrontFace = frontFace;
            _context.Renderer.Pipeline.SetFrontFace(frontFace);
        }

        /// <summary>
        /// Updates host render target color masks, based on guest GPU state.
        /// This defines which color channels are written to each color buffer.
        /// </summary>
        private void UpdateRtColorMask()
        {
            bool rtColorMaskShared = _state.State.RtColorMaskShared;

            Span<uint> componentMasks = stackalloc uint[Constants.TotalRenderTargets];

            for (int index = 0; index < Constants.TotalRenderTargets; index++)
            {
                var colorMask = _state.State.RtColorMask[rtColorMaskShared ? 0 : index];

                uint componentMask;

                componentMask = (colorMask.UnpackRed() ? 1u : 0u);
                componentMask |= (colorMask.UnpackGreen() ? 2u : 0u);
                componentMask |= (colorMask.UnpackBlue() ? 4u : 0u);
                componentMask |= (colorMask.UnpackAlpha() ? 8u : 0u);

                componentMasks[index] = componentMask;
                _pipeline.ColorWriteMask[index] = componentMask;
            }

            _context.Renderer.Pipeline.SetRenderTargetColorMasks(componentMasks);
        }

        /// <summary>
        /// Updates host render target color buffer blending state, based on guest state.
        /// </summary>
        private void UpdateBlendState()
        {
            bool blendIndependent = _state.State.BlendIndependent;
            ColorF blendConstant = _state.State.BlendConstant;

            if (blendIndependent)
            {
                for (int index = 0; index < Constants.TotalRenderTargets; index++)
                {
                    bool enable = _state.State.BlendEnable[index];
                    var blend = _state.State.BlendState[index];

                    var descriptor = new BlendDescriptor(
                        enable,
                        blendConstant,
                        blend.ColorOp,
                        FilterBlendFactor(blend.ColorSrcFactor, index),
                        FilterBlendFactor(blend.ColorDstFactor, index),
                        blend.AlphaOp,
                        FilterBlendFactor(blend.AlphaSrcFactor, index),
                        FilterBlendFactor(blend.AlphaDstFactor, index));

                    _pipeline.BlendDescriptors[index] = descriptor;
                    _context.Renderer.Pipeline.SetBlendState(index, descriptor);
                }
            }
            else
            {
                bool enable = _state.State.BlendEnable[0];
                var blend = _state.State.BlendStateCommon;

                var descriptor = new BlendDescriptor(
                    enable,
                    blendConstant,
                    blend.ColorOp,
                    FilterBlendFactor(blend.ColorSrcFactor, 0),
                    FilterBlendFactor(blend.ColorDstFactor, 0),
                    blend.AlphaOp,
                    FilterBlendFactor(blend.AlphaSrcFactor, 0),
                    FilterBlendFactor(blend.AlphaDstFactor, 0));

                for (int index = 0; index < Constants.TotalRenderTargets; index++)
                {
                    _pipeline.BlendDescriptors[index] = descriptor;
                    _context.Renderer.Pipeline.SetBlendState(index, descriptor);
                }
            }
        }

        /// <summary>
        /// Gets a blend factor for the color target currently.
        /// This will return <paramref name="factor"/> unless the target format has no alpha component,
        /// in which case it will replace destination alpha factor with a constant factor of one or zero.
        /// </summary>
        /// <param name="factor">Input factor</param>
        /// <param name="index">Color target index</param>
        /// <returns>New blend factor</returns>
        private BlendFactor FilterBlendFactor(BlendFactor factor, int index)
        {
            // If any color target format without alpha is being used, we need to make sure that
            // if blend is active, it will not use destination alpha as a factor.
            // That is required because RGBX formats are emulated using host RGBA formats.

            if (_state.State.RtColorState[index].Format.NoAlpha())
            {
                switch (factor)
                {
                    case BlendFactor.DstAlpha:
                    case BlendFactor.DstAlphaGl:
                        factor = BlendFactor.One;
                        break;
                    case BlendFactor.OneMinusDstAlpha:
                    case BlendFactor.OneMinusDstAlphaGl:
                        factor = BlendFactor.Zero;
                        break;
                }
            }

            return factor;
        }

        /// <summary>
        /// Updates host logical operation state, based on guest state.
        /// </summary>
        private void UpdateLogicOpState()
        {
            LogicalOpState logicOpState = _state.State.LogicOpState;

            _pipeline.SetLogicOpState(logicOpState.Enable, logicOpState.LogicalOp);
            _context.Renderer.Pipeline.SetLogicOpState(logicOpState.Enable, logicOpState.LogicalOp);
        }

        /// <summary>
        /// Updates multisample state, based on guest state.
        /// </summary>
        private void UpdateMultisampleState()
        {
            bool alphaToCoverageEnable = (_state.State.MultisampleControl & 1) != 0;
            bool alphaToOneEnable = (_state.State.MultisampleControl & 0x10) != 0;

            _context.Renderer.Pipeline.SetMultisampleState(new MultisampleDescriptor(
                alphaToCoverageEnable,
                _state.State.AlphaToCoverageDitherEnable,
                alphaToOneEnable));
        }

        /// <summary>
        /// Updates host shaders based on the guest GPU state.
        /// </summary>
        private void UpdateShaderState()
        {
            var shaderCache = _channel.MemoryManager.Physical.ShaderCache;

            _vtgWritesRtLayer = false;

            ShaderAddresses addresses = new ShaderAddresses();
            Span<ulong> addressesSpan = addresses.AsSpan();

            ulong baseAddress = _state.State.ShaderBaseAddress.Pack();

            for (int index = 0; index < 6; index++)
            {
                var shader = _state.State.ShaderState[index];
                if (!shader.UnpackEnable() && index != 1)
                {
                    continue;
                }

                addressesSpan[index] = baseAddress + shader.Offset;
            }

            GpuChannelPoolState poolState = GetPoolState();
            GpuChannelGraphicsState graphicsState = GetGraphicsState();

            CachedShaderProgram gs = shaderCache.GetGraphicsShader(ref _state.State, ref _pipeline, _channel, poolState, graphicsState, addresses);

            _shaderSpecState = gs.SpecializationState;

            byte oldVsClipDistancesWritten = _vsClipDistancesWritten;

            _drawState.VsUsesInstanceId = gs.Shaders[1]?.Info.UsesInstanceId ?? false;
            _vsUsesDrawParameters = gs.Shaders[1]?.Info.UsesDrawParameters ?? false;
            _vsClipDistancesWritten = gs.Shaders[1]?.Info.ClipDistancesWritten ?? 0;

            if (oldVsClipDistancesWritten != _vsClipDistancesWritten)
            {
                UpdateUserClipState();
            }

            for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++)
            {
                UpdateStageBindings(stageIndex, gs.Shaders[stageIndex + 1]?.Info);
            }

            _context.Renderer.Pipeline.SetProgram(gs.HostProgram);
        }

        /// <summary>
        /// Updates bindings consumed by the shader stage on the texture and buffer managers.
        /// </summary>
        /// <param name="stage">Shader stage to have the bindings updated</param>
        /// <param name="info">Shader stage bindings info</param>
        private void UpdateStageBindings(int stage, ShaderProgramInfo info)
        {
            _currentProgramInfo[stage] = info;

            if (info == null)
            {
                _channel.TextureManager.RentGraphicsTextureBindings(stage, 0);
                _channel.TextureManager.RentGraphicsImageBindings(stage, 0);
                _channel.BufferManager.SetGraphicsStorageBufferBindings(stage, null);
                _channel.BufferManager.SetGraphicsUniformBufferBindings(stage, null);
                return;
            }

            int maxTextureBinding = -1;
            int maxImageBinding = -1;

            Span<TextureBindingInfo> textureBindings = _channel.TextureManager.RentGraphicsTextureBindings(stage, info.Textures.Count);

            if (info.UsesRtLayer)
            {
                _vtgWritesRtLayer = true;
            }

            for (int index = 0; index < info.Textures.Count; index++)
            {
                var descriptor = info.Textures[index];

                Target target = ShaderTexture.GetTarget(descriptor.Type);

                textureBindings[index] = new TextureBindingInfo(
                    target,
                    descriptor.Binding,
                    descriptor.CbufSlot,
                    descriptor.HandleIndex,
                    descriptor.Flags);

                if (descriptor.Binding > maxTextureBinding)
                {
                    maxTextureBinding = descriptor.Binding;
                }
            }

            TextureBindingInfo[] imageBindings = _channel.TextureManager.RentGraphicsImageBindings(stage, info.Images.Count);

            for (int index = 0; index < info.Images.Count; index++)
            {
                var descriptor = info.Images[index];

                Target target = ShaderTexture.GetTarget(descriptor.Type);
                Format format = ShaderTexture.GetFormat(descriptor.Format);

                imageBindings[index] = new TextureBindingInfo(
                    target,
                    format,
                    descriptor.Binding,
                    descriptor.CbufSlot,
                    descriptor.HandleIndex,
                    descriptor.Flags);

                if (descriptor.Binding > maxImageBinding)
                {
                    maxImageBinding = descriptor.Binding;
                }
            }

            _channel.TextureManager.SetGraphicsMaxBindings(maxTextureBinding, maxImageBinding);

            _channel.BufferManager.SetGraphicsStorageBufferBindings(stage, info.SBuffers);
            _channel.BufferManager.SetGraphicsUniformBufferBindings(stage, info.CBuffers);
        }

        /// <summary>
        /// Gets the current texture pool state.
        /// </summary>
        /// <returns>Texture pool state</returns>
        private GpuChannelPoolState GetPoolState()
        {
            return new GpuChannelPoolState(
                _state.State.TexturePoolState.Address.Pack(),
                _state.State.TexturePoolState.MaximumId,
                (int)_state.State.TextureBufferIndex);
        }

        /// <summary>
        /// Gets the current GPU channel state for shader creation or compatibility verification.
        /// </summary>
        /// <returns>Current GPU channel state</returns>
        private GpuChannelGraphicsState GetGraphicsState()
        {
            ref var vertexAttribState = ref _state.State.VertexAttribState;

            Array32<AttributeType> attributeTypes = new Array32<AttributeType>();

            for (int location = 0; location < attributeTypes.Length; location++)
            {
                VertexAttribType type = vertexAttribState[location].UnpackType();

                attributeTypes[location] = type switch
                {
                    VertexAttribType.Sint => AttributeType.Sint,
                    VertexAttribType.Uint => AttributeType.Uint,
                    _ => AttributeType.Float
                };
            }

            return new GpuChannelGraphicsState(
                _state.State.EarlyZForce,
                _drawState.Topology,
                _state.State.TessMode,
                (_state.State.MultisampleControl & 1) != 0,
                _state.State.AlphaToCoverageDitherEnable,
                _state.State.ViewportTransformEnable == 0,
                GetDepthMode() == DepthMode.MinusOneToOne,
                _state.State.VertexProgramPointSize,
                _state.State.PointSize,
                _state.State.AlphaTestEnable,
                _state.State.AlphaTestFunc,
                _state.State.AlphaTestRef,
                ref attributeTypes,
                _drawState.HasConstantBufferDrawParameters,
                _channel.BufferManager.HasUnalignedStorageBuffers);
        }

        /// <summary>
        /// Gets the depth mode that is currently being used (zero to one or minus one to one).
        /// </summary>
        /// <returns>Current depth mode</returns>
        private DepthMode GetDepthMode()
        {
            ref var transform = ref _state.State.ViewportTransform[0];
            ref var extents = ref _state.State.ViewportExtents[0];

            DepthMode depthMode;

            if (!float.IsInfinity(extents.DepthNear) &&
                !float.IsInfinity(extents.DepthFar) &&
                (extents.DepthFar - extents.DepthNear) != 0)
            {
                // Try to guess the depth mode being used on the high level API
                // based on current transform.
                // It is setup like so by said APIs:
                // If depth mode is ZeroToOne:
                //  TranslateZ = Near
                //  ScaleZ = Far - Near
                // If depth mode is MinusOneToOne:
                //  TranslateZ = (Near + Far) / 2
                //  ScaleZ = (Far - Near) / 2
                // DepthNear/Far are sorted such as that Near is always less than Far.
                depthMode = extents.DepthNear != transform.TranslateZ &&
                            extents.DepthFar  != transform.TranslateZ
                    ? DepthMode.MinusOneToOne
                    : DepthMode.ZeroToOne;
            }
            else
            {
                // If we can't guess from the viewport transform, then just use the depth mode register.
                depthMode = (DepthMode)(_state.State.DepthMode & 1);
            }

            return depthMode;
        }

        /// <summary>
        /// Forces the shaders to be rebound on the next draw.
        /// </summary>
        public void ForceShaderUpdate()
        {
            _updateTracker.ForceDirty(ShaderStateIndex);
        }
    }
}