-
Notifications
You must be signed in to change notification settings - Fork 808
Expand file tree
/
Copy pathMetalRenderer.cpp
More file actions
2331 lines (1947 loc) · 83.2 KB
/
MetalRenderer.cpp
File metadata and controls
2331 lines (1947 loc) · 83.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Cafe/HW/Latte/Renderer/Metal/MetalRenderer.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalMemoryManager.h"
#include "Cafe/HW/Latte/Renderer/Metal/LatteTextureMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/LatteTextureViewMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/RendererShaderMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/CachedFBOMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalOutputShaderCache.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalPipelineCache.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalDepthStencilCache.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalSamplerCache.h"
#include "Cafe/HW/Latte/Renderer/Metal/LatteTextureReadbackMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalVoidVertexPipeline.h"
#include "Cafe/HW/Latte/Renderer/Metal/MetalQuery.h"
#include "Cafe/HW/Latte/Renderer/Metal/LatteToMtl.h"
#include "Cafe/HW/Latte/Renderer/Metal/UtilityShaderSource.h"
#include "Cafe/HW/Latte/Core/LatteShader.h"
#include "Cafe/HW/Latte/Core/LatteIndices.h"
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
#include "CafeSystem.h"
#include "Cemu/Logging/CemuLogging.h"
#include "Cafe/HW/Latte/Core/FetchShader.h"
#include "Cafe/HW/Latte/Core/LatteConst.h"
#include "config/CemuConfig.h"
#define IMGUI_IMPL_METAL_CPP
#include "imgui/imgui_extension.h"
#include "imgui/imgui_impl_metal.h"
#define EVENT_VALUE_WRAP 4096
extern bool hasValidFramebufferAttached;
float supportBufferData[512 * 4];
// Defined in the OpenGL renderer
void LatteDraw_handleSpecialState8_clearAsDepth();
std::vector<MetalRenderer::DeviceInfo> MetalRenderer::GetDevices()
{
NS_STACK_SCOPED auto devices = MTL::CopyAllDevices();
std::vector<MetalRenderer::DeviceInfo> result;
result.reserve(devices->count());
for (uint32 i = 0; i < devices->count(); i++)
{
MTL::Device* device = static_cast<MTL::Device*>(devices->object(i));
result.push_back({std::string(device->name()->utf8String()), device->registryID()});
}
return result;
}
MetalRenderer::MetalRenderer()
{
// Options
// Position invariance
switch (g_current_game_profile->GetPositionInvariance())
{
case PositionInvariance::Auto:
switch (CafeSystem::GetForegroundTitleId())
{
// Bayonetta
case 0x0005000010157F00: // EUR
case 0x0005000010157E00: // USA
case 0x000500001014DB00: // JPN
// Bayonetta 2
case 0x0005000010172700: // EUR
case 0x0005000010172600: // USA
// Disney Planes
case 0x0005000010136900: // EUR
case 0x0005000010136A00: // EUR (TODO: check)
case 0x0005000010136B00: // EUR (TODO: check)
case 0x000500001011C500: // USA (TODO: check)
// LEGO STAR WARS: The Force Awakens
case 0x00050000101DAA00: // EUR
case 0x00050000101DAB00: // USA
// Mario Kart 8
case 0x000500001010ED00: // EUR
case 0x000500001010EC00: // USA
case 0x000500001010EB00: // JPN
case 0x0005000010183A00: // JPN (TODO: check)
// Minecraft: Story Mode
case 0x000500001020A300: // EUR
case 0x00050000101E0100: // USA
//case 0x000500001020a200: // USA
// Ninja Gaiden 3: Razor's Edge
case 0x0005000010110B00: // EUR
case 0x0005000010139B00: // EUR (TODO: check)
case 0x0005000010110A00: // USA
case 0x0005000010110900: // JPN
// Resident Evil: Revelations
case 0x000500001012B400: // EUR
case 0x000500001012CF00: // USA
// Star Fox Zero
case 0x00050000101B0500: // EUR
case 0x0005000010201C00: // EUR (TODO: check)
case 0x00050000101B0400: // USA
case 0x0005000010201B00: // USA (TODO: check)
// The Legend of Zelda: Breath of the Wild
case 0x00050000101C9500: // EUR
case 0x00050000101C9400: // USA
case 0x00050000101C9300: // JPN
// Wonderful 101
case 0x0005000010135300: // EUR
case 0x000500001012DC00: // USA
case 0x0005000010116300: // JPN
case 0x0005000010185600: // JPN (TODO: check)
m_positionInvariance = true;
break;
default:
m_positionInvariance = false;
break;
}
break;
case PositionInvariance::False:
m_positionInvariance = false;
break;
case PositionInvariance::True:
m_positionInvariance = true;
break;
}
// Pick a device
auto& config = GetConfig();
const bool hasDeviceSet = config.mtl_graphic_device_uuid != 0;
// If a device is set, try to find it
if (hasDeviceSet)
{
NS_STACK_SCOPED auto devices = MTL::CopyAllDevices();
for (uint32 i = 0; i < devices->count(); i++)
{
MTL::Device* device = static_cast<MTL::Device*>(devices->object(i));
if (device->registryID() == config.mtl_graphic_device_uuid)
{
m_device = device;
break;
}
}
}
if (!m_device)
{
if (hasDeviceSet)
{
cemuLog_log(LogType::Force, "The selected GPU ({}) could not be found. Using the system default device.", config.mtl_graphic_device_uuid);
config.mtl_graphic_device_uuid = 0;
}
// Use the system default device
m_device = MTL::CreateSystemDefaultDevice();
}
// Vendor
const char* deviceName = m_device->name()->utf8String();
if (memcmp(deviceName, "Apple", 5) == 0)
m_vendor = GfxVendor::Apple;
else if (memcmp(deviceName, "AMD", 3) == 0)
m_vendor = GfxVendor::AMD;
else if (memcmp(deviceName, "Intel", 5) == 0)
m_vendor = GfxVendor::Intel;
else if (memcmp(deviceName, "NVIDIA", 6) == 0)
m_vendor = GfxVendor::Nvidia;
else
m_vendor = GfxVendor::Generic;
// Feature support
m_isAppleGPU = m_device->supportsFamily(MTL::GPUFamilyApple1);
m_supportsFramebufferFetch = GetConfig().framebuffer_fetch.GetValue() ? m_device->supportsFamily(MTL::GPUFamilyApple2) : false;
m_hasUnifiedMemory = m_device->hasUnifiedMemory();
m_supportsMetal3 = m_device->supportsFamily(MTL::GPUFamilyMetal3);
m_supportsMeshShaders = (m_supportsMetal3 && (m_vendor != GfxVendor::Intel || GetConfig().force_mesh_shaders.GetValue())); // Intel GPUs have issues with mesh shaders
m_recommendedMaxVRAMUsage = m_device->recommendedMaxWorkingSetSize();
m_pixelFormatSupport = MetalPixelFormatSupport(m_device);
CheckForPixelFormatSupport(m_pixelFormatSupport);
// Command queue
m_commandQueue = m_device->newCommandQueue();
// Synchronization resources
m_event = m_device->newEvent();
// Resources
NS_STACK_SCOPED MTL::SamplerDescriptor* samplerDescriptor = MTL::SamplerDescriptor::alloc()->init();
#ifdef CEMU_DEBUG_ASSERT
samplerDescriptor->setLabel(GetLabel("Nearest sampler state", samplerDescriptor));
#endif
m_nearestSampler = m_device->newSamplerState(samplerDescriptor);
samplerDescriptor->setMinFilter(MTL::SamplerMinMagFilterLinear);
samplerDescriptor->setMagFilter(MTL::SamplerMinMagFilterLinear);
#ifdef CEMU_DEBUG_ASSERT
samplerDescriptor->setLabel(GetLabel("Linear sampler state", samplerDescriptor));
#endif
m_linearSampler = m_device->newSamplerState(samplerDescriptor);
// Null resources
NS_STACK_SCOPED MTL::TextureDescriptor* textureDescriptor = MTL::TextureDescriptor::alloc()->init();
textureDescriptor->setTextureType(MTL::TextureType1D);
textureDescriptor->setWidth(1);
textureDescriptor->setUsage(MTL::TextureUsageShaderRead);
m_nullTexture1D = m_device->newTexture(textureDescriptor);
#ifdef CEMU_DEBUG_ASSERT
m_nullTexture1D->setLabel(GetLabel("Null texture 1D", m_nullTexture1D));
#endif
textureDescriptor->setTextureType(MTL::TextureType2D);
textureDescriptor->setHeight(1);
textureDescriptor->setUsage(MTL::TextureUsageShaderRead | MTL::TextureUsageRenderTarget);
m_nullTexture2D = m_device->newTexture(textureDescriptor);
#ifdef CEMU_DEBUG_ASSERT
m_nullTexture2D->setLabel(GetLabel("Null texture 2D", m_nullTexture2D));
#endif
m_memoryManager = new MetalMemoryManager(this);
m_outputShaderCache = new MetalOutputShaderCache(this);
m_pipelineCache = new MetalPipelineCache(this);
m_depthStencilCache = new MetalDepthStencilCache(this);
m_samplerCache = new MetalSamplerCache(this);
// Lower the commit treshold when buffer cache needs reduced latency
if (m_memoryManager->NeedsReducedLatency())
m_defaultCommitTreshlod = 64;
else
m_defaultCommitTreshlod = 196;
// Occlusion queries
m_occlusionQuery.m_resultBuffer = m_device->newBuffer(OCCLUSION_QUERY_POOL_SIZE * sizeof(uint64), MTL::ResourceStorageModeShared);
#ifdef CEMU_DEBUG_ASSERT
m_occlusionQuery.m_resultBuffer->setLabel(GetLabel("Occlusion query result buffer", m_occlusionQuery.m_resultBuffer));
#endif
m_occlusionQuery.m_resultsPtr = (uint64*)m_occlusionQuery.m_resultBuffer->contents();
// Reset vertex and uniform buffers
for (uint32 i = 0; i < MAX_MTL_VERTEX_BUFFERS; i++)
m_state.m_vertexBufferOffsets[i] = INVALID_OFFSET;
for (uint32 i = 0; i < METAL_GENERAL_SHADER_TYPE_TOTAL; i++)
{
for (uint32 j = 0; j < MAX_MTL_BUFFERS; j++)
m_state.m_uniformBufferOffsets[i][j] = INVALID_OFFSET;
}
// Utility shader library
// Create the library
NS::Error* error = nullptr;
NS_STACK_SCOPED MTL::Library* utilityLibrary = m_device->newLibrary(ToNSString(utilityShaderSource), nullptr, &error);
if (error)
{
cemuLog_log(LogType::Force, "failed to create utility library (error: {})", error->localizedDescription()->utf8String());
}
// Pipelines
NS_STACK_SCOPED MTL::Function* vertexFullscreenFunction = utilityLibrary->newFunction(ToNSString("vertexFullscreen"));
NS_STACK_SCOPED MTL::Function* fragmentCopyDepthToColorFunction = utilityLibrary->newFunction(ToNSString("fragmentCopyDepthToColor"));
m_copyDepthToColorDesc = MTL::RenderPipelineDescriptor::alloc()->init();
m_copyDepthToColorDesc->setVertexFunction(vertexFullscreenFunction);
m_copyDepthToColorDesc->setFragmentFunction(fragmentCopyDepthToColorFunction);
// Void vertex pipelines
if (m_isAppleGPU)
m_copyBufferToBufferPipeline = new MetalVoidVertexPipeline(this, utilityLibrary, "vertexCopyBufferToBuffer");
// HACK: for some reason, this variable ends up being initialized to some garbage data, even though its declared as bool m_captureFrame = false;
m_occlusionQuery.m_lastCommandBuffer = nullptr;
m_captureFrame = false;
}
MetalRenderer::~MetalRenderer()
{
if (m_isAppleGPU)
delete m_copyBufferToBufferPipeline;
//delete m_copyTextureToTexturePipeline;
//delete m_restrideBufferPipeline;
m_copyDepthToColorDesc->release();
for (const auto [pixelFormat, pipeline] : m_copyDepthToColorPipelines)
pipeline->release();
delete m_outputShaderCache;
delete m_pipelineCache;
delete m_depthStencilCache;
delete m_samplerCache;
delete m_memoryManager;
m_nullTexture1D->release();
m_nullTexture2D->release();
m_nearestSampler->release();
m_linearSampler->release();
if (m_readbackBuffer)
m_readbackBuffer->release();
if (m_xfbRingBuffer)
m_xfbRingBuffer->release();
m_occlusionQuery.m_resultBuffer->release();
m_event->release();
m_commandQueue->release();
m_device->release();
}
void MetalRenderer::InitializeLayer(const Vector2i& size, bool mainWindow)
{
auto& layer = GetLayer(mainWindow);
layer = MetalLayerHandle(m_device, size, mainWindow);
layer.GetLayer()->setPixelFormat(MTL::PixelFormatBGRA8Unorm);
}
void MetalRenderer::ShutdownLayer(bool mainWindow)
{
GetLayer(mainWindow) = MetalLayerHandle();
}
void MetalRenderer::ResizeLayer(const Vector2i& size, bool mainWindow)
{
GetLayer(mainWindow).Resize(size);
}
void MetalRenderer::Initialize()
{
Renderer::Initialize();
RendererShaderMtl::Initialize();
}
void MetalRenderer::Shutdown()
{
// TODO: should shutdown both layers
ImGui_ImplMetal_Shutdown();
CommitCommandBuffer();
Renderer::Shutdown();
RendererShaderMtl::Shutdown();
}
bool MetalRenderer::IsPadWindowActive()
{
return (GetLayer(false).GetLayer() != nullptr);
}
bool MetalRenderer::GetVRAMInfo(int& usageInMB, int& totalInMB) const
{
// Subtract host memory from total VRAM, since it's shared with the CPU
usageInMB = (m_device->currentAllocatedSize() - m_memoryManager->GetHostAllocationSize()) / 1024 / 1024;
totalInMB = m_recommendedMaxVRAMUsage / 1024 / 1024;
return true;
}
void MetalRenderer::ClearColorbuffer(bool padView)
{
if (!AcquireDrawable(!padView))
return;
ClearColorTextureInternal(GetLayer(!padView).GetDrawable()->texture(), 0, 0, 0.0f, 0.0f, 0.0f, 0.0f);
}
void MetalRenderer::DrawEmptyFrame(bool mainWindow)
{
if (!BeginFrame(mainWindow))
return;
SwapBuffers(mainWindow, !mainWindow);
}
void MetalRenderer::SwapBuffers(bool swapTV, bool swapDRC)
{
if (swapTV)
SwapBuffer(true);
if (swapDRC)
SwapBuffer(false);
// Reset the command buffers (they are released by TemporaryBufferAllocator)
CommitCommandBuffer();
// Debug
m_performanceMonitor.ResetPerFrameData();
// GPU capture
if (m_capturing)
{
EndCapture();
}
else if (m_captureFrame)
{
StartCapture();
m_captureFrame = false;
}
}
void MetalRenderer::HandleScreenshotRequest(LatteTextureView* texView, bool padView) {
if (!m_screenshot_requested && m_screenshot_state == ScreenshotState::None)
return;
if (m_mainLayer.GetDrawable())
{
// 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;
auto texMtl = static_cast<LatteTextureMtl*>(texView->baseTexture);
int width, height;
texMtl->GetEffectiveSize(width, height, 0);
uint32 bytesPerRow = GetMtlTextureBytesPerRow(texMtl->format, texMtl->isDepth, width);
uint32 size = GetMtlTextureBytesPerImage(texMtl->format, texMtl->isDepth, height, bytesPerRow);
auto blitCommandEncoder = GetBlitCommandEncoder();
auto& bufferAllocator = m_memoryManager->GetStagingAllocator();
auto buffer = bufferAllocator.AllocateBufferMemory(size, 1);
blitCommandEncoder->copyFromTexture(texMtl->GetTexture(), 0, 0, MTL::Origin(0, 0, 0), MTL::Size(width, height, 1), buffer.mtlBuffer, buffer.bufferOffset, bytesPerRow, 0);
bool formatValid = true;
std::vector<uint8> rgb_data;
rgb_data.reserve(3 * width * height);
auto pixelFormat = texMtl->GetTexture()->pixelFormat();
// TODO: implement more formats
switch (pixelFormat)
{
case MTL::PixelFormatRGBA8Unorm:
for (auto ptr = buffer.memPtr; ptr < buffer.memPtr + size; ptr += 4)
{
rgb_data.emplace_back(*ptr);
rgb_data.emplace_back(*(ptr + 1));
rgb_data.emplace_back(*(ptr + 2));
}
break;
case MTL::PixelFormatRGBA8Unorm_sRGB:
for (auto ptr = buffer.memPtr; ptr < buffer.memPtr + size; ptr += 4)
{
rgb_data.emplace_back(SRGBComponentToRGB(*ptr));
rgb_data.emplace_back(SRGBComponentToRGB(*(ptr + 1)));
rgb_data.emplace_back(SRGBComponentToRGB(*(ptr + 2)));
}
break;
default:
cemuLog_log(LogType::Force, "Unsupported screenshot texture pixel format {}", pixelFormat);
formatValid = false;
break;
}
if (formatValid)
SaveScreenshot(rgb_data, width, height, !padView);
}
void MetalRenderer::DrawBackbufferQuad(LatteTextureView* texView, RendererOutputShader* shader, bool useLinearTexFilter,
sint32 imageX, sint32 imageY, sint32 imageWidth, sint32 imageHeight,
bool padView, bool clearBackground)
{
if (!AcquireDrawable(!padView))
return;
MTL::Texture* presentTexture = static_cast<LatteTextureViewMtl*>(texView)->GetRGBAView();
// Create render pass
auto& layer = GetLayer(!padView);
NS_STACK_SCOPED MTL::RenderPassDescriptor* renderPassDescriptor = MTL::RenderPassDescriptor::alloc()->init();
auto colorAttachment = renderPassDescriptor->colorAttachments()->object(0);
colorAttachment->setTexture(layer.GetDrawable()->texture());
colorAttachment->setLoadAction(clearBackground ? MTL::LoadActionClear : MTL::LoadActionLoad);
colorAttachment->setStoreAction(MTL::StoreActionStore);
auto renderCommandEncoder = GetTemporaryRenderCommandEncoder(renderPassDescriptor);
// Get a render pipeline
// Find out which shader we are using
uint8 shaderIndex = 255;
if (shader == RendererOutputShader::s_copy_shader) shaderIndex = 0;
else if (shader == RendererOutputShader::s_bicubic_shader) shaderIndex = 1;
else if (shader == RendererOutputShader::s_hermit_shader) shaderIndex = 2;
else if (shader == RendererOutputShader::s_copy_shader_ud) shaderIndex = 3;
else if (shader == RendererOutputShader::s_bicubic_shader_ud) shaderIndex = 4;
else if (shader == RendererOutputShader::s_hermit_shader_ud) shaderIndex = 5;
uint8 shaderType = shaderIndex % 3;
// Get the render pipeline state
auto renderPipelineState = m_outputShaderCache->GetPipeline(shader, shaderIndex, m_state.m_usesSRGB);
// Draw to Metal layer
renderCommandEncoder->setRenderPipelineState(renderPipelineState);
renderCommandEncoder->setFragmentTexture(presentTexture, 0);
renderCommandEncoder->setFragmentSamplerState((useLinearTexFilter ? m_linearSampler : m_nearestSampler), 0);
// Set uniforms
float outputSize[2] = {(float)imageWidth, (float)imageHeight};
switch (shaderType)
{
case 2:
renderCommandEncoder->setFragmentBytes(outputSize, sizeof(outputSize), 0);
break;
default:
break;
}
renderCommandEncoder->setViewport(MTL::Viewport{(double)imageX, (double)imageY, (double)imageWidth, (double)imageHeight, 0.0, 1.0});
renderCommandEncoder->setScissorRect(MTL::ScissorRect{(uint32)imageX, (uint32)imageY, (uint32)imageWidth, (uint32)imageHeight});
renderCommandEncoder->drawPrimitives(MTL::PrimitiveTypeTriangle, NS::UInteger(0), NS::UInteger(3));
EndEncoding();
}
bool MetalRenderer::BeginFrame(bool mainWindow)
{
return AcquireDrawable(mainWindow);
}
void MetalRenderer::Flush(bool waitIdle)
{
if (m_recordedDrawcalls > 0 || waitIdle)
CommitCommandBuffer();
if (waitIdle && m_executingCommandBuffers.size() != 0)
m_executingCommandBuffers.back()->waitUntilCompleted();
}
void MetalRenderer::NotifyLatteCommandProcessorIdle()
{
//if (m_commitOnIdle)
// CommitCommandBuffer();
}
bool MetalRenderer::ImguiBegin(bool mainWindow)
{
if (!Renderer::ImguiBegin(mainWindow))
return false;
if (!AcquireDrawable(mainWindow))
return false;
EnsureImGuiBackend();
// Check if the font texture needs to be built
ImGuiIO& io = ImGui::GetIO();
if (!io.Fonts->IsBuilt())
ImGui_ImplMetal_CreateFontsTexture(m_device);
auto& layer = GetLayer(mainWindow);
// Render pass descriptor
NS_STACK_SCOPED MTL::RenderPassDescriptor* renderPassDescriptor = MTL::RenderPassDescriptor::alloc()->init();
auto colorAttachment = renderPassDescriptor->colorAttachments()->object(0);
colorAttachment->setTexture(layer.GetDrawable()->texture());
colorAttachment->setLoadAction(MTL::LoadActionLoad);
colorAttachment->setStoreAction(MTL::StoreActionStore);
// New frame
ImGui_ImplMetal_NewFrame(renderPassDescriptor);
ImGui_UpdateWindowInformation(mainWindow);
ImGui::NewFrame();
if (m_encoderType != MetalEncoderType::Render)
GetTemporaryRenderCommandEncoder(renderPassDescriptor);
return true;
}
void MetalRenderer::ImguiEnd()
{
EnsureImGuiBackend();
if (m_encoderType != MetalEncoderType::Render)
{
cemuLog_logOnce(LogType::Force, "no render command encoder, cannot draw ImGui");
return;
}
ImGui::Render();
ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), GetCurrentCommandBuffer(), (MTL::RenderCommandEncoder*)m_commandEncoder);
//ImGui::EndFrame();
EndEncoding();
}
ImTextureID MetalRenderer::GenerateTexture(const std::vector<uint8>& data, const Vector2i& size)
{
try
{
std::vector <uint8> tmp(size.x * size.y * 4);
for (size_t i = 0; i < data.size() / 3; ++i)
{
tmp[(i * 4) + 0] = data[(i * 3) + 0];
tmp[(i * 4) + 1] = data[(i * 3) + 1];
tmp[(i * 4) + 2] = data[(i * 3) + 2];
tmp[(i * 4) + 3] = 0xFF;
}
NS_STACK_SCOPED MTL::TextureDescriptor* desc = MTL::TextureDescriptor::alloc()->init();
desc->setTextureType(MTL::TextureType2D);
desc->setPixelFormat(MTL::PixelFormatRGBA8Unorm);
desc->setWidth(size.x);
desc->setHeight(size.y);
desc->setStorageMode(m_isAppleGPU ? MTL::StorageModeShared : MTL::StorageModeManaged);
desc->setUsage(MTL::TextureUsageShaderRead);
MTL::Texture* texture = m_device->newTexture(desc);
// TODO: do a GPU copy?
texture->replaceRegion(MTL::Region(0, 0, size.x, size.y), 0, 0, tmp.data(), size.x * 4, 0);
return (ImTextureID)texture;
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "can't generate imgui texture: {}", ex.what());
return nullptr;
}
}
void MetalRenderer::DeleteTexture(ImTextureID id)
{
EnsureImGuiBackend();
((MTL::Texture*)id)->release();
}
void MetalRenderer::DeleteFontTextures()
{
EnsureImGuiBackend();
ImGui_ImplMetal_DestroyFontsTexture();
}
void MetalRenderer::AppendOverlayDebugInfo()
{
ImGui::Text("--- GPU info ---");
ImGui::Text("GPU %s", m_device->name()->utf8String());
ImGui::Text("Is Apple GPU %s", (m_isAppleGPU ? "yes" : "no"));
ImGui::Text("Supports framebuffer fetch %s", (m_supportsFramebufferFetch ? "yes" : "no"));
ImGui::Text("Has unified memory %s", (m_hasUnifiedMemory ? "yes" : "no"));
ImGui::Text("Supports Metal3 %s", (m_supportsMetal3 ? "yes" : "no"));
ImGui::Text("--- Metal info ---");
ImGui::Text("Render pipeline states %zu", m_pipelineCache->GetPipelineCacheSize());
ImGui::Text("--- Metal info (per frame) ---");
ImGui::Text("Command buffers %u", m_performanceMonitor.m_commandBuffers);
ImGui::Text("Render passes %u", m_performanceMonitor.m_renderPasses);
ImGui::Text("Clears %u", m_performanceMonitor.m_clears);
ImGui::Text("Manual vertex fetch draws %u (mesh draws: %u)", m_performanceMonitor.m_manualVertexFetchDraws, m_performanceMonitor.m_meshDraws);
ImGui::Text("Triangle fans %u", m_performanceMonitor.m_triangleFans);
ImGui::Text("--- Cache debug info ---");
uint32 bufferCacheHeapSize = 0;
uint32 bufferCacheAllocationSize = 0;
uint32 bufferCacheNumAllocations = 0;
LatteBufferCache_getStats(bufferCacheHeapSize, bufferCacheAllocationSize, bufferCacheNumAllocations);
ImGui::Text("Buffer");
ImGui::SameLine(60.0f);
ImGui::Text("%06uKB / %06uKB Allocs: %u", (uint32)(bufferCacheAllocationSize + 1023) / 1024, ((uint32)bufferCacheHeapSize + 1023) / 1024, (uint32)bufferCacheNumAllocations);
uint32 numBuffers;
size_t totalSize, freeSize;
m_memoryManager->GetStagingAllocator().GetStats(numBuffers, totalSize, freeSize);
ImGui::Text("Staging");
ImGui::SameLine(60.0f);
ImGui::Text("%06uKB / %06uKB Buffers: %u", ((uint32)(totalSize - freeSize) + 1023) / 1024, ((uint32)totalSize + 1023) / 1024, (uint32)numBuffers);
m_memoryManager->GetIndexAllocator().GetStats(numBuffers, totalSize, freeSize);
ImGui::Text("Index");
ImGui::SameLine(60.0f);
ImGui::Text("%06uKB / %06uKB Buffers: %u", ((uint32)(totalSize - freeSize) + 1023) / 1024, ((uint32)totalSize + 1023) / 1024, (uint32)numBuffers);
}
void MetalRenderer::renderTarget_setViewport(float x, float y, float width, float height, float nearZ, float farZ, bool halfZ)
{
// halfZ is handled in the shader
m_state.m_viewport = MTL::Viewport{x, y, width, height, nearZ, farZ};
}
void MetalRenderer::renderTarget_setScissor(sint32 scissorX, sint32 scissorY, sint32 scissorWidth, sint32 scissorHeight)
{
m_state.m_scissor = MTL::ScissorRect{(uint32)scissorX, (uint32)scissorY, (uint32)scissorWidth, (uint32)scissorHeight};
}
LatteCachedFBO* MetalRenderer::rendertarget_createCachedFBO(uint64 key)
{
return new CachedFBOMtl(this, key);
}
void MetalRenderer::rendertarget_deleteCachedFBO(LatteCachedFBO* cfbo)
{
if (cfbo == (LatteCachedFBO*)m_state.m_activeFBO.m_fbo)
m_state.m_activeFBO = {nullptr};
}
void MetalRenderer::rendertarget_bindFramebufferObject(LatteCachedFBO* cfbo)
{
m_state.m_activeFBO = {(CachedFBOMtl*)cfbo, MetalAttachmentsInfo((CachedFBOMtl*)cfbo)};
m_state.m_fboChanged = true;
}
void* MetalRenderer::texture_acquireTextureUploadBuffer(uint32 size)
{
return m_memoryManager->AcquireTextureUploadBuffer(size);
}
void MetalRenderer::texture_releaseTextureUploadBuffer(uint8* mem)
{
m_memoryManager->ReleaseTextureUploadBuffer(mem);
}
TextureDecoder* MetalRenderer::texture_chooseDecodedFormat(Latte::E_GX2SURFFMT format, bool isDepth, Latte::E_DIM dim, uint32 width, uint32 height)
{
return GetMtlPixelFormatInfo(format, isDepth).textureDecoder;
}
void MetalRenderer::texture_clearSlice(LatteTexture* hostTexture, sint32 sliceIndex, sint32 mipIndex)
{
if (hostTexture->isDepth)
{
texture_clearDepthSlice(hostTexture, sliceIndex, mipIndex, true, hostTexture->hasStencil, 0.0f, 0);
}
else
{
texture_clearColorSlice(hostTexture, sliceIndex, mipIndex, 0.0f, 0.0f, 0.0f, 0.0f);
}
}
// TODO: do a cpu copy on Apple Silicon?
void MetalRenderer::texture_loadSlice(LatteTexture* hostTexture, sint32 width, sint32 height, sint32 depth, void* pixelData, sint32 sliceIndex, sint32 mipIndex, uint32 compressedImageSize)
{
auto textureMtl = (LatteTextureMtl*)hostTexture;
uint32 offsetZ = 0;
if (textureMtl->Is3DTexture())
{
offsetZ = sliceIndex;
sliceIndex = 0;
}
size_t bytesPerRow = GetMtlTextureBytesPerRow(textureMtl->format, textureMtl->isDepth, width);
// No need to set bytesPerImage for 3D textures, since we always load just one slice
//size_t bytesPerImage = GetMtlTextureBytesPerImage(textureMtl->GetFormat(), textureMtl->isDepth, height, bytesPerRow);
//if (m_isAppleGPU)
//{
// textureMtl->GetTexture()->replaceRegion(MTL::Region(0, 0, offsetZ, width, height, 1), mipIndex, sliceIndex, pixelData, bytesPerRow, 0);
//}
//else
//{
auto blitCommandEncoder = GetBlitCommandEncoder();
// Allocate a temporary buffer
auto& bufferAllocator = m_memoryManager->GetStagingAllocator();
auto allocation = bufferAllocator.AllocateBufferMemory(compressedImageSize, 1);
memcpy(allocation.memPtr, pixelData, compressedImageSize);
bufferAllocator.FlushReservation(allocation);
// TODO: specify blit options when copying to a depth stencil texture?
// Copy the data from the temporary buffer to the texture
blitCommandEncoder->copyFromBuffer(allocation.mtlBuffer, allocation.bufferOffset, bytesPerRow, 0, MTL::Size(width, height, 1), textureMtl->GetTexture(), sliceIndex, mipIndex, MTL::Origin(0, 0, offsetZ));
//}
}
void MetalRenderer::texture_clearColorSlice(LatteTexture* hostTexture, sint32 sliceIndex, sint32 mipIndex, float r, float g, float b, float a)
{
if (!FormatIsRenderable(hostTexture->format))
{
cemuLog_logOnce(LogType::Force, "cannot clear color texture with format {}, because it's not renderable", hostTexture->format);
return;
}
auto mtlTexture = static_cast<LatteTextureMtl*>(hostTexture)->GetTexture();
ClearColorTextureInternal(mtlTexture, sliceIndex, mipIndex, r, g, b, a);
}
void MetalRenderer::texture_clearDepthSlice(LatteTexture* hostTexture, uint32 sliceIndex, sint32 mipIndex, bool clearDepth, bool clearStencil, float depthValue, uint32 stencilValue)
{
clearStencil = (clearStencil && GetMtlPixelFormatInfo(hostTexture->format, true).hasStencil);
if (!clearDepth && !clearStencil)
{
cemuLog_logOnce(LogType::Force, "skipping depth/stencil clear");
return;
}
auto mtlTexture = static_cast<LatteTextureMtl*>(hostTexture)->GetTexture();
NS_STACK_SCOPED MTL::RenderPassDescriptor* renderPassDescriptor = MTL::RenderPassDescriptor::alloc()->init();
if (clearDepth)
{
auto depthAttachment = renderPassDescriptor->depthAttachment();
depthAttachment->setTexture(mtlTexture);
depthAttachment->setClearDepth(depthValue);
depthAttachment->setLoadAction(MTL::LoadActionClear);
depthAttachment->setStoreAction(MTL::StoreActionStore);
depthAttachment->setSlice(sliceIndex);
depthAttachment->setLevel(mipIndex);
}
if (clearStencil)
{
auto stencilAttachment = renderPassDescriptor->stencilAttachment();
stencilAttachment->setTexture(mtlTexture);
stencilAttachment->setClearStencil(stencilValue);
stencilAttachment->setLoadAction(MTL::LoadActionClear);
stencilAttachment->setStoreAction(MTL::StoreActionStore);
stencilAttachment->setSlice(sliceIndex);
stencilAttachment->setLevel(mipIndex);
}
GetTemporaryRenderCommandEncoder(renderPassDescriptor);
EndEncoding();
// Debug
m_performanceMonitor.m_clears++;
}
LatteTexture* MetalRenderer::texture_createTextureEx(Latte::E_DIM dim, MPTR physAddress, MPTR physMipAddress, Latte::E_GX2SURFFMT format, uint32 width, uint32 height, uint32 depth, uint32 pitch, uint32 mipLevels, uint32 swizzle, Latte::E_HWTILEMODE tileMode, bool isDepth)
{
return new LatteTextureMtl(this, dim, physAddress, physMipAddress, format, width, height, depth, pitch, mipLevels, swizzle, tileMode, isDepth);
}
void MetalRenderer::texture_setLatteTexture(LatteTextureView* textureView, uint32 textureUnit)
{
m_state.m_textures[textureUnit] = static_cast<LatteTextureViewMtl*>(textureView);
}
void MetalRenderer::texture_copyImageSubData(LatteTexture* src, sint32 srcMip, sint32 effectiveSrcX, sint32 effectiveSrcY, sint32 srcSlice, LatteTexture* dst, sint32 dstMip, sint32 effectiveDstX, sint32 effectiveDstY, sint32 dstSlice, sint32 effectiveCopyWidth, sint32 effectiveCopyHeight, sint32 srcDepth_)
{
// Source size seems to apply to the destination texture as well, therefore we need to adjust it when block size doesn't match
Uvec2 srcBlockTexelSize = GetMtlPixelFormatInfo(src->format, src->isDepth).blockTexelSize;
Uvec2 dstBlockTexelSize = GetMtlPixelFormatInfo(dst->format, dst->isDepth).blockTexelSize;
if (srcBlockTexelSize.x != dstBlockTexelSize.x || srcBlockTexelSize.y != dstBlockTexelSize.y)
{
uint32 multX = (srcBlockTexelSize.x > dstBlockTexelSize.x ? srcBlockTexelSize.x / dstBlockTexelSize.x : dstBlockTexelSize.x / srcBlockTexelSize.x);
effectiveCopyWidth *= multX;
uint32 multY = (srcBlockTexelSize.y > dstBlockTexelSize.y ? srcBlockTexelSize.y / dstBlockTexelSize.y : dstBlockTexelSize.y / srcBlockTexelSize.y);
effectiveCopyHeight *= multY;
}
auto blitCommandEncoder = GetBlitCommandEncoder();
auto mtlSrc = static_cast<LatteTextureMtl*>(src)->GetTexture();
auto mtlDst = static_cast<LatteTextureMtl*>(dst)->GetTexture();
uint32 srcBaseLayer = 0;
uint32 dstBaseLayer = 0;
uint32 srcOffsetZ = 0;
uint32 dstOffsetZ = 0;
uint32 srcLayerCount = 1;
uint32 dstLayerCount = 1;
uint32 srcDepth = 1;
uint32 dstDepth = 1;
if (src->Is3DTexture())
{
srcOffsetZ = srcSlice;
srcDepth = srcDepth_;
}
else
{
srcBaseLayer = srcSlice;
srcLayerCount = srcDepth_;
}
if (dst->Is3DTexture())
{
dstOffsetZ = dstSlice;
dstDepth = srcDepth_;
}
else
{
dstBaseLayer = dstSlice;
dstLayerCount = srcDepth_;
}
// If copying whole textures, we can do a more efficient copy
if (effectiveSrcX == 0 && effectiveSrcY == 0 && effectiveDstX == 0 && effectiveDstY == 0 &&
srcOffsetZ == 0 && dstOffsetZ == 0 &&
effectiveCopyWidth == src->GetMipWidth(srcMip) && effectiveCopyHeight == src->GetMipHeight(srcMip) && srcDepth == src->GetMipDepth(srcMip) &&
effectiveCopyWidth == dst->GetMipWidth(dstMip) && effectiveCopyHeight == dst->GetMipHeight(dstMip) && dstDepth == dst->GetMipDepth(dstMip) &&
srcLayerCount == dstLayerCount)
{
blitCommandEncoder->copyFromTexture(mtlSrc, srcBaseLayer, srcMip, mtlDst, dstBaseLayer, dstMip, srcLayerCount, 1);
}
else
{
if (srcLayerCount == dstLayerCount)
{
for (uint32 i = 0; i < srcLayerCount; i++)
{
blitCommandEncoder->copyFromTexture(mtlSrc, srcBaseLayer + i, srcMip, MTL::Origin(effectiveSrcX, effectiveSrcY, srcOffsetZ), MTL::Size(effectiveCopyWidth, effectiveCopyHeight, srcDepth), mtlDst, dstBaseLayer + i, dstMip, MTL::Origin(effectiveDstX, effectiveDstY, dstOffsetZ));
}
}
else
{
for (uint32 i = 0; i < std::max(srcLayerCount, dstLayerCount); i++)
{
if (srcLayerCount == 1)
srcOffsetZ++;
else
srcSlice++;
if (dstLayerCount == 1)
dstOffsetZ++;
else
dstSlice++;
blitCommandEncoder->copyFromTexture(mtlSrc, srcBaseLayer, srcMip, MTL::Origin(effectiveSrcX, effectiveSrcY, srcOffsetZ), MTL::Size(effectiveCopyWidth, effectiveCopyHeight, 1), mtlDst, dstBaseLayer, dstMip, MTL::Origin(effectiveDstX, effectiveDstY, dstOffsetZ));
}
}
}
}
LatteTextureReadbackInfo* MetalRenderer::texture_createReadback(LatteTextureView* textureView)
{
size_t uploadSize = static_cast<LatteTextureMtl*>(textureView->baseTexture)->GetTexture()->allocatedSize();
if ((m_readbackBufferWriteOffset + uploadSize) > TEXTURE_READBACK_SIZE)
{
m_readbackBufferWriteOffset = 0;
}
auto* result = new LatteTextureReadbackInfoMtl(this, textureView, m_readbackBufferWriteOffset);
m_readbackBufferWriteOffset += uploadSize;
return result;
}
void MetalRenderer::surfaceCopy_copySurfaceWithFormatConversion(LatteTexture* sourceTexture, sint32 srcMip, sint32 srcSlice, LatteTexture* destinationTexture, sint32 dstMip, sint32 dstSlice, sint32 width, sint32 height)
{
// scale copy size to effective size
sint32 effectiveCopyWidth = width;
sint32 effectiveCopyHeight = height;
LatteTexture_scaleToEffectiveSize(sourceTexture, &effectiveCopyWidth, &effectiveCopyHeight, 0);
//sint32 sourceEffectiveWidth, sourceEffectiveHeight;
//sourceTexture->GetEffectiveSize(sourceEffectiveWidth, sourceEffectiveHeight, srcMip);
texture_copyImageSubData(sourceTexture, srcMip, 0, 0, srcSlice, destinationTexture, dstMip, 0, 0, dstSlice, effectiveCopyWidth, effectiveCopyHeight, 1);
}
void MetalRenderer::bufferCache_init(const sint32 bufferSize)
{
m_memoryManager->InitBufferCache(bufferSize);
}
void MetalRenderer::bufferCache_upload(uint8* buffer, sint32 size, uint32 bufferOffset)
{
m_memoryManager->UploadToBufferCache(buffer, bufferOffset, size);
}
void MetalRenderer::bufferCache_copy(uint32 srcOffset, uint32 dstOffset, uint32 size)
{
m_memoryManager->CopyBufferCache(srcOffset, dstOffset, size);
}
void MetalRenderer::bufferCache_copyStreamoutToMainBuffer(uint32 srcOffset, uint32 dstOffset, uint32 size)
{
if (m_memoryManager->UseHostMemoryForCache())
dstOffset -= m_memoryManager->GetImportedMemBaseAddress();
CopyBufferToBuffer(GetXfbRingBuffer(), srcOffset, m_memoryManager->GetBufferCache(), dstOffset, size, MTL::RenderStageVertex | MTL::RenderStageMesh, ALL_MTL_RENDER_STAGES);
}
void MetalRenderer::buffer_bindVertexBuffer(uint32 bufferIndex, uint32 offset, uint32 size)
{
cemu_assert_debug(!m_memoryManager->UseHostMemoryForCache());
cemu_assert_debug(bufferIndex < LATTE_MAX_VERTEX_BUFFERS);
m_state.m_vertexBufferOffsets[bufferIndex] = offset;
}
void MetalRenderer::buffer_bindUniformBuffer(LatteConst::ShaderType shaderType, uint32 bufferIndex, uint32 offset, uint32 size)
{
cemu_assert_debug(!m_memoryManager->UseHostMemoryForCache());
m_state.m_uniformBufferOffsets[GetMtlGeneralShaderType(shaderType)][bufferIndex] = offset;
}
RendererShader* MetalRenderer::shader_create(RendererShader::ShaderType type, uint64 baseHash, uint64 auxHash, const std::string& source, bool isGameShader, bool isGfxPackShader)
{