-
Notifications
You must be signed in to change notification settings - Fork 502
/
OpenGLRendererCore.cpp
1607 lines (1459 loc) · 56.3 KB
/
OpenGLRendererCore.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Common/GLInclude/GLInclude.h"
#include "Cafe/HW/Latte/Core/LatteRingBuffer.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LattePerformanceMonitor.h"
#include "Cafe/HW/Latte/Core/LatteShader.h"
#include "Cafe/HW/Latte/Core/LatteSoftware.h"
#include "Cafe/HW/Latte/Core/FetchShader.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/OpenGLRenderer.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/LatteTextureGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/LatteTextureViewGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/CachedFBOGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/RendererShaderGL.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/GameProfile/GameProfile.h"
#include "config/ActiveSettings.h"
using _INDEX_TYPE = Latte::LATTE_VGT_DMA_INDEX_TYPE::E_INDEX_TYPE;
GLenum sGLActiveDrawMode = 0;
extern bool hasValidFramebufferAttached;
#define INDEX_CACHE_ENTRIES (8)
typedef struct
{
MPTR prevIndexDataMPTR;
sint32 prevIndexType;
sint32 prevCount;
// index data
uint8* indexData;
uint8* indexData2;
uint32 indexBufferOffset;
sint32 indexDataSize; // current size
sint32 indexDataLimit; // maximum size
// info
uint32 maxIndex;
uint32 minIndex;
}indexDataCacheEntry_t;
struct
{
indexDataCacheEntry_t indexCacheEntry[INDEX_CACHE_ENTRIES];
sint32 nextCacheEntryIndex;
// info about currently used index data
uint32 maxIndex;
uint32 minIndex;
uint8* indexData;
// buffer
GLuint glIndexCacheBuffer;
VirtualBufferHeap_t* indexBufferVirtualHeap;
uint8* mappedIndexBuffer;
LatteRingBuffer_t* indexRingBuffer;
uint8* tempIndexStorage;
// misc
bool initialized;
GLuint glActiveElementArrayBuffer;
}indexState = { 0 };
struct
{
uint8* vboOutput;
uint32 vboStride;
uint8 dataFormat;
uint8 nfa;
bool isSigned;
}activeAttributePointer[LATTE_VS_ATTRIBUTE_LIMIT] = { 0 };
void LatteDraw_resetAttributePointerCache()
{
for (sint32 i = 0; i < LATTE_VS_ATTRIBUTE_LIMIT; i++)
{
activeAttributePointer[i].vboOutput = (uint8*)-1;
activeAttributePointer[i].vboStride = (uint32)-1;
}
}
void _setAttributeBufferPointerRaw(uint32 attributeShaderLoc, uint8* buffer, uint32 bufferSize, uint32 stride, LatteParsedFetchShaderAttribute_t* attrib, uint8* vboOutput, uint32 vboStride)
{
uint32 dataFormat = attrib->format;
bool isSigned = attrib->isSigned != 0;
uint8 nfa = attrib->nfa;
// don't call glVertexAttribIPointer if parameters have not changed
if (activeAttributePointer[attributeShaderLoc].vboOutput == vboOutput && activeAttributePointer[attributeShaderLoc].vboStride == vboStride && activeAttributePointer[attributeShaderLoc].dataFormat == dataFormat && activeAttributePointer[attributeShaderLoc].nfa == nfa && activeAttributePointer[attributeShaderLoc].isSigned == isSigned)
{
return;
}
activeAttributePointer[attributeShaderLoc].vboOutput = vboOutput;
activeAttributePointer[attributeShaderLoc].vboStride = vboStride;
activeAttributePointer[attributeShaderLoc].dataFormat = dataFormat;
activeAttributePointer[attributeShaderLoc].nfa = nfa;
activeAttributePointer[attributeShaderLoc].isSigned = isSigned;
// setup attribute pointer
if (dataFormat == FMT_32_32_32_32_FLOAT || dataFormat == FMT_32_32_32_32)
{
glVertexAttribIPointer(attributeShaderLoc, 4, GL_UNSIGNED_INT, vboStride, vboOutput);
}
else if (dataFormat == FMT_32_32_32_FLOAT || dataFormat == FMT_32_32_32)
{
glVertexAttribIPointer(attributeShaderLoc, 3, GL_UNSIGNED_INT, vboStride, vboOutput);
}
else if (dataFormat == FMT_32_32_FLOAT || dataFormat == FMT_32_32)
{
glVertexAttribIPointer(attributeShaderLoc, 2, GL_UNSIGNED_INT, vboStride, vboOutput);
}
else if (dataFormat == FMT_32_FLOAT || dataFormat == FMT_32)
{
glVertexAttribIPointer(attributeShaderLoc, 1, GL_UNSIGNED_INT, vboStride, vboOutput);
}
else if (dataFormat == FMT_8_8_8_8)
{
glVertexAttribIPointer(attributeShaderLoc, 4, GL_UNSIGNED_BYTE, vboStride, vboOutput);
}
else if (dataFormat == FMT_8_8)
{
// workaround for AMD (alignment must be 4 for 2xbyte)
if (((uint32)(size_t)vboOutput & 0x3) == 2 && LatteGPUState.glVendor == GLVENDOR_AMD)
{
glVertexAttribIPointer(attributeShaderLoc, 4, GL_UNSIGNED_BYTE, vboStride, vboOutput - 2);
}
else
{
glVertexAttribIPointer(attributeShaderLoc, 2, GL_UNSIGNED_BYTE, vboStride, vboOutput);
}
}
else if (dataFormat == FMT_8)
{
glVertexAttribIPointer(attributeShaderLoc, 1, GL_UNSIGNED_BYTE, vboStride, vboOutput);
}
else if (dataFormat == FMT_16_16_16_16_FLOAT || dataFormat == FMT_16_16_16_16)
{
glVertexAttribIPointer(attributeShaderLoc, 4, GL_UNSIGNED_SHORT, vboStride, vboOutput);
}
else if (dataFormat == FMT_16_16_FLOAT || dataFormat == FMT_16_16)
{
glVertexAttribIPointer(attributeShaderLoc, 2, GL_UNSIGNED_SHORT, vboStride, vboOutput);
}
else if (dataFormat == FMT_16_FLOAT || dataFormat == FMT_16)
{
glVertexAttribIPointer(attributeShaderLoc, 1, GL_UNSIGNED_SHORT, vboStride, vboOutput);
}
else if (dataFormat == FMT_2_10_10_10)
{
glVertexAttribIPointer(attributeShaderLoc, 1, GL_UNSIGNED_INT, vboStride, vboOutput);
}
else
{
debug_printf("_setAttributeBufferPointerRaw(): Unsupported format %d\n", dataFormat);
cemu_assert_unimplemented();
}
}
bool glAttributeArrayIsEnabled[GPU_GL_MAX_NUM_ATTRIBUTE] = { 0 };
sint32 glAttributeArrayAluDivisor[GPU_GL_MAX_NUM_ATTRIBUTE] = { 0 };
void OpenGLRenderer::SetAttributeArrayState(uint32 index, bool isEnabled, sint32 aluDivisor)
{
cemu_assert_debug(index < GPU_GL_MAX_NUM_ATTRIBUTE);
catchOpenGLError();
if (glAttributeArrayIsEnabled[index] != isEnabled)
{
if (isEnabled)
{
// enable
glEnableVertexAttribArray(index);
glAttributeArrayIsEnabled[index] = true;
}
else
{
// disable
glDisableVertexAttribArray(index);
glAttributeArrayIsEnabled[index] = false;
}
catchOpenGLError();
}
// set divisor state
if (glAttributeArrayAluDivisor[index] != aluDivisor)
{
if (aluDivisor <= 0)
glVertexAttribDivisor(index, 0);
else
glVertexAttribDivisor(index, aluDivisor);
glAttributeArrayAluDivisor[index] = aluDivisor;
catchOpenGLError();
}
}
// Sets the currently active element array buffer and binds it
void OpenGLRenderer::SetArrayElementBuffer(GLuint arrayElementBuffer)
{
if (arrayElementBuffer == indexState.glActiveElementArrayBuffer)
return;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, arrayElementBuffer);
indexState.glActiveElementArrayBuffer = arrayElementBuffer;
}
typedef struct
{
MPTR physAddr;
sint32 count;
uint32 primitiveRestartIndex;
uint32 primitiveMode;
}indexDataCacheKey_t;
typedef struct _indexDataCacheEntry_t
{
indexDataCacheKey_t key;
_indexDataCacheEntry_t* nextInBucket; // points to next element in same bucket
uint32 physSize;
uint32 hash;
_INDEX_TYPE indexType;
//sint32 indexType;
uint32 minIndex;
uint32 maxIndex;
uint32 lastAccessFrameCount;
VirtualBufferHeapEntry_t* heapEntry;
_indexDataCacheEntry_t* nextInMostRecentUsage; // points to element which was used more recently
_indexDataCacheEntry_t* prevInMostRecentUsage; // points to element which was used less recently
}indexDataCacheEntry2_t;
#define INDEX_DATA_CACHE_BUCKETS (1783)
indexDataCacheEntry2_t* indexDataCacheBucket[INDEX_DATA_CACHE_BUCKETS] = { 0 };
indexDataCacheEntry2_t* indexDataCacheFirst = nullptr; // points to least recently used item
indexDataCacheEntry2_t* indexDataCacheLast = nullptr; // points to most recently used item
sint32 indexDataCacheEntryCount = 0;
void _appendToUsageLinkedList(indexDataCacheEntry2_t* entry)
{
if (indexDataCacheLast == nullptr)
{
indexDataCacheLast = entry;
indexDataCacheFirst = entry;
entry->nextInMostRecentUsage = nullptr;
entry->prevInMostRecentUsage = nullptr;
}
else
{
indexDataCacheLast->nextInMostRecentUsage = entry;
entry->prevInMostRecentUsage = indexDataCacheLast;
entry->nextInMostRecentUsage = nullptr;
indexDataCacheLast = entry;
}
}
void _removeFromUsageLinkedList(indexDataCacheEntry2_t* entry)
{
if (entry->prevInMostRecentUsage)
{
entry->prevInMostRecentUsage->nextInMostRecentUsage = entry->nextInMostRecentUsage;
}
else
indexDataCacheFirst = entry->nextInMostRecentUsage;
if (entry->nextInMostRecentUsage)
{
entry->nextInMostRecentUsage->prevInMostRecentUsage = entry->prevInMostRecentUsage;
}
else
indexDataCacheLast = entry->prevInMostRecentUsage;
entry->prevInMostRecentUsage = nullptr;
entry->nextInMostRecentUsage = nullptr;
}
void _removeFromBucket(indexDataCacheEntry2_t* entry)
{
uint32 indexDataBucketIdx = (uint32)((entry->key.physAddr + entry->key.count) ^ (entry->key.physAddr >> 16)) % INDEX_DATA_CACHE_BUCKETS;
if (indexDataCacheBucket[indexDataBucketIdx] == entry)
{
indexDataCacheBucket[indexDataBucketIdx] = entry->nextInBucket;
entry->nextInBucket = nullptr;
return;
}
indexDataCacheEntry2_t* cacheEntryItr = indexDataCacheBucket[indexDataBucketIdx];
while (cacheEntryItr)
{
if (cacheEntryItr->nextInBucket == entry)
{
cacheEntryItr->nextInBucket = entry->nextInBucket;
entry->nextInBucket = nullptr;
return;
}
// next
cacheEntryItr = cacheEntryItr->nextInBucket;
}
}
void _decodeAndUploadIndexData(indexDataCacheEntry2_t* cacheEntry)
{
uint32 count = cacheEntry->key.count;
uint32 primitiveRestartIndex = cacheEntry->key.primitiveRestartIndex;
if (cacheEntry->indexType == _INDEX_TYPE::U16_BE)
{
// 16bit indices
uint16* indexInputU16 = (uint16*)memory_getPointerFromPhysicalOffset(cacheEntry->key.physAddr);
uint16* indexOutputU16 = (uint16*)indexState.tempIndexStorage;
cemu_assert_debug(count != 0);
uint16 indexMinU16 = 0xFFFF;
uint16 indexMaxU16 = 0;
if (primitiveRestartIndex < 0x10000)
{
// with primitive restart index
uint16 primitiveRestartIndexU16 = (uint16)primitiveRestartIndex;
for (uint32 i = 0; i < count; i++)
{
uint16 idxU16 = _swapEndianU16(*indexInputU16);
indexInputU16++;
if (primitiveRestartIndexU16 != idxU16)
{
indexMinU16 = std::min(indexMinU16, idxU16);
indexMaxU16 = std::max(indexMaxU16, idxU16);
}
*indexOutputU16 = idxU16;
indexOutputU16++;
}
}
else
{
// without primitive restart index
for (uint32 i = 0; i < count; i++)
{
uint16 idxU16 = _swapEndianU16(*indexInputU16);
indexInputU16++;
indexMinU16 = std::min(indexMinU16, idxU16);
indexMaxU16 = std::max(indexMaxU16, idxU16);
*indexOutputU16 = idxU16;
indexOutputU16++;
}
}
cacheEntry->minIndex = indexMinU16;
cacheEntry->maxIndex = indexMaxU16;
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, cacheEntry->heapEntry->startOffset, count * sizeof(uint16), indexState.tempIndexStorage);
performanceMonitor.cycle[performanceMonitor.cycleIndex].indexDataUploaded += (count * sizeof(uint16));
}
else if(cacheEntry->indexType == _INDEX_TYPE::U32_BE)
{
// 32bit indices
uint32* indexInputU32 = (uint32*)memory_getPointerFromPhysicalOffset(cacheEntry->key.physAddr);
uint32* indexOutputU32 = (uint32*)indexState.tempIndexStorage;
cemu_assert_debug(count != 0);
uint32 indexMinU32 = _swapEndianU32(*indexInputU32);
uint32 indexMaxU32 = _swapEndianU32(*indexInputU32);
for (uint32 i = 0; i < count; i++)
{
uint32 idxU32 = _swapEndianU32(*indexInputU32);
indexInputU32++;
if (idxU32 != primitiveRestartIndex)
{
indexMinU32 = std::min(indexMinU32, idxU32);
indexMaxU32 = std::max(indexMaxU32, idxU32);
}
*indexOutputU32 = idxU32;
indexOutputU32++;
}
cacheEntry->minIndex = indexMinU32;
cacheEntry->maxIndex = indexMaxU32;
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, cacheEntry->heapEntry->startOffset, count * sizeof(uint32), indexState.tempIndexStorage);
performanceMonitor.cycle[performanceMonitor.cycleIndex].indexDataUploaded += (count * sizeof(uint32));
}
else
{
cemu_assert_debug(false);
}
}
void LatteDraw_cleanupAfterFrame()
{
// drop everything from cache that is older than 30 frames
uint32 frameCounter = LatteGPUState.frameCounter;
while (indexDataCacheFirst)
{
indexDataCacheEntry2_t* entry = indexDataCacheFirst;
if ((frameCounter - entry->lastAccessFrameCount) < 30)
break;
// remove entry
virtualBufferHeap_free(indexState.indexBufferVirtualHeap, entry->heapEntry);
_removeFromUsageLinkedList(entry);
_removeFromBucket(entry);
free(entry);
}
}
void LatteDrawGL_removeLeastRecentlyUsedIndexCacheEntries(sint32 count)
{
while (indexDataCacheFirst && count > 0)
{
indexDataCacheEntry2_t* entry = indexDataCacheFirst;
// remove entry
virtualBufferHeap_free(indexState.indexBufferVirtualHeap, entry->heapEntry);
_removeFromUsageLinkedList(entry);
_removeFromBucket(entry);
free(entry);
count--;
}
}
uint32 LatteDrawGL_calculateIndexDataHash(uint8* data, uint32 size)
{
uint32 h = 0;
if (size < 16)
{
// hash the bytes individually
while (size != 0)
{
h += (uint32)*data;
data++;
size--;
}
return h;
}
// first 16 bytes
h += *(uint32*)(data + 0);
h += *(uint32*)(data + 4);
h += *(uint32*)(data + 8);
h += *(uint32*)(data + 12);
// last 16 bytes
data = data + ((size - 16)&~3);
h += *(uint32*)(data + 0);
h += *(uint32*)(data + 4);
h += *(uint32*)(data + 8);
h += *(uint32*)(data + 12);
return h;
}
// index handling with cache
// todo - Outdated cache implementation. Update OpenGL renderer to use the generic implementation that is also used by the Vulkan renderer
void LatteDrawGL_prepareIndicesWithGPUCache(MPTR indexDataMPTR, _INDEX_TYPE indexType, sint32 count, sint32 primitiveMode)
{
if (indexType == _INDEX_TYPE::AUTO)
{
indexState.minIndex = 0;
indexState.maxIndex = count - 1;
// since no indices are used we don't need to unbind the element array buffer
return; // automatic indices
}
OpenGLRenderer::SetArrayElementBuffer(indexState.glIndexCacheBuffer);
uint32 indexDataBucketIdx = (uint32)((indexDataMPTR + count) ^ (indexDataMPTR >> 16)) % INDEX_DATA_CACHE_BUCKETS;
// find matching entry
uint32 primitiveRestartIndex = LatteGPUState.contextNew.VGT_MULTI_PRIM_IB_RESET_INDX.get_RESTART_INDEX();
indexDataCacheEntry2_t* cacheEntryItr = indexDataCacheBucket[indexDataBucketIdx];
indexDataCacheKey_t compareKey;
compareKey.physAddr = indexDataMPTR;
compareKey.count = count;
compareKey.primitiveMode = primitiveMode;
compareKey.primitiveRestartIndex = primitiveRestartIndex;
while (cacheEntryItr)
{
if (memcmp(&(cacheEntryItr->key), &compareKey, sizeof(compareKey)) != 0)
{
// next
cacheEntryItr = cacheEntryItr->nextInBucket;
continue;
}
// entry found
indexState.minIndex = cacheEntryItr->minIndex;
indexState.maxIndex = cacheEntryItr->maxIndex;
indexState.indexData = (uint8*)(size_t)cacheEntryItr->heapEntry->startOffset;
cacheEntryItr->lastAccessFrameCount = LatteGPUState.frameCounter;
// check if the data changed
uint32 h = LatteDrawGL_calculateIndexDataHash(memory_getPointerFromPhysicalOffset(indexDataMPTR), cacheEntryItr->physSize);
if (cacheEntryItr->hash != h)
{
cemuLog_logDebug(LogType::Force, "IndexData hash changed");
_decodeAndUploadIndexData(cacheEntryItr);
cacheEntryItr->hash = h;
}
// move entry to the front
_removeFromUsageLinkedList(cacheEntryItr);
_appendToUsageLinkedList(cacheEntryItr);
return;
}
// calculate size of index data in cache
sint32 cacheIndexDataSize = 0;
if (indexType == _INDEX_TYPE::U16_BE || indexType == _INDEX_TYPE::U16_LE)
cacheIndexDataSize = count * sizeof(uint16);
else
cacheIndexDataSize = count * sizeof(uint32);
// no matching entry, create new one
VirtualBufferHeapEntry_t* heapEntry = virtualBufferHeap_allocate(indexState.indexBufferVirtualHeap, cacheIndexDataSize);
if (heapEntry == nullptr)
{
while (true)
{
LatteDrawGL_removeLeastRecentlyUsedIndexCacheEntries(10);
heapEntry = virtualBufferHeap_allocate(indexState.indexBufferVirtualHeap, cacheIndexDataSize);
if (heapEntry != nullptr)
break;
if (indexDataCacheFirst == nullptr)
{
cemuLog_log(LogType::Force, "Unable to allocate entry in index cache");
assert_dbg();
}
}
}
indexDataCacheEntry2_t* cacheEntry = (indexDataCacheEntry2_t*)malloc(sizeof(indexDataCacheEntry2_t));
memset(cacheEntry, 0, sizeof(indexDataCacheEntry2_t));
cacheEntry->key.physAddr = indexDataMPTR;
cacheEntry->physSize = (indexType == _INDEX_TYPE::U16_BE || indexType == _INDEX_TYPE::U16_LE) ? (count * sizeof(uint16)) : (count * sizeof(uint32));
cacheEntry->hash = LatteDrawGL_calculateIndexDataHash(memory_getPointerFromPhysicalOffset(indexDataMPTR), cacheEntry->physSize);
cacheEntry->key.count = count;
cacheEntry->key.primitiveRestartIndex = primitiveRestartIndex;
cacheEntry->indexType = indexType;
cacheEntry->key.primitiveMode = primitiveMode;
cacheEntry->heapEntry = heapEntry;
cacheEntry->lastAccessFrameCount = LatteGPUState.frameCounter;
// append entry in bucket list
cacheEntry->nextInBucket = indexDataCacheBucket[indexDataBucketIdx];
indexDataCacheBucket[indexDataBucketIdx] = cacheEntry;
// append as most recently used entry
_appendToUsageLinkedList(cacheEntry);
// decode and upload the data
_decodeAndUploadIndexData(cacheEntry);
indexDataCacheEntryCount++;
indexState.minIndex = cacheEntry->minIndex;
indexState.maxIndex = cacheEntry->maxIndex;
indexState.indexData = (uint8*)(size_t)cacheEntry->heapEntry->startOffset;
}
void LatteDraw_handleSpecialState8_clearAsDepth()
{
if (LatteGPUState.contextNew.GetSpecialStateValues()[0] == 0)
cemuLog_logDebug(LogType::Force, "Special state 8 requires special state 0 but it is not set?");
// get depth buffer information
uint32 regDepthBuffer = LatteGPUState.contextRegister[mmDB_HTILE_DATA_BASE];
uint32 regDepthSize = LatteGPUState.contextRegister[mmDB_DEPTH_SIZE];
uint32 regDepthBufferInfo = LatteGPUState.contextRegister[mmDB_DEPTH_INFO];
// get format and tileMode from info reg
uint32 depthBufferTileMode = (regDepthBufferInfo >> 15) & 0xF;
MPTR depthBufferPhysMem = regDepthBuffer << 8;
uint32 depthBufferPitch = (((regDepthSize >> 0) & 0x3FF) + 1);
uint32 depthBufferHeight = ((((regDepthSize >> 10) & 0xFFFFF) + 1) / depthBufferPitch);
depthBufferPitch <<= 3;
depthBufferHeight <<= 3;
uint32 depthBufferWidth = depthBufferPitch;
sint32 sliceIndex = 0; // todo
sint32 mipIndex = 0;
// clear all color buffers that match the format of the depth buffer
sint32 searchIndex = 0;
bool targetFound = false;
while (true)
{
LatteTextureView* view = LatteTC_LookupTextureByData(depthBufferPhysMem, depthBufferWidth, depthBufferHeight, depthBufferPitch, 0, 1, sliceIndex, 1, &searchIndex);
if (!view)
{
// should we clear in RAM instead?
break;
}
sint32 effectiveClearWidth = view->baseTexture->width;
sint32 effectiveClearHeight = view->baseTexture->height;
LatteTexture_scaleToEffectiveSize(view->baseTexture, &effectiveClearWidth, &effectiveClearHeight, 0);
// hacky way to get clear color
float* regClearColor = (float*)(LatteGPUState.contextRegister + 0xC000 + 0); // REG_BASE_ALU_CONST
uint8 clearColor[4] = { 0 };
clearColor[0] = (uint8)(regClearColor[0] * 255.0f);
clearColor[1] = (uint8)(regClearColor[1] * 255.0f);
clearColor[2] = (uint8)(regClearColor[2] * 255.0f);
clearColor[3] = (uint8)(regClearColor[3] * 255.0f);
// todo - use fragment shader software emulation (evoke for one pixel) to determine clear color
// todo - dont clear entire slice, use effectiveClearWidth, effectiveClearHeight
if (g_renderer->GetType() == RendererAPI::OpenGL)
{
//cemu_assert_debug(false); // implement g_renderer->texture_clearColorSlice properly for OpenGL renderer
if (glClearTexSubImage)
glClearTexSubImage(((LatteTextureViewGL*)view)->glTexId, mipIndex, 0, 0, 0, effectiveClearWidth, effectiveClearHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE, clearColor);
}
else
{
if (view->baseTexture->isDepth)
g_renderer->texture_clearDepthSlice(view->baseTexture, sliceIndex + view->firstSlice, mipIndex + view->firstMip, true, view->baseTexture->hasStencil, 0.0f, 0);
else
g_renderer->texture_clearColorSlice(view->baseTexture, sliceIndex + view->firstSlice, mipIndex + view->firstMip, clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
}
}
}
void LatteDrawGL_doDraw(_INDEX_TYPE indexType, uint32 baseVertex, uint32 baseInstance, uint32 instanceCount, uint32 count)
{
if (indexType == _INDEX_TYPE::U16_BE)
{
// 16bit index, big endian
if (instanceCount > 1 || baseInstance != 0)
{
glDrawElementsInstancedBaseVertexBaseInstance(sGLActiveDrawMode, count, GL_UNSIGNED_SHORT, indexState.indexData, instanceCount, baseVertex, baseInstance);
}
else
{
if (baseVertex != 0)
glDrawRangeElementsBaseVertex(sGLActiveDrawMode, indexState.minIndex, indexState.maxIndex, count, GL_UNSIGNED_SHORT, indexState.indexData, baseVertex);
else
glDrawRangeElements(sGLActiveDrawMode, indexState.minIndex, indexState.maxIndex, count, GL_UNSIGNED_SHORT, indexState.indexData);
}
}
else if (indexType == _INDEX_TYPE::U32_BE)
{
// 32bit index, big endian
if (instanceCount > 1 || baseInstance != 0)
{
//debug_printf("Render instanced\n");
glDrawElementsInstancedBaseVertexBaseInstance(sGLActiveDrawMode, count, GL_UNSIGNED_INT, indexState.indexData, instanceCount, baseVertex, baseInstance);
}
else
{
glDrawRangeElementsBaseVertex(sGLActiveDrawMode, indexState.minIndex, indexState.maxIndex, count, GL_UNSIGNED_INT, indexState.indexData, baseVertex);
}
}
else if (indexType == _INDEX_TYPE::AUTO)
{
// render without index (automatic index generation)
cemu_assert_debug(baseInstance == 0);
if (instanceCount > 1)
glDrawArraysInstanced(sGLActiveDrawMode, baseVertex, count, instanceCount);
else
{
glDrawArrays(sGLActiveDrawMode, baseVertex, count);
}
}
else
{
cemu_assert_debug(false);
}
}
uint32 _glVertexBufferOffset[32] = { 0 };
void OpenGLRenderer::buffer_bindVertexBuffer(uint32 bufferIndex, uint32 offset, uint32 size)
{
_glVertexBufferOffset[bufferIndex] = offset;
}
void OpenGLRenderer::buffer_bindUniformBuffer(LatteConst::ShaderType shaderType, uint32 bufferIndex, uint32 offset, uint32 size)
{
switch (shaderType)
{
case LatteConst::ShaderType::Vertex:
bufferIndex += 0;
break;
case LatteConst::ShaderType::Pixel:
bufferIndex += 32;
break;
case LatteConst::ShaderType::Geometry:
bufferIndex += 64;
break;
}
if (offset == 0 && size == 0)
{
// when binding NULL we just bind some arbitrary undefined data so the OpenGL driver is happy since a size of 0 is not allowed (should we bind a buffer filled with zeroes instead?)
glBindBufferRange(GL_UNIFORM_BUFFER, bufferIndex, glAttributeCacheAB, 0, 32);
return;
}
glBindBufferRange(GL_UNIFORM_BUFFER, bufferIndex, glAttributeCacheAB, offset, size);
}
void LatteDraw_resetAttributePointerCache();
void _resetAttributes(LatteParsedFetchShaderBufferGroup_t* attribGroup, bool* attributeArrayUsed)
{
for (sint32 i = 0; i < attribGroup->attribCount; i++)
{
LatteParsedFetchShaderAttribute_t* attrib = attribGroup->attrib + i;
sint32 attributeShaderLocation = attrib->semanticId; // we now bind to the semanticId instead
attributeArrayUsed[attributeShaderLocation] = false;
}
}
void OpenGLRenderer::_setupVertexAttributes()
{
LatteFetchShader* fetchShader = LatteSHRC_GetActiveFetchShader();
LatteDecompilerShader* vertexShader = LatteSHRC_GetActiveVertexShader();
catchOpenGLError();
// bind buffer
attributeStream_bindVertexCacheBuffer();
catchOpenGLError();
LatteFetchShader* parsedFetchShader = LatteSHRC_GetActiveFetchShader();
bool attributeArrayUsed[32] = { 0 }; // used to keep track of enabled vertex attributes for this shader
sint32 attributeDataIndex = 0;
uint32 vboDataOffset = 0;
bool tfBufferIsBound = false;
sint32 maxReallocAttemptLimit = 1;
for(auto& bufferGroup : parsedFetchShader->bufferGroups)
{
uint32 bufferIndex = bufferGroup.attributeBufferIndex;
uint32 bufferBaseRegisterIndex = mmSQ_VTX_ATTRIBUTE_BLOCK_START + bufferIndex * 7;
MPTR bufferAddress = LatteGPUState.contextRegister[bufferBaseRegisterIndex + 0];
uint32 bufferSize = LatteGPUState.contextRegister[bufferBaseRegisterIndex + 1] + 1;
uint32 bufferStride = (LatteGPUState.contextRegister[bufferBaseRegisterIndex + 2] >> 11) & 0xFFFF;
if (bufferAddress == MPTR_NULL)
{
_resetAttributes(&bufferGroup, attributeArrayUsed);
continue;
}
vboDataOffset = _glVertexBufferOffset[bufferIndex];
for (sint32 i = 0; i < bufferGroup.attribCount; i++)
{
LatteParsedFetchShaderAttribute_t* attrib = bufferGroup.attrib + i;
sint32 attributeShaderLocation = attrib->semanticId; // we now bind to the semanticId instead
attributeShaderLocation = vertexShader->resourceMapping.getAttribHostShaderIndex(attrib->semanticId);
if (attributeShaderLocation == -1)
continue; // attribute not used
if (attributeShaderLocation >= GPU_GL_MAX_NUM_ATTRIBUTE)
continue;
if (attributeArrayUsed[attributeShaderLocation] == true)
{
debug_printf("Fetch shader attribute is bound multiple times\n");
}
// get buffer
uint32 bufferIndex = attrib->attributeBufferIndex;
cemu_assert_debug(bufferIndex < 0x10);
cemu_assert_debug(attrib->fetchType == LatteConst::VERTEX_DATA || attrib->fetchType == LatteConst::INSTANCE_DATA); // unsupported fetch type
SetAttributeArrayState(attributeShaderLocation, true, (bufferStride == 0) ? 99999999 : attrib->aluDivisor);
uint8* bufferInput = memory_getPointerFromPhysicalOffset(bufferAddress) + attrib->offset;
uint32 bufferSizeInput = bufferSize - attrib->offset;
uint8* vboGLPtr;
vboGLPtr = (uint8*)(size_t)(vboDataOffset + attrib->offset);
_setAttributeBufferPointerRaw(attributeShaderLocation, NULL, 0, bufferStride, attrib, vboGLPtr, bufferStride);
attributeArrayUsed[attributeShaderLocation] = true;
attributeDataIndex++;
catchOpenGLError();
}
}
for (uint32 i = 0; i < GPU_GL_MAX_NUM_ATTRIBUTE; i++)
{
if (attributeArrayUsed[i] == false && glAttributeArrayIsEnabled[i] == true)
SetAttributeArrayState(i, false, -1);
}
}
void rectsEmulationGS_outputSingleVertex(std::string& gsSrc, LatteDecompilerShader* vertexShader, LatteShaderPSInputTable* psInputTable, sint32 vIdx);
void rectsEmulationGS_outputGeneratedVertex(std::string& gsSrc, LatteDecompilerShader* vertexShader, LatteShaderPSInputTable* psInputTable, const char* variant);
void rectsEmulationGS_outputVerticesCode(std::string& gsSrc, LatteDecompilerShader* vertexShader, LatteShaderPSInputTable* psInputTable, sint32 p0, sint32 p1, sint32 p2, sint32 p3, const char* variant, const LatteContextRegister& latteRegister);
std::map<uint64, RendererShaderGL*> g_mapGLRectEmulationGS;
RendererShaderGL* rectsEmulationGS_generateShaderGL(LatteDecompilerShader* vertexShader)
{
LatteShaderPSInputTable* psInputTable = LatteSHRC_GetPSInputTable();
std::string gsSrc;
gsSrc.append("#version 450\r\n");
// layout
gsSrc.append("layout(triangles) in;\r\n");
gsSrc.append("layout(triangle_strip) out;\r\n");
gsSrc.append("layout(max_vertices = 4) out;\r\n");
// gl_PerVertex input
gsSrc.append("in gl_PerVertex {\r\n");
gsSrc.append("vec4 gl_Position;\r\n");
gsSrc.append("} gl_in[];\r\n");
// gl_PerVertex output
gsSrc.append("out gl_PerVertex {\r\n");
gsSrc.append("vec4 gl_Position;\r\n");
gsSrc.append("};\r\n");
// inputs & outputs
auto parameterMask = vertexShader->outputParameterMask;
for (sint32 f = 0; f < 2; f++)
{
for (uint32 i = 0; i < 32; i++)
{
if ((parameterMask & (1 << i)) == 0)
continue;
sint32 vsSemanticId = psInputTable->getVertexShaderOutParamSemanticId(LatteGPUState.contextRegister, i);
if (vsSemanticId < 0)
continue;
auto psImport = psInputTable->getPSImportBySemanticId(vsSemanticId);
if (psImport == nullptr)
continue;
gsSrc.append(fmt::format("layout(location = {}) ", psInputTable->getPSImportLocationBySemanticId(vsSemanticId)));
if (psImport->isFlat)
gsSrc.append("flat ");
if (psImport->isNoPerspective)
gsSrc.append("noperspective ");
if (f == 0)
gsSrc.append("in");
else
gsSrc.append("out");
if (f == 0)
gsSrc.append(fmt::format(" vec4 passParameterSem{}In[];\r\n", vsSemanticId));
else
gsSrc.append(fmt::format(" vec4 passParameterSem{}Out;\r\n", vsSemanticId));
}
}
// gen function
gsSrc.append("vec4 gen4thVertexA(vec4 a, vec4 b, vec4 c)\r\n");
gsSrc.append("{\r\n");
gsSrc.append("return b - (c - a);\r\n");
gsSrc.append("}\r\n");
gsSrc.append("vec4 gen4thVertexB(vec4 a, vec4 b, vec4 c)\r\n");
gsSrc.append("{\r\n");
gsSrc.append("return c - (b - a);\r\n");
gsSrc.append("}\r\n");
gsSrc.append("vec4 gen4thVertexC(vec4 a, vec4 b, vec4 c)\r\n");
gsSrc.append("{\r\n");
gsSrc.append("return c + (b - a);\r\n");
gsSrc.append("}\r\n");
// main
gsSrc.append("void main()\r\n");
gsSrc.append("{\r\n");
// there are two possible winding orders that need different triangle generation:
// 0 1
// 2 3
// and
// 0 1
// 3 2
// all others are just symmetries of these cases
// we can determine the case by comparing the distance 0<->1 and 0<->2
gsSrc.append("float dist0_1 = length(gl_in[1].gl_Position.xy - gl_in[0].gl_Position.xy);\r\n");
gsSrc.append("float dist0_2 = length(gl_in[2].gl_Position.xy - gl_in[0].gl_Position.xy);\r\n");
gsSrc.append("float dist1_2 = length(gl_in[2].gl_Position.xy - gl_in[1].gl_Position.xy);\r\n");
// emit vertices
gsSrc.append("if(dist0_1 > dist0_2 && dist0_1 > dist1_2)\r\n");
gsSrc.append("{\r\n");
// p0 to p1 is diagonal
rectsEmulationGS_outputVerticesCode(gsSrc, vertexShader, psInputTable, 2, 1, 0, 3, "A", LatteGPUState.contextNew);
gsSrc.append("} else if ( dist0_2 > dist0_1 && dist0_2 > dist1_2 ) {\r\n");
// p0 to p2 is diagonal
rectsEmulationGS_outputVerticesCode(gsSrc, vertexShader, psInputTable, 1, 2, 0, 3, "B", LatteGPUState.contextNew);
gsSrc.append("} else {\r\n");
// p1 to p2 is diagonal
rectsEmulationGS_outputVerticesCode(gsSrc, vertexShader, psInputTable, 0, 1, 2, 3, "C", LatteGPUState.contextNew);
gsSrc.append("}\r\n");
gsSrc.append("}\r\n");
auto glShader = new RendererShaderGL(RendererShader::ShaderType::kGeometry, 0, 0, false, false, gsSrc);
glShader->PreponeCompilation(true);
return glShader;
}
RendererShaderGL* rectsEmulationGS_getShaderGL(LatteDecompilerShader* vertexShader)
{
LatteShaderPSInputTable* psInputTable = LatteSHRC_GetPSInputTable();
uint64 h = vertexShader->baseHash + psInputTable->key;
auto itr = g_mapGLRectEmulationGS.find(h);
if (itr != g_mapGLRectEmulationGS.end())
return (*itr).second;
auto glShader = rectsEmulationGS_generateShaderGL(vertexShader);
g_mapGLRectEmulationGS.emplace(h, glShader);
return glShader;
}
uint32 sPrevTextureReadbackDrawcallUpdate = 0;
template<bool TIsMinimal, bool THasProfiling>
void OpenGLRenderer::draw_genericDrawHandler(uint32 baseVertex, uint32 baseInstance, uint32 instanceCount, uint32 count, MPTR indexDataMPTR, Latte::LATTE_VGT_DMA_INDEX_TYPE::E_INDEX_TYPE indexType)
{
ReleaseBufferCacheEntries();
catchOpenGLError();
void* indexData = indexDataMPTR != MPTR_NULL ? memory_getPointerFromPhysicalOffset(indexDataMPTR) : NULL;
auto primitiveMode = LatteGPUState.contextNew.VGT_PRIMITIVE_TYPE.get_PRIMITIVE_MODE();
// handle special state 8 (clear as depth)
if (LatteGPUState.contextNew.GetSpecialStateValues()[8] != 0)
{
LatteDraw_handleSpecialState8_clearAsDepth();
LatteGPUState.drawCallCounter++;
return;
}
// update shaders and uniforms
if constexpr (!TIsMinimal)
{
beginPerfMonProfiling(performanceMonitor.gpuTime_dcStageShaderAndUniformMgr);
LatteSHRC_UpdateActiveShaders();
LatteDecompilerShader* vs = (LatteDecompilerShader*)LatteSHRC_GetActiveVertexShader();
LatteDecompilerShader* gs = (LatteDecompilerShader*)LatteSHRC_GetActiveGeometryShader();
LatteDecompilerShader* ps = (LatteDecompilerShader*)LatteSHRC_GetActivePixelShader();
if (vs)
shader_bind(vs->shader);
else
shader_unbind(RendererShader::ShaderType::kVertex);
if (ps && LatteGPUState.contextRegister[mmVGT_STRMOUT_EN] == 0)
shader_bind(ps->shader);
else
shader_unbind(RendererShader::ShaderType::kFragment);
if (gs)
shader_bind(gs->shader);
else
shader_unbind(RendererShader::ShaderType::kGeometry);
endPerfMonProfiling(performanceMonitor.gpuTime_dcStageShaderAndUniformMgr);
}
if (LatteGPUState.activeShaderHasError)
{
debug_printf("Skipped drawcall due to shader error\n");
return;
}
// check for blacklisted shaders
uint64 vsShaderHash = 0;
if (LatteSHRC_GetActiveVertexShader())
vsShaderHash = LatteSHRC_GetActiveVertexShader()->baseHash;
uint64 psShaderHash = 0;
if (LatteSHRC_GetActivePixelShader())
psShaderHash = LatteSHRC_GetActivePixelShader()->baseHash;
// setup streamout (if enabled)
bool rasterizerEnable = LatteGPUState.contextNew.PA_CL_CLIP_CNTL.get_DX_RASTERIZATION_KILL() == false;
if (!LatteGPUState.contextNew.PA_CL_VTE_CNTL.get_VPORT_X_OFFSET_ENA())
rasterizerEnable = true;
bool streamoutEnable = LatteGPUState.contextRegister[mmVGT_STRMOUT_EN] != 0;
if (streamoutEnable)
{
if (glBeginTransformFeedback == nullptr)
{
cemu_assert_debug(false);
return; // transform feedback not supported
}
}
// skip draw if output is not used
if (rasterizerEnable == false && streamoutEnable == false)
{
// rasterizer and streamout disabled
LatteGPUState.drawCallCounter++;
return;
}
// get primitive
if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::TRIANGLES)
sGLActiveDrawMode = GL_TRIANGLES;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::TRIANGLE_STRIP)
sGLActiveDrawMode = GL_TRIANGLE_STRIP;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::QUADS)
sGLActiveDrawMode = GL_QUADS;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::TRIANGLE_FAN)
sGLActiveDrawMode = GL_TRIANGLE_FAN;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::RECTS)
sGLActiveDrawMode = GL_TRIANGLES;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::POINTS)
sGLActiveDrawMode = GL_POINTS;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::LINES)
sGLActiveDrawMode = GL_LINES;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::LINE_STRIP)
sGLActiveDrawMode = GL_LINE_STRIP;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::LINE_LOOP)
sGLActiveDrawMode = GL_LINE_LOOP;
else if (primitiveMode == Latte::LATTE_VGT_PRIMITIVE_TYPE::E_PRIMITIVE_TYPE::QUAD_STRIP)
sGLActiveDrawMode = GL_QUAD_STRIP;
else
{
cemu_assert_debug(false); // unsupported primitive type
LatteGPUState.drawCallCounter++;
return;
}
if constexpr (!TIsMinimal)
{
// update render targets and textures
LatteGPUState.requiresTextureBarrier = false;
beginPerfMonProfiling(performanceMonitor.gpuTime_dcStageTextures);
while (true)
{