-
Notifications
You must be signed in to change notification settings - Fork 502
/
OpenGLRenderer.cpp
1866 lines (1662 loc) · 63.4 KB
/
OpenGLRenderer.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 "Cafe/HW/Latte/Renderer/OpenGL/OpenGLRenderer.h"
#include "gui/guiWrapper.h"
#include "Cafe/HW/Latte/Core/LatteRingBuffer.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LatteOverlay.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/LatteTextureGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/LatteTextureViewGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/RendererShaderGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/CachedFBOGL.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/OpenGLTextureReadback.h"
#include "Cafe/HW/Latte/LegacyShaderDecompiler/LatteDecompiler.h"
#include "imgui/imgui_impl_opengl3.h"
#include "imgui/imgui_extension.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "gui/canvas/OpenGLCanvas.h"
#define STRINGIFY2(X) #X
#define STRINGIFY(X) STRINGIFY2(X)
namespace CemuGL
{
#define GLFUNC(__type, __name) __type __name;
#define EGLFUNC(__type, __name) __type __name;
#include "Common/GLInclude/glFunctions.h"
#undef GLFUNC
#undef EGLFUNC
}
#include "config/ActiveSettings.h"
#include "config/LaunchSettings.h"
static const int TEXBUFFER_SIZE = 1024 * 1024 * 32; // 32MB
struct
{
// options
bool useTextureUploadBuffer;
// texture upload
GLuint uploadBuffer;
sint32 uploadIndex;
void* uploadBufferPtr;
LatteRingBuffer_t* uploadRingBuffer;
// current texture work buffer (subrange of uploadRingBuffer)
uint8* texWorkBuffer;
sint32 texWorkBufferSize;
// texture upload buffer (when not using persistent buffer)
std::vector<uint8> texUploadBuffer;
// FBO for fast clearing (on Nvidia or if glClearTexSubImage is not supported)
GLuint clearFBO;
}glRendererState;
static const GLenum glDepthFuncTable[] =
{
GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS
};
static const GLenum glAlphaTestFunc[] =
{
GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS
};
OpenGLRenderer::OpenGLRenderer()
{
glRendererState.useTextureUploadBuffer = false;
if (glRendererState.useTextureUploadBuffer)
{
glCreateBuffers(1, &glRendererState.uploadBuffer);
glNamedBufferStorage(glRendererState.uploadBuffer, TEXBUFFER_SIZE, nullptr, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT);
void* buffer = glMapNamedBufferRange(glRendererState.uploadBuffer, 0, TEXBUFFER_SIZE, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);
if (buffer == nullptr)
{
cemuLog_log(LogType::Force, "Failed to allocate GL texture upload buffer. Using traditional API instead");
cemu_assert_debug(false);
}
glRendererState.uploadBufferPtr = buffer;
glRendererState.uploadRingBuffer = LatteRingBuffer_create((uint8*)buffer, TEXBUFFER_SIZE);
glRendererState.uploadIndex = 0;
}
#if BOOST_OS_WINDOWS
try
{
m_dxgi_wrapper = std::make_unique<DXGIWrapper>();
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "Unable to create dxgi wrapper: {} (VRAM overlay stat won't be available)", ex.what());
}
#endif
}
OpenGLRenderer::~OpenGLRenderer()
{
if(m_pipeline != 0)
glDeleteProgramPipelines(1, &m_pipeline);
}
OpenGLRenderer* OpenGLRenderer::GetInstance()
{
cemu_assert_debug(g_renderer && dynamic_cast<OpenGLRenderer*>(g_renderer.get()));
return (OpenGLRenderer*)g_renderer.get();
}
bool OpenGLRenderer::ImguiBegin(bool mainWindow)
{
if (!mainWindow)
{
GLCanvas_MakeCurrent(true);
m_isPadViewContext = true;
}
if(!Renderer::ImguiBegin(mainWindow))
return false;
renderstate_resetColorControl();
renderstate_resetDepthControl();
renderstate_resetStencilMask();
if (glClipControl)
glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
ImGui_ImplOpenGL3_NewFrame();
ImGui_UpdateWindowInformation(mainWindow);
ImGui::NewFrame();
return true;
}
void OpenGLRenderer::ImguiEnd()
{
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (m_isPadViewContext)
{
GLCanvas_MakeCurrent(false);
m_isPadViewContext = false;
}
if (glClipControl)
glClipControl(GL_UPPER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
}
ImTextureID OpenGLRenderer::GenerateTexture(const std::vector<uint8>& data, const Vector2i& size)
{
GLuint textureId;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glActiveTexture(GL_TEXTURE0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB, size.x, size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data());
return (ImTextureID)(uintptr_t)textureId;
}
void OpenGLRenderer::DeleteTexture(ImTextureID id)
{
if (id)
{
GLuint textureId = (GLuint)(uintptr_t)id;
glDeleteTextures(1, &textureId);
}
}
void OpenGLRenderer::DeleteFontTextures()
{
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
typedef void(*GL_IMPORT)();
#if BOOST_OS_WINDOWS
GL_IMPORT _GetOpenGLFunction(HMODULE hLib, const char* name)
{
GL_IMPORT r = (GL_IMPORT)wglGetProcAddress(name);
if (r == nullptr)
r = (GL_IMPORT)GetProcAddress(hLib, name);
return r;
}
void LoadOpenGLImports()
{
HMODULE hLib = LoadLibraryA("opengl32.dll");
#define GLFUNC(__type, __name) __name = (__type)_GetOpenGLFunction(hLib, STRINGIFY(__name));
#include "Common/GLInclude/glFunctions.h"
#undef GLFUNC
}
#elif BOOST_OS_LINUX
GL_IMPORT _GetOpenGLFunction(void* hLib, PFNGLXGETPROCADDRESSPROC func, const char* name)
{
GL_IMPORT r = (GL_IMPORT)func((const GLubyte*)name);
return r;
}
#include <dlfcn.h>
// #define RTLD_NOW 0x00002
// #define RTLD_GLOBAL 0x00100
void LoadOpenGLImports()
{
PFNGLXGETPROCADDRESSPROC _glXGetProcAddress = nullptr;
void* libGL = dlopen("libGL.so.1", RTLD_NOW | RTLD_GLOBAL);
_glXGetProcAddress = (PFNGLXGETPROCADDRESSPROC)dlsym(libGL, "glXGetProcAddressARB");
if(!_glXGetProcAddress)
{
libGL = dlopen("libGL.so", RTLD_NOW | RTLD_GLOBAL);
_glXGetProcAddress = (PFNGLXGETPROCADDRESSPROC)dlsym(libGL, "glXGetProcAddressARB");
}
void* libEGL = dlopen("libEGL.so.1", RTLD_NOW | RTLD_GLOBAL);
if(!libEGL)
{
libGL = dlopen("libEGL.so", RTLD_NOW | RTLD_GLOBAL);
}
#define GLFUNC(__type, __name) __name = (__type)_GetOpenGLFunction(libGL, _glXGetProcAddress, STRINGIFY(__name));
#define EGLFUNC(__type, __name) __name = (__type)dlsym(libEGL, STRINGIFY(__name));
#include "Common/GLInclude/glFunctions.h"
#undef GLFUNC
#undef EGLFUNC
}
#if BOOST_OS_LINUX
// dummy function for all code that is statically linked with cemu and attempts to use eglSwapInterval
// used to suppress wxWidgets calls to eglSwapInterval
extern "C"
EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval)
{
return EGL_TRUE;
}
#endif
#elif BOOST_OS_MACOS
void LoadOpenGLImports()
{
cemu_assert_unimplemented();
}
#endif
void OpenGLRenderer::Initialize()
{
Renderer::Initialize();
auto lock = cemuLog_acquire();
cemuLog_log(LogType::Force, "------- Init OpenGL graphics backend -------");
GLCanvas_MakeCurrent(false);
LoadOpenGLImports();
GetVendorInformation();
#if BOOST_OS_WINDOWS
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(0); // disable V-Sync per default
#endif
if (glMaxShaderCompilerThreadsARB)
glMaxShaderCompilerThreadsARB(0xFFFFFFFF);
cemuLog_log(LogType::Force, "OpenGL extensions:");
cemuLog_log(LogType::Force, "ARB_clip_control: {}", glClipControl ? "available" : "not supported");
cemuLog_log(LogType::Force, "ARB_get_program_binary: {}", (glGetProgramBinary != NULL && glProgramBinary != NULL) ? "available" : "not supported");
cemuLog_log(LogType::Force, "ARB_clear_texture: {}", (glClearTexImage != NULL) ? "available" : "not supported");
cemuLog_log(LogType::Force, "ARB_copy_image: {}", (glCopyImageSubData != NULL) ? "available" : "not supported");
cemuLog_log(LogType::Force, "NV_depth_buffer_float: {}", (glDepthRangedNV != NULL) ? "available" : "not supported");
// enable framebuffer SRGB support
glEnable(GL_FRAMEBUFFER_SRGB);
if (this->m_vendor != GfxVendor::AMD)
{
// don't enable this for AMD because GL_PROGRAM_POINT_SIZE breaks shader binaries for some reason
// it also seems like AMD ignores GL_POINT_SPRITE and gl_PointCoord is always 0.0/0.0
// point size is always defined via shader
glEnable(GL_PROGRAM_POINT_SIZE);
// since we are using compatibility profile point sprites are disabled by default (e.g. gl_PointCoord wont work)
glEnable(GL_POINT_SPRITE);
}
// check if clip control is available
if (glClipControl)
{
glClipControl(GL_UPPER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
}
else
{
cemuLog_log(LogType::Force, "ARB_CLIP_CONTROL not supported by graphics driver. This will lead to crashes or graphical artifacts.");
}
// set pixel unpack alignment to 1 byte
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// on NVIDIA rendering to SNORM textures is clamped to [0.0,1.0] range for non-core profiles
// we can still disable the clamping using an older function (note that AMD and Intel don't need this, which is technically incorrect according to the compatibility profile spec)
if (m_vendor == GfxVendor::Nvidia)
glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(0xFFFFFFFF);
glGenProgramPipelines(1, &m_pipeline);
glBindProgramPipeline(m_pipeline);
lock.unlock();
// create framebuffer for fast clearing (avoid glClearTexSubImage on Nvidia)
if (glCreateFramebuffers)
glCreateFramebuffers(1, &glRendererState.clearFBO);
else
{
glGenFramebuffers(1, &glRendererState.clearFBO);
// bind to initialize
glBindFramebuffer(GL_FRAMEBUFFER_EXT, glRendererState.clearFBO);
glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
}
draw_init();
catchOpenGLError();
glGenBuffers(1, &glStreamoutCacheRingBuffer);
glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, glStreamoutCacheRingBuffer);
glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, LatteStreamout_GetRingBufferSize(), NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, 0);
catchOpenGLError();
// imgui
ImGui_ImplOpenGL3_Init("#version 130");
}
bool OpenGLRenderer::IsPadWindowActive()
{
return GLCanvas_HasPadViewOpen();
}
void OpenGLRenderer::Flush(bool waitIdle)
{
glFlush();
if (waitIdle)
glFinish();
}
void OpenGLRenderer::NotifyLatteCommandProcessorIdle()
{
glFlush();
}
void OpenGLRenderer::GetVendorInformation()
{
// example vendor strings:
// ATI Technologies Inc.
// NVIDIA Corporation
// Intel
char* glVendorString = (char*)glGetString(GL_VENDOR);
char* glRendererString = (char*)glGetString(GL_RENDERER);
char* glVersionString = (char*)glGetString(GL_VERSION);
cemuLog_log(LogType::Force, "GL_VENDOR: {}", glVendorString ? glVendorString : "unknown");
cemuLog_log(LogType::Force, "GL_RENDERER: {}", glRendererString ? glRendererString : "unknown");
cemuLog_log(LogType::Force, "GL_VERSION: {}", glVersionString ? glVersionString : "unknown");
if(boost::icontains(glVersionString, "Mesa"))
{
m_vendor = GfxVendor::Mesa;
return;
}
if (glVendorString)
{
if ((toupper(glVendorString[0]) == 'A' && toupper(glVendorString[1]) == 'T' && toupper(glVendorString[2]) == 'I') ||
(toupper(glVendorString[0]) == 'A' && toupper(glVendorString[1]) == 'M' && toupper(glVendorString[2]) == 'D'))
{
m_vendor = GfxVendor::AMD;
return;
}
else if (memcmp(glVendorString, "NVIDIA", 6) == 0)
{
m_vendor = GfxVendor::Nvidia;
return;
}
else if (memcmp(glVendorString, "Intel", 5) == 0)
{
m_vendor = GfxVendor::Intel;
return;
}
}
m_vendor = GfxVendor::Generic;
}
void _glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
if (LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "Buffer"))
return;
if (LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "performance warning"))
return;
if (LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "Dithering is enabled"))
return;
if (LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "Blending is enabled, but is not supported for integer framebuffers"))
return;
if (LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "does not have a defined base level"))
return;
if(LatteGPUState.glVendor == GLVENDOR_NVIDIA && strstr(message, "has depth comparisons disabled, with a texture object"))
return;
cemuLog_log(LogType::Force, "GLDEBUG: {}", message);
cemu_assert_debug(false);
}
void OpenGLRenderer::EnableDebugMode()
{
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(_glDebugCallback, NULL);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true);
}
void OpenGLRenderer::SwapBuffers(bool swapTV, bool swapDRC)
{
GLCanvas_SwapBuffers(swapTV, swapDRC);
if (swapTV)
cleanupAfterFrame();
}
bool OpenGLRenderer::BeginFrame(bool mainWindow)
{
if (!mainWindow && !IsPadWindowActive())
return false;
GLCanvas_MakeCurrent(!mainWindow);
ClearColorbuffer(!mainWindow);
return true;
}
void OpenGLRenderer::DrawEmptyFrame(bool mainWindow)
{
if (!BeginFrame(mainWindow))
return;
SwapBuffers(mainWindow, !mainWindow);
}
void OpenGLRenderer::ClearColorbuffer(bool padView)
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
void OpenGLRenderer::HandleScreenshotRequest(LatteTextureView* texView, bool padView)
{
const bool hasScreenshotRequest = gui_hasScreenshotRequest();
if(!hasScreenshotRequest && m_screenshot_state == ScreenshotState::None)
return;
if (IsPadWindowActive())
{
// we already took a pad view screenshow and want a main window screenshot
if (m_screenshot_state == ScreenshotState::Main && padView)
return;
if (m_screenshot_state == ScreenshotState::Pad && !padView)
return;
// remember which screenshot is left to take
if (m_screenshot_state == ScreenshotState::None)
m_screenshot_state = padView ? ScreenshotState::Main : ScreenshotState::Pad;
else
m_screenshot_state = ScreenshotState::None;
}
else
m_screenshot_state = ScreenshotState::None;
int screenshotWidth, screenshotHeight;
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
texture_bindAndActivate(texView, 0);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &screenshotWidth);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &screenshotHeight);
glPixelStorei(GL_PACK_ALIGNMENT, 1); // set alignment to 1
const sint32 pixelDataSize = screenshotWidth * screenshotHeight * 3;
std::vector<uint8> rgb_data(pixelDataSize);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, rgb_data.data());
texture_bindAndActivate(nullptr, 0);
const bool srcUsesSRGB = HAS_FLAG(texView->format, Latte::E_GX2SURFFMT::FMT_BIT_SRGB);
const bool dstUsesSRGB = (!padView && LatteGPUState.tvBufferUsesSRGB) || (padView && LatteGPUState.drcBufferUsesSRGB);
if((srcUsesSRGB && !dstUsesSRGB) || (!srcUsesSRGB && dstUsesSRGB))
{
for (sint32 iy = 0; iy < screenshotHeight; ++iy)
{
for (sint32 ix = 0; ix < screenshotWidth; ++ix)
{
uint8* pData = rgb_data.data() + (ix + iy * screenshotWidth) * 3;
if (srcUsesSRGB && !dstUsesSRGB)
{
// SRGB -> RGB
pData[0] = SRGBComponentToRGB(pData[0]);
pData[1] = SRGBComponentToRGB(pData[1]);
pData[2] = SRGBComponentToRGB(pData[2]);
}
else if (!srcUsesSRGB && dstUsesSRGB)
{
// RGB -> SRGB
pData[0] = RGBComponentToSRGB(pData[0]);
pData[1] = RGBComponentToSRGB(pData[1]);
pData[2] = RGBComponentToSRGB(pData[2]);
}
}
}
}
SaveScreenshot(rgb_data, screenshotWidth, screenshotHeight, !padView);
}
void OpenGLRenderer::DrawBackbufferQuad(LatteTextureView* texView, RendererOutputShader* shader, bool useLinearTexFilter, sint32 imageX, sint32 imageY, sint32 imageWidth, sint32 imageHeight, bool padView, bool clearBackground)
{
if (padView && !IsPadWindowActive())
return;
catchOpenGLError();
GLCanvas_MakeCurrent(padView);
renderstate_resetColorControl();
renderstate_resetDepthControl();
attributeStream_reset();
// bind back buffer
rendertarget_bindFramebufferObject(nullptr);
if (clearBackground)
{
int windowWidth, windowHeight;
if (padView)
gui_getPadWindowPhysSize(windowWidth, windowHeight);
else
gui_getWindowPhysSize(windowWidth, windowHeight);
g_renderer->renderTarget_setViewport(0, 0, windowWidth, windowHeight, 0.0f, 1.0f);
g_renderer->ClearColorbuffer(padView);
}
sint32 effectiveWidth, effectiveHeight;
texView->baseTexture->GetEffectiveSize(effectiveWidth, effectiveHeight, 0);
shader_unbind(RendererShader::ShaderType::kGeometry);
shader_bind(shader->GetVertexShader());
shader_bind(shader->GetFragmentShader());
shader->SetUniformParameters(*texView, { effectiveWidth, effectiveHeight }, { imageWidth, imageHeight });
// set viewport
glViewportIndexedf(0, imageX, imageY, imageWidth, imageHeight);
LatteTextureViewGL* texViewGL = (LatteTextureViewGL*)texView;
texture_bindAndActivate(texView, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, useLinearTexFilter ? GL_LINEAR : GL_NEAREST);
texViewGL->samplerState.filterMag = 0xFFFFFFFF;
if ((!padView && !LatteGPUState.tvBufferUsesSRGB) || (padView && !LatteGPUState.drcBufferUsesSRGB))
glDisable(GL_FRAMEBUFFER_SRGB);
uint16 indexData[6] = { 0,1,2,3,4,5 };
glDrawRangeElements(GL_TRIANGLES, 0, 5, 6, GL_UNSIGNED_SHORT, indexData);
if ((!padView && !LatteGPUState.tvBufferUsesSRGB) || (padView && !LatteGPUState.drcBufferUsesSRGB))
glEnable(GL_FRAMEBUFFER_SRGB);
// unbind texture
texture_bindAndActivate(nullptr, 0);
catchOpenGLError();
// restore viewport
glViewportIndexedf(0, prevViewportX, prevViewportY, prevViewportWidth, prevViewportHeight);
// switch back to TV context
if (padView)
GLCanvas_MakeCurrent(false);
}
void OpenGLRenderer::renderTarget_setViewport(float x, float y, float width, float height, float nearZ, float farZ, bool halfZ /*= false*/)
{
if (prevNearZ != nearZ || prevFarZ != farZ || _prevHalfZ != halfZ)
{
if (*(uint32*)&farZ == 0x3f7fffff)
*(uint32*)&farZ = 0x3f800000;
if (glDepthRangedNV)
glDepthRangedNV(nearZ, farZ);
else
glDepthRange(nearZ, farZ);
prevNearZ = nearZ;
prevFarZ = farZ;
}
bool invertY = false;
if (height < 0.0)
{
invertY = true;
y += height;
height = -height;
}
if (glClipControl && (_prevInvertY != invertY || _prevHalfZ != halfZ))
{
GLenum clipDepth = halfZ ? GL_ZERO_TO_ONE : GL_NEGATIVE_ONE_TO_ONE;
if (invertY)
glClipControl(GL_LOWER_LEFT, clipDepth); // OpenGL style
else
glClipControl(GL_UPPER_LEFT, clipDepth); // DX style (default for GX2)
_prevInvertY = invertY;
_prevHalfZ = halfZ;
}
if (prevViewportX == x && prevViewportY == y && prevViewportWidth == width && prevViewportHeight == height)
return; // viewport did not change
glViewportIndexedf(0, x, y, width, height);
prevViewportX = x;
prevViewportY = y;
prevViewportWidth = width;
prevViewportHeight = height;
}
void OpenGLRenderer::renderTarget_setScissor(sint32 scissorX, sint32 scissorY, sint32 scissorWidth, sint32 scissorHeight)
{
if (prevScissorEnable != true)
{
// enable scissor box
glEnable(GL_SCISSOR_TEST);
prevScissorEnable = true;
}
glScissor(scissorX, scissorY, scissorWidth, scissorHeight);
}
LatteCachedFBO* OpenGLRenderer::rendertarget_createCachedFBO(uint64 key)
{
return new CachedFBOGL(key);
}
void OpenGLRenderer::rendertarget_deleteCachedFBO(LatteCachedFBO* cfbo)
{
auto cfboGL = (CachedFBOGL*)cfbo;
if (prevBoundFBO == cfboGL->glId_fbo)
{
glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
prevBoundFBO = 0;
}
glDeleteFramebuffers(1, &cfboGL->glId_fbo);
}
// set active FBO
void OpenGLRenderer::rendertarget_bindFramebufferObject(LatteCachedFBO* cfbo)
{
GLuint fboid;
if (cfbo)
{
const auto cfboGL = (CachedFBOGL*)cfbo;
fboid = cfboGL->glId_fbo;
}
else
fboid = 0;
if (prevBoundFBO != fboid)
{
glBindFramebuffer(GL_FRAMEBUFFER_EXT, fboid);
prevBoundFBO = fboid;
}
}
void OpenGLRenderer::renderstate_setChannelTargetMask(uint32 renderTargetMask)
{
if (renderTargetMask != prevTargetColorMask)
{
for (sint32 i = 0; i < 8; i++)
{
uint32 targetRGBAMask = ((renderTargetMask >> (i * 4)) & 0xF);
if (targetRGBAMask != ((prevTargetColorMask >> (i * 4)) & 0xF))
{
// update color mask
glColorMaski(i, (targetRGBAMask & 1) ? GL_TRUE : GL_FALSE, (targetRGBAMask & 2) ? GL_TRUE : GL_FALSE, (targetRGBAMask & 4) ? GL_TRUE : GL_FALSE, (targetRGBAMask & 8) ? GL_TRUE : GL_FALSE);
}
}
prevTargetColorMask = renderTargetMask;
}
}
void OpenGLRenderer::renderstate_setAlwaysWriteDepth()
{
if (prevDepthEnable == 0)
{
glEnable(GL_DEPTH_TEST);
prevDepthEnable = 1;
}
glDepthFunc(GL_ALWAYS);
prevDepthFunc = Latte::LATTE_DB_DEPTH_CONTROL::E_ZFUNC::ALWAYS;
}
static const GLuint table_glBlendSrcDst[] =
{
/* 0x00 */ GL_ZERO,
/* 0x01 */ GL_ONE,
/* 0x02 */ GL_SRC_COLOR,
/* 0x03 */ GL_ONE_MINUS_SRC_COLOR,
/* 0x04 */ GL_SRC_ALPHA,
/* 0x05 */ GL_ONE_MINUS_SRC_ALPHA,
/* 0x06 */ GL_DST_ALPHA,
/* 0x07 */ GL_ONE_MINUS_DST_ALPHA,
/* 0x08 */ GL_DST_COLOR,
/* 0x09 */ GL_ONE_MINUS_DST_COLOR,
/* 0x0A */ GL_SRC_ALPHA_SATURATE,
/* 0x0B */ 0xFFFFFFFF,
/* 0x0C */ 0xFFFFFFFF,
/* 0x0D */ GL_CONSTANT_COLOR,
/* 0x0E */ GL_ONE_MINUS_CONSTANT_COLOR,
/* 0x0F */ GL_SRC1_COLOR,
/* 0x10 */ GL_ONE_MINUS_SRC1_COLOR,
/* 0x11 */ GL_SRC1_ALPHA,
/* 0x12 */ GL_ONE_MINUS_SRC1_ALPHA,
/* 0x13 */ GL_CONSTANT_ALPHA,
/* 0x14 */ GL_ONE_MINUS_CONSTANT_ALPHA
};
static GLuint GetGLBlendFactor(Latte::LATTE_CB_BLENDN_CONTROL::E_BLENDFACTOR blendFactor)
{
uint32 blendFactorU = (uint32)blendFactor;
if (blendFactorU >= 0xF && blendFactorU <= 0x12)
{
debug_printf("Unsupported dual-source blending used\n");
cemu_assert_debug(false); // dual-source blending
return GL_ZERO;
}
if (blendFactorU >= (sizeof(table_glBlendSrcDst) / sizeof(table_glBlendSrcDst[0])))
{
debug_printf("GetGLBlendFactor: Constant 0x%x out of range\n", blendFactor);
return GL_ZERO;
}
if (table_glBlendSrcDst[blendFactorU] == -1)
{
debug_printf("GetGLBlendFactor: Constant 0x%x is invalid\n", blendFactor);
cemu_assert_debug(false);
return GL_ZERO;
}
return table_glBlendSrcDst[blendFactorU];
}
static const GLuint table_glBlendCombine[] =
{
GL_FUNC_ADD,
GL_FUNC_SUBTRACT,
GL_MIN,
GL_MAX,
GL_FUNC_REVERSE_SUBTRACT
};
GLuint GetGLBlendCombineFunc(Latte::LATTE_CB_BLENDN_CONTROL::E_COMBINEFUNC combineFunc)
{
uint32 combineFuncU = (uint32)combineFunc;
if (combineFuncU >= (sizeof(table_glBlendCombine) / sizeof(table_glBlendCombine[0])))
{
cemu_assert_suspicious();
return GL_FUNC_ADD;
}
return table_glBlendCombine[combineFuncU];
}
void* OpenGLRenderer::texture_acquireTextureUploadBuffer(uint32 size)
{
if (glRendererState.useTextureUploadBuffer)
{
glRendererState.texWorkBuffer = LatteRingBuffer_allocate(glRendererState.uploadRingBuffer, size, 1024);
glRendererState.texWorkBufferSize = size;
return glRendererState.texWorkBuffer;
}
// static memory buffer
if (glRendererState.texUploadBuffer.size() < size)
{
glRendererState.texUploadBuffer.resize(size);
}
return glRendererState.texUploadBuffer.data();
}
void OpenGLRenderer::texture_releaseTextureUploadBuffer(uint8* mem)
{
// do nothing
}
TextureDecoder* OpenGLRenderer::texture_chooseDecodedFormat(Latte::E_GX2SURFFMT format, bool isDepth, Latte::E_DIM dim, uint32 width, uint32 height)
{
TextureDecoder* texDecoder = nullptr;
if (isDepth)
{
if (format == Latte::E_GX2SURFFMT::R32_FLOAT)
{
return TextureDecoder_R32_FLOAT::getInstance();
}
if (format == Latte::E_GX2SURFFMT::D24_S8_UNORM)
{
return TextureDecoder_D24_S8::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::D24_S8_FLOAT)
{
return TextureDecoder_NullData64::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::D32_S8_FLOAT)
{
return TextureDecoder_D32_S8_UINT_X24::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::R32_FLOAT)
{
return TextureDecoder_R32_FLOAT::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::R16_UNORM)
{
return TextureDecoder_R16_FLOAT::getInstance();
}
return nullptr;
}
if (format == Latte::E_GX2SURFFMT::R4_G4_UNORM)
texDecoder = TextureDecoder_R4_G4_UNORM_To_RGBA4::getInstance();
else if (format == Latte::E_GX2SURFFMT::R4_G4_B4_A4_UNORM)
texDecoder = TextureDecoder_R4_G4_B4_A4_UNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT)
texDecoder = TextureDecoder_R16_G16_B16_A16_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_FLOAT)
texDecoder = TextureDecoder_R16_G16_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_SNORM)
texDecoder = TextureDecoder_R16_SNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_FLOAT)
texDecoder = TextureDecoder_R16_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_FLOAT)
texDecoder = TextureDecoder_R32_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC1_UNORM)
texDecoder = TextureDecoder_BC1::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC1_SRGB)
texDecoder = TextureDecoder_BC1::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC2_UNORM)
texDecoder = TextureDecoder_BC2_UNORM_uncompress::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC2_SRGB)
texDecoder = TextureDecoder_BC2_SRGB_uncompress::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC3_UNORM)
texDecoder = TextureDecoder_BC3::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC3_SRGB)
texDecoder = TextureDecoder_BC3::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC4_UNORM)
{
if (dim != Latte::E_DIM::DIM_2D && dim != Latte::E_DIM::DIM_2D_ARRAY)
texDecoder = TextureDecoder_BC4_UNORM_uncompress::getInstance();
else
texDecoder = TextureDecoder_BC4::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::BC4_SNORM)
{
if (dim != Latte::E_DIM::DIM_2D && dim != Latte::E_DIM::DIM_2D_ARRAY)
texDecoder = TextureDecoder_BC4::getInstance();
else
texDecoder = TextureDecoder_BC4_UNORM_uncompress::getInstance();
}
else if (format == Latte::E_GX2SURFFMT::BC5_UNORM)
texDecoder = TextureDecoder_BC5::getInstance();
else if (format == Latte::E_GX2SURFFMT::BC5_SNORM)
texDecoder = TextureDecoder_BC5::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM)
texDecoder = TextureDecoder_R8_G8_B8_A8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SNORM)
texDecoder = TextureDecoder_R8_G8_B8_A8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB)
texDecoder = TextureDecoder_R8_G8_B8_A8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_UNORM)
texDecoder = TextureDecoder_R8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_SNORM)
texDecoder = TextureDecoder_R8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_UNORM)
texDecoder = TextureDecoder_R8_G8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_SNORM)
texDecoder = TextureDecoder_R8_G8::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_UNORM)
texDecoder = TextureDecoder_R16_UNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_B16_A16_UNORM)
texDecoder = TextureDecoder_R16_G16_B16_A16::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_B16_A16_SNORM)
texDecoder = TextureDecoder_R16_G16_B16_A16::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_UNORM)
texDecoder = TextureDecoder_R16_G16::getInstance();
else if (format == Latte::E_GX2SURFFMT::R5_G6_B5_UNORM)
texDecoder = TextureDecoder_R5_G6_B5::getInstance();
else if (format == Latte::E_GX2SURFFMT::R5_G5_B5_A1_UNORM)
texDecoder = TextureDecoder_R5_G5_B5_A1_UNORM_swappedOpenGL::getInstance();
else if (format == Latte::E_GX2SURFFMT::A1_B5_G5_R5_UNORM)
texDecoder = TextureDecoder_A1_B5_G5_R5_UNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_G32_FLOAT)
texDecoder = TextureDecoder_R32_G32_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_G32_UINT)
texDecoder = TextureDecoder_R32_G32_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_UINT)
texDecoder = TextureDecoder_R32_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_UINT)
texDecoder = TextureDecoder_R16_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_UINT)
texDecoder = TextureDecoder_R8_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_G32_B32_A32_FLOAT)
texDecoder = TextureDecoder_R32_G32_B32_A32_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R10_G10_B10_A2_UNORM)
texDecoder = TextureDecoder_R10_G10_B10_A2_UNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::A2_B10_G10_R10_UNORM)
texDecoder = TextureDecoder_A2_B10_G10_R10_UNORM_To_RGBA16::getInstance();
else if (format == Latte::E_GX2SURFFMT::R10_G10_B10_A2_SNORM)
texDecoder = TextureDecoder_R10_G10_B10_A2_SNORM_To_RGBA16::getInstance();
else if (format == Latte::E_GX2SURFFMT::R10_G10_B10_A2_SRGB)
texDecoder = TextureDecoder_R10_G10_B10_A2_UNORM::getInstance();
else if (format == Latte::E_GX2SURFFMT::R11_G11_B10_FLOAT)
texDecoder = TextureDecoder_R11_G11_B10_FLOAT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R32_G32_B32_A32_UINT)
texDecoder = TextureDecoder_R32_G32_B32_A32_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R16_G16_B16_A16_UINT)
texDecoder = TextureDecoder_R16_G16_B16_A16_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UINT)
texDecoder = TextureDecoder_R8_G8_B8_A8_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::R24_X8_UNORM)
texDecoder = TextureDecoder_R24_X8::getInstance();
else if (format == Latte::E_GX2SURFFMT::X24_G8_UINT)
texDecoder = TextureDecoder_X24_G8_UINT::getInstance();
else if (format == Latte::E_GX2SURFFMT::D32_S8_FLOAT)
texDecoder = TextureDecoder_D32_S8_UINT_X24::getInstance();
else
cemu_assert_debug(false);
cemu_assert_debug(!isDepth);
return texDecoder;
}
// use standard API to upload texture data
void OpenGLRenderer_texture_loadSlice_normal(LatteTexture* hostTextureGeneric, sint32 width, sint32 height, sint32 depth, void* pixelData, sint32 sliceIndex, sint32 mipIndex, uint32 imageSize)
{
auto hostTexture = (LatteTextureGL*)hostTextureGeneric;
sint32 effectiveWidth = width;
sint32 effectiveHeight = height;
sint32 effectiveDepth = depth;
cemu_assert_debug(hostTexture->overwriteInfo.hasResolutionOverwrite == false); // not supported in _loadSlice
cemu_assert_debug(hostTexture->overwriteInfo.hasFormatOverwrite == false); // not supported in _loadSlice
// get format info
LatteTextureGL::FormatInfoGL glFormatInfo;
LatteTextureGL::GetOpenGLFormatInfo(hostTexture->isDepth, hostTexture->overwriteInfo.hasFormatOverwrite ? (Latte::E_GX2SURFFMT)hostTexture->overwriteInfo.format : hostTexture->format, hostTexture->dim, &glFormatInfo);
// upload slice
catchOpenGLError();
if (mipIndex >= hostTexture->maxPossibleMipLevels)
{
cemuLog_logDebug(LogType::Force, "2D texture mip level allocated out of range");
return;
}
if (hostTexture->dim == Latte::E_DIM::DIM_2D || hostTexture->dim == Latte::E_DIM::DIM_2D_MSAA)
{
if (glFormatInfo.glIsCompressed)
glCompressedTextureSubImage2DWrapper(hostTexture->glTexTarget, hostTexture->glId_texture, mipIndex, 0, 0, effectiveWidth, effectiveHeight, glFormatInfo.glInternalFormat, imageSize, pixelData);
else
glTextureSubImage2DWrapper(hostTexture->glTexTarget, hostTexture->glId_texture, mipIndex, 0, 0, effectiveWidth, effectiveHeight, glFormatInfo.glSuppliedFormat, glFormatInfo.glSuppliedFormatType, pixelData);
}
else if (hostTexture->dim == Latte::E_DIM::DIM_1D)
{
if (glFormatInfo.glIsCompressed)
glCompressedTextureSubImage1DWrapper(hostTexture->glTexTarget, hostTexture->glId_texture, mipIndex, 0, width, glFormatInfo.glInternalFormat, imageSize, pixelData);
else
glTextureSubImage1DWrapper(hostTexture->glTexTarget, hostTexture->glId_texture, mipIndex, 0, width, glFormatInfo.glSuppliedFormat, glFormatInfo.glSuppliedFormatType, pixelData);
}
else if (hostTexture->dim == Latte::E_DIM::DIM_2D_ARRAY || hostTexture->dim == Latte::E_DIM::DIM_2D_ARRAY_MSAA ||
hostTexture->dim == Latte::E_DIM::DIM_3D ||
hostTexture->dim == Latte::E_DIM::DIM_CUBEMAP)
{
if (glFormatInfo.glIsCompressed)