Repository navigation
Expand file tree
/
Copy pathState.cpp
More file actions
2052 lines (1950 loc) · 135 KB
/
Copy pathState.cpp
File metadata and controls
2052 lines (1950 loc) · 135 KB
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
#include <cstdio>
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureSwizzleEquations.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/General.hpp"
#include <algorithm>
#include <bit>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <span>
#include <array>
#include <sstream>
#include <string_view>
namespace AgcDriver::Graphics {
void NormalizeUnusedViewportDepth(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel) {
if (state.depth || pixel.posZ) return;
if (!std::isfinite(state.viewport.minDepth) || !std::isfinite(state.viewport.maxDepth)) return;
state.viewport.minDepth = std::clamp(state.viewport.minDepth, 0.0f, 1.0f);
state.viewport.maxDepth = std::clamp(state.viewport.maxDepth, 0.0f, 1.0f);
}
namespace {
std::uint32_t read(const Registers& registers, std::uint32_t offset, RegisterBank bank = RegisterBank::Context) {
NoteRegisterRead(bank, offset);
const auto it = registers.find(offset);
if (it == registers.end()) {
std::ostringstream message;
message << "missing register in " << RegisterBankName(bank) << " bank at DWORD 0x" << std::hex << offset << " (" << std::dec << offset << ')';
throw std::runtime_error("AGC graphics: " + message.str());
}
return it->second;
}
// A register that may be absent (the decoders' find/contains), through the facade.
Registers::const_iterator find(const Registers& registers, std::uint32_t offset, RegisterBank bank = RegisterBank::Context) {
NoteRegisterRead(bank, offset);
return registers.find(offset);
}
float readFloat(const Registers& registers, std::uint32_t offset) {
const auto value = std::bit_cast<float>(read(registers, offset));
if (!std::isfinite(value)) Require(false, "non-finite register at DWORD " + std::to_string(offset));
return value;
}
float readDepthBound(const Registers& registers, std::uint32_t offset) {
const auto value = std::bit_cast<float>(read(registers, offset));
if (std::isnan(value)) Require(false, "NaN depth bound at DWORD " + std::to_string(offset));
return value;
}
std::string zeroMessage(std::uint32_t offset, std::uint32_t value, const char* name) {
char detail[64];
std::snprintf(detail, sizeof(detail), " (register 0x%x = 0x%08x)", offset, value);
return std::string(name) + " is unsupported" + detail;
}
std::string tessellationMessage(std::uint32_t config, std::uint32_t parameters, const ShaderRecompiler::TessellationConfiguration& tess) {
static constexpr std::array<std::string_view, 3> Types{"TESS_ISOLINE", "TESS_TRIANGLE", "TESS_QUAD"};
static constexpr std::array<std::string_view, 4> Partitionings{"PART_INTEGER", "PART_POW2", "PART_FRAC_ODD", "PART_FRAC_EVEN"};
static constexpr std::array<std::string_view, 4> Topologies{"OUTPUT_POINT", "OUTPUT_LINE", "OUTPUT_TRIANGLE_CW", "OUTPUT_TRIANGLE_CCW"};
std::ostringstream message;
const auto field = [&](std::string_view name, std::uint32_t value, std::span<const std::string_view> names) {
message << name << '=' << value;
if (value < names.size()) message << ' ' << names[value];
};
message << "VGT_TF_PARAM=0x" << std::hex << parameters << std::dec << " (";
field("TYPE", tess.domain, Types);
message << ", ";
field("PARTITIONING", tess.partitioning, Partitionings);
message << ", ";
field("TOPOLOGY", tess.outputTopology, Topologies);
message << "), VGT_LS_HS_CONFIG=0x" << std::hex << config << std::dec << " (NUM_PATCHES=" << tess.patchesPerGroup << ", HS_NUM_INPUT_CP=" << tess.inputControlPoints << ", HS_NUM_OUTPUT_CP=" << tess.outputControlPoints << "): only triangle and quad domains with integer, fractional-even or fractional-odd partitioning and triangle output are supported by the reference path";
return message.str();
}
void zero(const Registers& registers, std::uint32_t offset, std::uint32_t mask, const char* name, RegisterBank bank = RegisterBank::Context) {
const auto value = read(registers, offset, bank);
if ((value & mask) != 0) throw std::runtime_error(zeroMessage(offset, value, name));
}
std::string vteMessage(std::uint32_t viewportControl) {
std::ostringstream message;
message << "AGC graphics: PA_CL_VTE_CNTL=0x" << std::hex << viewportControl << ": expected 0x43f for homogeneous positions and all viewport transforms; pre-divided coordinates, reciprocal W or disabled transforms are unsupported";
return message.str();
}
std::string conservativeMessage(std::uint32_t control) {
std::ostringstream message;
message << "AGC graphics: PA_SC_CONSERVATIVE_RASTERIZATION_CNTL=0x" << std::hex << control << ": only off (over- and underestimation disabled, with at most the inner-to-normal overrides, NULL_SQUAD_AA_MASK_ENABLE and the uncertainty-region mode and edge rules set) and 0x6001 (overestimation) are supported";
return message.str();
}
void requireConservativeTriangles(bool triangles, const char* primitive, const char* source, std::uint32_t value) {
if (triangles) return;
std::ostringstream message;
message << "AGC graphics: conservative rasterization of " << primitive << " is unsupported (" << source << "=0x" << std::hex << value << "): only triangles are overestimated";
throw std::runtime_error(message.str());
}
VkConservativeRasterizationModeEXT decodeConservativeRasterization(const QueueState& queue) {
const auto& cx = queue.context;
const auto control = read(cx, 0x313);
if ((control & ~0x001f6000u) == 0) return VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT;
if (control != 0x6001u) throw std::runtime_error(conservativeMessage(control));
const auto stages = read(cx, 0x2d5);
if ((stages & 0x20u) != 0) {
const auto output = read(cx, 0x29b);
const auto type = output & 0x3fu;
const bool perStream = (output & 0x80000000u) != 0;
requireConservativeTriangles(!perStream && type == 2u, perStream ? "per-stream primitive types" : type == 0u ? "points" : type == 1u ? "lines" : "other primitive types", "VGT_GS_OUT_PRIM_TYPE", output);
} else if ((stages & 4u) != 0) {
const auto parameters = read(cx, 0x2db);
const auto domain = parameters & 3u;
const auto topology = (parameters >> 5u) & 7u;
requireConservativeTriangles((domain == 1u || domain == 2u) && (topology == 2u || topology == 3u), topology == 0u ? "points" : topology == 1u || domain == 0u ? "lines" : "other primitive types", "VGT_TF_PARAM", parameters);
} else {
const auto primitive = read(queue.userConfig, 0x242, RegisterBank::UserConfig);
requireConservativeTriangles(primitive == 4u || primitive == 5u || primitive == 6u || primitive == 21u, primitive == 1u ? "points" : primitive == 2u || primitive == 3u ? "lines" : primitive == 7u || primitive == 17u ? "rectangles" : "other primitive types", "VGT_PRIMITIVE_TYPE", primitive);
}
Require((read(cx, 0x1b3) & 0x44u) == 0 || (read(cx, 0x2f8) & 7u) == 0, "conservative rasterization with centroid interpolation of more than one rasterized sample is unsupported");
return VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT;
}
// The register rules DecodeState and DrawRejection share (the precheck must reject exactly what
// DecodeState would): the masks whose set bits are unsupported, and the depth-control verdict.
constexpr std::uint32_t LayerExports = (1u << 18u) | (1u << 19u) | (1u << 21u) | (1u << 24u);
constexpr std::uint32_t ClipCullExports = 0xffffu | (1u << 22u) | (1u << 23u);
std::uint32_t inactiveVertexPointSize(const QueueState& queue) {
const auto stages = find(queue.context, 0x2d5);
const auto primitive = find(queue.userConfig, 0x242, RegisterBank::UserConfig);
const auto raster = find(queue.context, 0x205);
if (stages == queue.context.end() || primitive == queue.userConfig.end() || raster == queue.context.end()) return 0;
if ((stages->second & 0x24u) != 0) return 0;
if ((raster->second & 8u) != 0 && (raster->second & 0x7e0u) != 0x240u) return 0;
switch (primitive->second) {
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 17:
case 21:
case 19:
return 1u << 16u;
default:
return 0;
}
}
constexpr std::uint32_t DepthControlMask = ~0x007007f0u;
// EXEC_ON_HIER_FAIL / EXEC_ON_NOOP / EXEC_IF_OVERLAPPED (bits 9, 10, 17) only force the pixel shader
// to run, which it always does here.
constexpr std::uint32_t ShaderControlMask = ~(0x0000f870u | 0x00020600u | 0x00010000u);
constexpr std::uint32_t PixelStageRunsMask = 0x000207c7u;
constexpr std::uint32_t AlphaToCoverageMask = ~0x0001ff00u;
constexpr std::uint32_t AlphaToCoverageUndithered = 0x0000aa01u;
constexpr std::uint32_t AlphaToCoverageDithered = 0x00018701u;
bool alphaToCoverageDisabled(const Registers& cx) {
const auto control = find(cx, 0x203);
return control != cx.end() && (control->second & 0x800u) != 0;
}
bool ditheredAlphaSamplesSupported(const Registers& cx) {
const auto config = find(cx, 0x2f8);
const auto eqaa = find(cx, 0x201);
return config != cx.end() && (config->second & 0x700007u) == 0x300003u && eqaa != cx.end() && (eqaa->second & 0x207777u) == 0x3303u;
}
bool ditheredAlphaLocationsSupported(const Registers& cx) {
for (std::uint32_t pixel = 0; pixel < 4; ++pixel) {
const auto first = find(cx, 0x2fe + pixel * 4u);
const auto second = find(cx, 0x2ff + pixel * 4u);
if (first == cx.end() || second == cx.end() || first->second != 0xbd153fd1u || second->second != 0x9773f95bu) return false;
}
return true;
}
constexpr std::uint32_t ScanModeMask = ~0x22u;
constexpr std::uint32_t ScanControlMask = ~0x76033fffu;
constexpr std::uint32_t PixelShaderIteratesSamples = 0x10000u;
constexpr std::uint32_t PixelSampleCoverageInput = 0x4000u;
constexpr std::uint32_t PixelSampleRateInputs = 0x2011u;
constexpr std::uint32_t ScreenOffsetMask = ~0x01ff01ffu;
// Bits 26/27 (ZCLIP_NEAR/FAR_DISABLE) become depth clamping; bit 19 selects the [0, 1] clip space.
constexpr std::uint32_t ClipControlMask = ~(0x80000u | 0x01000000u | 0x0c000000u);
bool zFormatSupported(std::uint32_t format) {
return format == 0u || format == 1u || format == 2u || format == 3u || format == 9u;
}
std::uint32_t shaderControlMask(std::uint32_t zFormat) {
constexpr std::uint32_t zExportEnable = 0x1u;
constexpr std::uint32_t stencilTestValExportEnable = 0x2u;
constexpr std::uint32_t stencilOpValExportEnable = 0x4u;
constexpr std::uint32_t maskExportEnable = 0x100u;
auto mask = ShaderControlMask;
if (zFormat != 0u && zFormatSupported(zFormat)) mask &= ~zExportEnable;
if (zFormat == 2u || zFormat == 9u) mask &= ~(stencilTestValExportEnable | stencilOpValExportEnable);
if (zFormat == 9u) mask &= ~maskExportEnable;
return mask;
}
// Debug aid: APS5_IGNORE_DEPTH_TEST=1 renders depth- and stencil-tested draws without a depth
// target as if their tests always passed (wrong occlusion, but the draws run), so stages that
// depth-test everything can exercise the draw paths before depth targets exist.
bool IgnoreDepthTest() {
static const bool ignore = std::getenv("APS5_IGNORE_DEPTH_TEST") != nullptr;
return ignore;
}
bool depthSurfaceBound(const Registers& cx) {
const auto z = find(cx, 0x010);
const auto stencil = find(cx, 0x011);
return (z != cx.end() && (z->second & 3u) != 0) || (stencil != cx.end() && (stencil->second & 1u) != 0);
}
std::uint32_t planeTests(const Registers& cx, std::uint32_t depthControl) {
const auto z = find(cx, 0x010);
const auto stencil = find(cx, 0x011);
if (z != cx.end() && (z->second & 3u) == 0) depthControl &= ~2u;
if (stencil != cx.end() && (stencil->second & 1u) == 0) depthControl &= ~1u;
return depthControl & 0xbu;
}
bool depthPlanesAbsent(const Registers& cx) {
const auto z = find(cx, 0x010);
const auto stencil = find(cx, 0x011);
return z != cx.end() && stencil != cx.end() && (z->second & 3u) == 0 && (stencil->second & 1u) == 0;
}
VkStencilOpState stencilFace(std::uint32_t compare, std::uint32_t ops, std::uint32_t refMask, bool readOnly, bool testValExport, bool opValExport, bool opValReference) {
VkStencilOpState face{};
face.compareOp = static_cast<VkCompareOp>(compare);
face.compareMask = (refMask >> 8u) & 0xffu;
face.writeMask = readOnly ? 0u : (refMask >> 16u) & 0xffu;
const auto test = refMask & 0xffu;
const auto opValue = refMask >> 24u;
auto reference = test;
auto fixed = compare == 0 || compare == 7 ? 0u : face.compareMask;
const auto convert = [&](std::uint32_t op) {
if (face.writeMask == 0) return VK_STENCIL_OP_KEEP;
char detail[112];
if (opValExport && ((op == 4 && !opValReference) || op == 5 || op == 6 || op == 8 || op == 9)) {
std::snprintf(detail, sizeof(detail), "AGC graphics: stencil operation %u with a pixel shader that exports the stencil operation value is unsupported", op);
throw std::runtime_error(detail);
}
switch (op) {
case 0: return VK_STENCIL_OP_KEEP;
case 1: return VK_STENCIL_OP_ZERO;
case 2:
case 3:
case 4: {
if (testValExport) {
if (op != 3) throw std::runtime_error("AGC graphics: stencil replacement by a value other than the test value is unsupported with a pixel shader that exports the stencil test value");
return VK_STENCIL_OP_REPLACE;
}
if (opValReference) {
if (op != 4) throw std::runtime_error("AGC graphics: stencil replacement by a value other than the operation value is unsupported with a pixel shader that exports the stencil operation value");
return VK_STENCIL_OP_REPLACE;
}
const auto value = op == 2 ? 0xffu : op == 3 ? test : opValue;
if (((reference ^ value) & fixed & face.writeMask) != 0) {
std::snprintf(detail, sizeof(detail), "AGC graphics: stencil replacement 0x%02x against test value 0x%02x (masks 0x%02x/0x%02x) is unsupported", value, test, face.compareMask, face.writeMask);
throw std::runtime_error(detail);
}
reference = (reference & ~face.writeMask) | (value & face.writeMask);
fixed |= face.writeMask;
return VK_STENCIL_OP_REPLACE;
}
case 5:
case 6:
case 8:
case 9:
if (opValue != 1) {
std::snprintf(detail, sizeof(detail), "AGC graphics: stencil add/subtract of 0x%02x is unsupported", opValue);
throw std::runtime_error(detail);
}
return op == 5 ? VK_STENCIL_OP_INCREMENT_AND_CLAMP : op == 6 ? VK_STENCIL_OP_DECREMENT_AND_CLAMP : op == 8 ? VK_STENCIL_OP_INCREMENT_AND_WRAP : VK_STENCIL_OP_DECREMENT_AND_WRAP;
case 7: return VK_STENCIL_OP_INVERT;
default:
std::snprintf(detail, sizeof(detail), "AGC graphics: stencil operation %u is unsupported", op);
throw std::runtime_error(detail);
}
};
face.failOp = convert(ops & 0xfu);
face.passOp = convert((ops >> 4u) & 0xfu);
face.depthFailOp = convert((ops >> 8u) & 0xfu);
face.reference = reference;
Require(!opValReference || compare == 0 || compare == 7 || face.compareMask == 0, "a stencil compare against the test value is unsupported with a pixel shader that exports the stencil operation value");
return face;
}
void decodeDepth(const Registers& cx, std::uint32_t depthControl, bool testValExport, bool opValExport, State& result) {
const bool opValReference = opValExport && StencilOperationValueReplaces(cx);
zero(cx, 0x000, 0x0000101cu, "depth copy, resummarize or decompress draws (DB_RENDER_CONTROL)");
const bool depthClear = (read(cx, 0x000) & 1u) != 0;
const bool stencilClear = (read(cx, 0x000) & 2u) != 0;
const auto view = read(cx, 0x002);
zero(cx, 0x002, 0x3c000000u, "depth mips (DB_DEPTH_VIEW MIP_LEVEL)");
zero(cx, 0x010, 0x000f1000u, "partially resident or mipmapped depth (DB_Z_INFO)");
zero(cx, 0x011, 0x00001000u, "partially resident stencil (DB_STENCIL_INFO)");
const auto zFormat = read(cx, 0x010) & 3u;
const bool stencil = (read(cx, 0x011) & 1u) != 0;
Require(zFormat != 2, "Z_24 depth is unsupported");
if (zFormat == 0) depthControl &= ~6u;
if (!stencil) depthControl &= ~1u;
const auto base = [&](std::uint32_t low, std::uint32_t highOffset) {
const auto high = find(cx, highOffset);
return (high == cx.end() ? 0ull : static_cast<std::uint64_t>(high->second & 0xffu) << 40u) | (static_cast<std::uint64_t>(read(cx, low)) << 8u);
};
const bool depthReadOnly = (view & 0x01000000u) != 0;
const bool stencilReadOnly = (view & 0x02000000u) != 0;
Require(!stencilClear || (stencil && !stencilReadOnly), "stencil clear requires a writable stencil plane");
Require(!stencilClear || !testValExport, "stencil clear with a pixel shader that exports the stencil test value is unsupported");
Require(!depthClear || (zFormat != 0 && !depthReadOnly), "depth clear requires a writable depth plane");
DepthTarget depth{};
depth.samples = 1u << ((read(cx, 0x010) >> 2u) & 3u);
depth.depthSwizzle = (read(cx, 0x010) >> 4u) & 31u;
depth.iterate256 = (read(cx, 0x010) & (1u << 20u)) != 0;
depth.firstSlice = view & 0x1fffu;
depth.lastSlice = (view >> 13u) & 0x7ffu;
depth.address = zFormat != 0 ? base(0x012, 0x01a) : 0;
depth.stencilAddress = stencil ? base(0x013, 0x01b) : 0;
const bool depthWritten = zFormat != 0 && !depthReadOnly && (depthClear || (depthControl & 6u) == 6u || (read(cx, 0x000) & 0x60u) != 0);
Require(!depthWritten || base(0x014, 0x01c) == depth.address, "depth read and written at different addresses is unsupported");
Require(!stencil || stencilReadOnly || base(0x015, 0x01d) == depth.stencilAddress, "stencil read and written at different addresses is unsupported");
if (depth.samples != 1u) {
depth.pipeBankXor = static_cast<std::uint32_t>(depth.address & 65535u);
depth.address &= ~std::uint64_t{65535u};
depth.stencilAddress &= ~std::uint64_t{65535u};
if (const auto surface = find(cx, 0x2af); surface != cx.end()) {
depth.htilePipeAligned = (surface->second & (1u << 18u)) != 0;
depth.htileVrsEncoding = (surface->second >> 19u) & 3u;
}
}
const auto size = read(cx, 0x007);
depth.extent = {(size & 0x3fffu) + 1u, ((size >> 16u) & 0x3fffu) + 1u};
if (const auto slice = view & 0x1fffu; slice != 0) {
if (depth.address != 0) depth.address += static_cast<std::uint64_t>(slice) * DepthSliceBytes(depth.extent, zFormat == 1 ? 2u : 4u);
if (depth.stencilAddress != 0) depth.stencilAddress += static_cast<std::uint64_t>(slice) * DepthSliceBytes(depth.extent, 1u);
}
depth.format = zFormat == 1 ? (stencil ? VK_FORMAT_D16_UNORM_S8_UINT : VK_FORMAT_D16_UNORM) : (stencil ? VK_FORMAT_D32_SFLOAT_S8_UINT : VK_FORMAT_D32_SFLOAT);
depth.clearDepth = readFloat(cx, 0x00b);
depth.clearStencil = static_cast<std::uint8_t>(read(cx, 0x00a) & 0xffu);
depth.htileDepthOnly = (read(cx, 0x011) & (1u << 29u)) != 0u;
if (const auto htile = find(cx, 0x005); zFormat != 0 && htile != cx.end() && htile->second != 0 && (read(cx, 0x010) & (1u << 29u)) != 0) {
depth.htileAddress = base(0x005, 0x01e) + static_cast<std::uint64_t>(view & 0x1fffu) * HtileMetadataBytes(depth.extent);
depth.htileStencil = stencil && !depth.htileDepthOnly;
}
result.depth = depth;
result.depthTest = (depthControl & 2u) != 0;
result.depthWrite = result.depthTest && (depthControl & 4u) != 0 && !depthReadOnly;
result.depthCompare = static_cast<VkCompareOp>((depthControl >> 4u) & 7u);
result.depthBoundsTest = (depthControl & 8u) != 0;
if (result.depthBoundsTest) {
Require(zFormat != 0, "depth bounds without a depth plane");
result.minDepthBounds = readDepthBound(cx, 0x008);
result.maxDepthBounds = readDepthBound(cx, 0x009);
}
if (depthClear) {
result.depthTest = true;
result.depthWrite = true;
result.depthCompare = VK_COMPARE_OP_ALWAYS;
result.depthBoundsTest = false;
}
result.stencilTest = (depthControl & 1u) != 0;
if (stencilClear) {
VkStencilOpState clear{};
clear.failOp = VK_STENCIL_OP_REPLACE;
clear.passOp = VK_STENCIL_OP_REPLACE;
clear.depthFailOp = VK_STENCIL_OP_REPLACE;
clear.compareOp = VK_COMPARE_OP_ALWAYS;
clear.compareMask = 0xffu;
clear.writeMask = 0xffu;
clear.reference = depth.clearStencil;
result.stencilTest = true;
result.stencilFront = clear;
result.stencilBack = clear;
} else if (result.stencilTest) {
const auto ops = read(cx, 0x10b);
result.stencilFront = stencilFace((depthControl >> 8u) & 7u, ops, read(cx, 0x10c), stencilReadOnly, testValExport, opValExport, opValReference);
result.stencilBack = (depthControl & 0x80u) != 0 ? stencilFace((depthControl >> 20u) & 7u, ops >> 12u, read(cx, 0x10d), stencilReadOnly, testValExport, opValExport, opValReference) : result.stencilFront;
}
}
void decodeDepthBias(const Registers& cx, std::uint32_t raster, State& result) {
const bool front = (result.cullMode & VK_CULL_MODE_FRONT_BIT) == 0;
const bool back = (result.cullMode & VK_CULL_MODE_BACK_BIT) == 0;
const bool frontBias = (raster & 0x800u) != 0;
const bool backBias = (raster & 0x1000u) != 0;
if (!(front && frontBias) && !(back && backBias)) return;
const bool perFace = front && back && (frontBias != backBias || read(cx, 0x2e0) != read(cx, 0x2e2) || read(cx, 0x2e1) != read(cx, 0x2e3));
const bool d16 = result.depth->format == VK_FORMAT_D16_UNORM || result.depth->format == VK_FORMAT_D16_UNORM_S8_UINT;
const auto format = find(cx, 0x2de) == cx.end() ? (d16 ? 0xf0u : 0x1e9u) : read(cx, 0x2de);
if (format != (d16 ? 0xf0u : 0x1e9u)) throw std::runtime_error("AGC graphics: " + zeroMessage(0x2de, format, "depth bias in units other than the depth format"));
const auto scale = front && frontBias ? 0x2e0u : 0x2e2u;
result.depthBias = true;
result.depthBiasSlope = frontBias || !perFace ? readFloat(cx, scale) / 16.0f : 0.0f;
result.depthBiasConstant = frontBias || !perFace ? readFloat(cx, scale + 1u) : 0.0f;
result.depthBiasClamp = readFloat(cx, 0x2df);
if (!perFace) return;
result.depthBiasPerFace = true;
result.backDepthBiasSlope = backBias ? readFloat(cx, 0x2e2) / 16.0f : 0.0f;
result.backDepthBiasConstant = backBias ? readFloat(cx, 0x2e3) : 0.0f;
}
bool depthPassThrough(std::uint32_t depthControl) {
const bool stencil = (depthControl & 1u) != 0;
const bool depth = (depthControl & 2u) != 0;
const bool depthWrite = (depthControl & 4u) != 0;
const bool passThroughDepth = !depth || (!depthWrite && ((depthControl >> 4u) & 7u) == 7u);
const bool passThroughStencil = !stencil || (((depthControl >> 8u) & 7u) == 7u && ((depthControl & 0x80u) == 0 || ((depthControl >> 20u) & 7u) == 7u));
return (stencil || depth) && passThroughDepth && passThroughStencil;
}
std::uint32_t effectiveDepthControl(std::uint32_t depthControl) {
return (depthControl & 3u) == 0 ? depthControl & ~4u : depthControl;
}
constexpr std::array<std::array<std::int8_t, 2>, 2> StandardLocations2{{{4, 4}, {-4, -4}}};
constexpr std::array<std::array<std::int8_t, 2>, 4> StandardLocations4{{{-2, -6}, {6, -2}, {-6, 2}, {2, 6}}};
constexpr std::array<std::array<std::int8_t, 2>, 8> StandardLocations8{{{1, -3}, {-1, 3}, {5, 1}, {-3, -5}, {-5, 5}, {-7, -1}, {3, 7}, {7, -7}}};
std::string nonTriangleRejection(const QueueState& queue, const char* message, bool rectangles = false) {
const auto word = [](const Registers& registers, std::uint32_t offset, RegisterBank bank = RegisterBank::Context) -> std::optional<std::uint32_t> {
const auto it = find(registers, offset, bank);
if (it == registers.end()) return std::nullopt;
return it->second;
};
const auto& cx = queue.context;
const auto stages = word(cx, 0x2d5);
if (!stages) return {};
if ((*stages & 0x20u) != 0) {
if (const auto output = word(cx, 0x29b); output && ((*output & 0x80000000u) != 0 || (*output & 0x3fu) != 2u)) return zeroMessage(0x29b, *output, message);
} else if ((*stages & 4u) != 0) {
if (const auto parameters = word(cx, 0x2db)) {
const auto domain = *parameters & 3u;
const auto topology = (*parameters >> 5u) & 7u;
if ((domain != 1u && domain != 2u) || (topology != 2u && topology != 3u)) return zeroMessage(0x2db, *parameters, message);
}
} else if (const auto primitive = word(queue.userConfig, 0x242, RegisterBank::UserConfig); primitive && *primitive != 4u && *primitive != 5u && *primitive != 6u && *primitive != 21u && !(rectangles && (*primitive == 7u || *primitive == 17u))) {
return zeroMessage(0x242, *primitive, message);
}
return {};
}
std::string singleSampleMsaaRejection(const QueueState& queue) {
const auto& cx = queue.context;
const auto word = [](const Registers& registers, std::uint32_t offset, RegisterBank bank = RegisterBank::Context) -> std::optional<std::uint32_t> {
const auto it = find(registers, offset, bank);
if (it == registers.end()) return std::nullopt;
return it->second;
};
for (std::uint32_t pixel = 0; pixel < 4; ++pixel) {
const auto offset = 0x2feu + pixel * 4u;
if (const auto locations = word(cx, offset); locations && (*locations & 0xffu) != 0) return zeroMessage(offset, *locations, "MSAA_ENABLE on a single-sample target whose sample is off the pixel center");
}
if (const auto alphaToMask = word(cx, 0x2dc); alphaToMask && (*alphaToMask & 1u) != 0 && !(*alphaToMask == AlphaToCoverageDithered && alphaToCoverageDisabled(cx))) return zeroMessage(0x2dc, *alphaToMask, "MSAA_ENABLE on a single-sample target with alpha-to-coverage");
if (const auto conservative = word(cx, 0x313); conservative && (*conservative & ~0x001f6000u) != 0) return zeroMessage(0x313, *conservative, "MSAA_ENABLE on a single-sample target with conservative rasterization");
return nonTriangleRejection(queue, "MSAA_ENABLE on a single-sample target for primitives other than triangles and rectangles", true);
}
std::string singleSampleDepthScanRejection(const QueueState& queue) {
if (auto reason = nonTriangleRejection(queue, "a single-sample scan into a multisampled depth target for primitives other than triangles and rectangles", true); !reason.empty()) return reason;
const auto& cx = queue.context;
if (const auto eqaa = find(cx, 0x201); eqaa != cx.end() && (eqaa->second & 0x0f0c0000u) != 0) return zeroMessage(0x201, eqaa->second, "a single-sample scan into a multisampled depth target with Z interpolation or overrasterization (DB_EQAA)");
if (PixelProgramSkipped(queue)) return {};
constexpr std::uint32_t sampleIndex = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::Ancillary);
const auto ena = find(cx, 0x1b3);
const auto addr = find(cx, 0x1b4);
if (ena != cx.end() && addr != cx.end() && (ena->second & addr->second & sampleIndex) != 0) return zeroMessage(0x1b3, ena->second, "a single-sample scan into a multisampled depth target with a pixel program reading the sample index");
if (const auto control = find(cx, 0x203); control != cx.end() && (control->second & 0x100u) != 0) return zeroMessage(0x203, control->second, "a single-sample scan into a multisampled depth target with a sample-mask export");
return {};
}
constexpr std::uint32_t CoveredCentroidIsCenter = 1u << 29u;
constexpr std::uint32_t SampleZeroRefusedInputs = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PerspectiveCentroid) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::LinearCentroid) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::SampleCoverage);
constexpr std::uint32_t CentroidInputs = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PerspectiveCentroid) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::LinearCentroid);
bool overrasterized(const Registers& cx, std::uint32_t samples) {
const auto eqaa = find(cx, 0x201);
const auto mode = find(cx, 0x292);
return samples > 1u && eqaa != cx.end() && mode != cx.end() && (mode->second & 1u) != 0 && ((eqaa->second >> 24u) & 7u) == static_cast<std::uint32_t>(std::countr_zero(samples));
}
bool sampleCoverageSupported(const QueueState& queue, std::uint32_t samples, bool perSampleShading) {
if (samples == 1u || PixelProgramSkipped(queue)) return true;
const auto ena = find(queue.context, 0x1b3);
const auto addr = find(queue.context, 0x1b4);
if (ena == queue.context.end() || addr == queue.context.end()) return true;
const auto inputs = ena->second & addr->second;
return (inputs & PixelSampleCoverageInput) == 0u || (!perSampleShading && (inputs & PixelSampleRateInputs) == 0u);
}
bool coveredCentroidSupported(const QueueState& queue) {
const auto config = find(queue.context, 0x2f8);
if (config == queue.context.end() || (config->second & CoveredCentroidIsCenter) == 0 || PixelProgramSkipped(queue)) return true;
const auto ena = find(queue.context, 0x1b3);
const auto addr = find(queue.context, 0x1b4);
return ena != queue.context.end() && addr != queue.context.end() && (ena->second & addr->second & CentroidInputs) == 0;
}
std::array<std::uint32_t, 4> sampleMaskFields(std::uint32_t top, std::uint32_t bottom) {
return {top & 0xffffu, top >> 16u, bottom & 0xffffu, bottom >> 16u};
}
std::string sampleMaskRejection(const QueueState& queue, std::uint32_t config, std::uint32_t top, std::uint32_t bottom) {
const auto log2 = config & 7u;
if (log2 > 3u) return {};
const auto full = (1u << (1u << log2)) - 1u;
auto masks = sampleMaskFields(top, bottom);
for (auto& mask : masks) mask &= full;
if (std::ranges::all_of(masks, [&](std::uint32_t mask) { return mask == full; })) return {};
const bool uniform = std::ranges::all_of(masks, [&](std::uint32_t mask) { return mask == masks[0]; });
const bool wholePixels = std::ranges::all_of(masks, [&](std::uint32_t mask) { return mask == 0u || mask == full; });
char detail[96];
std::snprintf(detail, sizeof(detail), " (PA_SC_AA_MASK_X0Y0_X1Y0=0x%08x, PA_SC_AA_MASK_X0Y1_X1Y1=0x%08x)", top, bottom);
const auto conservative = find(queue.context, 0x313);
if (conservative != queue.context.end() && (conservative->second & ~0x001f6000u) != 0) return std::string("AGC graphics: sample masks with conservative rasterization are unsupported") + detail;
if (!wholePixels && uniform && !PixelProgramSkipped(queue)) {
const auto ena = find(queue.context, 0x1b3);
const auto addr = find(queue.context, 0x1b4);
if (ena != queue.context.end() && addr != queue.context.end() && (ena->second & addr->second & CentroidInputs) != 0) return std::string("AGC graphics: sample masks that remove some samples of a pixel with centroid interpolation are unsupported") + detail;
}
return {};
}
std::array<std::uint16_t, 4> decodeQuadSampleMask(const Registers& cx, std::uint32_t samples) {
const bool singleSample = (read(cx, 0x2f8) & 7u) == 0u;
const auto full = (1u << samples) - 1u;
const auto fields = sampleMaskFields(read(cx, 0x30e), read(cx, 0x30f));
std::array<std::uint16_t, 4> masks{};
for (std::size_t pixel = 0; pixel < masks.size(); ++pixel) masks[pixel] = static_cast<std::uint16_t>(singleSample ? ((fields[pixel] & 1u) != 0u ? full : 0u) : fields[pixel] & full);
return masks;
}
std::uint32_t decodeSamples(const Registers& cx) {
const auto config = read(cx, 0x2f8);
zero(cx, 0x2f8, ~(0x7u | 0x1e000u | 0x700000u | CoveredCentroidIsCenter), "coverage conversion or nonstandard multisampling");
const auto log2 = config & 7u;
if (log2 == 0) {
Require(((config >> 20u) & 7u) == 0, "exposed samples without multisampling are unsupported");
return 1;
}
Require(log2 <= 3u, "more than eight samples are unsupported");
Require(((config >> 20u) & 7u) == log2, "exposing fewer samples than are rasterized is unsupported");
return 1u << log2;
}
void decodeSampleLocations(const Registers& cx, State& state) {
const auto samples = state.samples;
if (samples == 1) return;
const std::span<const std::array<std::int8_t, 2>> standard = samples == 2 ? std::span<const std::array<std::int8_t, 2>>(StandardLocations2) : samples == 4 ? std::span<const std::array<std::int8_t, 2>>(StandardLocations4) : std::span<const std::array<std::int8_t, 2>>(StandardLocations8);
for (std::uint32_t pixel = 0; pixel < 4; ++pixel) {
for (std::uint32_t sample = 0; sample < samples; ++sample) {
const auto word = read(cx, 0x2fe + pixel * 4u + sample / 4u);
const auto bits = (word >> (8u * (sample % 4u))) & 0xffu;
const auto x = static_cast<std::int8_t>(static_cast<std::uint8_t>(bits << 4u)) >> 4;
const auto y = static_cast<std::int8_t>(static_cast<std::uint8_t>(bits & 0xf0u)) >> 4;
state.sampleLocations[pixel * 8u + sample] = static_cast<std::uint8_t>(bits);
state.customSampleLocations |= x != standard[sample][0] || y != standard[sample][1];
state.sampleLocationGrid |= bits != state.sampleLocations[sample];
}
}
}
bool rasterizesSampleZeroOnly(const Registers& cx, const State& state) {
if (state.samples <= 1 || state.alphaToCoverage || (read(cx, 0x292) & 1u) == 0) return false;
const auto inputs = read(cx, 0x1b3) & read(cx, 0x1b4);
const auto refused = state.perSampleShading ? ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::SampleCoverage) : SampleZeroRefusedInputs;
return (inputs & refused) == 0;
}
void rasterizeSampleZero(State& state) {
std::array<std::uint8_t, 32> sampleZero{};
for (std::uint32_t pixel = 0; pixel < 4; ++pixel) sampleZero[pixel * 8u] = state.sampleLocations[pixel * 8u];
state.samples = 1;
state.perSampleShading = false;
state.sampleLocations = sampleZero;
state.customSampleLocations = std::any_of(sampleZero.begin(), sampleZero.end(), [](std::uint8_t bits) { return bits != 0; });
state.sampleLocationGrid = sampleZero[8] != sampleZero[0] || sampleZero[16] != sampleZero[0] || sampleZero[24] != sampleZero[0];
}
bool colorControlSupported(std::uint32_t colorControl, bool hasColorTarget) {
colorControl &= ~1u;
return colorControl == 0xcc0010u || ((colorControl >> 4u) & 7u) == 0u || (!hasColorTarget && (colorControl & ~0x70u) == 0xcc0000u);
}
std::string colorControlMessage(std::uint32_t colorControl) {
static constexpr const char* modes[8] = {"disable", "normal", "eliminate fast clear", "resolve", "decompress", "FMASK decompress", "DCC decompress", "reserved"};
char text[160];
std::snprintf(text, sizeof(text), "AGC graphics: only normal color rendering with copy ROP is supported (CB_COLOR_CONTROL 0x%08x, mode %s)", colorControl, modes[(colorControl >> 4u) & 7u]);
return text;
}
VkBlendFactor blendFactor(std::uint32_t value) {
switch (value) {
case 0: return VK_BLEND_FACTOR_ZERO;
case 1: return VK_BLEND_FACTOR_ONE;
case 2: return VK_BLEND_FACTOR_SRC_COLOR;
case 3: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
case 4: return VK_BLEND_FACTOR_SRC_ALPHA;
case 5: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
case 6: return VK_BLEND_FACTOR_DST_ALPHA;
case 7: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
case 8: return VK_BLEND_FACTOR_DST_COLOR;
case 9: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
case 10: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
case 13: return VK_BLEND_FACTOR_CONSTANT_COLOR;
case 14: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
case 15: return VK_BLEND_FACTOR_SRC1_COLOR;
case 16: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR;
case 17: return VK_BLEND_FACTOR_SRC1_ALPHA;
case 18: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
case 19: return VK_BLEND_FACTOR_CONSTANT_ALPHA;
case 20: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA;
default: throw std::runtime_error("AGC graphics: unsupported blend factor " + std::to_string(value));
}
}
VkBlendFactor colorFactorWithOpaqueDestination(VkBlendFactor factor) {
switch (factor) {
case VK_BLEND_FACTOR_DST_ALPHA: return VK_BLEND_FACTOR_ONE;
case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: return VK_BLEND_FACTOR_ZERO;
case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE: return VK_BLEND_FACTOR_ZERO;
default: return factor;
}
}
VkBlendFactor alphaFactorWithOpaqueDestination(VkBlendFactor factor) {
switch (factor) {
case VK_BLEND_FACTOR_DST_ALPHA: case VK_BLEND_FACTOR_DST_COLOR: return VK_BLEND_FACTOR_ONE;
case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR: return VK_BLEND_FACTOR_ZERO;
default: return factor;
}
}
bool secondSource(VkBlendFactor factor) {
return factor == VK_BLEND_FACTOR_SRC1_COLOR || factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR || factor == VK_BLEND_FACTOR_SRC1_ALPHA || factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
}
VkBlendOp blendOp(std::uint32_t value) {
switch (value) {
case 0: return VK_BLEND_OP_ADD;
case 1: return VK_BLEND_OP_SUBTRACT;
case 2: return VK_BLEND_OP_MIN;
case 3: return VK_BLEND_OP_MAX;
case 4: return VK_BLEND_OP_REVERSE_SUBTRACT;
default: throw std::runtime_error("AGC graphics: unsupported blend operation " + std::to_string(value));
}
}
constexpr std::uint8_t TermComplement = 0x80u;
constexpr std::uint8_t TermUnsupported = 0xffu;
std::uint8_t exportTerm(std::uint32_t component) {
return static_cast<std::uint8_t>(1u + component);
}
std::uint8_t destinationTerm(std::uint32_t component) {
return static_cast<std::uint8_t>(5u + component);
}
std::uint8_t guestBlendTerm(VkBlendFactor factor, std::uint32_t component) {
switch (factor) {
case VK_BLEND_FACTOR_ZERO: return 0u;
case VK_BLEND_FACTOR_ONE: return TermComplement;
case VK_BLEND_FACTOR_SRC_COLOR: return exportTerm(component);
case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR: return TermComplement | exportTerm(component);
case VK_BLEND_FACTOR_SRC_ALPHA: return exportTerm(0u);
case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA: return TermComplement | exportTerm(0u);
case VK_BLEND_FACTOR_DST_COLOR: return destinationTerm(component);
case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR: return TermComplement | destinationTerm(component);
case VK_BLEND_FACTOR_DST_ALPHA: return destinationTerm(0u);
case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: return TermComplement | destinationTerm(0u);
case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE: return component == 0u ? TermComplement : TermUnsupported;
default: return TermUnsupported;
}
}
std::uint8_t routedTerm(std::uint32_t route, std::uint32_t component) {
namespace Code = ShaderRecompiler::ReversedBlendCode;
switch (route) {
case Code::Own: return exportTerm(component);
case Code::Component0: return exportTerm(0u);
case Code::Zero: return 0u;
default: return TermComplement;
}
}
std::uint8_t hostBlendTerm(VkBlendFactor factor, std::uint32_t component, const std::array<std::uint32_t, 4>& color, const std::array<std::uint32_t, 4>& second) {
switch (factor) {
case VK_BLEND_FACTOR_ZERO: return 0u;
case VK_BLEND_FACTOR_ONE: return TermComplement;
case VK_BLEND_FACTOR_SRC_COLOR: return routedTerm(color[component], component);
case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR: return TermComplement ^ routedTerm(color[component], component);
case VK_BLEND_FACTOR_SRC_ALPHA: return routedTerm(color[3], 3u);
case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA: return TermComplement ^ routedTerm(color[3], 3u);
case VK_BLEND_FACTOR_DST_COLOR: return destinationTerm(component);
case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR: return TermComplement | destinationTerm(component);
case VK_BLEND_FACTOR_DST_ALPHA: return destinationTerm(3u);
case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: return TermComplement | destinationTerm(3u);
case VK_BLEND_FACTOR_SRC1_COLOR: return routedTerm(second[component], component);
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR: return TermComplement ^ routedTerm(second[component], component);
case VK_BLEND_FACTOR_SRC1_ALPHA: return routedTerm(second[3], 3u);
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA: return TermComplement ^ routedTerm(second[3], 3u);
default: return TermUnsupported;
}
}
struct BlendRouting {
std::array<VkBlendFactor, 4> factors;
std::uint32_t code;
};
std::optional<BlendRouting> routeReversedBlend(const std::array<VkBlendFactor, 2>& color, const std::array<VkBlendFactor, 2>& alpha) {
namespace Code = ShaderRecompiler::ReversedBlendCode;
static constexpr std::array<VkBlendFactor, 14> colorFactors{
VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_COLOR,
VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA};
static constexpr std::array<VkBlendFactor, 8> alphaFactors{
VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA};
std::array<std::array<std::uint8_t, 2>, 4> wanted{};
std::uint32_t replaceable = 0;
for (std::uint32_t component = 0; component < 4; ++component) {
for (std::size_t position = 0; position < 2; ++position) {
wanted[component][position] = guestBlendTerm(component == 0u ? alpha[position] : color[position], component);
if (wanted[component][position] == TermUnsupported) return std::nullopt;
}
if (wanted[component][0] == TermComplement) replaceable |= 1u << component;
}
const auto search = [&](bool routed) -> std::optional<BlendRouting> {
const auto usable = [&](VkBlendFactor factor) { return routed || !secondSource(factor); };
const std::uint32_t routeCount = routed ? 4u : 1u;
std::uint32_t ones = 0;
do {
std::array<std::uint32_t, 4> colorRoutes{};
for (std::uint32_t component = 0; component < 4; ++component) colorRoutes[component] = ((ones >> component) & 1u) != 0 ? Code::One : Code::Own;
const auto matches = [&](VkBlendFactor factor, std::size_t position, std::uint32_t component, const std::array<std::uint32_t, 4>& second) {
const auto term = hostBlendTerm(factor, component, colorRoutes, second);
if (position == 1 || colorRoutes[component] == Code::Own) return term == wanted[component][position];
return term == exportTerm(component);
};
for (std::uint32_t secondAlpha = 0; secondAlpha < routeCount; ++secondAlpha) {
const std::array<std::uint32_t, 4> second{Code::Own, Code::Own, Code::Own, secondAlpha};
std::array<std::optional<VkBlendFactor>, 2> alphaFactor{};
for (std::size_t position = 0; position < 2; ++position) {
const auto found = std::find_if(alphaFactors.begin(), alphaFactors.end(), [&](VkBlendFactor factor) { return usable(factor) && matches(factor, position, 3u, second); });
if (found != alphaFactors.end()) alphaFactor[position] = *found;
}
if (!alphaFactor[0] || !alphaFactor[1]) continue;
std::array<std::array<std::array<std::uint8_t, 3>, colorFactors.size()>, 2> masks{};
for (std::size_t position = 0; position < 2; ++position) {
for (std::size_t index = 0; index < colorFactors.size(); ++index) {
if (!usable(colorFactors[index])) continue;
for (std::uint32_t component = 0; component < 3; ++component) {
auto routes = second;
for (std::uint32_t route = 0; route < routeCount; ++route) {
routes[component] = route;
if (matches(colorFactors[index], position, component, routes)) masks[position][index][component] |= static_cast<std::uint8_t>(1u << route);
}
}
}
}
for (std::size_t source = 0; source < colorFactors.size(); ++source) {
for (std::size_t destination = 0; destination < colorFactors.size(); ++destination) {
std::uint32_t code = Code::Enable;
for (std::uint32_t component = 0; component < 4; ++component) {
const auto shared = component == 3u ? 1u << secondAlpha : static_cast<std::uint32_t>(masks[0][source][component] & masks[1][destination][component]);
if (shared == 0u) {
code = 0u;
break;
}
const auto route = static_cast<std::uint32_t>(std::countr_zero(shared));
code |= (colorRoutes[component] << (Code::ColorShift + Code::RouteBits * component)) | (route << (Code::SecondShift + Code::RouteBits * component));
}
if (code != 0u) return BlendRouting{{colorFactors[source], colorFactors[destination], *alphaFactor[0], *alphaFactor[1]}, routed ? code : 0u};
}
}
}
ones = (ones - replaceable) & replaceable;
} while (routed && ones != 0u);
return std::nullopt;
};
if (auto native = search(false)) return native;
return search(true);
}
struct DecodedColorFormat {
VkFormat format;
std::uint32_t elementBytes;
std::uint8_t componentMapping = 0xe4u;
ShaderRecompiler::ColorExportPacking packing = ShaderRecompiler::ColorExportPacking::None;
};
const char* PackedColorTargetName(ShaderRecompiler::ColorExportPacking packing) {
return packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 ? "11_11_10 float" : "10_11_11 unorm";
}
// CB_COLOR_INFO FORMAT / NUMBER_TYPE / COMP_SWAP to a Vulkan attachment format. AMD formats list
// components from the least significant bits, as Vulkan's non-packed formats do.
DecodedColorFormat DecodeColorFormat(std::uint32_t format, std::uint32_t number, std::uint32_t swap) {
constexpr std::uint32_t unorm = 0, snorm = 1, sint = 5, srgb = 6, floating = 7;
constexpr std::uint32_t uint = 4;
const auto fail = [&]() -> DecodedColorFormat {
throw std::runtime_error("AGC graphics: unsupported color format " + std::to_string(format) + " number type " + std::to_string(number) + " component swap " + std::to_string(swap));
};
const bool alternate = swap == 1;
const auto single = [&](VkFormat vkFormat, std::uint32_t bytes) { return DecodedColorFormat{vkFormat, bytes, static_cast<std::uint8_t>((0xe4u & ~3u) | swap)}; };
if (swap > 1 && format != 1 && format != 2 && format != 4 && format != 7 && format != 10 && format != 12 && format != 16) return fail();
switch (format) {
case 1:
if (number == unorm) return single(VK_FORMAT_R8_UNORM, 1);
if (number == snorm) return single(VK_FORMAT_R8_SNORM, 1);
if (number == uint) return single(VK_FORMAT_R8_UINT, 1);
if (number == srgb && swap == 0) return single(VK_FORMAT_R8_SRGB, 1);
return fail();
case 2:
if (number == unorm) return single(VK_FORMAT_R16_UNORM, 2);
if (number == snorm) return single(VK_FORMAT_R16_SNORM, 2);
if (number == floating) return single(VK_FORMAT_R16_SFLOAT, 2);
if (number == uint) return single(VK_FORMAT_R16_UINT, 2);
return fail();
case 3: {
if (swap > 1) return fail();
const auto mapping = static_cast<std::uint8_t>(alternate ? 0xecu : 0xe4u);
if (number == unorm) return {VK_FORMAT_R8G8_UNORM, 2, mapping};
if (number == snorm) return {VK_FORMAT_R8G8_SNORM, 2, mapping};
if (number == uint) return {VK_FORMAT_R8G8_UINT, 2, mapping};
return fail();
}
case 4:
if (number == floating) return single(VK_FORMAT_R32_SFLOAT, 4);
if (number == uint) return single(VK_FORMAT_R32_UINT, 4);
if (number == sint) return single(VK_FORMAT_R32_SINT, 4);
return fail();
case 5:
if (swap != 0) return fail();
if (number == floating) return {VK_FORMAT_R16G16_SFLOAT, 4};
if (number == unorm) return {VK_FORMAT_R16G16_UNORM, 4};
if (number == snorm) return {VK_FORMAT_R16G16_SNORM, 4};
if (number == uint) return {VK_FORMAT_R16G16_UINT, 4};
return fail();
case 6:
// COLOR_10_11_11: red in the low 11 bits, the Vulkan B10G11R11 packing.
if (swap != 0 || (number != floating && number != unorm)) return fail();
if (number == unorm) return {VK_FORMAT_R32_UINT, 4, 0xe4u, ShaderRecompiler::ColorExportPacking::Unorm10_11_11};
return {VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4};
case 7:
if (swap != 2 || number != floating) return fail();
return {VK_FORMAT_R32_UINT, 4, 0xc6u, ShaderRecompiler::ColorExportPacking::Float11_11_10};
case 9:
// COLOR_2_10_10_10 keeps red in the low bits, the Vulkan A2B10G10R10 packing.
if (number != unorm) return fail();
return {alternate ? VK_FORMAT_A2R10G10B10_UNORM_PACK32 : VK_FORMAT_A2B10G10R10_UNORM_PACK32, 4};
case 10: {
const auto reversed = static_cast<std::uint8_t>(swap == 2 ? 0x1bu : swap == 3 ? 0x93u : 0xe4u);
if (number == unorm) return {alternate ? VK_FORMAT_B8G8R8A8_UNORM : VK_FORMAT_R8G8B8A8_UNORM, 4, reversed};
if (number == snorm) return {alternate ? VK_FORMAT_B8G8R8A8_SNORM : VK_FORMAT_R8G8B8A8_SNORM, 4, reversed};
if (number == srgb) return {alternate ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_R8G8B8A8_SRGB, 4, reversed};
if (number == uint && !alternate) return {VK_FORMAT_R8G8B8A8_UINT, 4, reversed};
return fail();
}
case 11:
if (swap != 0) return fail();
if (number == floating) return {VK_FORMAT_R32G32_SFLOAT, 8};
if (number == uint) return {VK_FORMAT_R32G32_UINT, 8};
return fail();
case 12: {
const auto reversed = static_cast<std::uint8_t>(alternate ? 0xc6u : swap == 2 ? 0x1bu : swap == 3 ? 0x93u : 0xe4u);
if (number == floating) return {VK_FORMAT_R16G16B16A16_SFLOAT, 8, reversed};
if (number == unorm) return {VK_FORMAT_R16G16B16A16_UNORM, 8, reversed};
if (number == snorm) return {VK_FORMAT_R16G16B16A16_SNORM, 8, reversed};
if (number == uint) return {VK_FORMAT_R16G16B16A16_UINT, 8, reversed};
return fail();
}
case 14:
if (swap != 0) return fail();
if (number == floating) return {VK_FORMAT_R32G32B32A32_SFLOAT, 16};
if (number == uint) return {VK_FORMAT_R32G32B32A32_UINT, 16};
return fail();
case 16:
if ((swap != 0 && swap != 2) || number != unorm) return fail();
return {VK_FORMAT_R5G6B5_UNORM_PACK16, 2, static_cast<std::uint8_t>(swap == 2 ? 0xe4u : 0xc6u)};
case 17:
if (swap != 0 || number != unorm) return fail();
return {VK_FORMAT_A1R5G5B5_UNORM_PACK16, 2, 0xc6u};
default:
return fail();
}
}
void intersect(VkRect2D& result, const Registers& registers, std::uint32_t offset, bool screen) {
const auto tl = read(registers, offset);
const auto br = read(registers, offset + 1);
if (!screen) Require((tl & 0x8000u) == 0 && (br & 0x80008000u) == 0, "scissor reserved bits are unsupported");
const auto x = tl & 0xffffu;
const auto y = (tl >> 16u) & (screen ? 0xffffu : 0x7fffu);
const auto right = br & 0xffffu;
const auto bottom = br >> 16u;
const auto oldRight = static_cast<std::uint32_t>(result.offset.x) + result.extent.width;
const auto oldBottom = static_cast<std::uint32_t>(result.offset.y) + result.extent.height;
const auto left = std::max(static_cast<std::uint32_t>(result.offset.x), x);
const auto top = std::max(static_cast<std::uint32_t>(result.offset.y), y);
result.offset = {static_cast<std::int32_t>(left), static_cast<std::int32_t>(top)};
result.extent = {std::min(oldRight, right) > left ? std::min(oldRight, right) - left : 0, std::min(oldBottom, bottom) > top ? std::min(oldBottom, bottom) - top : 0};
}
}
VkExtent2D SampleLocationGrid(const State& state) {
return state.sampleLocationGrid ? VkExtent2D{2, 2} : VkExtent2D{1, 1};
}
std::array<VkSampleLocationEXT, 32> SampleLocations(const State& state) {
Require(state.samples == 1 || state.samples == 2 || state.samples == 4 || state.samples == 8, "invalid sample count");
std::array<VkSampleLocationEXT, 32> locations{};
const auto grid = SampleLocationGrid(state);
for (std::uint32_t pixel = 0; pixel < grid.width * grid.height; ++pixel) {
for (std::uint32_t sample = 0; sample < state.samples; ++sample) {
std::array<int, 2> position{};
if (state.customSampleLocations) {
const auto bits = state.sampleLocations[pixel * 8u + sample];
position = {static_cast<int>(bits & 7u) - static_cast<int>(bits & 8u), static_cast<int>((bits >> 4u) & 7u) - static_cast<int>((bits >> 4u) & 8u)};
} else if (state.samples != 1) {
const auto& standard = state.samples == 2 ? StandardLocations2[sample] : state.samples == 4 ? StandardLocations4[sample] : StandardLocations8[sample];
position = {standard[0], standard[1]};
}
locations[pixel * state.samples + sample] = {0.5f + position[0] / 16.0f, 0.5f + position[1] / 16.0f};
}
}
return locations;
}
std::array<std::uint8_t, 32> PixelSampleLocations(const State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel) {
using ShaderRecompiler::PixelInput;
using ShaderRecompiler::PixelInputBit;
std::array<std::uint8_t, 32> locations{};
const bool sampleBarycentrics = (pixel.inputAddr & (PixelInputBit(PixelInput::PerspectiveSample) | PixelInputBit(PixelInput::LinearSample))) != 0u;
const bool samplePosition = !state.perSampleShading && (pixel.posX || pixel.posY) && pixel.positionLocation == ShaderRecompiler::PixelPositionLocation::Sample;
if (!sampleBarycentrics && !samplePosition) return locations;
const auto samples = state.perSampleShading ? state.samples : 1u;
for (std::uint32_t pixelIndex = 0; pixelIndex < 4u; ++pixelIndex) {
for (std::uint32_t sample = 0; sample < samples; ++sample) {
if (state.customSampleLocations) {
locations[pixelIndex * 8u + sample] = state.sampleLocations[pixelIndex * 8u + sample];
} else if (state.samples != 1) {
const auto& standard = state.samples == 2 ? StandardLocations2[sample] : state.samples == 4 ? StandardLocations4[sample] : StandardLocations8[sample];
locations[pixelIndex * 8u + sample] = static_cast<std::uint8_t>((standard[0] & 0xf) | ((standard[1] & 0xf) << 4u));
}
}
}
return locations;
}
ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) {
const auto value = read(queue.context, 0x2d5);
const auto validate = [&](bool condition, const char* reason) {
if (condition) return;
std::ostringstream prefix;
prefix << "VGT_SHADER_STAGES_EN=0x" << std::hex << value << ": " << reason;
Require(false, prefix.str());
};
validate((value & 0xfc000000u) == 0, "reserved stage bits are set");
validate((value & 3u) != 3u && ((value >> 3u) & 3u) != 3u && ((value >> 6u) & 3u) != 3u, "reserved LS_EN, ES_EN or VS_EN encoding");
const auto primitive = read(queue.userConfig, 0x242, RegisterBank::UserConfig);
const bool tessellation = primitive == 9;
validate(!vertexWorkgroup || ((value & 0x02002020u) == 0x2000u && !tessellation), "a vertex program that needs a workgroup requires PRIMGEN_EN without GS_EN, PRIMGEN_PASSTHRU_EN or tessellation");
const bool geometry = (value & 0x20u) != 0 || vertexWorkgroup;
validate(tessellation == ((value & 4u) != 0), "Patch topology and HS_EN disagree");
validate(!tessellation || !geometry, "combined tessellation and geometry is unsupported by the reference path");
const auto path = tessellation ? ShaderPath::Tessellation : geometry ? ShaderPath::Geometry : ShaderPath::Vertex;
ShaderStages result{path, value, (value & 0x00400000u) != 0 ? 32u : 64u, (read(queue.context, 0x1b6) & 0x8000u) != 0 ? 32u : 64u, {}, {}};
APS5_LOG_OUT_DEBUG("DecodeShaderStages value=0x%x primitive=%u path=%u vertexWave=%u", value, primitive, static_cast<unsigned>(result.path), result.vertexWaveSize);
if (path == ShaderPath::Vertex) {
validate((value & 0x2000u) != 0, "legacy vertex routing without PRIMGEN_EN is unsupported");
validate((value & ~0x0247a010u) == 0 || value == 0x02002008u, "unsupported vertex routing, scheduling or wave-ID state");
} else if (path == ShaderPath::Tessellation) {
validate((value & 0x00600020u) == 0, "wave32 tessellation or geometry amplification is unsupported");
validate((value & ~0x0207ed0du) == 0 && (value & 0x02002000u) == 0x02002000u && (value & 3u) == 1u && ((value >> 3u) & 3u) == 1u, "unsupported tessellation routing");
const auto config = read(queue.context, 0x2d6);
const auto parameters = read(queue.context, 0x2db);
const auto primitiveGroup = find(queue.userConfig, 0x25b, RegisterBank::UserConfig);
ShaderRecompiler::TessellationConfiguration tess{(config >> 8u) & 0x3fu, (config >> 14u) & 0x3fu, parameters & 3u, (parameters >> 2u) & 7u, (parameters >> 5u) & 7u, config & 0xffu, primitiveGroup == queue.userConfig.end() ? 0u : primitiveGroup->second & 0x1ffu, primitiveGroup != queue.userConfig.end() && (primitiveGroup->second & 0x40000u) != 0u};
validate(tess.inputControlPoints != 0 && tess.inputControlPoints <= 32 && tess.outputControlPoints != 0 && tess.outputControlPoints <= 32, "invalid tessellation control-point counts");
validate(tess.patchesPerGroup != 0, "VGT_LS_HS_CONFIG.NUM_PATCHES is zero");
if ((parameters & ~0x000600ffu) != 0) Require(false, zeroMessage(0x2db, parameters, "VGT_TF_PARAM donut, factor detection, memory type or reserved state"));