Repository navigation
Expand file tree
/
Copy pathrt64.patch
More file actions
2845 lines (2738 loc) · 158 KB
/
Copy pathrt64.patch
File metadata and controls
2845 lines (2738 loc) · 158 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
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 79dfc38..237a00d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -327,6 +327,7 @@ set (SOURCES
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3d.cpp"
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dex.cpp"
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dex2.cpp"
+ "${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dex2cbfd.cpp"
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dgolden.cpp"
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dpd.cpp"
"${PROJECT_SOURCE_DIR}/src/gbi/rt64_gbi_f3dwave.cpp"
@@ -359,6 +360,7 @@ set (SOURCES
"${PROJECT_SOURCE_DIR}/src/hle/rt64_projection.cpp"
"${PROJECT_SOURCE_DIR}/src/hle/rt64_rdp.cpp"
"${PROJECT_SOURCE_DIR}/src/hle/rt64_rdp_tmem.cpp"
+ "${PROJECT_SOURCE_DIR}/src/hle/rt64_rice_hash.cpp"
"${PROJECT_SOURCE_DIR}/src/hle/rt64_rigid_body.cpp"
"${PROJECT_SOURCE_DIR}/src/hle/rt64_rsp.cpp"
"${PROJECT_SOURCE_DIR}/src/hle/rt64_state.cpp"
diff --git a/include/rt64_extended_gbi.h b/include/rt64_extended_gbi.h
index d387090..75ab87d 100644
--- a/include/rt64_extended_gbi.h
+++ b/include/rt64_extended_gbi.h
@@ -113,6 +113,9 @@
#define G_EX_ASPECT_AUTO 0x0
#define G_EX_ASPECT_STRETCH 0x1
#define G_EX_ASPECT_ADJUST 0x2
+// Stretched to the width like G_EX_ASPECT_STRETCH, and scaled as much vertically about the
+// middle of the scissor, keeping the rect's proportions (its top and bottom are cropped).
+#define G_EX_ASPECT_ZOOM 0x3
#define G_EX_VERTEX_POSITION 0x0
#define G_EX_VERTEX_VELOCITY 0x1
diff --git a/src/common/rt64_common.h b/src/common/rt64_common.h
index f79adbf..6e0a6f9 100644
--- a/src/common/rt64_common.h
+++ b/src/common/rt64_common.h
@@ -70,6 +70,18 @@ namespace RT64 {
int x, y, w, h;
};
+ // How far (10.2 fixed point) a projection's scissor may fall short of its framebuffer pair's scissor on each
+ // side and still count as covering the whole width, for the widescreen viewport and projection adjustment.
+ // Conker's 3D scissor stops 2 pixels short of each edge of the frame, and a full-frame rectangle drawn in the
+ // same pair would otherwise put its 3D back in the 4:3 area.
+ constexpr int32_t CoversWidthSlack = 4 * 4;
+
+ // The same for a 3D view's viewport, which may fall further short: Conker's split-screen multiplayer draws each
+ // player's view 32 pixels in from each edge, and the top view shares its pair with full-frame drawing, so with
+ // the rects' slack only the bottom view was widened. Rects keep the smaller slack, so 2D a little inside the
+ // frame isn't stretched to the widened edges.
+ constexpr int32_t CoversWidthViewportSlack = 40 * 4;
+
struct FixedRect {
int32_t ulx;
int32_t uly;
diff --git a/src/common/rt64_fblog.h b/src/common/rt64_fblog.h
new file mode 100644
index 0000000..c9dd621
--- /dev/null
+++ b/src/common/rt64_fblog.h
@@ -0,0 +1,80 @@
+//
+// RT64
+//
+
+// TEMP-DEBUG (Conker): a log of what happens to framebuffers, depth and widening, for the
+// widescreen door clipping. Off unless CONKER_RT64_FBLOG is set. It then logs 2 frames out of
+// every 150 (about every 5 seconds), 40 times, to rt64_fb_log.txt in the working directory.
+// Frames are workload submission frames: the same number on the game's side (hle) and on the
+// renderer's side, which run on different threads.
+
+#pragma once
+
+#include <cstdarg>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <mutex>
+
+namespace RT64 {
+ namespace FbLog {
+ constexpr uint64_t Period = 150;
+ constexpr uint64_t FramesPerCapture = 2;
+ constexpr uint64_t Captures = 40;
+
+ inline bool enabled() {
+ static const bool on = (std::getenv("CONKER_RT64_FBLOG") != nullptr);
+ return on;
+ }
+
+ inline bool frameLogged(uint64_t frame) {
+ return enabled() && ((frame % Period) < FramesPerCapture) && ((frame / Period) < Captures);
+ }
+
+ // The frame being processed on this thread, for code that doesn't know its workload.
+ inline uint64_t &threadFrame() {
+ thread_local uint64_t frame = UINT64_MAX;
+ return frame;
+ }
+
+ // Which side this thread is: "hle" (the game's display lists, and the native render to
+ // RDRAM) or "hires" (the widened picture on screen).
+ inline const char *&threadSide() {
+ thread_local const char *side = "?";
+ return side;
+ }
+
+ inline void setThreadFrame(uint64_t frame, const char *side = nullptr) {
+ threadFrame() = frame;
+ if (side != nullptr) {
+ threadSide() = side;
+ }
+ }
+
+ inline bool threadActive() {
+ return (threadFrame() != UINT64_MAX) && frameLogged(threadFrame());
+ }
+
+ inline void print(const char *fmt, ...) {
+ static std::mutex mutex;
+ static FILE *file = nullptr;
+ std::lock_guard<std::mutex> lock(mutex);
+ if (file == nullptr) {
+ file = std::fopen("rt64_fb_log.txt", "w");
+ if (file == nullptr) {
+ return;
+ }
+ }
+
+ va_list args;
+ va_start(args, fmt);
+ std::vfprintf(file, fmt, args);
+ va_end(args);
+ std::fputc('\n', file);
+ std::fflush(file);
+ }
+ };
+};
+
+#define RT64_FBLOG_RECT(r) (r).ulx, (r).uly, (r).lrx, (r).lry
+#define RT64_FBLOG_RECT_FMT "(%d,%d)-(%d,%d)"
diff --git a/src/common/rt64_hlslpp.h b/src/common/rt64_hlslpp.h
index 1450565..032ed28 100644
--- a/src/common/rt64_hlslpp.h
+++ b/src/common/rt64_hlslpp.h
@@ -10,4 +10,8 @@
#define HLSLPP_SCALAR
#endif
+// The scalar implementation uses labs() without including <stdlib.h>, which recent
+// macOS SDKs no longer bring in through <math.h>.
+#include <stdlib.h>
+
#include "hlsl++.h"
\ No newline at end of file
diff --git a/src/common/rt64_replacement_database.cpp b/src/common/rt64_replacement_database.cpp
index 9f331c9..1d3f107 100644
--- a/src/common/rt64_replacement_database.cpp
+++ b/src/common/rt64_replacement_database.cpp
@@ -145,7 +145,7 @@ namespace RT64 {
}
}
- void ReplacementDatabase::resolvePaths(const FileSystem *fileSystem, uint32_t fileSystemIndex, std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap, bool onlyDDS, std::vector<uint64_t> *hashesMissing, std::unordered_set<std::string> *pathsToPreload) {
+ void ReplacementDatabase::resolvePaths(const FileSystem *fileSystem, uint32_t fileSystemIndex, std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap, bool onlyDDS, std::vector<uint64_t> *hashesMissing, std::unordered_set<std::string> *pathsToPreload, std::unordered_map<std::string, ReplacementResolvedPath> *ricePathMap) {
std::unordered_map<std::string, std::string> autoPathMap;
for (const std::string &relativePath : *fileSystem) {
const std::filesystem::path relativePathFs = std::filesystem::u8path(relativePath);
@@ -172,6 +172,19 @@ namespace RT64 {
}
}
+ if ((ricePathMap != nullptr) && (config.autoPath == ReplacementAutoPath::Rice)) {
+ const ReplacementTexture defaultTexture;
+ for (const auto &[riceHash, relativePath] : autoPathMap) {
+ ReplacementResolvedPath &resolvedPath = (*ricePathMap)[riceHash];
+ resolvedPath.fileSystemIndex = fileSystemIndex;
+ resolvedPath.relativePath = relativePath;
+ resolvedPath.originalOperation = defaultTexture.operation;
+ resolvedPath.originalShift = defaultTexture.shift;
+ resolvedPath.resolvedOperation = resolveOperation(relativePath, defaultTexture.operation);
+ resolvedPath.resolvedShift = resolveShift(relativePath, defaultTexture.shift);
+ }
+ }
+
auto addResolvedPath = [&](uint64_t hash, const std::string &relativePath, ReplacementOperation operation, ReplacementShift shift) {
// Do not modify the entry if it's already in the map.
if (resolvedPathMap.find(hash) != resolvedPathMap.end()) {
diff --git a/src/common/rt64_replacement_database.h b/src/common/rt64_replacement_database.h
index 3f74ea2..3988595 100644
--- a/src/common/rt64_replacement_database.h
+++ b/src/common/rt64_replacement_database.h
@@ -126,7 +126,9 @@ namespace RT64 {
void buildHashMaps();
ReplacementOperation resolveOperation(const std::string &relativePath, ReplacementOperation operation);
ReplacementShift resolveShift(const std::string &relativePath, ReplacementShift shift);
- void resolvePaths(const FileSystem *fileSystem, uint32_t fileSystemIndex, std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap, bool onlyDDS, std::vector<uint64_t> *hashesMissing = nullptr, std::unordered_set<std::string> *pathsToPreload = nullptr);
+ // With ricePathMap, a database whose auto path is Rice also gives each file found by its Rice hash, resolved as an
+ // entry without a path would be: for textures matched by their Rice hash as they're loaded (hle/rt64_rice_hash.h).
+ void resolvePaths(const FileSystem *fileSystem, uint32_t fileSystemIndex, std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap, bool onlyDDS, std::vector<uint64_t> *hashesMissing = nullptr, std::unordered_set<std::string> *pathsToPreload = nullptr, std::unordered_map<std::string, ReplacementResolvedPath> *ricePathMap = nullptr);
void resolveOperations(std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap);
void resolveShifts(std::unordered_map<uint64_t, ReplacementResolvedPath> &resolvedPathMap);
static uint64_t stringToHash(const std::string &str);
diff --git a/src/gbi/rt64_gbi.cpp b/src/gbi/rt64_gbi.cpp
index 7006549..4984e7c 100644
--- a/src/gbi/rt64_gbi.cpp
+++ b/src/gbi/rt64_gbi.cpp
@@ -13,6 +13,7 @@
#include "rt64_gbi_f3dpd.h"
#include "rt64_gbi_f3dex.h"
#include "rt64_gbi_f3dex2.h"
+#include "rt64_gbi_f3dex2cbfd.h"
#include "rt64_gbi_f3dwave.h"
#include "rt64_gbi_f3dzex2.h"
#include "rt64_gbi_l3dex2.h"
@@ -110,6 +111,8 @@ namespace RT64 {
const GBIInstance F3DLX2_FIFO_2_08_REJ = { "F3DLX2.fifo 2.08.Rej", GBIUCode::F3DEX2, { true, false, true, false, false } }; // Needs confirmation.
const GBIInstance F3DEX2_FIFO_2_08_CRUISN = { "F3DEX2.fifo 2.08 (Cruis'n Exotica)", GBIUCode::Unknown, { false, false, false, false, false } }; // Needs confirmation.
const GBIInstance F3DEX2_FIFO_2_08_PL = { "F3DEX2.fifo 2.08 (POSLIGHT)", GBIUCode::F3DEX2, { false, false, false, false, true } };
+ const GBIInstance F3DEXBG_NON_FIFO_2_08 = { "F3DEXBG.NoN fifo 2.08 (Conker's Bad Fur Day)", GBIUCode::F3DEX2CBFD, { false, true, false, false, false } };
+ const GBIInstance F3DEX_NON_FIFO_2_08_CBFD = { "F3DEX.NoN fifo 2.08 (Conker's Bad Fur Day)", GBIUCode::F3DEX2CBFD, { false, true, false, false, false } };
const GBIInstance F3DEX2_XBUS_2_05 = { "F3DEX2.xbus 2.05", GBIUCode::F3DEX2, { false, false, false, false, false } }; // Needs confirmation.
const GBIInstance F3DEX2_XBUS_2_07 = { "F3DEX2.xbus 2.07", GBIUCode::F3DEX2, { false, false, false, false, false } }; // Needs confirmation.
const GBIInstance F3DLX2_XBUS_2_07_REJ = { "F3DLX2.xbus 2.07.Rej", GBIUCode::F3DEX2, { true, false, true, false, false } }; // Needs confirmation.
@@ -160,7 +163,7 @@ namespace RT64 {
//
// Length Hash Known instances
//
- static std::array<GBISegment, 94> textSegments = {
+ static std::array<GBISegment, 96> textSegments = {
GBISegment{ 0x1408, 0x9C0926F5E466BE70ULL, { &F3D_SDK_E } }, // Needs confirmation.
GBISegment{ 0x1400, 0x34EAA6E921BCF1B2ULL, { &F3D_SDK_F, &F3D_SDK_UNKNOWN_G, &F3D_SDK_UNKNOWN_H } }, // Needs confirmation.
GBISegment{ 0x1408, 0x3E05E9BBE814C700ULL, { &F3D_FIFO_SDK_E } }, // Needs confirmation.
@@ -211,6 +214,8 @@ namespace RT64 {
GBISegment{ 0x1390, 0x0B8FE363267ADCB4ULL, { &F3DEX2_FIFO_2_06 } },
GBISegment{ 0x1390, 0x8C1C9814E75E1B4BULL, { &F3DEX2_FIFO_2_07 } },
GBISegment{ 0x1390, 0xCF55FAE288BFE48DULL, { &F3DEX2_FIFO_2_08 } }, // Needs confirmation.
+ GBISegment{ 0x1390, 0xEFF7E499684E95B2ULL, { &F3DEXBG_NON_FIFO_2_08 } },
+ GBISegment{ 0x1390, 0x5B76BAEB4121C82CULL, { &F3DEX_NON_FIFO_2_08_CBFD } },
GBISegment{ 0x1188, 0xB9FBB8E71F72B596ULL, { &F3DEX2_FIFO_2_08_REJ } }, // Needs confirmation.
GBISegment{ 0x1188, 0x5235C026EC14B4FBULL, { &F3DLX2_FIFO_2_08_REJ } }, // Needs confirmation.
GBISegment{ 0x1378, 0xC2AE06B691610132ULL, { &F3DEX2_FIFO_2_08_CRUISN } }, // Needs confirmation.
@@ -257,7 +262,7 @@ namespace RT64 {
GBISegment{ 0x10B0, 0xE8028E4BC6529E6EULL, { &ZSORTP_0_33 } }, // Needs confirmation.
};
- static std::array<GBISegment, 105> dataSegments = {
+ static std::array<GBISegment, 107> dataSegments = {
GBISegment{ 0x800, 0xEEB10D73400213B3ULL, { &F3D_SDK_E } }, // Needs confirmation.
GBISegment{ 0x800, 0x49651E384B48F694ULL, { &F3D_SDK_F } }, // Needs confirmation.
GBISegment{ 0x800, 0x1A736198F90E81C5ULL, { &F3D_SDK_UNKNOWN_G } }, // Needs confirmation.
@@ -318,6 +323,8 @@ namespace RT64 {
GBISegment{ 0x410, 0x47BA278DD7DB79EBULL, { &F3DLX2_FIFO_2_06_REJ } }, // Needs confirmation.
GBISegment{ 0x420, 0xF8649121FAB40A06ULL, { &F3DEX2_FIFO_2_07 } },
GBISegment{ 0x420, 0x3D4CAB9C82AD3772ULL, { &F3DEX2_FIFO_2_08 } }, // Needs confirmation.
+ GBISegment{ 0x420, 0xAD59E246BCF1B2C2ULL, { &F3DEXBG_NON_FIFO_2_08 } },
+ GBISegment{ 0x420, 0xD6FA1415D3E78D13ULL, { &F3DEX_NON_FIFO_2_08_CBFD } },
GBISegment{ 0x410, 0x14F9D11C0F58AFB5ULL, { &F3DEX2_FIFO_2_08_REJ } }, // Needs confirmation.
GBISegment{ 0x410, 0x25A00931C3C2A573ULL, { &F3DLX2_FIFO_2_08_REJ } }, // Needs confirmation.
GBISegment{ 0x420, 0xD381B0139965EE5CULL, { &F3DEX2_FIFO_2_08_CRUISN } }, // Needs confirmation.
@@ -499,6 +506,9 @@ namespace RT64 {
case GBIUCode::L3DEX2:
GBI_L3DEX2::setup(&gbi);
break;
+ case GBIUCode::F3DEX2CBFD:
+ GBI_F3DEX2CBFD::setup(&gbi);
+ break;
default:
assert(false && "Unknown UCode.");
break;
diff --git a/src/gbi/rt64_gbi.h b/src/gbi/rt64_gbi.h
index 69c35d2..bcea8ec 100644
--- a/src/gbi/rt64_gbi.h
+++ b/src/gbi/rt64_gbi.h
@@ -28,6 +28,7 @@ namespace RT64 {
S2DEX,
S2DEX2,
L3DEX2,
+ F3DEX2CBFD,
Count
};
diff --git a/src/gbi/rt64_gbi_f3dex2cbfd.cpp b/src/gbi/rt64_gbi_f3dex2cbfd.cpp
new file mode 100644
index 0000000..96768bb
--- /dev/null
+++ b/src/gbi/rt64_gbi_f3dex2cbfd.cpp
@@ -0,0 +1,123 @@
+//
+// RT64
+//
+// Conker's Bad Fur Day's modified F3DEX2, based on GLideN64's F3DEX2CBFD.
+// Commands not listed here behave as in F3DEX2.
+//
+
+#include "rt64_gbi_f3dex2cbfd.h"
+
+#include "hle/rt64_interpreter.h"
+
+#include "rt64_f3d.h"
+#include "rt64_gbi_f3dex2.h"
+
+namespace RT64 {
+ namespace GBI_F3DEX2CBFD {
+ // The game's G_LIGHTING and G_TEXTURE_GEN are kept aside: lighting is computed into the
+ // vertex colours on the CPU (RSP::lightVerticesCBFD), so the shaders must not light them
+ // again, and texture generation, which needs the normals the shaders can't see (they're
+ // held apart from the vertices, and the colours hold the lighting), is computed into the
+ // vertices' texture coordinates on the CPU too (RSP::textureGenVerticesCBFD).
+ void geometryMode(State *state, DisplayList **dl) {
+ RSP *rsp = state->rsp.get();
+ const uint32_t offMask = (*dl)->p0(0, 24);
+ const uint32_t onMask = (*dl)->w1;
+ const uint32_t current = rsp->geometryModeStack[rsp->geometryModeStackSize - 1];
+ const uint32_t previous = current | (rsp->cbfd.lighting ? G_LIGHTING : 0) |
+ (rsp->cbfd.textureGen ? G_TEXTURE_GEN : 0) | (rsp->cbfd.textureGenLinear ? G_TEXTURE_GEN_LINEAR : 0);
+ const uint32_t requested = (previous & offMask) | onMask;
+ rsp->cbfd.lighting = (requested & G_LIGHTING) != 0;
+ rsp->cbfd.textureGen = (requested & G_TEXTURE_GEN) != 0;
+ rsp->cbfd.textureGenLinear = (requested & G_TEXTURE_GEN_LINEAR) != 0;
+ rsp->modifyGeometryMode(0, requested & ~(G_LIGHTING | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR));
+ }
+
+ void vertex(State *state, DisplayList **dl) {
+ uint8_t vtxCount = (*dl)->p0(12, 8);
+ state->rsp->setVertexCBFD((*dl)->w1, vtxCount, (*dl)->p0(1, 7) - vtxCount);
+ }
+
+ void moveWord(State *state, DisplayList **dl) {
+ switch ((*dl)->p0(16, 8)) {
+ case G_MW_NUMLIGHT:
+ state->rsp->cbfd.lightCount = (*dl)->w1 / 48;
+ break;
+ case F3DEX2CBFD_G_MW_COORD_MOD:
+ state->rsp->setCoordModCBFD((*dl)->w0, (*dl)->w1);
+ break;
+ default:
+ GBI_F3DEX2::moveWord(state, dl);
+ break;
+ }
+ }
+
+ void moveMem(State *state, DisplayList **dl) {
+ switch ((*dl)->p0(0, 8)) {
+ case F3DEX2_G_MV_VIEWPORT:
+ state->rsp->setViewport((*dl)->w1);
+ break;
+ case F3DEX2_G_MV_LIGHT: {
+ const uint32_t offset = (*dl)->p0(5, 14);
+ const uint32_t n = offset / 48;
+ if (n < 2) {
+ state->rsp->setLookAt(n, (*dl)->w1);
+ }
+ else {
+ state->rsp->setLightCBFD(n - 2, (*dl)->w1);
+ }
+
+ break;
+ }
+ case F3DEX2CBFD_G_MV_NORMALES:
+ state->rsp->cbfd.normalBase = state->rsp->fromSegmentedMasked((*dl)->w1);
+ break;
+ default:
+ break;
+ }
+ }
+
+ // The microcode reuses G_LOAD_UCODE to switch to its advanced lighting mode.
+ void switchLightingMode(State *state, DisplayList **dl) {
+ state->rsp->cbfd.advancedLighting = true;
+ }
+
+ void tri4(State *state, DisplayList **dl) {
+ const uint32_t w0 = (*dl)->w0;
+ const uint32_t w1 = (*dl)->w1;
+ auto field = [](uint32_t w, uint32_t shift, uint32_t bits) { return (w >> shift) & ((1U << bits) - 1); };
+ const uint32_t v[12] = {
+ field(w0, 23, 5), field(w0, 18, 5), (field(w0, 15, 3) << 2) | field(w1, 30, 2),
+ field(w0, 10, 5), field(w0, 5, 5), field(w0, 0, 5),
+ field(w1, 25, 5), field(w1, 20, 5), field(w1, 15, 5),
+ field(w1, 10, 5), field(w1, 5, 5), field(w1, 0, 5),
+ };
+
+ for (int t = 0; t < 4; t++) {
+ const uint32_t a = v[t * 3 + 0], b = v[t * 3 + 1], c = v[t * 3 + 2];
+ // Unused slots repeat an index.
+ if ((a != b) && (b != c) && (a != c)) {
+ state->rsp->drawIndexedTri(a, b, c);
+ }
+ }
+ }
+
+ void reset(State *state) {
+ state->rsp->setClipRatioAll(2U);
+ state->rsp->cbfd.advancedLighting = false;
+ }
+
+ void setup(GBI *gbi) {
+ GBI_F3DEX2::setup(gbi);
+ gbi->resetFromTask = &reset;
+ gbi->map[F3DEX2_G_GEOMETRYMODE] = &geometryMode;
+ gbi->map[F3DEX2_G_VTX] = &vertex;
+ gbi->map[F3DEX2_G_MOVEWORD] = &moveWord;
+ gbi->map[F3DEX2_G_MOVEMEM] = &moveMem;
+ gbi->map[F3DEX2_G_LOAD_UCODE] = &switchLightingMode;
+ for (uint32_t i = 0; i < 16; i++) {
+ gbi->map[F3DEX2CBFD_G_TRI4 + i] = &tri4;
+ }
+ }
+ }
+};
diff --git a/src/gbi/rt64_gbi_f3dex2cbfd.h b/src/gbi/rt64_gbi_f3dex2cbfd.h
new file mode 100644
index 0000000..99ef5c2
--- /dev/null
+++ b/src/gbi/rt64_gbi_f3dex2cbfd.h
@@ -0,0 +1,20 @@
+//
+// RT64
+//
+
+#pragma once
+
+#include "rt64_gbi.h"
+
+// Conker's Bad Fur Day's modified F3DEX2: F3DEX2 with a different lighting
+// model (point lights, per-vertex normals held apart from the vertices, a
+// coordinate modifier) and a four-triangle command.
+#define F3DEX2CBFD_G_TRI4 0x10
+#define F3DEX2CBFD_G_MV_NORMALES 14
+#define F3DEX2CBFD_G_MW_COORD_MOD 0x10
+
+namespace RT64 {
+ namespace GBI_F3DEX2CBFD {
+ void setup(GBI *gbi);
+ };
+};
diff --git a/src/hle/rt64_application.cpp b/src/hle/rt64_application.cpp
index ee8bc1f..428208c 100644
--- a/src/hle/rt64_application.cpp
+++ b/src/hle/rt64_application.cpp
@@ -245,6 +245,11 @@ namespace RT64 {
// We don't know yet what driver will fix the issue for RDNA4, so if it's newer than BrokenRDNA4DriverD3D12, we only force Vulkan if it's in Automatic mode.
forceVulkanForCompatibility = true;
}
+ else if (device->getCapabilities().uma) {
+ // Integrated AMD graphics (sharing system memory) crashed at start in D3D12: a Ryzen 5 5560U (Vega) failed to create
+ // its render targets and upload buffers, and nothing got drawn. Vulkan runs on the same machine, so it's the automatic choice here.
+ forceVulkanForCompatibility = true;
+ }
else {
// Wireframe artifacts have been reported when using a high-precision color format on RDNA3 GPUs in D3D12. The workaround is to switch to Vulkan if this is the case.
const bool isRX7 = deviceDescription.name.find("AMD Radeon RX 7") != std::string::npos;
diff --git a/src/hle/rt64_framebuffer_manager.cpp b/src/hle/rt64_framebuffer_manager.cpp
index d7caa12..60112aa 100644
--- a/src/hle/rt64_framebuffer_manager.cpp
+++ b/src/hle/rt64_framebuffer_manager.cpp
@@ -4,6 +4,8 @@
#include "rt64_framebuffer_manager.h"
+#include "common/rt64_fblog.h"
+
#include <cassert>
#include <algorithm>
@@ -91,6 +93,12 @@ namespace RT64 {
RenderTargetManager &targetManager, const ShaderLibrary *shaderLibrary)
{
auto it = framebuffers.find(op.writeChanges.address);
+ if (FbLog::threadActive()) {
+ FbLog::print("[%s %llu] writeChanges (RDRAM upload) to fb 0x%08X: %s", FbLog::threadSide(), (unsigned long long)(FbLog::threadFrame()), op.writeChanges.address,
+ (it == framebuffers.end()) ? "no fb" : ((it->second.lastWriteType == Framebuffer::Type::None) ? "skipped, lastWriteType None" :
+ ((it->second.lastWriteType == Framebuffer::Type::Depth) ? "into the DEPTH target" : "into the color target")));
+ }
+
if ((it != framebuffers.end()) && (it->second.lastWriteType != Framebuffer::Type::None)) {
const FramebufferChange *fbChange = fbChangePool.get(op.writeChanges.id);
assert(fbChange != nullptr);
@@ -174,6 +182,12 @@ namespace RT64 {
tileCopy.readDepthFromStorage = true;
}
}
+
+ if (FbLog::threadActive()) {
+ FbLog::print("[%s %llu] tileCopy setup id %llu fb 0x%08X (w %u h %u everUsedAsDepth %d) tile (%u,%u)-(%u,%u) -> scaled left %u top %u size %ux%u, rt %ux%u misalign %u, readColorFromStorage %d readDepthFromStorage %d",
+ FbLog::threadSide(), (unsigned long long)(FbLog::threadFrame()), (unsigned long long)(tileCopy.id), fbIt->second.addressStart, fbIt->second.width, fbIt->second.height, fbIt->second.everUsedAsDepth,
+ fbTile.left, fbTile.top, fbTile.right, fbTile.bottom, tileCopy.left, tileCopy.top, tileWidth, tileHeight, rtWidth, rtHeight, rtMisalignX, tileCopy.readColorFromStorage, tileCopy.readDepthFromStorage);
+ }
}
void FramebufferManager::createTileCopyRecord(RenderWorker *renderWorker, const FramebufferOperation &op, const FramebufferStorage &fbStorage,
@@ -198,6 +212,13 @@ namespace RT64 {
}
}
+ if (FbLog::threadActive()) {
+ const FixedRect &r = fbIt->second.lastWriteRect;
+ FbLog::print("[%s %llu] tileCopy record id %llu fb 0x%08X lastWriteType %d lastWriteRect " RT64_FBLOG_RECT_FMT " colorTarget %ux%u%s",
+ FbLog::threadSide(), (unsigned long long)(FbLog::threadFrame()), (unsigned long long)(tileCopy.id), fbIt->second.addressStart, int(fbIt->second.lastWriteType), RT64_FBLOG_RECT(r),
+ colorTarget.width, colorTarget.height, (fbIt->second.lastWriteType == Framebuffer::Type::Depth) ? ": copies depth to color, then discards the fb's last write" : "");
+ }
+
// Copy from depth target if the last write was a depth buffer.
if (fbIt->second.lastWriteType == Framebuffer::Type::Depth) {
RenderTargetKey depthTargetKey(fbIt->second.addressStart, fbIt->second.width, fbIt->second.siz, Framebuffer::Type::Depth);
@@ -908,6 +929,11 @@ namespace RT64 {
auto it = framebuffers.begin();
while (it != framebuffers.end()) {
if ((&it->second != changedFb) && (it->second.overlaps(addressStart, addressEnd))) {
+ if (FbLog::threadActive()) {
+ FbLog::print("[%s %llu] changeRAM: fb 0x%08X wrote 0x%08X-0x%08X, overlapping fb 0x%08X-0x%08X (w %u h %u), which is marked rdramChanged",
+ FbLog::threadSide(), (unsigned long long)(FbLog::threadFrame()), changedFb->addressStart, addressStart, addressEnd, it->second.addressStart, it->second.addressEnd, it->second.width, it->second.height);
+ }
+
it->second.rdramChanged = true;
}
diff --git a/src/hle/rt64_framebuffer_pair.cpp b/src/hle/rt64_framebuffer_pair.cpp
index c944393..f611522 100644
--- a/src/hle/rt64_framebuffer_pair.cpp
+++ b/src/hle/rt64_framebuffer_pair.cpp
@@ -69,6 +69,48 @@ namespace RT64 {
return (gameCallCount == 0) && startFbOperations.empty() && endFbOperations.empty();
}
+ FixedRect FramebufferPair::wideningScissor() const {
+ if (scissorRect.isNull()) {
+ return scissorRect;
+ }
+
+ // The pair's scissor without its projections of fill rects only.
+ FixedRect drawnScissor;
+ drawnScissor.reset();
+ bool fillsLeftOut = false;
+ for (uint32_t p = 0; p < projectionCount; p++) {
+ const Projection &proj = projections[p];
+ if (proj.scissorRect.isNull()) {
+ continue;
+ }
+
+ bool fillsOnly = (proj.type == Projection::Type::Rectangle) && (proj.gameCallCount > 0);
+ for (uint32_t c = 0; fillsOnly && (c < proj.gameCallCount); c++) {
+ fillsOnly = (proj.gameCalls[c].callDesc.otherMode.cycleType() == G_CYC_FILL);
+ }
+
+ if (fillsOnly) {
+ fillsLeftOut = true;
+ }
+ else {
+ drawnScissor.merge(proj.scissorRect);
+ }
+ }
+
+ if (!fillsLeftOut || drawnScissor.isNull()) {
+ return scissorRect;
+ }
+
+ const bool reachesLeft = (drawnScissor.ulx <= scissorRect.ulx + CoversWidthSlack);
+ const bool reachesRight = (drawnScissor.lrx >= scissorRect.lrx - CoversWidthSlack);
+ const bool wideEnough = (int64_t(drawnScissor.lrx - drawnScissor.ulx) * 10) >= (int64_t(scissorRect.lrx - scissorRect.ulx) * 4);
+ if ((reachesLeft != reachesRight) && wideEnough) {
+ return drawnScissor;
+ }
+
+ return scissorRect;
+ }
+
bool FramebufferPair::earlyPresentCandidate() const {
// Some games might use screen framebuffers as temporary output for some operations that are clearly
// not intended to be presented to the user. This function includes some cases commonly found in games.
diff --git a/src/hle/rt64_framebuffer_pair.h b/src/hle/rt64_framebuffer_pair.h
index 60b0fa4..6c80bb6 100644
--- a/src/hle/rt64_framebuffer_pair.h
+++ b/src/hle/rt64_framebuffer_pair.h
@@ -60,5 +60,13 @@ namespace RT64 {
int changeProjection(uint32_t transformsIndex, Projection::Type type);
bool isEmpty() const;
bool earlyPresentCandidate() const;
+
+ // The scissor a viewport is compared with to tell whether it's widened (FramebufferRenderer and
+ // ProjectionProcessor, which must agree). Usually the pair's own. In split screen (Conker, issue #78)
+ // the first player's view shares its pair with the frame's clear, a fill across the whole frame, so
+ // its view didn't cover the pair's scissor and wasn't widened, though the other views (each in a pair
+ // of its own) were. Leaving out projections of fill rects only, the rest's scissor is used when it's a
+ // split-screen view: reaching one side of the frame but not the other, at least 40% of its width.
+ FixedRect wideningScissor() const;
};
};
\ No newline at end of file
diff --git a/src/hle/rt64_game_frame.cpp b/src/hle/rt64_game_frame.cpp
index 87392d0..1f5e54a 100644
--- a/src/hle/rt64_game_frame.cpp
+++ b/src/hle/rt64_game_frame.cpp
@@ -296,7 +296,11 @@ namespace RT64 {
prevWorkloadMap = &prevFrame.frameMap.workloads[workloadMap.prevWorkloadIndex];
}
- // Match the transforms linearly in the order they were submitted.
+ // Match the transforms linearly in the order they were submitted. An ID with a different number of
+ // transforms than last frame can't be paired in order: each transform after the first one added or removed
+ // would be paired with its neighbour's, and the model would fly apart for a frame (Conker's characters,
+ // cut into chunks differently as their animation changes). Each is paired with last frame's closest instead
+ // (alignTransforms). Matching none of them made the whole model snap each time (issue #76).
ModifiedBuffers modifiedBuffers;
auto curIt = curWorkload.transformIdMap.begin();
auto prevIt = prevWorkload.transformIdMap.begin();
@@ -309,9 +313,31 @@ namespace RT64 {
prevIt++;
}
else {
- matchTransform(curWorkload, prevWorkload, curWorkloadMap, prevWorkloadMap, curIt->second, prevIt->second, modifiedBuffers);
- curIt++;
- prevIt++;
+ const uint32_t id = curIt->first;
+ const size_t curCount = curWorkload.transformIdMap.count(id);
+ const size_t prevCount = prevWorkload.transformIdMap.count(id);
+ if (curCount != prevCount) {
+ thread_local std::vector<uint32_t> curIndices;
+ thread_local std::vector<uint32_t> prevIndices;
+ curIndices.clear();
+ prevIndices.clear();
+ for (size_t i = 0; i < curCount; i++, curIt++) {
+ curIndices.push_back(curIt->second);
+ }
+
+ for (size_t i = 0; i < prevCount; i++, prevIt++) {
+ prevIndices.push_back(prevIt->second);
+ }
+
+ alignTransforms(curWorkload, prevWorkload, curWorkloadMap, prevWorkloadMap, curIndices, prevIndices, modifiedBuffers);
+ continue;
+ }
+
+ for (size_t i = 0; i < curCount; i++) {
+ matchTransform(curWorkload, prevWorkload, curWorkloadMap, prevWorkloadMap, curIt->second, prevIt->second, modifiedBuffers);
+ curIt++;
+ prevIt++;
+ }
}
}
@@ -486,6 +512,17 @@ namespace RT64 {
viewProjMap.rigidBody = prevViewProjMap.rigidBody;
}
+ // A game that doesn't say how its camera interpolates (Conker) gets it interpolated always, cuts between
+ // cutscene shots too: the frames drawn between the game's showed the camera partway from one shot to the
+ // next, inside the scenery. A cut isn't interpolated.
+ const bool projectionAutomatic = (curProjGroup.matrixId == G_EX_ID_IGNORE) || (curProjGroup.matrixId == G_EX_ID_AUTO);
+ if (viewProjMap.rigidBody.updateCameraCut(prevView, curView) && projectionAutomatic) {
+ projectionLinearComponent = G_EX_COMPONENT_SKIP;
+ projectionAngularComponent = G_EX_COMPONENT_SKIP;
+ projectionScaleComponent = G_EX_COMPONENT_SKIP;
+ projectionSkewComponent = G_EX_COMPONENT_SKIP;
+ }
+
viewProjMap.rigidBody.updateLinear(prevView, curView, projectionLinearComponent);
viewProjMap.rigidBody.updateAngular(prevView, curView, projectionAngularComponent, projectionScaleComponent, projectionSkewComponent);
viewProjMap.rigidBody.updateDecomposition(curView, projectionDecompose);
@@ -709,7 +746,45 @@ namespace RT64 {
}
}
- void GameFrame::matchTransform(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap, uint32_t curTransformIndex, uint32_t prevTransformIndex, ModifiedBuffers &modifiedBuffers) {
+ void GameFrame::alignTransforms(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap,
+ const std::vector<uint32_t> &curIndices, const std::vector<uint32_t> &prevIndices, ModifiedBuffers &modifiedBuffers)
+ {
+ // Conker's characters are skinned meshes drawn in chunks, a few vertices each with one bone's matrix, the same
+ // bone's matrix loaded again for each of its chunks. When the animation changes, the mesh is cut into chunks
+ // differently: their number, sizes and order change, but the bones they're drawn with are the same ones. So each
+ // transform is paired with last frame's closest (its position moved on by its velocity, plus OrientationWeight
+ // times how differently it's turned; mirrored ones aren't), however many vertices either draws, and several may
+ // pair with the same one: those are the same bone. None further than MaxAlignCost is paired: that one snaps. The
+ // chunks paired aren't the same geometry, so their vertices aren't interpolated (in a frame with the same chunks,
+ // a character's vertices don't move: the bones do).
+ const float OrientationWeight = 32.0f;
+ const float MaxAlignCost = 64.0f;
+ const hlslpp::float4x4 identity = hlslpp::float4x4::identity();
+ for (uint32_t curIndex : curIndices) {
+ const hlslpp::float4x4 &curTransform = curWorkload.drawData.worldTransforms[curIndex];
+ float bestCost = MaxAlignCost;
+ uint32_t bestPrev = UINT32_MAX;
+ for (uint32_t prevIndex : prevIndices) {
+ const RigidBody *prevRigidBody = (prevWorkloadMap != nullptr) ? &prevWorkloadMap->transforms[prevIndex].rigidBody : nullptr;
+ const TransformMatchResult result = computeTransformMatch(curTransform, identity, prevWorkload.drawData.worldTransforms[prevIndex], identity, prevRigidBody);
+ if (!result.valid) {
+ continue;
+ }
+
+ const float cost = result.positionDifference + OrientationWeight * result.orientationDifference;
+ if (cost < bestCost) {
+ bestCost = cost;
+ bestPrev = prevIndex;
+ }
+ }
+
+ if (bestPrev != UINT32_MAX) {
+ matchTransform(curWorkload, prevWorkload, curWorkloadMap, prevWorkloadMap, curIndex, bestPrev, modifiedBuffers, false);
+ }
+ }
+ }
+
+ void GameFrame::matchTransform(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap, uint32_t curTransformIndex, uint32_t prevTransformIndex, ModifiedBuffers &modifiedBuffers, bool interpolateVertices) {
GameFrameMap::TransformMap &curTransformMap = curWorkloadMap.transforms[curTransformIndex];
if (prevWorkloadMap != nullptr) {
curTransformMap.rigidBody = prevWorkloadMap->transforms[prevTransformIndex].rigidBody;
@@ -733,7 +808,7 @@ namespace RT64 {
uint32_t curVertexCount = curWorkload.drawData.worldTransformVertexCount(curTransformIndex);
uint32_t prevVertexIndex = prevWorkload.drawData.worldTransformVertexIndices[prevTransformIndex];
uint32_t prevVertexCount = prevWorkload.drawData.worldTransformVertexCount(prevTransformIndex);
- if (((curGroup.vertexInterpolation != G_EX_COMPONENT_SKIP) || (curGroup.texcoordInterpolation == G_EX_COMPONENT_AUTO)) && (curVertexCount == prevVertexCount)) {
+ if (interpolateVertices && ((curGroup.vertexInterpolation != G_EX_COMPONENT_SKIP) || (curGroup.texcoordInterpolation == G_EX_COMPONENT_AUTO)) && (curVertexCount == prevVertexCount)) {
const std::vector<float> &curPosFloats = curWorkload.drawData.posFloats;
const std::vector<float> &prevPosFloats = prevWorkload.drawData.posFloats;
std::vector<float> &curVelFloats = curWorkload.drawData.velFloats;
@@ -744,17 +819,178 @@ namespace RT64 {
const float *curPosFloatsRef = &curPosFloats[curVertexIndex * 3];
const float *prevPosFloatsRef = &prevPosFloats[prevVertexIndex * 3];
float *curVelFloatsRef = &curVelFloats[curVertexIndex * 3];
- for (uint32_t i = 0; i < curVertexCount; i++) {
- for (uint32_t j = 0; j < 3; j++) {
- curVelFloatsRef[i * 3 + j] = (curPosFloatsRef[i * 3 + j] - prevPosFloatsRef[i * 3 + j]);
- }
+ // Vertices are paired by their order, so a transform matched to one drawing other geometry (same vertex
+ // count) would smear it. Motion that large in one frame isn't a model moving: leave those as they are.
+ const float MaxVertexStep = 64.0f;
+ bool plausible = true;
+ for (uint32_t i = 0; (i < curVertexCount * 3) && plausible; i++) {
+ plausible = fabsf(curPosFloatsRef[i] - prevPosFloatsRef[i]) < MaxVertexStep;
}
- modifiedBuffers.positionVelocity = true;
+ if (plausible) {
+ for (uint32_t i = 0; i < curVertexCount; i++) {
+ for (uint32_t j = 0; j < 3; j++) {
+ curVelFloatsRef[i * 3 + j] = (curPosFloatsRef[i * 3 + j] - prevPosFloatsRef[i * 3 + j]);
+ }
+ }
+
+ modifiedBuffers.positionVelocity = true;
+ }
}
}
- if ((curGroup.texcoordInterpolation != G_EX_COMPONENT_SKIP) && (curVertexCount == prevVertexCount)) {
+ // Texture coordinates interpolated while the positions aren't: geometry rebuilt every frame with its
+ // coordinates projected from its position (Conker's Bad Fur Day's shadows: the ground under a character,
+ // clipped anew each frame, with the shadow's texture projected onto it from the light's point of view).
+ // Its vertices can't be paired with last frame's, so last frame's projection is fitted instead (a
+ // perspective map from position to texture coordinates, by least squares, in world space) and each
+ // vertex's coordinates last frame are taken from it.
+ if ((curGroup.texcoordInterpolation == G_EX_COMPONENT_INTERPOLATE) && (curGroup.vertexInterpolation == G_EX_COMPONENT_SKIP) && (curVertexCount > 0) && (prevVertexCount >= 3)) {
+ const float *prevLocal = &prevWorkload.drawData.posFloats[prevVertexIndex * 3];
+ const float *prevTc = &prevWorkload.drawData.tcFloats[prevVertexIndex * 2];
+ const float *curLocal = &curWorkload.drawData.posFloats[curVertexIndex * 3];
+ const float *curTc = &curWorkload.drawData.tcFloats[curVertexIndex * 2];
+ float *curTcVel = &curWorkload.drawData.tcVelFloats[curVertexIndex * 2];
+
+ // Positions in the world: each frame's are relative to its own transform, which can move.
+ thread_local std::vector<float> prevWorld, curWorld;
+ auto toWorld = [](const float *local, uint32_t count, const hlslpp::float4x4 &m, std::vector<float> &out) {
+ out.resize(count * 3);
+ for (uint32_t i = 0; i < count; i++) {
+ const hlslpp::float4 w = hlslpp::mul(hlslpp::float4(local[i * 3 + 0], local[i * 3 + 1], local[i * 3 + 2], 1.0f), m);
+ out[i * 3 + 0] = w.x;
+ out[i * 3 + 1] = w.y;
+ out[i * 3 + 2] = w.z;
+ }
+ };
+ toWorld(prevLocal, prevVertexCount, prevTransform, prevWorld);
+ toWorld(curLocal, curVertexCount, curTransform, curWorld);
+ const float *prevPos = prevWorld.data();
+ const float *curPos = curWorld.data();
+
+ // The texture's extent last frame.
+ float tcMin[2] = { FLT_MAX, FLT_MAX }, tcMax[2] = { -FLT_MAX, -FLT_MAX };
+ double mean[3] = {}, meanSq = 0.0;
+ for (uint32_t i = 0; i < prevVertexCount; i++) {
+ for (int b = 0; b < 2; b++) {
+ tcMin[b] = std::min(tcMin[b], prevTc[i * 2 + b]);
+ tcMax[b] = std::max(tcMax[b], prevTc[i * 2 + b]);
+ }
+ for (int j = 0; j < 3; j++) mean[j] += prevPos[i * 3 + j];
+ }
+ for (int j = 0; j < 3; j++) mean[j] /= prevVertexCount;
+ for (uint32_t i = 0; i < prevVertexCount; i++) {
+ for (int j = 0; j < 3; j++) meanSq += (prevPos[i * 3 + j] - mean[j]) * (prevPos[i * 3 + j] - mean[j]);
+ }
+ const double scale = std::sqrt(meanSq / prevVertexCount) + 1e-9;
+
+ // s = (a . q + a0) / (d . q + 1) and t = (b . q + b0) / (d . q + 1), q the normalised position,
+ // made linear: a . q + a0 - s (d . q) = s. Eleven unknowns: a, a0, b, b0 and d.
+ double normal[11][12] = {};
+ uint32_t used = 0;
+ auto addRow = [&](const double row[11], double rhs) {
+ for (int r = 0; r < 11; r++) {
+ for (int c = 0; c < 11; c++) normal[r][c] += row[r] * row[c];
+ normal[r][11] += row[r] * rhs;
+ }
+ };
+ // Every vertex follows the projection, those on the texture's edges too: the game clips the ground
+ // where the projection reaches them.
+ for (uint32_t i = 0; i < prevVertexCount; i++) {
+ const double q[3] = { (prevPos[i * 3 + 0] - mean[0]) / scale, (prevPos[i * 3 + 1] - mean[1]) / scale, (prevPos[i * 3 + 2] - mean[2]) / scale };
+ const double s = prevTc[i * 2 + 0], t = prevTc[i * 2 + 1];
+ const double rowS[11] = { q[0], q[1], q[2], 1.0, 0.0, 0.0, 0.0, 0.0, -s * q[0], -s * q[1], -s * q[2] };
+ const double rowT[11] = { 0.0, 0.0, 0.0, 0.0, q[0], q[1], q[2], 1.0, -t * q[0], -t * q[1], -t * q[2] };
+ addRow(rowS, s);
+ addRow(rowT, t);
+ used++;
+ }
+
+ // A little ridge: flat ground leaves the coefficients across it undetermined.
+ double trace = 0.0;
+ for (int r = 0; r < 11; r++) trace += normal[r][r];
+ for (int r = 0; r < 11; r++) normal[r][r] += 1e-7 * trace + 1e-12;
+
+ // Gaussian elimination with partial pivoting.
+ bool solved = (used >= 6);
+ for (int c = 0; (c < 11) && solved; c++) {
+ int pivot = c;
+ for (int r = c + 1; r < 11; r++) {
+ if (fabs(normal[r][c]) > fabs(normal[pivot][c])) pivot = r;
+ }
+ if (fabs(normal[pivot][c]) < 1e-18) {
+ solved = false;
+ break;
+ }
+ if (pivot != c) {
+ for (int k = 0; k < 12; k++) std::swap(normal[c][k], normal[pivot][k]);
+ }
+ for (int r = 0; r < 11; r++) {
+ if (r == c) continue;
+ const double f = normal[r][c] / normal[c][c];
+ for (int k = c; k < 12; k++) normal[r][k] -= f * normal[c][k];
+ }
+ }
+
+ if (solved) {
+ double coef[11];
+ for (int r = 0; r < 11; r++) coef[r] = normal[r][11] / normal[r][r];
+ auto project = [&](const float *p, double out[2]) {
+ const double q[3] = { (p[0] - mean[0]) / scale, (p[1] - mean[1]) / scale, (p[2] - mean[2]) / scale };
+ const double w = coef[8] * q[0] + coef[9] * q[1] + coef[10] * q[2] + 1.0;
+ out[0] = (coef[0] * q[0] + coef[1] * q[1] + coef[2] * q[2] + coef[3]) / w;
+ out[1] = (coef[4] * q[0] + coef[5] * q[1] + coef[6] * q[2] + coef[7]) / w;
+ };
+
+ // Only if last frame's coordinates fit it closely (on average within 1% of the texture's extent).
+ double residual = 0.0;
+ for (uint32_t i = 0; i < prevVertexCount; i++) {
+ double predicted[2];
+ project(&prevPos[i * 3], predicted);
+ residual += fabs(predicted[0] - prevTc[i * 2 + 0]) + fabs(predicted[1] - prevTc[i * 2 + 1]);
+ }
+ residual /= std::max(used, 1U);
+ const double spread = std::max(tcMax[0] - tcMin[0], tcMax[1] - tcMin[1]);
+
+ // The vertices fitted must cover the texture in both directions: a few, or ones along a line,
+ // fit closely while leaving the map across them undetermined.
+ float usedMin[2] = { FLT_MAX, FLT_MAX }, usedMax[2] = { -FLT_MAX, -FLT_MAX };
+ for (uint32_t i = 0; i < prevVertexCount; i++) {
+ for (int b = 0; b < 2; b++) {
+ usedMin[b] = std::min(usedMin[b], prevTc[i * 2 + b]);
+ usedMax[b] = std::max(usedMax[b], prevTc[i * 2 + b]);
+ }
+ }
+ const bool covered = (used >= 12) && ((usedMax[0] - usedMin[0]) > 0.25 * spread) && ((usedMax[1] - usedMin[1]) > 0.25 * spread);
+ if (covered && (spread > 0.0) && (residual <= 0.01 * spread)) {
+ // The shadow moves a few texels a frame: a vertex whose coordinates would move more than a
+ // quarter of the texture means the map doesn't hold there, and the frame is drawn as it is.
+ const double maxStep = 0.25 * spread;
+ bool plausible = true;
+ for (uint32_t i = 0; (i < curVertexCount) && plausible; i++) {
+ double predicted[2];
+ project(&curPos[i * 3], predicted);
+ for (int b = 0; b < 2; b++) {
+ // Last frame's coordinates were clipped to the texture's edges too.
+ const double previous = std::clamp(predicted[b], double(tcMin[b]), double(tcMax[b]));
+ const double step = curTc[i * 2 + b] - previous;
+ plausible = plausible && std::isfinite(step) && (fabs(step) <= maxStep);
+ curTcVel[i * 2 + b] = float(step);
+ }
+ }
+
+ if (plausible) {
+ modifiedBuffers.texcoordVelocity = true;
+ }
+ else {
+ for (uint32_t i = 0; i < curVertexCount * 2; i++) {
+ curTcVel[i] = 0.0f;
+ }
+ }
+ }
+ }
+ }
+ else if ((curGroup.texcoordInterpolation != G_EX_COMPONENT_SKIP) && (curVertexCount == prevVertexCount)) {
const std::vector<float> &curTcFloats = curWorkload.drawData.tcFloats;
const std::vector<float> &prevTcFloats = prevWorkload.drawData.tcFloats;
std::vector<float> &curVelFloats = curWorkload.drawData.tcVelFloats;
diff --git a/src/hle/rt64_game_frame.h b/src/hle/rt64_game_frame.h
index 00a72f6..32e9300 100644
--- a/src/hle/rt64_game_frame.h
+++ b/src/hle/rt64_game_frame.h
@@ -127,7 +127,10 @@ namespace RT64 {
void set(WorkloadQueue &workloadQueue, const uint32_t *workloadIndices, uint32_t indicesCount);
void match(RenderWorker *worker, WorkloadQueue &workloadQueue, const GameFrame &prevFrame, BufferUploader *velocityUploader, bool &velocityUploaderUsed, bool &tileInterpolationUsed, bool &lookAtInterpolationUsed);
void matchScene(WorkloadQueue &workloadQueue, const GameFrame &prevFrame, const GameScene &curScene, const GameScene &prevScene, std::unordered_map<uint32_t, ModifiedBuffers> &workloadsModified, bool &tileInterpolationUsed, bool &lookAtInterpolationUsed);
- void matchTransform(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap, uint32_t curTransformIndex, uint32_t prevTransformIndex, ModifiedBuffers &modifiedBuffers);
+ void matchTransform(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap, uint32_t curTransformIndex, uint32_t prevTransformIndex, ModifiedBuffers &modifiedBuffers, bool interpolateVertices = true);
+ // Conker: matches an ID's transforms when there are more or fewer than last frame, each with last frame's closest.
+ void alignTransforms(Workload &curWorkload, const Workload &prevWorkload, GameFrameMap::WorkloadMap &curWorkloadMap, const GameFrameMap::WorkloadMap *prevWorkloadMap,
+ const std::vector<uint32_t> &curIndices, const std::vector<uint32_t> &prevIndices, ModifiedBuffers &modifiedBuffers);
void buildCallHashMap(uint32_t sceneProjIndex, const Workload &workload, const Projection &proj, std::multimap<uint64_t, GameCallMap> &hashMap) const;
void buildTransformIdMap(const Workload &workload, std::multimap<uint32_t, uint32_t> &idMap, std::vector<uint32_t> &ignoredIdVector) const;
uint64_t hashFromCall(const GameCall &call, uint32_t matrixIdHash) const;
diff --git a/src/hle/rt64_present_queue.cpp b/src/hle/rt64_present_queue.cpp
index 7de5b69..2ef2ef5 100644
--- a/src/hle/rt64_present_queue.cpp
+++ b/src/hle/rt64_present_queue.cpp
@@ -9,7 +9,16 @@
#include "rt64_workload_queue.h"
+#include <atomic>
+
namespace RT64 {
+ // Frames presented to the screen so far (Conker: its FPS counter reads it, host/src/fps_counter.cpp).
+ static std::atomic<uint64_t> presentedFrames = 0;
+
+ uint64_t presentedFrameCount() {
+ return presentedFrames.load(std::memory_order_relaxed);
+ }
+
// PresentQueue
PresentQueue::PresentQueue() {
@@ -402,6 +411,7 @@ namespace RT64 {
RenderCommandSemaphore *waitSemaphore = drawSemaphores[swapChainIndex].get();
presentTimestamp = Timer::current();
swapChainValid = ext.swapChain->present(swapChainIndex, &waitSemaphore, 1);
+ presentedFrames.fetch_add(1, std::memory_order_relaxed);
presentProfiler.logAndRestart();
}
}
diff --git a/src/hle/rt64_present_queue.h b/src/hle/rt64_present_queue.h
index e08b02c..084ccfd 100644
--- a/src/hle/rt64_present_queue.h
+++ b/src/hle/rt64_present_queue.h
@@ -17,6 +17,9 @@
namespace RT64 {
struct WorkloadQueue;
+ // The number of frames presented to the screen so far, from any thread (Conker's FPS counter).
+ uint64_t presentedFrameCount();
+
struct PresentQueue {
struct External {
ApplicationWindow *appWindow = nullptr;
diff --git a/src/hle/rt64_rdp_tmem.cpp b/src/hle/rt64_rdp_tmem.cpp
index 6051f4e..8f00934 100644
--- a/src/hle/rt64_rdp_tmem.cpp
+++ b/src/hle/rt64_rdp_tmem.cpp
@@ -11,6 +11,7 @@
#include "common/rt64_tmem_hasher.h"
+#include "rt64_rice_hash.h"
#include "rt64_state.h"
namespace RT64 {
@@ -52,6 +53,7 @@ namespace RT64 {
uint64_t TextureManager::uploadTexture(State *state, const LoadTile &loadTile, TextureCache *textureCache, uint64_t creationFrame, uint16_t width, uint16_t height, uint32_t tlut) {
const uint8_t *TMEM = reinterpret_cast<const uint8_t *>(state->rdp->TMEM);
uint64_t hash = TMEMHasher::hash(TMEM, loadTile, width, height, tlut, TMEMHasher::CurrentHashVersion);
+ checkRiceReplacement(state, loadTile, textureCache, hash, width, height, tlut);
if (hashSet.find(hash) == hashSet.end()) {
hashSet.insert(hash);
textureCache->queueGPUUploadTMEM(hash, creationFrame, TMEM, RDP_TMEM_BYTES, width, height, tlut, loadTile, true);
@@ -189,6 +191,27 @@ namespace RT64 {
}
}
+ void TextureManager::checkRiceReplacement(State *state, const LoadTile &loadTile, TextureCache *textureCache, uint64_t hash, uint16_t width, uint16_t height, uint32_t tlut) {
+ if (!textureCache->hasRiceReplacements() || (width == 0) || (height == 0)) {
+ return;
+ }
+
+ const uint32_t generation = textureCache->getRiceGeneration();
+ if (generation != riceCheckedGeneration) {
+ riceCheckedSet.clear();
+ riceCheckedGeneration = generation;
+ }
+
+ if (!riceCheckedSet.insert(hash).second) {
+ return;
+ }