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

#include "VideoCommon/BPStructs.h"

#include <cmath>
#include <cstring>
#include <string>

#include <fmt/format.h>

#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Core/ConfigManager.h"
#include "Core/CoreTiming.h"
#include "Core/FifoPlayer/FifoPlayer.h"
#include "Core/FifoPlayer/FifoRecorder.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/VideoInterface.h"

#include "VideoCommon/BPFunctions.h"
#include "VideoCommon/BPMemory.h"
#include "VideoCommon/BoundingBox.h"
#include "VideoCommon/Fifo.h"
#include "VideoCommon/FramebufferManager.h"
#include "VideoCommon/GeometryShaderManager.h"
#include "VideoCommon/PerfQueryBase.h"
#include "VideoCommon/PixelEngine.h"
#include "VideoCommon/PixelShaderManager.h"
#include "VideoCommon/RenderBase.h"
#include "VideoCommon/TextureCacheBase.h"
#include "VideoCommon/TextureDecoder.h"
#include "VideoCommon/VertexShaderManager.h"
#include "VideoCommon/VideoBackendBase.h"
#include "VideoCommon/VideoCommon.h"
#include "VideoCommon/VideoConfig.h"

using namespace BPFunctions;

static const float s_gammaLUT[] = {1.0f, 1.7f, 2.2f, 1.0f};

void BPInit()
{
  memset(&bpmem, 0, sizeof(bpmem));
  bpmem.bpMask = 0xFFFFFF;
}

static void BPWritten(const BPCmd& bp)
{
  /*
  ----------------------------------------------------------------------------------------------------------------
  Purpose: Writes to the BP registers
  Called: At the end of every: OpcodeDecoding.cpp ExecuteDisplayList > Decode() > LoadBPReg
  How It Works: First the pipeline is flushed then update the bpmem with the new value.
          Some of the BP cases have to call certain functions while others just update the bpmem.
          some bp cases check the changes variable, because they might not have to be updated all
  the time
  NOTE: it seems not all bp cases like checking changes, so calling if (bp.changes == 0 ? false :
  true)
      had to be ditched and the games seem to work fine with out it.
  NOTE2: Yet Another GameCube Documentation calls them Bypass Raster State Registers but possibly
  completely wrong
  NOTE3: This controls the register groups: RAS1/2, SU, TF, TEV, C/Z, PEC
  TODO: Turn into function table. The (future) DisplayList (DL) jit can then call the functions
  directly,
      getting rid of dynamic dispatch. Unfortunately, few games use DLs properly - most\
      just stuff geometry in them and don't put state changes there
  ----------------------------------------------------------------------------------------------------------------
  */

  if (((s32*)&bpmem)[bp.address] == bp.newvalue)
  {
    if (!(bp.address == BPMEM_TRIGGER_EFB_COPY || bp.address == BPMEM_CLEARBBOX1 ||
          bp.address == BPMEM_CLEARBBOX2 || bp.address == BPMEM_SETDRAWDONE ||
          bp.address == BPMEM_PE_TOKEN_ID || bp.address == BPMEM_PE_TOKEN_INT_ID ||
          bp.address == BPMEM_LOADTLUT0 || bp.address == BPMEM_LOADTLUT1 ||
          bp.address == BPMEM_TEXINVALIDATE || bp.address == BPMEM_PRELOAD_MODE ||
          bp.address == BPMEM_CLEAR_PIXEL_PERF))
    {
      return;
    }
  }

  FlushPipeline();

  ((u32*)&bpmem)[bp.address] = bp.newvalue;

  switch (bp.address)
  {
  case BPMEM_GENMODE:  // Set the Generation Mode
    PRIM_LOG("genmode: texgen=%d, col=%d, multisampling=%d, tev=%d, cullmode=%d, ind=%d, zfeeze=%d",
             (u32)bpmem.genMode.numtexgens, (u32)bpmem.genMode.numcolchans,
             (u32)bpmem.genMode.multisampling, (u32)bpmem.genMode.numtevstages + 1,
             (u32)bpmem.genMode.cullmode, (u32)bpmem.genMode.numindstages,
             (u32)bpmem.genMode.zfreeze);

    if (bp.changes)
      PixelShaderManager::SetGenModeChanged();

    // Only call SetGenerationMode when cull mode changes.
    if (bp.changes & 0xC000)
      SetGenerationMode();
    return;
  case BPMEM_IND_MTXA:  // Index Matrix Changed
  case BPMEM_IND_MTXB:
  case BPMEM_IND_MTXC:
  case BPMEM_IND_MTXA + 3:
  case BPMEM_IND_MTXB + 3:
  case BPMEM_IND_MTXC + 3:
  case BPMEM_IND_MTXA + 6:
  case BPMEM_IND_MTXB + 6:
  case BPMEM_IND_MTXC + 6:
    if (bp.changes)
      PixelShaderManager::SetIndMatrixChanged((bp.address - BPMEM_IND_MTXA) / 3);
    return;
  case BPMEM_RAS1_SS0:  // Index Texture Coordinate Scale 0
    if (bp.changes)
      PixelShaderManager::SetIndTexScaleChanged(false);
    return;
  case BPMEM_RAS1_SS1:  // Index Texture Coordinate Scale 1
    if (bp.changes)
      PixelShaderManager::SetIndTexScaleChanged(true);
    return;
  // ----------------
  // Scissor Control
  // ----------------
  case BPMEM_SCISSORTL:      // Scissor Rectable Top, Left
  case BPMEM_SCISSORBR:      // Scissor Rectable Bottom, Right
  case BPMEM_SCISSOROFFSET:  // Scissor Offset
    SetScissor();
    SetViewport();
    VertexShaderManager::SetViewportChanged();
    GeometryShaderManager::SetViewportChanged();
    return;
  case BPMEM_LINEPTWIDTH:  // Line Width
    GeometryShaderManager::SetLinePtWidthChanged();
    return;
  case BPMEM_ZMODE:  // Depth Control
    PRIM_LOG("zmode: test=%u, func=%u, upd=%u", bpmem.zmode.testenable.Value(),
             bpmem.zmode.func.Value(), bpmem.zmode.updateenable.Value());
    SetDepthMode();
    PixelShaderManager::SetZModeControl();
    return;
  case BPMEM_BLENDMODE:  // Blending Control
    if (bp.changes & 0xFFFF)
    {
      PRIM_LOG("blendmode: en=%u, open=%u, colupd=%u, alphaupd=%u, dst=%u, src=%u, sub=%u, mode=%u",
               bpmem.blendmode.blendenable.Value(), bpmem.blendmode.logicopenable.Value(),
               bpmem.blendmode.colorupdate.Value(), bpmem.blendmode.alphaupdate.Value(),
               bpmem.blendmode.dstfactor.Value(), bpmem.blendmode.srcfactor.Value(),
               bpmem.blendmode.subtract.Value(), bpmem.blendmode.logicmode.Value());

      SetBlendMode();

      PixelShaderManager::SetBlendModeChanged();
    }
    return;
  case BPMEM_CONSTANTALPHA:  // Set Destination Alpha
    PRIM_LOG("constalpha: alp=%d, en=%d", bpmem.dstalpha.alpha.Value(),
             bpmem.dstalpha.enable.Value());
    if (bp.changes)
    {
      PixelShaderManager::SetAlpha();
      PixelShaderManager::SetDestAlphaChanged();
    }
    if (bp.changes & 0x100)
      SetBlendMode();
    return;

  // This is called when the game is done drawing the new frame (eg: like in DX: Begin(); Draw();
  // End();)
  // Triggers an interrupt on the PPC side so that the game knows when the GPU has finished drawing.
  // Tokens are similar.
  case BPMEM_SETDRAWDONE:
    switch (bp.newvalue & 0xFF)
    {
    case 0x02:
      g_texture_cache->FlushEFBCopies();
      g_framebuffer_manager->InvalidatePeekCache(false);
      if (!Fifo::UseDeterministicGPUThread())
        PixelEngine::SetFinish();  // may generate interrupt
      DEBUG_LOG(VIDEO, "GXSetDrawDone SetPEFinish (value: 0x%02X)", (bp.newvalue & 0xFFFF));
      return;

    default:
      WARN_LOG(VIDEO, "GXSetDrawDone ??? (value 0x%02X)", (bp.newvalue & 0xFFFF));
      return;
    }
    return;
  case BPMEM_PE_TOKEN_ID:  // Pixel Engine Token ID
    g_texture_cache->FlushEFBCopies();
    g_framebuffer_manager->InvalidatePeekCache(false);
    if (!Fifo::UseDeterministicGPUThread())
      PixelEngine::SetToken(static_cast<u16>(bp.newvalue & 0xFFFF), false);
    DEBUG_LOG(VIDEO, "SetPEToken 0x%04x", (bp.newvalue & 0xFFFF));
    return;
  case BPMEM_PE_TOKEN_INT_ID:  // Pixel Engine Interrupt Token ID
    g_texture_cache->FlushEFBCopies();
    g_framebuffer_manager->InvalidatePeekCache(false);
    if (!Fifo::UseDeterministicGPUThread())
      PixelEngine::SetToken(static_cast<u16>(bp.newvalue & 0xFFFF), true);
    DEBUG_LOG(VIDEO, "SetPEToken + INT 0x%04x", (bp.newvalue & 0xFFFF));
    return;

  // ------------------------
  // EFB copy command. This copies a rectangle from the EFB to either RAM in a texture format or to
  // XFB as YUYV.
  // It can also optionally clear the EFB while copying from it. To emulate this, we of course copy
  // first and clear afterwards.
  case BPMEM_TRIGGER_EFB_COPY:  // Copy EFB Region or Render to the XFB or Clear the screen.
  {
    // The bottom right is within the rectangle
    // The values in bpmem.copyTexSrcXY and bpmem.copyTexSrcWH are updated in case 0x49 and 0x4a in
    // this function

    u32 destAddr = bpmem.copyTexDest << 5;
    u32 destStride = bpmem.copyMipMapStrideChannels << 5;

    MathUtil::Rectangle<int> srcRect;
    srcRect.left = static_cast<int>(bpmem.copyTexSrcXY.x);
    srcRect.top = static_cast<int>(bpmem.copyTexSrcXY.y);

    // Here Width+1 like Height, otherwise some textures are corrupted already since the native
    // resolution.
    srcRect.right = static_cast<int>(bpmem.copyTexSrcXY.x + bpmem.copyTexSrcWH.x + 1);
    srcRect.bottom = static_cast<int>(bpmem.copyTexSrcXY.y + bpmem.copyTexSrcWH.y + 1);

    // Since the copy X and Y coordinates/sizes are 10-bit, the game can configure a copy region up
    // to 1024x1024. Hardware tests have found that the number of bytes written does not depend on
    // the configured stride, instead it is based on the size registers, writing beyond the length
    // of a single row. The data written for the pixels which lie outside the EFB bounds does not
    // wrap around instead returning different colors based on the pixel format of the EFB. This
    // suggests it's not based on coordinates, but instead on memory addresses. The effect of a
    // within-bounds size but out-of-bounds offset (e.g. offset 320,0, size 640,480) are the same.

    // As it would be difficult to emulate the exact behavior of out-of-bounds reads, instead of
    // writing the junk data, we don't write anything to RAM at all for over-sized copies, and clamp
    // to the EFB borders for over-offset copies. The arcade virtual console games (e.g. 1942) are
    // known for configuring these out-of-range copies.
    int copy_width = srcRect.GetWidth();
    int copy_height = srcRect.GetHeight();
    if (srcRect.right > EFB_WIDTH || srcRect.bottom > EFB_HEIGHT)
    {
      WARN_LOG(VIDEO, "Oversized EFB copy: %dx%d (offset %d,%d stride %u)", copy_width, copy_height,
               srcRect.left, srcRect.top, destStride);

      // Adjust the copy size to fit within the EFB. So that we don't end up with a stretched image,
      // instead of clamping the source rectangle, we reduce it by the over-sized amount.
      if (copy_width > EFB_WIDTH)
      {
        srcRect.right -= copy_width - EFB_WIDTH;
        copy_width = EFB_WIDTH;
      }
      if (copy_height > EFB_HEIGHT)
      {
        srcRect.bottom -= copy_height - EFB_HEIGHT;
        copy_height = EFB_HEIGHT;
      }
    }

    // Check if we are to copy from the EFB or draw to the XFB
    const UPE_Copy PE_copy = bpmem.triggerEFBCopy;
    if (PE_copy.copy_to_xfb == 0)
    {
      // bpmem.zcontrol.pixel_format to PEControl::Z24 is when the game wants to copy from ZBuffer
      // (Zbuffer uses 24-bit Format)
      static constexpr CopyFilterCoefficients::Values filter_coefficients = {
          {0, 0, 21, 22, 21, 0, 0}};
      bool is_depth_copy = bpmem.zcontrol.pixel_format == PEControl::Z24;
      g_texture_cache->CopyRenderTargetToTexture(
          destAddr, PE_copy.tp_realFormat(), copy_width, copy_height, destStride, is_depth_copy,
          srcRect, !!PE_copy.intensity_fmt, !!PE_copy.half_scale, 1.0f, 1.0f,
          bpmem.triggerEFBCopy.clamp_top, bpmem.triggerEFBCopy.clamp_bottom, filter_coefficients);
    }
    else
    {
      // We should be able to get away with deactivating the current bbox tracking
      // here. Not sure if there's a better spot to put this.
      // the number of lines copied is determined by the y scale * source efb height
      BoundingBox::Disable();

      float yScale;
      if (PE_copy.scale_invert)
        yScale = 256.0f / static_cast<float>(bpmem.dispcopyyscale);
      else
        yScale = static_cast<float>(bpmem.dispcopyyscale) / 256.0f;

      float num_xfb_lines = 1.0f + bpmem.copyTexSrcWH.y * yScale;

      u32 height = static_cast<u32>(num_xfb_lines);

      DEBUG_LOG(VIDEO,
                "RenderToXFB: destAddr: %08x | srcRect {%d %d %d %d} | fbWidth: %u | "
                "fbStride: %u | fbHeight: %u | yScale: %f",
                destAddr, srcRect.left, srcRect.top, srcRect.right, srcRect.bottom,
                bpmem.copyTexSrcWH.x + 1, destStride, height, yScale);

      bool is_depth_copy = bpmem.zcontrol.pixel_format == PEControl::Z24;
      g_texture_cache->CopyRenderTargetToTexture(
          destAddr, EFBCopyFormat::XFB, copy_width, height, destStride, is_depth_copy, srcRect,
          false, false, yScale, s_gammaLUT[PE_copy.gamma], bpmem.triggerEFBCopy.clamp_top,
          bpmem.triggerEFBCopy.clamp_bottom, bpmem.copyfilter.GetCoefficients());

      // This stays in to signal end of a "frame"
      g_renderer->RenderToXFB(destAddr, srcRect, destStride, height, s_gammaLUT[PE_copy.gamma]);

      if (g_ActiveConfig.bImmediateXFB)
      {
        // below div two to convert from bytes to pixels - it expects width, not stride
        g_renderer->Swap(destAddr, destStride / 2, destStride, height, CoreTiming::GetTicks());
      }
      else
      {
        if (FifoPlayer::GetInstance().IsRunningWithFakeVideoInterfaceUpdates())
        {
          VideoInterface::FakeVIUpdate(destAddr, srcRect.GetWidth(), destStride, height);
        }
      }
    }

    // Clear the rectangular region after copying it.
    if (PE_copy.clear)
    {
      ClearScreen(srcRect);
    }

    return;
  }
  case BPMEM_LOADTLUT0:  // This one updates bpmem.tlutXferSrc, no need to do anything here.
    return;
  case BPMEM_LOADTLUT1:  // Load a Texture Look Up Table
  {
    u32 tlutTMemAddr = (bp.newvalue & 0x3FF) << 9;
    u32 tlutXferCount = (bp.newvalue & 0x1FFC00) >> 5;
    u32 addr = bpmem.tmem_config.tlut_src << 5;

    // The GameCube ignores the upper bits of this address. Some games (WW, MKDD) set them.
    if (!SConfig::GetInstance().bWii)
      addr = addr & 0x01FFFFFF;

    Memory::CopyFromEmu(texMem + tlutTMemAddr, addr, tlutXferCount);

    if (g_bRecordFifoData)
      FifoRecorder::GetInstance().UseMemory(addr, tlutXferCount, MemoryUpdate::TMEM);

    TextureCacheBase::InvalidateAllBindPoints();

    return;
  }
  case BPMEM_FOGRANGE:  // Fog Settings Control
  case BPMEM_FOGRANGE + 1:
  case BPMEM_FOGRANGE + 2:
  case BPMEM_FOGRANGE + 3:
  case BPMEM_FOGRANGE + 4:
  case BPMEM_FOGRANGE + 5:
    if (bp.changes)
      PixelShaderManager::SetFogRangeAdjustChanged();
    return;
  case BPMEM_FOGPARAM0:
  case BPMEM_FOGBMAGNITUDE:
  case BPMEM_FOGBEXPONENT:
  case BPMEM_FOGPARAM3:
    if (bp.changes)
      PixelShaderManager::SetFogParamChanged();
    return;
  case BPMEM_FOGCOLOR:  // Fog Color
    if (bp.changes)
      PixelShaderManager::SetFogColorChanged();
    return;
  case BPMEM_ALPHACOMPARE:  // Compare Alpha Values
    PRIM_LOG("alphacmp: ref0=%d, ref1=%d, comp0=%d, comp1=%d, logic=%d", (int)bpmem.alpha_test.ref0,
             (int)bpmem.alpha_test.ref1, (int)bpmem.alpha_test.comp0, (int)bpmem.alpha_test.comp1,
             (int)bpmem.alpha_test.logic);
    if (bp.changes & 0xFFFF)
      PixelShaderManager::SetAlpha();
    if (bp.changes)
    {
      PixelShaderManager::SetAlphaTestChanged();
      SetBlendMode();
    }
    return;
  case BPMEM_BIAS:  // BIAS
    PRIM_LOG("ztex bias=0x%x", bpmem.ztex1.bias.Value());
    if (bp.changes)
      PixelShaderManager::SetZTextureBias();
    return;
  case BPMEM_ZTEX2:  // Z Texture type
  {
    if (bp.changes & 3)
      PixelShaderManager::SetZTextureTypeChanged();
    if (bp.changes & 12)
      PixelShaderManager::SetZTextureOpChanged();
#if defined(_DEBUG) || defined(DEBUGFAST)
    const char* pzop[] = {"DISABLE", "ADD", "REPLACE", "?"};
    const char* pztype[] = {"Z8", "Z16", "Z24", "?"};
    PRIM_LOG("ztex op=%s, type=%s", pzop[bpmem.ztex2.op], pztype[bpmem.ztex2.type]);
#endif
  }
    return;
  // ----------------------------------
  // Display Copy Filtering Control - GX_SetCopyFilter(u8 aa,u8 sample_pattern[12][2],u8 vf,u8
  // vfilter[7])
  // Fields: Destination, Frame2Field, Gamma, Source
  // ----------------------------------
  case BPMEM_DISPLAYCOPYFILTER:      // if (aa) { use sample_pattern } else { use 666666 }
  case BPMEM_DISPLAYCOPYFILTER + 1:  // if (aa) { use sample_pattern } else { use 666666 }
  case BPMEM_DISPLAYCOPYFILTER + 2:  // if (aa) { use sample_pattern } else { use 666666 }
  case BPMEM_DISPLAYCOPYFILTER + 3:  // if (aa) { use sample_pattern } else { use 666666 }
  case BPMEM_COPYFILTER0:            // if (vf) { use vfilter } else { use 595000 }
  case BPMEM_COPYFILTER1:            // if (vf) { use vfilter } else { use 000015 }
    return;
  // -----------------------------------
  // Interlacing Control
  // -----------------------------------
  case BPMEM_FIELDMASK:  // GX_SetFieldMask(u8 even_mask,u8 odd_mask)
  case BPMEM_FIELDMODE:  // GX_SetFieldMode(u8 field_mode,u8 half_aspect_ratio)
    // TODO
    return;
  // ----------------------------------------
  // Unimportant regs (Clock, Perf, ...)
  // ----------------------------------------
  case BPMEM_BUSCLOCK0:   // TB Bus Clock ?
  case BPMEM_BUSCLOCK1:   // TB Bus Clock ?
  case BPMEM_PERF0_TRI:   // Perf: Triangles
  case BPMEM_PERF0_QUAD:  // Perf: Quads
  case BPMEM_PERF1:       // Perf: Some Clock, Texels, TX, TC
    return;
  // ----------------
  // EFB Copy config
  // ----------------
  case BPMEM_EFB_TL:    // EFB Source Rect. Top, Left
  case BPMEM_EFB_BR:    // EFB Source Rect. Bottom, Right (w, h - 1)
  case BPMEM_EFB_ADDR:  // EFB Target Address
    return;
  // --------------
  // Clear Config
  // --------------
  case BPMEM_CLEAR_AR:  // Alpha and Red Components
  case BPMEM_CLEAR_GB:  // Green and Blue Components
  case BPMEM_CLEAR_Z:   // Z Components (24-bit Zbuffer)
    return;
  // -------------------------
  // Bounding Box Control
  // -------------------------
  case BPMEM_CLEARBBOX1:
  case BPMEM_CLEARBBOX2:
  {
    const u8 offset = bp.address & 2;
    BoundingBox::Enable();

    if (g_ActiveConfig.backend_info.bSupportsBBox && g_ActiveConfig.bBBoxEnable)
    {
      g_renderer->BBoxWrite(offset, bp.newvalue & 0x3ff);
      g_renderer->BBoxWrite(offset + 1, bp.newvalue >> 10);
    }
  }
    return;
  case BPMEM_TEXINVALIDATE:
    // TODO: Needs some restructuring in TextureCacheBase.
    TextureCacheBase::InvalidateAllBindPoints();
    return;

  case BPMEM_ZCOMPARE:  // Set the Z-Compare and EFB pixel format
    OnPixelFormatChange();
    if (bp.changes & 7)
      SetBlendMode();  // dual source could be activated by changing to PIXELFMT_RGBA6_Z24
    PixelShaderManager::SetZModeControl();
    return;

  case BPMEM_MIPMAP_STRIDE:  // MipMap Stride Channel
  case BPMEM_COPYYSCALE:     // Display Copy Y Scale

  /* 24 RID
   * 21 BC3 - Ind. Tex Stage 3 NTexCoord
   * 18 BI3 - Ind. Tex Stage 3 NTexMap
   * 15 BC2 - Ind. Tex Stage 2 NTexCoord
   * 12 BI2 - Ind. Tex Stage 2 NTexMap
   * 9 BC1 - Ind. Tex Stage 1 NTexCoord
   * 6 BI1 - Ind. Tex Stage 1 NTexMap
   * 3 BC0 - Ind. Tex Stage 0 NTexCoord
   * 0 BI0 - Ind. Tex Stage 0 NTexMap */
  case BPMEM_IREF:
  {
    if (bp.changes)
      PixelShaderManager::SetTevIndirectChanged();
    return;
  }

  case BPMEM_TEV_KSEL:      // Texture Environment Swap Mode Table 0
  case BPMEM_TEV_KSEL + 1:  // Texture Environment Swap Mode Table 1
  case BPMEM_TEV_KSEL + 2:  // Texture Environment Swap Mode Table 2
  case BPMEM_TEV_KSEL + 3:  // Texture Environment Swap Mode Table 3
  case BPMEM_TEV_KSEL + 4:  // Texture Environment Swap Mode Table 4
  case BPMEM_TEV_KSEL + 5:  // Texture Environment Swap Mode Table 5
  case BPMEM_TEV_KSEL + 6:  // Texture Environment Swap Mode Table 6
  case BPMEM_TEV_KSEL + 7:  // Texture Environment Swap Mode Table 7
    PixelShaderManager::SetTevKSel(bp.address - BPMEM_TEV_KSEL, bp.newvalue);
    return;

  /* This Register can be used to limit to which bits of BP registers is
   * actually written to. The mask is only valid for the next BP write,
   * and will reset itself afterwards. It's handled as a special case in
   * LoadBPReg. */
  case BPMEM_BP_MASK:

  case BPMEM_IND_IMASK:  // Index Mask ?
  case BPMEM_REVBITS:    // Always set to 0x0F when GX_InitRevBits() is called.
    return;

  case BPMEM_CLEAR_PIXEL_PERF:
    // GXClearPixMetric writes 0xAAA here, Sunshine alternates this register between values 0x000
    // and 0xAAA
    if (PerfQueryBase::ShouldEmulate())
      g_perf_query->ResetQuery();
    return;

  case BPMEM_PRELOAD_ADDR:
  case BPMEM_PRELOAD_TMEMEVEN:
  case BPMEM_PRELOAD_TMEMODD:  // Used when PRELOAD_MODE is set
    return;

  case BPMEM_PRELOAD_MODE:  // Set to 0 when GX_TexModeSync() is called.
    // if this is different from 0, manual TMEM management is used (GX_PreloadEntireTexture).
    if (bp.newvalue != 0)
    {
      // TODO: Not quite sure if this is completely correct (likely not)
      // NOTE: libogc's implementation of GX_PreloadEntireTexture seems flawed, so it's not
      // necessarily a good reference for RE'ing this feature.

      BPS_TmemConfig& tmem_cfg = bpmem.tmem_config;
      u32 src_addr = tmem_cfg.preload_addr << 5;  // TODO: Should we add mask here on GC?
      u32 bytes_read = 0;
      u32 tmem_addr_even = tmem_cfg.preload_tmem_even * TMEM_LINE_SIZE;

      if (tmem_cfg.preload_tile_info.type != 3)
      {
        bytes_read = tmem_cfg.preload_tile_info.count * TMEM_LINE_SIZE;
        if (tmem_addr_even + bytes_read > TMEM_SIZE)
          bytes_read = TMEM_SIZE - tmem_addr_even;

        Memory::CopyFromEmu(texMem + tmem_addr_even, src_addr, bytes_read);
      }
      else  // RGBA8 tiles (and CI14, but that might just be stupid libogc!)
      {
        u8* src_ptr = Memory::GetPointer(src_addr);

        // AR and GB tiles are stored in separate TMEM banks => can't use a single memcpy for
        // everything
        u32 tmem_addr_odd = tmem_cfg.preload_tmem_odd * TMEM_LINE_SIZE;

        for (u32 i = 0; i < tmem_cfg.preload_tile_info.count; ++i)
        {
          if (tmem_addr_even + TMEM_LINE_SIZE > TMEM_SIZE ||
              tmem_addr_odd + TMEM_LINE_SIZE > TMEM_SIZE)
            break;

          memcpy(texMem + tmem_addr_even, src_ptr + bytes_read, TMEM_LINE_SIZE);
          memcpy(texMem + tmem_addr_odd, src_ptr + bytes_read + TMEM_LINE_SIZE, TMEM_LINE_SIZE);
          tmem_addr_even += TMEM_LINE_SIZE;
          tmem_addr_odd += TMEM_LINE_SIZE;
          bytes_read += TMEM_LINE_SIZE * 2;
        }
      }

      if (g_bRecordFifoData)
        FifoRecorder::GetInstance().UseMemory(src_addr, bytes_read, MemoryUpdate::TMEM);

      TextureCacheBase::InvalidateAllBindPoints();
    }
    return;

  // ---------------------------------------------------
  // Set the TEV Color
  // ---------------------------------------------------
  //
  // NOTE: Each of these registers actually maps to two variables internally.
  //       There's a bit that specifies which one is currently written to.
  //
  // NOTE: Some games write only to the RA register (or only to the BG register).
  //       We may not assume that the unwritten register holds a valid value, hence
  //       both component pairs need to be loaded individually.
  case BPMEM_TEV_COLOR_RA:
  case BPMEM_TEV_COLOR_RA + 2:
  case BPMEM_TEV_COLOR_RA + 4:
  case BPMEM_TEV_COLOR_RA + 6:
  {
    int num = (bp.address >> 1) & 0x3;
    if (bpmem.tevregs[num].type_ra)
    {
      PixelShaderManager::SetTevKonstColor(num, 0, (s32)bpmem.tevregs[num].red);
      PixelShaderManager::SetTevKonstColor(num, 3, (s32)bpmem.tevregs[num].alpha);
    }
    else
    {
      PixelShaderManager::SetTevColor(num, 0, (s32)bpmem.tevregs[num].red);
      PixelShaderManager::SetTevColor(num, 3, (s32)bpmem.tevregs[num].alpha);
    }
    return;
  }

  case BPMEM_TEV_COLOR_BG:
  case BPMEM_TEV_COLOR_BG + 2:
  case BPMEM_TEV_COLOR_BG + 4:
  case BPMEM_TEV_COLOR_BG + 6:
  {
    int num = (bp.address >> 1) & 0x3;
    if (bpmem.tevregs[num].type_bg)
    {
      PixelShaderManager::SetTevKonstColor(num, 1, (s32)bpmem.tevregs[num].green);
      PixelShaderManager::SetTevKonstColor(num, 2, (s32)bpmem.tevregs[num].blue);
    }
    else
    {
      PixelShaderManager::SetTevColor(num, 1, (s32)bpmem.tevregs[num].green);
      PixelShaderManager::SetTevColor(num, 2, (s32)bpmem.tevregs[num].blue);
    }
    return;
  }

  default:
    break;
  }

  switch (bp.address & 0xFC)  // Texture sampler filter
  {
  // -------------------------
  // Texture Environment Order
  // -------------------------
  case BPMEM_TREF:
  case BPMEM_TREF + 4:
    PixelShaderManager::SetTevOrder(bp.address - BPMEM_TREF, bp.newvalue);
    return;
  // ----------------------
  // Set wrap size
  // ----------------------
  case BPMEM_SU_SSIZE:  // Matches BPMEM_SU_TSIZE too
  case BPMEM_SU_SSIZE + 4:
  case BPMEM_SU_SSIZE + 8:
  case BPMEM_SU_SSIZE + 12:
    if (bp.changes)
    {
      PixelShaderManager::SetTexCoordChanged((bp.address - BPMEM_SU_SSIZE) >> 1);
      GeometryShaderManager::SetTexCoordChanged((bp.address - BPMEM_SU_SSIZE) >> 1);
    }
    return;
  // ------------------------
  // BPMEM_TX_SETMODE0 - (Texture lookup and filtering mode) LOD/BIAS Clamp, MaxAnsio, LODBIAS,
  // DiagLoad, Min Filter, Mag Filter, Wrap T, S
  // BPMEM_TX_SETMODE1 - (LOD Stuff) - Max LOD, Min LOD
  // ------------------------
  case BPMEM_TX_SETMODE0:  // (0x90 for linear)
  case BPMEM_TX_SETMODE0_4:
    TextureCacheBase::InvalidateAllBindPoints();
    return;

  case BPMEM_TX_SETMODE1:
  case BPMEM_TX_SETMODE1_4:
    TextureCacheBase::InvalidateAllBindPoints();
    return;
  // --------------------------------------------
  // BPMEM_TX_SETIMAGE0 - Texture width, height, format
  // BPMEM_TX_SETIMAGE1 - even LOD address in TMEM - Image Type, Cache Height, Cache Width, TMEM
  // Offset
  // BPMEM_TX_SETIMAGE2 - odd LOD address in TMEM - Cache Height, Cache Width, TMEM Offset
  // BPMEM_TX_SETIMAGE3 - Address of Texture in main memory
  // --------------------------------------------
  case BPMEM_TX_SETIMAGE0:
  case BPMEM_TX_SETIMAGE0_4:
  case BPMEM_TX_SETIMAGE1:
  case BPMEM_TX_SETIMAGE1_4:
  case BPMEM_TX_SETIMAGE2:
  case BPMEM_TX_SETIMAGE2_4:
  case BPMEM_TX_SETIMAGE3:
  case BPMEM_TX_SETIMAGE3_4:
    TextureCacheBase::InvalidateAllBindPoints();
    return;
  // -------------------------------
  // Set a TLUT
  // BPMEM_TX_SETTLUT - Format, TMEM Offset (offset of TLUT from start of TMEM high bank > > 5)
  // -------------------------------
  case BPMEM_TX_SETTLUT:
  case BPMEM_TX_SETTLUT_4:
    TextureCacheBase::InvalidateAllBindPoints();
    return;

  default:
    break;
  }

  switch (bp.address & 0xF0)
  {
  // --------------
  // Indirect Tev
  // --------------
  case BPMEM_IND_CMD:
    PixelShaderManager::SetTevIndirectChanged();
    return;
  // --------------------------------------------------
  // Set Color/Alpha of a Tev
  // BPMEM_TEV_COLOR_ENV - Dest, Shift, Clamp, Sub, Bias, Sel A, Sel B, Sel C, Sel D
  // BPMEM_TEV_ALPHA_ENV - Dest, Shift, Clamp, Sub, Bias, Sel A, Sel B, Sel C, Sel D, T Swap, R Swap
  // --------------------------------------------------
  case BPMEM_TEV_COLOR_ENV:  // Texture Environment 1
  case BPMEM_TEV_COLOR_ENV + 16:
    PixelShaderManager::SetTevCombiner((bp.address - BPMEM_TEV_COLOR_ENV) >> 1,
                                       (bp.address - BPMEM_TEV_COLOR_ENV) & 1, bp.newvalue);
    return;
  default:
    break;
  }

  WARN_LOG(VIDEO, "Unknown BP opcode: address = 0x%08x value = 0x%08x", bp.address, bp.newvalue);
}

// Call browser: OpcodeDecoding.cpp ExecuteDisplayList > Decode() > LoadBPReg()
void LoadBPReg(u32 value0)
{
  int regNum = value0 >> 24;
  int oldval = ((u32*)&bpmem)[regNum];
  int newval = (oldval & ~bpmem.bpMask) | (value0 & bpmem.bpMask);
  int changes = (oldval ^ newval) & 0xFFFFFF;

  BPCmd bp = {regNum, changes, newval};

  // Reset the mask register if we're not trying to set it ourselves.
  if (regNum != BPMEM_BP_MASK)
    bpmem.bpMask = 0xFFFFFF;

  BPWritten(bp);
}

void LoadBPRegPreprocess(u32 value0)
{
  int regNum = value0 >> 24;
  // masking could hypothetically be a problem
  u32 newval = value0 & 0xffffff;
  switch (regNum)
  {
  case BPMEM_SETDRAWDONE:
    if ((newval & 0xff) == 0x02)
      PixelEngine::SetFinish();
    break;
  case BPMEM_PE_TOKEN_ID:
    PixelEngine::SetToken(newval & 0xffff, false);
    break;
  case BPMEM_PE_TOKEN_INT_ID:  // Pixel Engine Interrupt Token ID
    PixelEngine::SetToken(newval & 0xffff, true);
    break;
  }
}

void GetBPRegInfo(const u8* data, std::string* name, std::string* desc)
{
  const char* no_yes[2] = {"No", "Yes"};

  u8 cmd = data[0];
  u32 cmddata = Common::swap32(data) & 0xFFFFFF;
  switch (cmd)
  {
// Macro to set the register name and make sure it was written correctly via compile time assertion
#define SetRegName(reg)                                                                            \
  *name = #reg;                                                                                    \
  (void)(reg);

  case BPMEM_GENMODE:  // 0x00
    SetRegName(BPMEM_GENMODE);
    // TODO: Description
    break;

  case BPMEM_DISPLAYCOPYFILTER:  // 0x01
    // TODO: This is actually the sample pattern used for copies from an antialiased EFB
    SetRegName(BPMEM_DISPLAYCOPYFILTER);
    // TODO: Description
    break;

  case 0x02:  // 0x02
  case 0x03:  // 0x03
  case 0x04:  // 0x04
    // TODO: same as BPMEM_DISPLAYCOPYFILTER
    break;

  case BPMEM_IND_MTXA:  // 0x06
  case BPMEM_IND_MTXA + 3:
  case BPMEM_IND_MTXA + 6:
    SetRegName(BPMEM_IND_MTXA);
    // TODO: Description
    break;

  case BPMEM_IND_MTXB:  // 0x07
  case BPMEM_IND_MTXB + 3:
  case BPMEM_IND_MTXB + 6:
    SetRegName(BPMEM_IND_MTXB);
    // TODO: Descriptio
    break;

  case BPMEM_IND_MTXC:  // 0x08
  case BPMEM_IND_MTXC + 3:
  case BPMEM_IND_MTXC + 6:
    SetRegName(BPMEM_IND_MTXC);
    // TODO: Description
    break;

  case BPMEM_IND_IMASK:  // 0x0F
    SetRegName(BPMEM_IND_IMASK);
    // TODO: Description
    break;

  case BPMEM_IND_CMD:  // 0x10
  case BPMEM_IND_CMD + 1:
  case BPMEM_IND_CMD + 2:
  case BPMEM_IND_CMD + 3:
  case BPMEM_IND_CMD + 4:
  case BPMEM_IND_CMD + 5:
  case BPMEM_IND_CMD + 6:
  case BPMEM_IND_CMD + 7:
  case BPMEM_IND_CMD + 8:
  case BPMEM_IND_CMD + 9:
  case BPMEM_IND_CMD + 10:
  case BPMEM_IND_CMD + 11:
  case BPMEM_IND_CMD + 12:
  case BPMEM_IND_CMD + 13:
  case BPMEM_IND_CMD + 14:
  case BPMEM_IND_CMD + 15:
    SetRegName(BPMEM_IND_CMD);
    // TODO: Description
    break;

  case BPMEM_SCISSORTL:  // 0x20
    SetRegName(BPMEM_SCISSORTL);
    // TODO: Description
    break;

  case BPMEM_SCISSORBR:  // 0x21
    SetRegName(BPMEM_SCISSORBR);
    // TODO: Description
    break;

  case BPMEM_LINEPTWIDTH:  // 0x22
    SetRegName(BPMEM_LINEPTWIDTH);
    // TODO: Description
    break;

  case BPMEM_PERF0_TRI:  // 0x23
    SetRegName(BPMEM_PERF0_TRI);
    // TODO: Description
    break;

  case BPMEM_PERF0_QUAD:  // 0x24
    SetRegName(BPMEM_PERF0_QUAD);
    // TODO: Description
    break;

  case BPMEM_RAS1_SS0:  // 0x25
    SetRegName(BPMEM_RAS1_SS0);
    // TODO: Description
    break;

  case BPMEM_RAS1_SS1:  // 0x26
    SetRegName(BPMEM_RAS1_SS1);
    // TODO: Description
    break;

  case BPMEM_IREF:  // 0x27
    SetRegName(BPMEM_IREF);
    // TODO: Description
    break;

  case BPMEM_TREF:  // 0x28
  case BPMEM_TREF + 1:
  case BPMEM_TREF + 2:
  case BPMEM_TREF + 3:
  case BPMEM_TREF + 4:
  case BPMEM_TREF + 5:
  case BPMEM_TREF + 6:
  case BPMEM_TREF + 7:
    SetRegName(BPMEM_TREF);
    // TODO: Description
    break;

  case BPMEM_SU_SSIZE:  // 0x30
  case BPMEM_SU_SSIZE + 2:
  case BPMEM_SU_SSIZE + 4:
  case BPMEM_SU_SSIZE + 6:
  case BPMEM_SU_SSIZE + 8:
  case BPMEM_SU_SSIZE + 10:
  case BPMEM_SU_SSIZE + 12:
  case BPMEM_SU_SSIZE + 14:
    SetRegName(BPMEM_SU_SSIZE);
    // TODO: Description
    break;

  case BPMEM_SU_TSIZE:  // 0x31
  case BPMEM_SU_TSIZE + 2:
  case BPMEM_SU_TSIZE + 4:
  case BPMEM_SU_TSIZE + 6:
  case BPMEM_SU_TSIZE + 8:
  case BPMEM_SU_TSIZE + 10:
  case BPMEM_SU_TSIZE + 12:
  case BPMEM_SU_TSIZE + 14:
    SetRegName(BPMEM_SU_TSIZE);
    // TODO: Description
    break;

  case BPMEM_ZMODE:  // 0x40
    SetRegName(BPMEM_ZMODE);
    // TODO: Description
    break;

  case BPMEM_BLENDMODE:  // 0x41
  {
    SetRegName(BPMEM_BLENDMODE);
    BlendMode mode;
    mode.hex = cmddata;
    const char* dstfactors[] = {"0",         "1",           "src_color", "1-src_color",
                                "src_alpha", "1-src_alpha", "dst_alpha", "1-dst_alpha"};
    const char* srcfactors[] = {"0",         "1",           "dst_color", "1-dst_color",
                                "src_alpha", "1-src_alpha", "dst_alpha", "1-dst_alpha"};
    const char* logicmodes[] = {"0",     "s & d",  "s & ~d",   "s",        "~s & d", "d",
                                "s ^ d", "s | d",  "~(s | d)", "~(s ^ d)", "~d",     "s | ~d",
                                "~s",    "~s | d", "~(s & d)", "1"};
    *desc =
        fmt::format("Enable: {}\n"
                    "Logic ops: {}\n"
                    "Dither: {}\n"
                    "Color write: {}\n"
                    "Alpha write: {}\n"
                    "Dest factor: {}\n"
                    "Source factor: {}\n"
                    "Subtract: {}\n"
                    "Logic mode: {}\n",
                    no_yes[mode.blendenable], no_yes[mode.logicopenable], no_yes[mode.dither],
                    no_yes[mode.colorupdate], no_yes[mode.alphaupdate], dstfactors[mode.dstfactor],
                    srcfactors[mode.srcfactor], no_yes[mode.subtract], logicmodes[mode.logicmode]);
  }
  break;

  case BPMEM_CONSTANTALPHA:  // 0x42
    SetRegName(BPMEM_CONSTANTALPHA);
    // TODO: Description
    break;

  case BPMEM_ZCOMPARE:  // 0x43
  {
    SetRegName(BPMEM_ZCOMPARE);
    PEControl config;
    config.hex = cmddata;
    const char* pixel_formats[] = {"RGB8_Z24", "RGBA6_Z24", "RGB565_Z16", "Z24",
                                   "Y8",       "U8",        "V8",         "YUV420"};
    const char* zformats[] = {
        "linear",     "compressed (near)",     "compressed (mid)",     "compressed (far)",
        "inv linear", "compressed (inv near)", "compressed (inv mid)", "compressed (inv far)"};
    *desc = fmt::format("EFB pixel format: {}\n"
                        "Depth format: {}\n"
                        "Early depth test: {}\n",
                        pixel_formats[config.pixel_format], zformats[config.zformat],
                        no_yes[config.early_ztest]);
  }
  break;

  case BPMEM_FIELDMASK:  // 0x44
    SetRegName(BPMEM_FIELDMASK);
    // TODO: Description
    break;

  case BPMEM_SETDRAWDONE:  // 0x45
    SetRegName(BPMEM_SETDRAWDONE);
    // TODO: Description
    break;

  case BPMEM_BUSCLOCK0:  // 0x46
    SetRegName(BPMEM_BUSCLOCK0);
    // TODO: Description
    break;

  case BPMEM_PE_TOKEN_ID:  // 0x47
    SetRegName(BPMEM_PE_TOKEN_ID);
    // TODO: Description
    break;

  case BPMEM_PE_TOKEN_INT_ID:  // 0x48
    SetRegName(BPMEM_PE_TOKEN_INT_ID);
    // TODO: Description
    break;

  case BPMEM_EFB_TL:  // 0x49
  {
    SetRegName(BPMEM_EFB_TL);
    X10Y10 left_top;
    left_top.hex = cmddata;
    *desc = fmt::format("Left: {}\nTop: {}", left_top.x, left_top.y);
  }
  break;

  case BPMEM_EFB_BR:  // 0x4A
  {
    // TODO: Misleading name, should be BPMEM_EFB_WH instead
    SetRegName(BPMEM_EFB_BR);
    X10Y10 width_height;
    width_height.hex = cmddata;
    *desc = fmt::format("Width: {}\nHeight: {}", width_height.x + 1, width_height.y + 1);
  }
  break;

  case BPMEM_EFB_ADDR:  // 0x4B
    SetRegName(BPMEM_EFB_ADDR);
    *desc = fmt::format("Target address (32 byte aligned): 0x{:06X}", cmddata << 5);
    break;

  case BPMEM_MIPMAP_STRIDE:  // 0x4D
    SetRegName(BPMEM_MIPMAP_STRIDE);
    // TODO: Description
    break;

  case BPMEM_COPYYSCALE:  // 0x4E
    SetRegName(BPMEM_COPYYSCALE);
    *desc = fmt::format("Scaling factor (XFB copy only): 0x{:X} ({} or inverted {})", cmddata,
                        static_cast<float>(cmddata) / 256.f, 256.f / static_cast<float>(cmddata));
    break;

  case BPMEM_CLEAR_AR:  // 0x4F
    SetRegName(BPMEM_CLEAR_AR);
    *desc = fmt::format("Alpha: 0x{:02X}\nRed: 0x{:02X}", (cmddata & 0xFF00) >> 8, cmddata & 0xFF);
    break;

  case BPMEM_CLEAR_GB:  // 0x50
    SetRegName(BPMEM_CLEAR_GB);
    *desc = fmt::format("Green: 0x{:02X}\nBlue: 0x{:02X}", (cmddata & 0xFF00) >> 8, cmddata & 0xFF);
    break;

  case BPMEM_CLEAR_Z:  // 0x51
    SetRegName(BPMEM_CLEAR_Z);
    *desc = fmt::format("Z value: 0x{:06X}", cmddata);
    break;

  case BPMEM_TRIGGER_EFB_COPY:  // 0x52
  {
    SetRegName(BPMEM_TRIGGER_EFB_COPY);
    UPE_Copy copy;
    copy.Hex = cmddata;
    *desc = fmt::format(
        "Clamping: {}\n"
        "Converting from RGB to YUV: {}\n"
        "Target pixel format: 0x{:X}\n"
        "Gamma correction: {}\n"
        "Mipmap filter: {}\n"
        "Vertical scaling: {}\n"
        "Clear: {}\n"
        "Frame to field: 0x{:01X}\n"
        "Copy to XFB: {}\n"
        "Intensity format: {}\n"
        "Automatic color conversion: {}",
        (copy.clamp_top && copy.clamp_bottom) ?
            "Top and Bottom" :
            (copy.clamp_top) ? "Top only" : (copy.clamp_bottom) ? "Bottom only" : "None",
        no_yes[copy.yuv], static_cast<int>(copy.tp_realFormat()),
        (copy.gamma == 0) ?
            "1.0" :
            (copy.gamma == 1) ? "1.7" : (copy.gamma == 2) ? "2.2" : "Invalid value 0x3?",
        no_yes[copy.half_scale], no_yes[copy.scale_invert], no_yes[copy.clear],
        static_cast<u32>(copy.frame_to_field), no_yes[copy.copy_to_xfb], no_yes[copy.intensity_fmt],
        no_yes[copy.auto_conv]);
  }
  break;

  case BPMEM_COPYFILTER0:  // 0x53
    SetRegName(BPMEM_COPYFILTER0);
    // TODO: Description
    break;

  case BPMEM_COPYFILTER1:  // 0x54
    SetRegName(BPMEM_COPYFILTER1);
    // TODO: Description
    break;

  case BPMEM_CLEARBBOX1:  // 0x55
    SetRegName(BPMEM_CLEARBBOX1);
    // TODO: Description
    break;

  case BPMEM_CLEARBBOX2:  // 0x56
    SetRegName(BPMEM_CLEARBBOX2);
    // TODO: Description
    break;

  case BPMEM_CLEAR_PIXEL_PERF:  // 0x57
    SetRegName(BPMEM_CLEAR_PIXEL_PERF);
    // TODO: Description
    break;

  case BPMEM_REVBITS:  // 0x58
    SetRegName(BPMEM_REVBITS);
    // TODO: Description
    break;

  case BPMEM_SCISSOROFFSET:  // 0x59
    SetRegName(BPMEM_SCISSOROFFSET);
    // TODO: Description
    break;

  case BPMEM_PRELOAD_ADDR:  // 0x60
    SetRegName(BPMEM_PRELOAD_ADDR);
    // TODO: Description
    break;

  case BPMEM_PRELOAD_TMEMEVEN:  // 0x61
    SetRegName(BPMEM_PRELOAD_TMEMEVEN);
    // TODO: Description
    break;

  case BPMEM_PRELOAD_TMEMODD:  // 0x62
    SetRegName(BPMEM_PRELOAD_TMEMODD);
    // TODO: Description
    break;

  case BPMEM_PRELOAD_MODE:  // 0x63
    SetRegName(BPMEM_PRELOAD_MODE);
    // TODO: Description
    break;

  case BPMEM_LOADTLUT0:  // 0x64
    SetRegName(BPMEM_LOADTLUT0);
    // TODO: Description
    break;

  case BPMEM_LOADTLUT1:  // 0x65
    SetRegName(BPMEM_LOADTLUT1);
    // TODO: Description
    break;

  case BPMEM_TEXINVALIDATE:  // 0x66
    SetRegName(BPMEM_TEXINVALIDATE);
    // TODO: Description
    break;

  case BPMEM_PERF1:  // 0x67
    SetRegName(BPMEM_PERF1);
    // TODO: Description
    break;

  case BPMEM_FIELDMODE:  // 0x68
    SetRegName(BPMEM_FIELDMODE);
    // TODO: Description
    break;

  case BPMEM_BUSCLOCK1:  // 0x69
    SetRegName(BPMEM_BUSCLOCK1);
    // TODO: Description
    break;

  case BPMEM_TX_SETMODE0:  // 0x80
  case BPMEM_TX_SETMODE0 + 1:
  case BPMEM_TX_SETMODE0 + 2:
  case BPMEM_TX_SETMODE0 + 3:
    SetRegName(BPMEM_TX_SETMODE0);
    // TODO: Description
    break;

  case BPMEM_TX_SETMODE1:  // 0x84
  case BPMEM_TX_SETMODE1 + 1:
  case BPMEM_TX_SETMODE1 + 2:
  case BPMEM_TX_SETMODE1 + 3:
    SetRegName(BPMEM_TX_SETMODE1);
    // TODO: Description
    break;

  case BPMEM_TX_SETIMAGE0:  // 0x88
  case BPMEM_TX_SETIMAGE0 + 1:
  case BPMEM_TX_SETIMAGE0 + 2:
  case BPMEM_TX_SETIMAGE0 + 3:
  case BPMEM_TX_SETIMAGE0_4:  // 0xA8
  case BPMEM_TX_SETIMAGE0_4 + 1:
  case BPMEM_TX_SETIMAGE0_4 + 2:
  case BPMEM_TX_SETIMAGE0_4 + 3:
  {
    SetRegName(BPMEM_TX_SETIMAGE0);
    int texnum =
        (cmd < BPMEM_TX_SETIMAGE0_4) ? cmd - BPMEM_TX_SETIMAGE0 : cmd - BPMEM_TX_SETIMAGE0_4 + 4;
    TexImage0 teximg;
    teximg.hex = cmddata;
    *desc = fmt::format("Texture Unit: {}\n"
                        "Width: {}\n"
                        "Height: {}\n"
                        "Format: {:x}\n",
                        texnum, teximg.width + 1, teximg.height + 1, teximg.format);
  }
  break;

  case BPMEM_TX_SETIMAGE1:  // 0x8C
  case BPMEM_TX_SETIMAGE1 + 1:
  case BPMEM_TX_SETIMAGE1 + 2:
  case BPMEM_TX_SETIMAGE1 + 3:
  case BPMEM_TX_SETIMAGE1_4:  // 0xAC
  case BPMEM_TX_SETIMAGE1_4 + 1:
  case BPMEM_TX_SETIMAGE1_4 + 2:
  case BPMEM_TX_SETIMAGE1_4 + 3:
  {
    SetRegName(BPMEM_TX_SETIMAGE1);
    int texnum =
        (cmd < BPMEM_TX_SETIMAGE1_4) ? cmd - BPMEM_TX_SETIMAGE1 : cmd - BPMEM_TX_SETIMAGE1_4 + 4;
    TexImage1 teximg;
    teximg.hex = cmddata;
    *desc = fmt::format("Texture Unit: {}\n"
                        "Even TMEM Offset: {:x}\n"
                        "Even TMEM Width: {}\n"
                        "Even TMEM Height: {}\n"
                        "Cache is manually managed: {}\n",
                        texnum, teximg.tmem_even, teximg.cache_width, teximg.cache_height,
                        no_yes[teximg.image_type]);
  }
  break;

  case BPMEM_TX_SETIMAGE2:  // 0x90
  case BPMEM_TX_SETIMAGE2 + 1:
  case BPMEM_TX_SETIMAGE2 + 2:
  case BPMEM_TX_SETIMAGE2 + 3:
  case BPMEM_TX_SETIMAGE2_4:  // 0xB0
  case BPMEM_TX_SETIMAGE2_4 + 1:
  case BPMEM_TX_SETIMAGE2_4 + 2:
  case BPMEM_TX_SETIMAGE2_4 + 3:
  {
    SetRegName(BPMEM_TX_SETIMAGE2);
    int texnum =
        (cmd < BPMEM_TX_SETIMAGE2_4) ? cmd - BPMEM_TX_SETIMAGE2 : cmd - BPMEM_TX_SETIMAGE2_4 + 4;
    TexImage2 teximg;
    teximg.hex = cmddata;
    *desc = fmt::format("Texture Unit: {}\n"
                        "Odd TMEM Offset: {:x}\n"
                        "Odd TMEM Width: {}\n"
                        "Odd TMEM Height: {}\n",
                        texnum, teximg.tmem_odd, teximg.cache_width, teximg.cache_height);
  }
  break;

  case BPMEM_TX_SETIMAGE3:  // 0x94
  case BPMEM_TX_SETIMAGE3 + 1:
  case BPMEM_TX_SETIMAGE3 + 2:
  case BPMEM_TX_SETIMAGE3 + 3:
  case BPMEM_TX_SETIMAGE3_4:  // 0xB4
  case BPMEM_TX_SETIMAGE3_4 + 1:
  case BPMEM_TX_SETIMAGE3_4 + 2:
  case BPMEM_TX_SETIMAGE3_4 + 3:
  {
    SetRegName(BPMEM_TX_SETIMAGE3);
    int texnum =
        (cmd < BPMEM_TX_SETIMAGE3_4) ? cmd - BPMEM_TX_SETIMAGE3 : cmd - BPMEM_TX_SETIMAGE3_4 + 4;
    TexImage3 teximg;
    teximg.hex = cmddata;
    *desc = fmt::format("Texture {} source address (32 byte aligned): 0x{:06X}", texnum,
                        teximg.image_base << 5);
  }
  break;

  case BPMEM_TX_SETTLUT:  // 0x98
  case BPMEM_TX_SETTLUT + 1:
  case BPMEM_TX_SETTLUT + 2:
  case BPMEM_TX_SETTLUT + 3:
  case BPMEM_TX_SETTLUT_4:  // 0xB8
  case BPMEM_TX_SETTLUT_4 + 1:
  case BPMEM_TX_SETTLUT_4 + 2:
  case BPMEM_TX_SETTLUT_4 + 3:
    SetRegName(BPMEM_TX_SETTLUT);
    // TODO: Description
    break;

  case BPMEM_TEV_COLOR_ENV:  // 0xC0
  case BPMEM_TEV_COLOR_ENV + 2:
  case BPMEM_TEV_COLOR_ENV + 4:
  case BPMEM_TEV_COLOR_ENV + 8:
  case BPMEM_TEV_COLOR_ENV + 10:
  case BPMEM_TEV_COLOR_ENV + 12:
  case BPMEM_TEV_COLOR_ENV + 14:
  case BPMEM_TEV_COLOR_ENV + 16:
  case BPMEM_TEV_COLOR_ENV + 18:
  case BPMEM_TEV_COLOR_ENV + 20:
  case BPMEM_TEV_COLOR_ENV + 22:
  case BPMEM_TEV_COLOR_ENV + 24:
  case BPMEM_TEV_COLOR_ENV + 26:
  case BPMEM_TEV_COLOR_ENV + 28:
  case BPMEM_TEV_COLOR_ENV + 30:
  {
    SetRegName(BPMEM_TEV_COLOR_ENV);
    TevStageCombiner::ColorCombiner cc;
    cc.hex = cmddata;
    const char* tevin[] = {
        "prev.rgb", "prev.aaa", "c0.rgb",  "c0.aaa",  "c1.rgb", "c1.aaa", "c2.rgb",    "c2.aaa",
        "tex.rgb",  "tex.aaa",  "ras.rgb", "ras.aaa", "ONE",    "HALF",   "konst.rgb", "ZERO",
    };
    const char* tevbias[] = {"0", "+0.5", "-0.5", "compare"};
    const char* tevop[] = {"add", "sub"};
    const char* tevscale[] = {"1", "2", "4", "0.5"};
    const char* tevout[] = {"prev.rgb", "c0.rgb", "c1.rgb", "c2.rgb"};
    *desc = fmt::format("Tev stage: {}\n"
                        "a: {}\n"
                        "b: {}\n"
                        "c: {}\n"
                        "d: {}\n"
                        "Bias: {}\n"
                        "Op: {}\n"
                        "Clamp: {}\n"
                        "Scale factor: {}\n"
                        "Dest: {}\n",
                        (data[0] - BPMEM_TEV_COLOR_ENV) / 2, tevin[cc.a], tevin[cc.b], tevin[cc.c],
                        tevin[cc.d], tevbias[cc.bias], tevop[cc.op], no_yes[cc.clamp],
                        tevscale[cc.shift], tevout[cc.dest]);
    break;
  }

  case BPMEM_TEV_ALPHA_ENV:  // 0xC1
  case BPMEM_TEV_ALPHA_ENV + 2:
  case BPMEM_TEV_ALPHA_ENV + 4:
  case BPMEM_TEV_ALPHA_ENV + 6:
  case BPMEM_TEV_ALPHA_ENV + 8:
  case BPMEM_TEV_ALPHA_ENV + 10:
  case BPMEM_TEV_ALPHA_ENV + 12:
  case BPMEM_TEV_ALPHA_ENV + 14:
  case BPMEM_TEV_ALPHA_ENV + 16:
  case BPMEM_TEV_ALPHA_ENV + 18:
  case BPMEM_TEV_ALPHA_ENV + 20:
  case BPMEM_TEV_ALPHA_ENV + 22:
  case BPMEM_TEV_ALPHA_ENV + 24:
  case BPMEM_TEV_ALPHA_ENV + 26:
  case BPMEM_TEV_ALPHA_ENV + 28:
  case BPMEM_TEV_ALPHA_ENV + 30:
  {
    SetRegName(BPMEM_TEV_ALPHA_ENV);
    TevStageCombiner::AlphaCombiner ac;
    ac.hex = cmddata;
    const char* tevin[] = {
        "prev", "c0", "c1", "c2", "tex", "ras", "konst", "ZERO",
    };
    const char* tevbias[] = {"0", "+0.5", "-0.5", "compare"};
    const char* tevop[] = {"add", "sub"};
    const char* tevscale[] = {"1", "2", "4", "0.5"};
    const char* tevout[] = {"prev", "c0", "c1", "c2"};
    *desc = fmt::format("Tev stage: {}\n"
                        "a: {}\n"
                        "b: {}\n"
                        "c: {}\n"
                        "d: {}\n"
                        "Bias: {}\n"
                        "Op: {}\n"
                        "Clamp: {}\n"
                        "Scale factor: {}\n"
                        "Dest: {}\n"
                        "Ras sel: {}\n"
                        "Tex sel: {}\n",
                        (data[0] - BPMEM_TEV_ALPHA_ENV) / 2, tevin[ac.a], tevin[ac.b], tevin[ac.c],
                        tevin[ac.d], tevbias[ac.bias], tevop[ac.op], no_yes[ac.clamp],
                        tevscale[ac.shift], tevout[ac.dest], ac.rswap.Value(), ac.tswap.Value());
    break;
  }

  case BPMEM_TEV_COLOR_RA:      // 0xE0
  case BPMEM_TEV_COLOR_RA + 2:  // 0xE2
  case BPMEM_TEV_COLOR_RA + 4:  // 0xE4
  case BPMEM_TEV_COLOR_RA + 6:  // 0xE6
    SetRegName(BPMEM_TEV_COLOR_RA);
    // TODO: Description
    break;

  case BPMEM_TEV_COLOR_BG:      // 0xE1
  case BPMEM_TEV_COLOR_BG + 2:  // 0xE3
  case BPMEM_TEV_COLOR_BG + 4:  // 0xE5
  case BPMEM_TEV_COLOR_BG + 6:  // 0xE7
    SetRegName(BPMEM_TEV_COLOR_BG);
    // TODO: Description
    break;

  case BPMEM_FOGRANGE:  // 0xE8
  case BPMEM_FOGRANGE + 1:
  case BPMEM_FOGRANGE + 2:
  case BPMEM_FOGRANGE + 3:
  case BPMEM_FOGRANGE + 4:
  case BPMEM_FOGRANGE + 5:
    SetRegName(BPMEM_FOGRANGE);
    // TODO: Description
    break;

  case BPMEM_FOGPARAM0:  // 0xEE
    SetRegName(BPMEM_FOGPARAM0);
    // TODO: Description
    break;

  case BPMEM_FOGBMAGNITUDE:  // 0xEF
    SetRegName(BPMEM_FOGBMAGNITUDE);
    // TODO: Description
    break;

  case BPMEM_FOGBEXPONENT:  // 0xF0
    SetRegName(BPMEM_FOGBEXPONENT);
    // TODO: Description
    break;

  case BPMEM_FOGPARAM3:  // 0xF1
    SetRegName(BPMEM_FOGPARAM3);
    // TODO: Description
    break;

  case BPMEM_FOGCOLOR:  // 0xF2
    SetRegName(BPMEM_FOGCOLOR);
    // TODO: Description
    break;

  case BPMEM_ALPHACOMPARE:  // 0xF3
  {
    SetRegName(BPMEM_ALPHACOMPARE);
    AlphaTest test;
    test.hex = cmddata;
    const char* functions[] = {"NEVER",   "LESS",   "EQUAL",  "LEQUAL",
                               "GREATER", "NEQUAL", "GEQUAL", "ALWAYS"};
    const char* logic[] = {"AND", "OR", "XOR", "XNOR"};
    *desc = fmt::format("Test 1: {} (ref: 0x{:02x})\n"
                        "Test 2: {} (ref: 0x{:02x})\n"
                        "Logic: {}\n",
                        functions[test.comp0], test.ref0.Value(), functions[test.comp1],
                        test.ref1.Value(), logic[test.logic]);
    break;
  }

  case BPMEM_BIAS:  // 0xF4
    SetRegName(BPMEM_BIAS);
    // TODO: Description
    break;

  case BPMEM_ZTEX2:  // 0xF5
    SetRegName(BPMEM_ZTEX2);
    // TODO: Description
    break;

  case BPMEM_TEV_KSEL:  // 0xF6
  case BPMEM_TEV_KSEL + 1:
  case BPMEM_TEV_KSEL + 2:
  case BPMEM_TEV_KSEL + 3:
  case BPMEM_TEV_KSEL + 4:
  case BPMEM_TEV_KSEL + 5:
  case BPMEM_TEV_KSEL + 6:
  case BPMEM_TEV_KSEL + 7:
    SetRegName(BPMEM_TEV_KSEL);
    // TODO: Description
    break;

#undef SetRegName
  }
}

// Called when loading a saved state.
void BPReload()
{
  // restore anything that goes straight to the renderer.
  // let's not risk actually replaying any writes.
  // note that PixelShaderManager is already covered since it has its own DoState.
  SetGenerationMode();
  SetScissor();
  SetViewport();
  SetDepthMode();
  SetBlendMode();
  OnPixelFormatChange();
}