-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
GSDeviceMTL.mm
2026 lines (1827 loc) · 82.1 KB
/
GSDeviceMTL.mm
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
/* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2021 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "GSMetalCPPAccessible.h"
#include "GSDeviceMTL.h"
#include "Frontend/MetalHostDisplay.h"
#include "GSTextureMTL.h"
#include "GS/GSPerfMon.h"
#include "HostDisplay.h"
#include <imgui.h>
#ifdef __APPLE__
#include "GSMTLSharedHeader.h"
static constexpr simd::float2 ToSimd(const GSVector2& vec)
{
return simd::make_float2(vec.x, vec.y);
}
GSDevice* MakeGSDeviceMTL()
{
return new GSDeviceMTL();
}
bool GSDeviceMTL::UsageTracker::PrepareForAllocation(u64 last_draw, size_t amt)
{
auto removeme = std::find_if(m_usage.begin(), m_usage.end(), [last_draw](UsageEntry usage){ return usage.drawno > last_draw; });
if (removeme != m_usage.begin())
m_usage.erase(m_usage.begin(), removeme);
bool still_in_use = false;
bool needs_wrap = m_pos + amt > m_size;
if (!m_usage.empty())
{
size_t used = m_usage.front().pos;
if (needs_wrap)
still_in_use = used >= m_pos || used < amt;
else
still_in_use = used >= m_pos && used < m_pos + amt;
}
if (needs_wrap)
m_pos = 0;
return still_in_use || amt > m_size;
}
size_t GSDeviceMTL::UsageTracker::Allocate(u64 current_draw, size_t amt)
{
if (m_usage.empty() || m_usage.back().drawno != current_draw)
m_usage.push_back({current_draw, m_pos});
size_t ret = m_pos;
m_pos += amt;
return ret;
}
void GSDeviceMTL::UsageTracker::Reset(size_t new_size)
{
m_usage.clear();
m_size = new_size;
m_pos = 0;
}
GSDeviceMTL::GSDeviceMTL()
: m_backref(std::make_shared<std::pair<std::mutex, GSDeviceMTL*>>())
, m_dev(nil)
{
m_backref->second = this;
}
GSDeviceMTL::~GSDeviceMTL()
{ @autoreleasepool {
FlushEncoders();
std::lock_guard<std::mutex> guard(m_backref->first);
m_backref->second = nullptr;
}}
GSDeviceMTL::Map GSDeviceMTL::Allocate(UploadBuffer& buffer, size_t amt)
{
amt = (amt + 31) & ~31ull;
u64 last_draw = m_last_finished_draw.load(std::memory_order_acquire);
bool needs_new = buffer.usage.PrepareForAllocation(last_draw, amt);
if (unlikely(needs_new))
{
// Orphan buffer
size_t newsize = std::max<size_t>(buffer.usage.Size() * 2, 4096);
while (newsize < amt)
newsize *= 2;
MTLResourceOptions options = MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined;
buffer.mtlbuffer = MRCTransfer([m_dev.dev newBufferWithLength:newsize options:options]);
pxAssertRel(buffer.mtlbuffer, "Failed to allocate MTLBuffer (out of memory?)");
buffer.buffer = [buffer.mtlbuffer contents];
buffer.usage.Reset(newsize);
}
size_t pos = buffer.usage.Allocate(m_current_draw, amt);
Map ret = {buffer.mtlbuffer, pos, reinterpret_cast<char*>(buffer.buffer) + pos};
ASSERT(pos <= buffer.usage.Size() && "Previous code should have guaranteed there was enough space");
return ret;
}
/// Allocate space in the given buffer for use with the given render command encoder
GSDeviceMTL::Map GSDeviceMTL::Allocate(BufferPair& buffer, size_t amt)
{
amt = (amt + 31) & ~31ull;
u64 last_draw = m_last_finished_draw.load(std::memory_order_acquire);
size_t base_pos = buffer.usage.Pos();
bool needs_new = buffer.usage.PrepareForAllocation(last_draw, amt);
bool needs_upload = needs_new || buffer.usage.Pos() == 0;
if (!m_dev.features.unified_memory && needs_upload)
{
if (base_pos != buffer.last_upload)
{
id<MTLBlitCommandEncoder> enc = GetVertexUploadEncoder();
[enc copyFromBuffer:buffer.cpubuffer
sourceOffset:buffer.last_upload
toBuffer:buffer.gpubuffer
destinationOffset:buffer.last_upload
size:base_pos - buffer.last_upload];
}
buffer.last_upload = 0;
}
if (unlikely(needs_new))
{
// Orphan buffer
size_t newsize = std::max<size_t>(buffer.usage.Size() * 2, 4096);
while (newsize < amt)
newsize *= 2;
MTLResourceOptions options = MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined;
buffer.cpubuffer = MRCTransfer([m_dev.dev newBufferWithLength:newsize options:options]);
pxAssertRel(buffer.cpubuffer, "Failed to allocate MTLBuffer (out of memory?)");
buffer.buffer = [buffer.cpubuffer contents];
buffer.usage.Reset(newsize);
if (!m_dev.features.unified_memory)
{
options = MTLResourceStorageModePrivate | MTLResourceHazardTrackingModeUntracked;
buffer.gpubuffer = MRCTransfer([m_dev.dev newBufferWithLength:newsize options:options]);
pxAssertRel(buffer.gpubuffer, "Failed to allocate MTLBuffer (out of memory?)");
}
}
size_t pos = buffer.usage.Allocate(m_current_draw, amt);
Map ret = {nil, pos, reinterpret_cast<char*>(buffer.buffer) + pos};
ret.gpu_buffer = m_dev.features.unified_memory ? buffer.cpubuffer : buffer.gpubuffer;
ASSERT(pos <= buffer.usage.Size() && "Previous code should have guaranteed there was enough space");
return ret;
}
void GSDeviceMTL::Sync(BufferPair& buffer)
{
if (m_dev.features.unified_memory || buffer.usage.Pos() == buffer.last_upload)
return;
id<MTLBlitCommandEncoder> enc = GetVertexUploadEncoder();
[enc copyFromBuffer:buffer.cpubuffer
sourceOffset:buffer.last_upload
toBuffer:buffer.gpubuffer
destinationOffset:buffer.last_upload
size:buffer.usage.Pos() - buffer.last_upload];
[enc updateFence:m_draw_sync_fence];
buffer.last_upload = buffer.usage.Pos();
}
id<MTLBlitCommandEncoder> GSDeviceMTL::GetTextureUploadEncoder()
{
if (!m_texture_upload_cmdbuf)
{
m_texture_upload_cmdbuf = MRCRetain([m_queue commandBuffer]);
m_texture_upload_encoder = MRCRetain([m_texture_upload_cmdbuf blitCommandEncoder]);
pxAssertRel(m_texture_upload_encoder, "Failed to create texture upload encoder!");
[m_texture_upload_cmdbuf setLabel:@"Texture Upload"];
}
return m_texture_upload_encoder;
}
id<MTLBlitCommandEncoder> GSDeviceMTL::GetLateTextureUploadEncoder()
{
if (!m_late_texture_upload_encoder)
{
EndRenderPass();
m_late_texture_upload_encoder = MRCRetain([GetRenderCmdBuf() blitCommandEncoder]);
pxAssertRel(m_late_texture_upload_encoder, "Failed to create late texture upload encoder!");
[m_late_texture_upload_encoder setLabel:@"Late Texture Upload"];
if (!m_dev.features.unified_memory)
[m_late_texture_upload_encoder waitForFence:m_draw_sync_fence];
}
return m_late_texture_upload_encoder;
}
id<MTLBlitCommandEncoder> GSDeviceMTL::GetVertexUploadEncoder()
{
if (!m_vertex_upload_cmdbuf)
{
m_vertex_upload_cmdbuf = MRCRetain([m_queue commandBuffer]);
m_vertex_upload_encoder = MRCRetain([m_vertex_upload_cmdbuf blitCommandEncoder]);
pxAssertRel(m_vertex_upload_encoder, "Failed to create vertex upload encoder!");
[m_vertex_upload_cmdbuf setLabel:@"Vertex Upload"];
}
return m_vertex_upload_encoder;
}
/// Get the draw command buffer, creating a new one if it doesn't exist
id<MTLCommandBuffer> GSDeviceMTL::GetRenderCmdBuf()
{
if (!m_current_render_cmdbuf)
{
m_encoders_in_current_cmdbuf = 0;
m_current_render_cmdbuf = MRCRetain([m_queue commandBuffer]);
pxAssertRel(m_current_render_cmdbuf, "Failed to create draw command buffer!");
[m_current_render_cmdbuf setLabel:@"Draw"];
}
return m_current_render_cmdbuf;
}
id<MTLCommandBuffer> GSDeviceMTL::GetRenderCmdBufWithoutCreate()
{
return m_current_render_cmdbuf;
}
id<MTLFence> GSDeviceMTL::GetSpinFence()
{
return m_spin_timer ? m_spin_fence : nil;
}
void GSDeviceMTL::DrawCommandBufferFinished(u64 draw, id<MTLCommandBuffer> buffer)
{
// We can do the update non-atomically because we only ever update under the lock
u64 newval = std::max(draw, m_last_finished_draw.load(std::memory_order_relaxed));
m_last_finished_draw.store(newval, std::memory_order_release);
static_cast<MetalHostDisplay*>(g_host_display.get())->AccumulateCommandBufferTime(buffer);
}
void GSDeviceMTL::FlushEncoders()
{
if (!m_current_render_cmdbuf)
return;
EndRenderPass();
Sync(m_vertex_upload_buf);
if (m_dev.features.unified_memory)
{
ASSERT(!m_vertex_upload_cmdbuf && "Should never be used!");
}
else if (m_vertex_upload_cmdbuf)
{
[m_vertex_upload_encoder endEncoding];
[m_vertex_upload_cmdbuf commit];
m_vertex_upload_encoder = nil;
m_vertex_upload_cmdbuf = nil;
}
if (m_texture_upload_cmdbuf)
{
[m_texture_upload_encoder endEncoding];
[m_texture_upload_cmdbuf commit];
m_texture_upload_encoder = nil;
m_texture_upload_cmdbuf = nil;
}
if (m_late_texture_upload_encoder)
{
[m_late_texture_upload_encoder endEncoding];
m_late_texture_upload_encoder = nil;
}
u32 spin_cycles = 0;
constexpr double s_to_ns = 1000000000;
if (m_spin_timer)
{
u32 spin_id;
{
std::lock_guard<std::mutex> guard(m_backref->first);
auto draw = m_spin_manager.DrawSubmitted(m_encoders_in_current_cmdbuf);
u32 constant_offset = 200000 * m_spin_manager.SpinsPerUnitTime(); // 200µs
u32 minimum_spin = 2 * constant_offset; // 400µs (200µs after subtracting constant_offset)
u32 maximum_spin = std::max<u32>(1024, 16000000 * m_spin_manager.SpinsPerUnitTime()); // 16ms
if (draw.recommended_spin > minimum_spin)
spin_cycles = std::min(draw.recommended_spin - constant_offset, maximum_spin);
spin_id = draw.id;
}
[m_current_render_cmdbuf addCompletedHandler:[backref = m_backref, draw = m_current_draw, spin_id](id<MTLCommandBuffer> buf)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
// Starting from kernelStartTime includes time the command buffer spent waiting to execute
// This is useful for avoiding issues on GPUs without async compute (Intel) where spinning
// delays the next command buffer start, which then makes the spin manager think it should spin more
// (If a command buffer contains multiple encoders, the GPU will start before the kernel finishes,
// so we choose kernelStartTime over kernelEndTime)
u64 begin = [buf kernelStartTime] * s_to_ns;
u64 end = [buf GPUEndTime] * s_to_ns;
#pragma clang diagnostic pop
std::lock_guard<std::mutex> guard(backref->first);
if (GSDeviceMTL* dev = backref->second)
{
dev->DrawCommandBufferFinished(draw, buf);
dev->m_spin_manager.DrawCompleted(spin_id, static_cast<u32>(begin), static_cast<u32>(end));
}
}];
}
else
{
[m_current_render_cmdbuf addCompletedHandler:[backref = m_backref, draw = m_current_draw](id<MTLCommandBuffer> buf)
{
std::lock_guard<std::mutex> guard(backref->first);
if (GSDeviceMTL* dev = backref->second)
dev->DrawCommandBufferFinished(draw, buf);
}];
}
[m_current_render_cmdbuf commit];
m_current_render_cmdbuf = nil;
m_current_draw++;
if (spin_cycles)
{
id<MTLCommandBuffer> spinCmdBuf = [m_queue commandBuffer];
[spinCmdBuf setLabel:@"Spin"];
id<MTLComputeCommandEncoder> spinCmdEncoder = [spinCmdBuf computeCommandEncoder];
[spinCmdEncoder setLabel:@"Spin"];
[spinCmdEncoder waitForFence:m_spin_fence];
[spinCmdEncoder setComputePipelineState:m_spin_pipeline];
[spinCmdEncoder setBytes:&spin_cycles length:sizeof(spin_cycles) atIndex:0];
[spinCmdEncoder setBuffer:m_spin_buffer offset:0 atIndex:1];
[spinCmdEncoder dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
[spinCmdEncoder endEncoding];
[spinCmdBuf addCompletedHandler:[backref = m_backref, spin_cycles](id<MTLCommandBuffer> buf)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
u64 begin = [buf GPUStartTime] * s_to_ns;
u64 end = [buf GPUEndTime] * s_to_ns;
#pragma clang diagnostic pop
std::lock_guard<std::mutex> guard(backref->first);
if (GSDeviceMTL* dev = backref->second)
dev->m_spin_manager.SpinCompleted(spin_cycles, static_cast<u32>(begin), static_cast<u32>(end));
}];
[spinCmdBuf commit];
}
}
void GSDeviceMTL::FlushEncodersForReadback()
{
FlushEncoders();
if (@available(macOS 10.15, iOS 10.3, *))
{
if (GSConfig.HWSpinGPUForReadbacks)
{
m_spin_manager.ReadbackRequested();
m_spin_timer = 30;
}
}
}
void GSDeviceMTL::EndRenderPass()
{
if (m_current_render.encoder)
{
EndDebugGroup(m_current_render.encoder);
if (m_spin_timer)
[m_current_render.encoder updateFence:m_spin_fence afterStages:MTLRenderStageFragment];
[m_current_render.encoder endEncoding];
m_current_render.encoder = nil;
memset(&m_current_render, 0, offsetof(MainRenderEncoder, depth_sel));
m_current_render.depth_sel = DepthStencilSelector::NoDepth();
}
}
void GSDeviceMTL::BeginRenderPass(NSString* name, GSTexture* color, MTLLoadAction color_load, GSTexture* depth, MTLLoadAction depth_load, GSTexture* stencil, MTLLoadAction stencil_load)
{
GSTextureMTL* mc = static_cast<GSTextureMTL*>(color);
GSTextureMTL* md = static_cast<GSTextureMTL*>(depth);
GSTextureMTL* ms = static_cast<GSTextureMTL*>(stencil);
bool needs_new = color != m_current_render.color_target
|| depth != m_current_render.depth_target
|| stencil != m_current_render.stencil_target;
GSVector4 color_clear;
float depth_clear;
int stencil_clear;
bool needs_color_clear = false;
bool needs_depth_clear = false;
bool needs_stencil_clear = false;
if (mc) needs_color_clear = mc->GetResetNeedsColorClear(color_clear);
if (md) needs_depth_clear = md->GetResetNeedsDepthClear(depth_clear);
if (ms) needs_stencil_clear = ms->GetResetNeedsStencilClear(stencil_clear);
if (needs_color_clear && color_load != MTLLoadActionDontCare) color_load = MTLLoadActionClear;
if (needs_depth_clear && depth_load != MTLLoadActionDontCare) depth_load = MTLLoadActionClear;
if (needs_stencil_clear && stencil_load != MTLLoadActionDontCare) stencil_load = MTLLoadActionClear;
needs_new |= mc && color_load == MTLLoadActionClear;
needs_new |= md && depth_load == MTLLoadActionClear;
needs_new |= ms && stencil_load == MTLLoadActionClear;
if (!needs_new)
{
if (m_current_render.name != (__bridge void*)name)
{
m_current_render.name = (__bridge void*)name;
[m_current_render.encoder setLabel:name];
}
return;
}
m_encoders_in_current_cmdbuf++;
if (m_late_texture_upload_encoder)
{
[m_late_texture_upload_encoder endEncoding];
m_late_texture_upload_encoder = nullptr;
}
int idx = 0;
if (mc) idx |= 1;
if (md) idx |= 2;
if (ms) idx |= 4;
MTLRenderPassDescriptor* desc = m_render_pass_desc[idx];
if (mc)
{
mc->m_last_write = m_current_draw;
desc.colorAttachments[0].texture = mc->GetTexture();
if (color_load == MTLLoadActionClear)
desc.colorAttachments[0].clearColor = MTLClearColorMake(color_clear.r, color_clear.g, color_clear.b, color_clear.a);
desc.colorAttachments[0].loadAction = color_load;
}
if (md)
{
md->m_last_write = m_current_draw;
desc.depthAttachment.texture = md->GetTexture();
if (depth_load == MTLLoadActionClear)
desc.depthAttachment.clearDepth = depth_clear;
desc.depthAttachment.loadAction = depth_load;
}
if (ms)
{
ms->m_last_write = m_current_draw;
desc.stencilAttachment.texture = ms->GetTexture();
if (stencil_load == MTLLoadActionClear)
desc.stencilAttachment.clearStencil = stencil_clear;
desc.stencilAttachment.loadAction = stencil_load;
}
EndRenderPass();
m_current_render.encoder = MRCRetain([GetRenderCmdBuf() renderCommandEncoderWithDescriptor:desc]);
m_current_render.name = (__bridge void*)name;
[m_current_render.encoder setLabel:name];
if (!m_dev.features.unified_memory)
[m_current_render.encoder waitForFence:m_draw_sync_fence
beforeStages:MTLRenderStageVertex];
m_current_render.color_target = color;
m_current_render.depth_target = depth;
m_current_render.stencil_target = stencil;
pxAssertRel(m_current_render.encoder, "Failed to create render encoder!");
}
void GSDeviceMTL::FrameCompleted()
{
if (m_spin_timer)
m_spin_timer--;
m_spin_manager.NextFrame();
}
static constexpr MTLPixelFormat ConvertPixelFormat(GSTexture::Format format)
{
switch (format)
{
case GSTexture::Format::PrimID: return MTLPixelFormatR32Float;
case GSTexture::Format::UInt32: return MTLPixelFormatR32Uint;
case GSTexture::Format::UInt16: return MTLPixelFormatR16Uint;
case GSTexture::Format::UNorm8: return MTLPixelFormatA8Unorm;
case GSTexture::Format::Color: return MTLPixelFormatRGBA8Unorm;
case GSTexture::Format::HDRColor: return MTLPixelFormatRGBA16Unorm;
case GSTexture::Format::DepthStencil: return MTLPixelFormatDepth32Float_Stencil8;
case GSTexture::Format::Invalid: return MTLPixelFormatInvalid;
case GSTexture::Format::BC1: return MTLPixelFormatBC1_RGBA;
case GSTexture::Format::BC2: return MTLPixelFormatBC2_RGBA;
case GSTexture::Format::BC3: return MTLPixelFormatBC3_RGBA;
case GSTexture::Format::BC7: return MTLPixelFormatBC7_RGBAUnorm;
}
}
GSTexture* GSDeviceMTL::CreateSurface(GSTexture::Type type, int width, int height, int levels, GSTexture::Format format)
{ @autoreleasepool {
MTLPixelFormat fmt = ConvertPixelFormat(format);
pxAssertRel(format != GSTexture::Format::Invalid, "Can't create surface of this format!");
MTLTextureDescriptor* desc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:fmt
width:std::max(1, std::min(width, m_dev.features.max_texsize))
height:std::max(1, std::min(height, m_dev.features.max_texsize))
mipmapped:levels > 1];
if (levels > 1)
[desc setMipmapLevelCount:levels];
[desc setStorageMode:MTLStorageModePrivate];
switch (type)
{
case GSTexture::Type::Texture:
[desc setUsage:MTLTextureUsageShaderRead];
break;
case GSTexture::Type::RenderTarget:
if (m_dev.features.slow_color_compression)
[desc setUsage:MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsagePixelFormatView]; // Force color compression off by including PixelFormatView
else
[desc setUsage:MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget];
break;
case GSTexture::Type::RWTexture:
[desc setUsage:MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite];
break;
default:
[desc setUsage:MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget];
}
MRCOwned<id<MTLTexture>> tex = MRCTransfer([m_dev.dev newTextureWithDescriptor:desc]);
if (tex)
{
GSTextureMTL* t = new GSTextureMTL(this, tex, type, format);
switch (type)
{
case GSTexture::Type::RenderTarget:
ClearRenderTarget(t, 0);
break;
case GSTexture::Type::DepthStencil:
ClearDepth(t);
break;
default:
break;
}
return t;
}
else
{
return nullptr;
}
}}
void GSDeviceMTL::DoMerge(GSTexture* sTex[3], GSVector4* sRect, GSTexture* dTex, GSVector4* dRect, const GSRegPMODE& PMODE, const GSRegEXTBUF& EXTBUF, const GSVector4& c, const bool linear)
{ @autoreleasepool {
id<MTLCommandBuffer> cmdbuf = GetRenderCmdBuf();
GSScopedDebugGroupMTL dbg(cmdbuf, @"DoMerge");
GSVector4 full_r(0.0f, 0.0f, 1.0f, 1.0f);
bool feedback_write_2 = PMODE.EN2 && sTex[2] != nullptr && EXTBUF.FBIN == 1;
bool feedback_write_1 = PMODE.EN1 && sTex[2] != nullptr && EXTBUF.FBIN == 0;
bool feedback_write_2_but_blend_bg = feedback_write_2 && PMODE.SLBG == 1;
ClearRenderTarget(dTex, c);
vector_float4 cb_c = { c.r, c.g, c.b, c.a };
GSMTLConvertPSUniform cb_yuv = {};
cb_yuv.emoda = EXTBUF.EMODA;
cb_yuv.emodc = EXTBUF.EMODC;
if (sTex[1] && (PMODE.SLBG == 0 || feedback_write_2_but_blend_bg))
{
// 2nd output is enabled and selected. Copy it to destination so we can blend it with 1st output
// Note: value outside of dRect must contains the background color (c)
StretchRect(sTex[1], sRect[1], dTex, dRect[1], ShaderConvert::COPY, linear);
}
// Save 2nd output
if (feedback_write_2) // FIXME I'm not sure dRect[1] is always correct
DoStretchRect(dTex, full_r, sTex[2], dRect[1], m_convert_pipeline[static_cast<int>(ShaderConvert::YUV)], linear, LoadAction::DontCareIfFull, &cb_yuv, sizeof(cb_yuv));
if (feedback_write_2_but_blend_bg)
ClearRenderTarget(dTex, c);
if (sTex[0])
{
int idx = (PMODE.AMOD << 1) | PMODE.MMOD;
id<MTLRenderPipelineState> pipeline = m_merge_pipeline[idx];
// 1st output is enabled. It must be blended
if (PMODE.MMOD == 1)
{
// Blend with a constant alpha
DoStretchRect(sTex[0], sRect[0], dTex, dRect[0], pipeline, linear, LoadAction::Load, &cb_c, sizeof(cb_c));
}
else
{
// Blend with 2 * input alpha
DoStretchRect(sTex[0], sRect[0], dTex, dRect[0], pipeline, linear, LoadAction::Load, nullptr, 0);
}
}
if (feedback_write_1) // FIXME I'm not sure dRect[0] is always correct
StretchRect(dTex, full_r, sTex[2], dRect[0], ShaderConvert::YUV, linear);
}}
void GSDeviceMTL::DoInterlace(GSTexture* sTex, GSTexture* dTex, int shader, bool linear, float yoffset, int bufIdx)
{ @autoreleasepool {
id<MTLCommandBuffer> cmdbuf = GetRenderCmdBuf();
GSScopedDebugGroupMTL dbg(cmdbuf, @"DoInterlace");
GSVector4 ds = GSVector4(dTex->GetSize());
GSVector4 sRect(0, 0, 1, 1);
GSVector4 dRect(0.f, yoffset, ds.x, ds.y + yoffset);
GSMTLInterlacePSUniform cb = {};
cb.ZrH = {static_cast<float>(bufIdx), 1.0f / ds.y, ds.y, MAD_SENSITIVITY};
const bool can_discard = shader == 0 || shader == 3;
DoStretchRect(sTex, sRect, dTex, dRect, m_interlace_pipeline[shader], linear, !can_discard ? LoadAction::DontCareIfFull : LoadAction::Load, &cb, sizeof(cb));
}}
void GSDeviceMTL::DoFXAA(GSTexture* sTex, GSTexture* dTex)
{
BeginRenderPass(@"FXAA", dTex, MTLLoadActionDontCare, nullptr, MTLLoadActionDontCare);
RenderCopy(sTex, m_fxaa_pipeline, GSVector4i(0, 0, dTex->GetSize().x, dTex->GetSize().y));
}
void GSDeviceMTL::DoShadeBoost(GSTexture* sTex, GSTexture* dTex, const float params[4])
{
BeginRenderPass(@"ShadeBoost", dTex, MTLLoadActionDontCare, nullptr, MTLLoadActionDontCare);
[m_current_render.encoder setFragmentBytes:params
length:sizeof(float) * 4
atIndex:GSMTLBufferIndexUniforms];
RenderCopy(sTex, m_shadeboost_pipeline, GSVector4i(0, 0, dTex->GetSize().x, dTex->GetSize().y));
}
bool GSDeviceMTL::DoCAS(GSTexture* sTex, GSTexture* dTex, bool sharpen_only, const std::array<u32, NUM_CAS_CONSTANTS>& constants)
{ @autoreleasepool {
static constexpr int threadGroupWorkRegionDim = 16;
const int dispatchX = (dTex->GetWidth() + (threadGroupWorkRegionDim - 1)) / threadGroupWorkRegionDim;
const int dispatchY = (dTex->GetHeight() + (threadGroupWorkRegionDim - 1)) / threadGroupWorkRegionDim;
static_assert(sizeof(constants) == sizeof(GSMTLCASPSUniform));
EndRenderPass();
id<MTLComputeCommandEncoder> enc = [GetRenderCmdBuf() computeCommandEncoder];
[enc setLabel:@"CAS"];
[enc setComputePipelineState:m_cas_pipeline[sharpen_only]];
[enc setTexture:static_cast<GSTextureMTL*>(sTex)->GetTexture() atIndex:0];
[enc setTexture:static_cast<GSTextureMTL*>(dTex)->GetTexture() atIndex:1];
[enc setBytes:&constants length:sizeof(constants) atIndex:GSMTLBufferIndexUniforms];
[enc dispatchThreadgroups:MTLSizeMake(dispatchX, dispatchY, 1)
threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
[enc endEncoding];
return true;
}}
MRCOwned<id<MTLFunction>> GSDeviceMTL::LoadShader(NSString* name)
{
NSError* err = nil;
MRCOwned<id<MTLFunction>> fn = MRCTransfer([m_dev.shaders newFunctionWithName:name constantValues:m_fn_constants error:&err]);
if (unlikely(err))
{
NSString* msg = [NSString stringWithFormat:@"Failed to load shader %@: %@", name, [err localizedDescription]];
Console.Error("%s", [msg UTF8String]);
throw GSRecoverableError();
}
return fn;
}
MRCOwned<id<MTLRenderPipelineState>> GSDeviceMTL::MakePipeline(MTLRenderPipelineDescriptor* desc, id<MTLFunction> vertex, id<MTLFunction> fragment, NSString* name)
{
[desc setLabel:name];
[desc setVertexFunction:vertex];
[desc setFragmentFunction:fragment];
NSError* err;
MRCOwned<id<MTLRenderPipelineState>> res = MRCTransfer([m_dev.dev newRenderPipelineStateWithDescriptor:desc error:&err]);
if (unlikely(err))
{
NSString* msg = [NSString stringWithFormat:@"Failed to create pipeline %@: %@", name, [err localizedDescription]];
Console.Error("%s", [msg UTF8String]);
throw GSRecoverableError();
}
return res;
}
MRCOwned<id<MTLComputePipelineState>> GSDeviceMTL::MakeComputePipeline(id<MTLFunction> compute, NSString* name)
{
MRCOwned<MTLComputePipelineDescriptor*> desc = MRCTransfer([MTLComputePipelineDescriptor new]);
[desc setLabel:name];
[desc setComputeFunction:compute];
NSError* err;
MRCOwned<id<MTLComputePipelineState>> res = MRCTransfer([m_dev.dev
newComputePipelineStateWithDescriptor:desc
options:0
reflection:nil
error:&err]);
if (unlikely(err))
{
NSString* msg = [NSString stringWithFormat:@"Failed to create pipeline %@: %@", name, [err localizedDescription]];
Console.Error("%s", [msg UTF8String]);
throw GSRecoverableError();
}
return res;
}
static void applyAttribute(MTLVertexDescriptor* desc, NSUInteger idx, MTLVertexFormat fmt, NSUInteger offset, NSUInteger buffer_index)
{
MTLVertexAttributeDescriptor* attrs = desc.attributes[idx];
attrs.format = fmt;
attrs.offset = offset;
attrs.bufferIndex = buffer_index;
}
static void setFnConstantB(MTLFunctionConstantValues* fc, bool value, GSMTLFnConstants constant)
{
[fc setConstantValue:&value type:MTLDataTypeBool atIndex:constant];
}
static void setFnConstantI(MTLFunctionConstantValues* fc, unsigned int value, GSMTLFnConstants constant)
{
[fc setConstantValue:&value type:MTLDataTypeUInt atIndex:constant];
}
bool GSDeviceMTL::Create()
{ @autoreleasepool {
if (!GSDevice::Create())
return false;
if (g_host_display->GetRenderAPI() != RenderAPI::Metal)
return false;
if (!g_host_display->HasDevice() || !g_host_display->HasSurface())
return false;
m_dev = *static_cast<const GSMTLDevice*>(g_host_display->GetDevice());
m_queue = MRCRetain((__bridge id<MTLCommandQueue>)g_host_display->GetContext());
MTLPixelFormat layer_px_fmt = [(__bridge CAMetalLayer*)g_host_display->GetSurface() pixelFormat];
m_features.broken_point_sampler = [[m_dev.dev name] containsString:@"AMD"];
m_features.geometry_shader = false;
m_features.vs_expand = true;
m_features.primitive_id = m_dev.features.primid;
m_features.texture_barrier = true;
m_features.provoking_vertex_last = false;
m_features.point_expand = true;
m_features.line_expand = false;
m_features.prefer_new_textures = true;
m_features.dxt_textures = true;
m_features.bptc_textures = true;
m_features.framebuffer_fetch = m_dev.features.framebuffer_fetch;
m_features.dual_source_blend = true;
m_features.clip_control = true;
m_features.stencil_buffer = true;
m_features.cas_sharpening = true;
try
{
// Init metal stuff
m_fn_constants = MRCTransfer([MTLFunctionConstantValues new]);
vector_float2 upscale2 = vector2(GSConfig.UpscaleMultiplier, GSConfig.UpscaleMultiplier);
[m_fn_constants setConstantValue:&upscale2 type:MTLDataTypeFloat2 atIndex:GSMTLConstantIndex_SCALING_FACTOR];
setFnConstantB(m_fn_constants, m_dev.features.framebuffer_fetch, GSMTLConstantIndex_FRAMEBUFFER_FETCH);
m_draw_sync_fence = MRCTransfer([m_dev.dev newFence]);
[m_draw_sync_fence setLabel:@"Draw Sync Fence"];
m_spin_fence = MRCTransfer([m_dev.dev newFence]);
[m_spin_fence setLabel:@"Spin Fence"];
constexpr MTLResourceOptions spin_opts = MTLResourceStorageModePrivate | MTLResourceHazardTrackingModeUntracked;
m_spin_buffer = MRCTransfer([m_dev.dev newBufferWithLength:4 options:spin_opts]);
[m_spin_buffer setLabel:@"Spin Buffer"];
id<MTLCommandBuffer> initCommands = [m_queue commandBuffer];
id<MTLBlitCommandEncoder> clearSpinBuffer = [initCommands blitCommandEncoder];
[clearSpinBuffer fillBuffer:m_spin_buffer range:NSMakeRange(0, 4) value:0];
[clearSpinBuffer updateFence:m_spin_fence];
[clearSpinBuffer endEncoding];
m_spin_pipeline = MakeComputePipeline(LoadShader(@"waste_time"), @"waste_time");
for (int sharpen_only = 0; sharpen_only < 2; sharpen_only++)
{
setFnConstantB(m_fn_constants, sharpen_only, GSMTLConstantIndex_CAS_SHARPEN_ONLY);
NSString* shader = m_dev.features.has_fast_half ? @"CASHalf" : @"CASFloat";
m_cas_pipeline[sharpen_only] = MakeComputePipeline(LoadShader(shader), sharpen_only ? @"CAS Sharpen" : @"CAS Upscale");
}
m_hw_vertex = MRCTransfer([MTLVertexDescriptor new]);
[[[m_hw_vertex layouts] objectAtIndexedSubscript:GSMTLBufferIndexHWVertices] setStride:sizeof(GSVertex)];
applyAttribute(m_hw_vertex, GSMTLAttributeIndexST, MTLVertexFormatFloat2, offsetof(GSVertex, ST), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexC, MTLVertexFormatUChar4, offsetof(GSVertex, RGBAQ.R), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexQ, MTLVertexFormatFloat, offsetof(GSVertex, RGBAQ.Q), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexXY, MTLVertexFormatUShort2, offsetof(GSVertex, XYZ.X), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexZ, MTLVertexFormatUInt, offsetof(GSVertex, XYZ.Z), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexUV, MTLVertexFormatUShort2, offsetof(GSVertex, UV), GSMTLBufferIndexHWVertices);
applyAttribute(m_hw_vertex, GSMTLAttributeIndexF, MTLVertexFormatUChar4Normalized, offsetof(GSVertex, FOG), GSMTLBufferIndexHWVertices);
for (auto& desc : m_render_pass_desc)
{
desc = MRCTransfer([MTLRenderPassDescriptor new]);
[[desc depthAttachment] setStoreAction:MTLStoreActionStore];
[[desc stencilAttachment] setStoreAction:MTLStoreActionStore];
}
// Init samplers
MTLSamplerDescriptor* sdesc = [[MTLSamplerDescriptor new] autorelease];
for (size_t i = 0; i < std::size(m_sampler_hw); i++)
{
GSHWDrawConfig::SamplerSelector sel;
sel.key = i;
const char* minname = sel.biln ? "Ln" : "Pt";
const char* magname = minname;
sdesc.minFilter = sel.biln ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
sdesc.magFilter = sel.biln ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
switch (static_cast<GS_MIN_FILTER>(sel.triln))
{
case GS_MIN_FILTER::Nearest:
case GS_MIN_FILTER::Linear:
sdesc.mipFilter = MTLSamplerMipFilterNotMipmapped;
break;
case GS_MIN_FILTER::Nearest_Mipmap_Nearest:
minname = "PtPt";
sdesc.minFilter = MTLSamplerMinMagFilterNearest;
sdesc.mipFilter = MTLSamplerMipFilterNearest;
break;
case GS_MIN_FILTER::Nearest_Mipmap_Linear:
minname = "PtLn";
sdesc.minFilter = MTLSamplerMinMagFilterNearest;
sdesc.mipFilter = MTLSamplerMipFilterLinear;
break;
case GS_MIN_FILTER::Linear_Mipmap_Nearest:
minname = "LnPt";
sdesc.minFilter = MTLSamplerMinMagFilterLinear;
sdesc.mipFilter = MTLSamplerMipFilterNearest;
break;
case GS_MIN_FILTER::Linear_Mipmap_Linear:
minname = "LnLn";
sdesc.minFilter = MTLSamplerMinMagFilterLinear;
sdesc.mipFilter = MTLSamplerMipFilterLinear;
break;
}
const char* taudesc = sel.tau ? "Repeat" : "Clamp";
const char* tavdesc = sel.tav == sel.tau ? "" : sel.tav ? "Repeat" : "Clamp";
sdesc.sAddressMode = sel.tau ? MTLSamplerAddressModeRepeat : MTLSamplerAddressModeClampToEdge;
sdesc.tAddressMode = sel.tav ? MTLSamplerAddressModeRepeat : MTLSamplerAddressModeClampToEdge;
sdesc.rAddressMode = MTLSamplerAddressModeClampToEdge;
sdesc.maxAnisotropy = GSConfig.MaxAnisotropy && sel.aniso ? GSConfig.MaxAnisotropy : 1;
sdesc.lodMaxClamp = sel.lodclamp ? 0.25f : FLT_MAX;
[sdesc setLabel:[NSString stringWithFormat:@"%s%s %s%s", taudesc, tavdesc, magname, minname]];
m_sampler_hw[i] = MRCTransfer([m_dev.dev newSamplerStateWithDescriptor:sdesc]);
}
// Init depth stencil states
MTLDepthStencilDescriptor* dssdesc = [[MTLDepthStencilDescriptor new] autorelease];
MTLStencilDescriptor* stencildesc = [[MTLStencilDescriptor new] autorelease];
stencildesc.stencilCompareFunction = MTLCompareFunctionAlways;
stencildesc.depthFailureOperation = MTLStencilOperationKeep;
stencildesc.stencilFailureOperation = MTLStencilOperationKeep;
stencildesc.depthStencilPassOperation = MTLStencilOperationReplace;
dssdesc.frontFaceStencil = stencildesc;
dssdesc.backFaceStencil = stencildesc;
[dssdesc setLabel:@"Stencil Write"];
m_dss_stencil_write = MRCTransfer([m_dev.dev newDepthStencilStateWithDescriptor:dssdesc]);
dssdesc.frontFaceStencil.depthStencilPassOperation = MTLStencilOperationZero;
dssdesc.backFaceStencil.depthStencilPassOperation = MTLStencilOperationZero;
[dssdesc setLabel:@"Stencil Zero"];
m_dss_stencil_zero = MRCTransfer([m_dev.dev newDepthStencilStateWithDescriptor:dssdesc]);
stencildesc.stencilCompareFunction = MTLCompareFunctionEqual;
stencildesc.readMask = 1;
stencildesc.writeMask = 1;
for (size_t i = 0; i < std::size(m_dss_hw); i++)
{
GSHWDrawConfig::DepthStencilSelector sel;
sel.key = i;
if (sel.date)
{
if (sel.date_one)
stencildesc.depthStencilPassOperation = MTLStencilOperationZero;
else
stencildesc.depthStencilPassOperation = MTLStencilOperationKeep;
dssdesc.frontFaceStencil = stencildesc;
dssdesc.backFaceStencil = stencildesc;
}
else
{
dssdesc.frontFaceStencil = nil;
dssdesc.backFaceStencil = nil;
}
dssdesc.depthWriteEnabled = sel.zwe ? YES : NO;
static constexpr MTLCompareFunction ztst[] =
{
MTLCompareFunctionNever,
MTLCompareFunctionAlways,
MTLCompareFunctionGreaterEqual,
MTLCompareFunctionGreater,
};
static constexpr const char* ztstname[] =
{
"DepthNever",
"DepthAlways",
"DepthGEq",
"DepthEq",
};
const char* datedesc = sel.date ? (sel.date_one ? " DATE_ONE" : " DATE") : "";
const char* zwedesc = sel.zwe ? " ZWE" : "";
dssdesc.depthCompareFunction = ztst[sel.ztst];
[dssdesc setLabel:[NSString stringWithFormat:@"%s%s%s", ztstname[sel.ztst], zwedesc, datedesc]];
m_dss_hw[i] = MRCTransfer([m_dev.dev newDepthStencilStateWithDescriptor:dssdesc]);
}
// Init HW Vertex Shaders
for (size_t i = 0; i < std::size(m_hw_vs); i++)
{
VSSelector sel;
sel.key = i;
if (sel.point_size && sel.expand != GSMTLExpandType::None)
continue;
setFnConstantB(m_fn_constants, sel.fst, GSMTLConstantIndex_FST);
setFnConstantB(m_fn_constants, sel.iip, GSMTLConstantIndex_IIP);
setFnConstantB(m_fn_constants, sel.point_size, GSMTLConstantIndex_VS_POINT_SIZE);
NSString* shader = @"vs_main";
if (sel.expand != GSMTLExpandType::None)
{
setFnConstantI(m_fn_constants, static_cast<u32>(sel.expand), GSMTLConstantIndex_VS_EXPAND_TYPE);
shader = @"vs_main_expand";
}
m_hw_vs[i] = LoadShader(shader);
}
// Init pipelines
auto vs_convert = LoadShader(@"vs_convert");
auto fs_triangle = LoadShader(@"fs_triangle");
auto ps_copy = LoadShader(@"ps_copy");
auto pdesc = [[MTLRenderPipelineDescriptor new] autorelease];
// FS Triangle Pipelines
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::Color);
m_hdr_resolve_pipeline = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_hdr_resolve"), @"HDR Resolve");
m_fxaa_pipeline = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_fxaa"), @"fxaa");
m_shadeboost_pipeline = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_shadeboost"), @"shadeboost");
m_clut_pipeline[0] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_convert_clut_4"), @"4-bit CLUT Update");
m_clut_pipeline[1] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_convert_clut_8"), @"8-bit CLUT Update");
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::HDRColor);
m_hdr_init_pipeline = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_hdr_init"), @"HDR Init");
pdesc.colorAttachments[0].pixelFormat = MTLPixelFormatInvalid;
pdesc.stencilAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
m_datm_pipeline[0] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_datm0"), @"datm0");
m_datm_pipeline[1] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_datm1"), @"datm1");
m_stencil_clear_pipeline = MakePipeline(pdesc, fs_triangle, nil, @"Stencil Clear");
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::PrimID);
pdesc.stencilAttachmentPixelFormat = MTLPixelFormatInvalid;
pdesc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
m_primid_init_pipeline[1][0] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_primid_init_datm0"), @"PrimID DATM0 Clear");
m_primid_init_pipeline[1][1] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_primid_init_datm1"), @"PrimID DATM1 Clear");
pdesc.depthAttachmentPixelFormat = MTLPixelFormatInvalid;
m_primid_init_pipeline[0][0] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_primid_init_datm0"), @"PrimID DATM0 Clear");
m_primid_init_pipeline[0][1] = MakePipeline(pdesc, fs_triangle, LoadShader(@"ps_primid_init_datm1"), @"PrimID DATM1 Clear");
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::Color);
applyAttribute(pdesc.vertexDescriptor, 0, MTLVertexFormatFloat2, offsetof(ConvertShaderVertex, pos), 0);
applyAttribute(pdesc.vertexDescriptor, 1, MTLVertexFormatFloat2, offsetof(ConvertShaderVertex, texpos), 0);
pdesc.vertexDescriptor.layouts[0].stride = sizeof(ConvertShaderVertex);
for (size_t i = 0; i < std::size(m_interlace_pipeline); i++)
{
NSString* name = [NSString stringWithFormat:@"ps_interlace%zu", i];
m_interlace_pipeline[i] = MakePipeline(pdesc, vs_convert, LoadShader(name), name);
}
for (size_t i = 0; i < std::size(m_convert_pipeline); i++)
{
ShaderConvert conv = static_cast<ShaderConvert>(i);
NSString* name = [NSString stringWithCString:shaderName(conv) encoding:NSUTF8StringEncoding];
switch (conv)
{
case ShaderConvert::COPY:
case ShaderConvert::Count:
case ShaderConvert::DATM_0:
case ShaderConvert::DATM_1:
case ShaderConvert::CLUT_4:
case ShaderConvert::CLUT_8:
case ShaderConvert::HDR_INIT:
case ShaderConvert::HDR_RESOLVE:
continue;
case ShaderConvert::FLOAT32_TO_32_BITS:
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::UInt32);
pdesc.depthAttachmentPixelFormat = MTLPixelFormatInvalid;
break;
case ShaderConvert::FLOAT32_TO_16_BITS:
case ShaderConvert::RGBA8_TO_16_BITS:
pdesc.colorAttachments[0].pixelFormat = ConvertPixelFormat(GSTexture::Format::UInt16);
pdesc.depthAttachmentPixelFormat = MTLPixelFormatInvalid;
break;
case ShaderConvert::DEPTH_COPY:
case ShaderConvert::RGBA8_TO_FLOAT32:
case ShaderConvert::RGBA8_TO_FLOAT24:
case ShaderConvert::RGBA8_TO_FLOAT16:
case ShaderConvert::RGB5A1_TO_FLOAT16:
case ShaderConvert::RGBA8_TO_FLOAT32_BILN:
case ShaderConvert::RGBA8_TO_FLOAT24_BILN:
case ShaderConvert::RGBA8_TO_FLOAT16_BILN:
case ShaderConvert::RGB5A1_TO_FLOAT16_BILN:
pdesc.colorAttachments[0].pixelFormat = MTLPixelFormatInvalid;
pdesc.depthAttachmentPixelFormat = ConvertPixelFormat(GSTexture::Format::DepthStencil);
break;
case ShaderConvert::RGBA_TO_8I: // Yes really
case ShaderConvert::TRANSPARENCY_FILTER:
case ShaderConvert::FLOAT32_TO_RGBA8:
case ShaderConvert::FLOAT16_TO_RGB5A1:
case ShaderConvert::YUV: