Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qrhimetal.mm
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qrhimetal_p.h"
7#include "qshader_p.h"
8#include <QGuiApplication>
9#include <QWindow>
10#include <QUrl>
11#include <QFile>
12#include <QTemporaryFile>
13#include <QFileInfo>
14#include <qmath.h>
15#include <QtCore/qendian.h>
16#include <QOperatingSystemVersion>
17
18#include <QtCore/private/qcore_mac_p.h>
19#include <QtGui/private/qmetallayer_p.h>
20#include <QtGui/qpa/qplatformwindow_p.h>
21
22#ifdef Q_OS_MACOS
23#include <AppKit/AppKit.h>
24#else
25#include <UIKit/UIKit.h>
26#endif
27
28#include <QuartzCore/CATransaction.h>
29
30#include <Metal/Metal.h>
31
32#include <utility> // for std::pair
33
35
36/*
37 Metal backend. Double buffers and throttles to vsync. "Dynamic" buffers are
38 Shared (host visible) and duplicated (to help having 2 frames in flight),
39 "static" and "immutable" are Managed on macOS and Shared on iOS/tvOS.
40 Textures are Private (device local) and a host visible staging buffer is
41 used to upload data to them. Does not rely on strong objects refs from
42 command buffers but does rely on the automatic resource tracking of the
43 command encoders. Assumes that an autorelease pool (ideally per frame) is
44 available on the thread on which QRhi is used.
45*/
46
47#if __has_feature(objc_arc)
48#error ARC not supported
49#endif
50
51// Even though the macOS 13 MTLBinaryArchive problem (QTBUG-106703) seems
52// to be solved in later 13.x releases, we have reports from old Intel hardware
53// and older macOS versions where this causes problems (QTBUG-114338).
54// Thus we no longer do OS version based differentiation, but rather have a
55// single toggle that is currently on, and so QRhi::(set)pipelineCache()
56// does nothing with Metal.
57#define QRHI_METAL_DISABLE_BINARY_ARCHIVE
58
59// We should be able to operate with command buffers that do not automatically
60// retain/release the resources used by them. (since we have logic that mirrors
61// other backends such as the Vulkan one anyway)
62#define QRHI_METAL_COMMAND_BUFFERS_WITH_UNRETAINED_REFERENCES
63
64/*!
65 \class QRhiMetalInitParams
66 \inmodule QtGuiPrivate
67 \inheaderfile rhi/qrhi.h
68 \since 6.6
69 \brief Metal specific initialization parameters.
70
71 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
72 for details.
73
74 A Metal-based QRhi needs no special parameters for initialization.
75
76 \badcode
77 QRhiMetalInitParams params;
78 rhi = QRhi::create(QRhi::Metal, &params);
79 \endcode
80
81 \note Metal API validation cannot be enabled programmatically by the QRhi.
82 Instead, either run the debug build of the application in XCode, by
83 generating a \c{.xcodeproj} file via \c{cmake -G Xcode}, or set the
84 environment variable \c{METAL_DEVICE_WRAPPER_TYPE=1}. The variable needs to
85 be set early on in the environment, preferably before starting the process;
86 attempting to set it at QRhi creation time is not functional in practice.
87 (too late probably)
88
89 \note QRhiSwapChain can only target QWindow instances that have their
90 surface type set to QSurface::MetalSurface.
91
92 \section2 Working with existing Metal devices
93
94 When interoperating with another graphics engine, it may be necessary to
95 get a QRhi instance that uses the same Metal device. This can be achieved
96 by passing a pointer to a QRhiMetalNativeHandles to QRhi::create(). The
97 device must be set to a non-null value then. Optionally, a command queue
98 object can be specified as well.
99
100 The QRhi does not take ownership of any of the external objects.
101 */
102
103/*!
104 \class QRhiMetalNativeHandles
105 \inmodule QtGuiPrivate
106 \inheaderfile rhi/qrhi.h
107 \since 6.6
108 \brief Holds the Metal device used by the QRhi.
109
110 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
111 for details.
112 */
113
114/*!
115 \variable QRhiMetalNativeHandles::dev
116
117 Set to a valid MTLDevice to import an existing device.
118*/
119
120/*!
121 \variable QRhiMetalNativeHandles::cmdQueue
122
123 Set to a valid MTLCommandQueue when importing an existing command queue.
124 When \nullptr, QRhi will create a new command queue.
125*/
126
127/*!
128 \class QRhiMetalCommandBufferNativeHandles
129 \inmodule QtGuiPrivate
130 \inheaderfile rhi/qrhi.h
131 \since 6.6
132 \brief Holds the MTLCommandBuffer and MTLRenderCommandEncoder objects that are backing a QRhiCommandBuffer.
133
134 \note The command buffer object is only guaranteed to be valid while
135 recording a frame, that is, between a \l{QRhi::beginFrame()}{beginFrame()}
136 - \l{QRhi::endFrame()}{endFrame()} or
137 \l{QRhi::beginOffscreenFrame()}{beginOffscreenFrame()} -
138 \l{QRhi::endOffscreenFrame()}{endOffscreenFrame()} pair.
139
140 \note The command encoder is only valid while recording a pass, that is,
141 between \l{QRhiCommandBuffer::beginPass()} -
142 \l{QRhiCommandBuffer::endPass()}.
143
144 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
145 for details.
146 */
147
148/*!
149 \variable QRhiMetalCommandBufferNativeHandles::commandBuffer
150*/
151
152/*!
153 \variable QRhiMetalCommandBufferNativeHandles::encoder
154*/
155
157{
160 std::array<uint, 3> localSize = {};
167
168 void destroy() {
169 nativeResourceBindingMap.clear();
170 [lib release];
171 lib = nil;
172 [func release];
173 func = nil;
174 [argumentEncoder release];
175 argumentEncoder = nil;
177 }
178};
179
181{
182 QRhiMetalData(QRhiMetal *rhi) : q(rhi), ofr(rhi) { }
183
188
191 const QColor &colorClearValue,
192 const QRhiDepthStencilClearValue &depthStencilClearValue,
193 int colorAttCount,
194 QRhiShadingRateMap *shadingRateMap);
195 id<MTLLibrary> createMetalLib(const QShader &shader, QShader::Variant shaderVariant,
196 bool preferArgumentBuffers,
197 QString *error, QByteArray *entryPoint, QShaderKey *activeKey);
198 id<MTLFunction> createMSLShaderFunction(id<MTLLibrary> lib, const QByteArray &entryPoint);
199 bool setupBinaryArchive(NSURL *sourceFileUrl = nil);
200 void addRenderPipelineToBinaryArchive(MTLRenderPipelineDescriptor *rpDesc);
201 void trySeedingRenderPipelineFromBinaryArchive(MTLRenderPipelineDescriptor *rpDesc);
202 void addComputePipelineToBinaryArchive(MTLComputePipelineDescriptor *cpDesc);
203 void trySeedingComputePipelineFromBinaryArchive(MTLComputePipelineDescriptor *cpDesc);
204
218 int lastActiveFrameSlot; // -1 if not used otherwise 0..FRAMES_IN_FLIGHT-1
219 union {
220 struct {
221 id<MTLBuffer> buffers[QMTL_FRAMES_IN_FLIGHT];
222 } buffer;
223 struct {
224 id<MTLTexture> texture;
225 } renderbuffer;
226 struct {
227 id<MTLTexture> texture;
228 id<MTLBuffer> stagingBuffers[QMTL_FRAMES_IN_FLIGHT];
229 id<MTLTexture> views[QRhi::MAX_MIP_LEVELS];
230 id<MTLTexture> samplingView;
231 id<MTLTexture> writeView;
232 } texture;
233 struct {
234 id<MTLSamplerState> samplerState;
235 } sampler;
236 struct {
237 id<MTLBuffer> buffer;
238 } stagingBuffer;
239 struct {
240 id<MTLRenderPipelineState> pipelineState;
241 id<MTLDepthStencilState> depthStencilState;
242 std::array<id<MTLComputePipelineState>, 3> tessVertexComputeState;
243 id<MTLComputePipelineState> tessTessControlComputeState;
244 } graphicsPipeline;
245 struct {
246 id<MTLComputePipelineState> pipelineState;
247 } computePipeline;
248 struct {
249 id<MTLRasterizationRateMap> rateMap;
250 } shadingRateMap;
251 struct {
252 id<MTLIndirectCommandBuffer> icb;
253 id<MTLBuffer> argBuffer;
254 } stagingIcbBuffer;
255 };
256 };
258
260 OffscreenFrame(QRhiImplementation *rhi) : cbWrapper(rhi) { }
261 bool active = false;
262 double lastGpuTime = 0;
264 } ofr;
265
274 // Only used for depth(-stencil) textures whose Metal pixel format does
275 // not match the layout of the readback result, where the staging
276 // buffer holds a densely packed depth plane, followed by a densely
277 // packed stencil plane when the format has stencil. See
278 // enqueueResourceUpdates() and finishActiveReadbacks().
281 // Whether the depth plane holds 32-bit floats (as opposed to a
282 // 24-bit unorm value in the low bits of each 32-bit word).
283 bool depthPlaneIsFloat = false;
284 };
286
294
296
299
300 // Indirect Command Buffer (ICB) infrastructure for GPU-driven multi-draw
310 // Written by the encode kernel, consumed by executeCommandsInBuffer.
312 // Holds 0xFFFFFFFF, stands in for the count buffer when there is none.
314 bool icbSetupFailed = false;
315
316 static const int TEXBUF_ALIGN = 256; // probably not accurate
317
318 using ShaderCacheKey = std::pair<QRhiShaderStage, bool>; // stage, argument_buffers
320
329 StagingArea argBufPool[QMTL_FRAMES_IN_FLIGHT];
330 StagingArea bufStagingPool[QMTL_FRAMES_IN_FLIGHT];
331 id<MTLBuffer> allocFromStagingArea(StagingArea *area, quint32 size, quint32 alignment,
332 int frameSlot, quint32 minBlockSize, quint32 *offset);
333 id<MTLBuffer> allocArgumentBuffer(quint32 size, quint32 alignment, int frameSlot, quint32 *offset);
334 id<MTLBuffer> allocBufferStaging(quint32 size, int frameSlot, quint32 *offset);
335 id<MTLBuffer> newOneShotStagingBuffer(quint32 size, int frameSlot);
337
338 // Uploads larger than this always get their own one-shot MTLBuffer and do
339 // not count towards the area's size, so that a one-off large upload cannot
340 // inflate it.
341 static constexpr quint32 LARGE_STAGING_ALLOC = 512 * 1024;
342 static constexpr quint32 STAGING_AREA_MIN = 64 * 1024;
343 static constexpr quint32 STAGING_AREA_MAX = 16 * 1024 * 1024;
344 static constexpr int STAGING_AREA_LOW_DEMAND_FRAMES = 60;
345 static constexpr int STAGING_AREA_HIGH_DEMAND_FRAMES = 3;
346
347 // Counts both swapchain and offscreen frames. Never 0 once a frame started,
348 // so that a default-initialized "used in frame" cannot match.
350};
351
354
356{
357 bool managed = false;
358 bool slotted = false;
359 bool isDeviceLocal = false; // true = MTLResourceStorageModePrivate buf[0], no slotting, non-host visible
360 id<MTLBuffer> buf[QMTL_FRAMES_IN_FLIGHT];
365 QVarLengthArray<BufferUpdate, 16> pendingUpdates[QMTL_FRAMES_IN_FLIGHT];
366};
367
373
395
400
405
433
456
458{
460 float dpr = 1;
461 int sampleCount = 1;
463 int dsAttCount = 0;
464
476
477 struct {
479 id<MTLTexture> dsTex = nil;
480 id<MTLTexture> dsResolveTex = nil;
481 bool hasStencil = false;
482 bool depthNeedsStore = false;
483 bool preserveColor = false;
484 bool preserveDs = false;
485 } fb;
486
488};
489
491{
495 bool icbCapable = false;
516 bool enabled = false;
517 bool failed = false;
525 quint32 vsCompOutputBufferSize(quint32 vertexOrIndexCount, quint32 instanceCount) const
526 {
527 // max vertex output components = resourceLimit(MaxVertexOutputs) * 4 = 60
528 return vertexOrIndexCount * instanceCount * sizeof(float) * 60;
529 }
530 quint32 tescCompOutputBufferSize(quint32 patchCount) const
531 {
532 return outControlPointCount * patchCount * sizeof(float) * 60;
533 }
534 quint32 tescCompPatchOutputBufferSize(quint32 patchCount) const
535 {
536 // assume maxTessellationControlPerPatchOutputComponents is 128
537 return patchCount * sizeof(float) * 128;
538 }
539 quint32 patchCountForDrawCall(quint32 vertexOrIndexCount, quint32 instanceCount) const
540 {
541 return ((vertexOrIndexCount + inControlPointCount - 1) / inControlPointCount) * instanceCount;
542 }
547 } tess;
548 void setupVertexInputDescriptor(MTLVertexDescriptor *desc);
549 void setupStageInputDescriptor(MTLStageInputOutputDescriptor *desc);
550
551 // SPIRV-Cross buffer size buffers
553};
554
556{
560
561 // SPIRV-Cross buffer size buffers
563};
564
576
577QRhiMetal::QRhiMetal(QRhiMetalInitParams *params, QRhiMetalNativeHandles *importDevice)
578{
579 Q_UNUSED(params);
580
581 d = new QRhiMetalData(this);
582
583 importedDevice = importDevice != nullptr;
584 if (importedDevice) {
585 if (importDevice->dev) {
586 d->dev = (id<MTLDevice>) importDevice->dev;
587 importedCmdQueue = importDevice->cmdQueue != nullptr;
588 if (importedCmdQueue)
589 d->cmdQueue = (id<MTLCommandQueue>) importDevice->cmdQueue;
590 } else {
591 qWarning("No MTLDevice given, cannot import");
592 importedDevice = false;
593 }
594 }
595}
596
598{
599 delete d;
600}
601
602template <class Int>
603inline Int aligned(Int v, Int byteAlign)
604{
605 return (v + byteAlign - 1) & ~(byteAlign - 1);
606}
607
608bool QRhiMetal::probe(QRhiMetalInitParams *params)
609{
610 QMacAutoReleasePool pool;
611
612 Q_UNUSED(params);
613 id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
614 if (dev) {
615 [dev release];
616 return true;
617 }
618 return false;
619}
620
622{
624 // Do not let the command buffer mess with the refcount of objects. We do
625 // have a proper render loop and will manage lifetimes similarly to other
626 // backends (Vulkan).
627 return [cmdQueue commandBufferWithUnretainedReferences];
628#else
629 return [cmdQueue commandBuffer];
630#endif
631}
632
633bool QRhiMetalData::setupBinaryArchive(NSURL *sourceFileUrl)
634{
636 return false;
637#endif
638
639 [binArch release];
640 MTLBinaryArchiveDescriptor *binArchDesc = [MTLBinaryArchiveDescriptor new];
641 binArchDesc.url = sourceFileUrl;
642 NSError *err = nil;
643 binArch = [dev newBinaryArchiveWithDescriptor: binArchDesc error: &err];
644 [binArchDesc release];
645 if (!binArch) {
646 const QString msg = QString::fromNSString(err.localizedDescription);
647 qWarning("newBinaryArchiveWithDescriptor failed: %s", qPrintable(msg));
648 return false;
649 }
650 return true;
651}
652
653bool QRhiMetal::create(QRhi::Flags flags)
654{
655 rhiFlags = flags;
656
657 if (importedDevice)
658 [d->dev retain];
659 else
660 d->dev = MTLCreateSystemDefaultDevice();
661
662 if (!d->dev) {
663 qWarning("No MTLDevice");
664 return false;
665 }
666
667 const QString deviceName = QString::fromNSString([d->dev name]);
668 qCDebug(QRHI_LOG_INFO, "Metal device: %s", qPrintable(deviceName));
669 driverInfoStruct.deviceName = deviceName.toUtf8();
670
671 // deviceId and vendorId stay unset for now. Note that registryID is not
672 // suitable as deviceId because it does not seem stable on macOS and can
673 // apparently change when the system is rebooted.
674
675#ifdef Q_OS_MACOS
676 const MTLDeviceLocation deviceLocation = [d->dev location];
677 switch (deviceLocation) {
678 case MTLDeviceLocationBuiltIn:
679 driverInfoStruct.deviceType = QRhiDriverInfo::IntegratedDevice;
680 break;
681 case MTLDeviceLocationSlot:
682 driverInfoStruct.deviceType = QRhiDriverInfo::DiscreteDevice;
683 break;
684 case MTLDeviceLocationExternal:
685 driverInfoStruct.deviceType = QRhiDriverInfo::ExternalDevice;
686 break;
687 default:
688 break;
689 }
690#else
691 driverInfoStruct.deviceType = QRhiDriverInfo::IntegratedDevice;
692#endif
693
694 const QOperatingSystemVersion ver = QOperatingSystemVersion::current();
695 osMajor = ver.majorVersion();
696 osMinor = ver.minorVersion();
697
699 [d->cmdQueue retain];
700 else
701 d->cmdQueue = [d->dev newCommandQueue];
702
703 d->captureMgr = [MTLCaptureManager sharedCaptureManager];
704 // Have a custom capture scope as well which then shows up in XCode as
705 // an option when capturing, and becomes especially useful when having
706 // multiple windows with multiple QRhis.
707 d->captureScope = [d->captureMgr newCaptureScopeWithCommandQueue: d->cmdQueue];
708 const QString label = QString::asprintf("Qt capture scope for QRhi %p", this);
709 d->captureScope.label = label.toNSString();
710
711#if defined(Q_OS_MACOS) || defined(Q_OS_VISIONOS)
712 caps.maxTextureSize = 16384;
713 caps.baseVertexAndInstance = true;
714 caps.isAppleGPU = [d->dev supportsFamily:MTLGPUFamilyApple7];
715 caps.maxThreadGroupSize = 1024;
716 caps.multiView = true;
717#elif defined(Q_OS_TVOS)
718 if ([d->dev supportsFamily:MTLGPUFamilyApple3])
719 caps.maxTextureSize = 16384;
720 else
721 caps.maxTextureSize = 8192;
722 caps.baseVertexAndInstance = false;
723 caps.isAppleGPU = true;
724#elif defined(Q_OS_IOS)
725 if ([d->dev supportsFamily:MTLGPUFamilyApple3]) {
726 caps.maxTextureSize = 16384;
727 caps.baseVertexAndInstance = true;
728 } else if ([d->dev supportsFamily:MTLGPUFamilyApple2]) {
729 caps.maxTextureSize = 8192;
730 caps.baseVertexAndInstance = false;
731 } else {
732 caps.maxTextureSize = 4096;
733 caps.baseVertexAndInstance = false;
734 }
735 caps.isAppleGPU = true;
736 if ([d->dev supportsFamily:MTLGPUFamilyApple4])
737 caps.maxThreadGroupSize = 1024;
738 if ([d->dev supportsFamily:MTLGPUFamilyApple5])
739 caps.multiView = true;
740#endif
741
742 // MTLBlitCommandEncoder's buffer-to-buffer copy requires 4 byte aligned
743 // offsets and size on non-Apple GPUs, whereas uploadStaticBuffer() takes
744 // any offset and size. Keep the legacy host-write path there.
745 caps.usePrivateStaticBuffers = caps.isAppleGPU;
746 if (qEnvironmentVariableIntValue("QT_METAL_NO_PRIVATE_STATIC_BUFFERS"))
747 caps.usePrivateStaticBuffers = false;
748
749 caps.supportedSampleCounts = { 1 };
750 for (int sampleCount : { 2, 4, 8 }) {
751 if ([d->dev supportsTextureSampleCount: sampleCount])
752 caps.supportedSampleCounts.append(sampleCount);
753 }
754
755 caps.indirectCommandBuffers = ([d->dev supportsFamily:MTLGPUFamilyApple5]
756 || [d->dev supportsFamily:MTLGPUFamilyMac2])
757 && [d->dev supportsFamily:MTLGPUFamilyMetal3];
758
759 caps.shadingRateMap = [d->dev supportsRasterizationRateMapWithLayerCount: 1];
760 if (caps.shadingRateMap && caps.multiView)
761 caps.shadingRateMap = [d->dev supportsRasterizationRateMapWithLayerCount: 2];
762
763 // QTBUG-144444: setDepthClipMode is not available on the Simulator
764 caps.depthClamp = [d->dev supportsFamily:MTLGPUFamilyApple3];
765
766#if defined(Q_OS_MACOS) || defined(Q_OS_VISIONOS)
767 caps.fragmentStoresAndAtomics = true;
768#else
769 caps.fragmentStoresAndAtomics = [d->dev supportsFamily:MTLGPUFamilyApple3];
770#endif
771
772 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
773 d->setupBinaryArchive();
774
775 nativeHandlesStruct.dev = (MTLDevice *) d->dev;
776 nativeHandlesStruct.cmdQueue = (MTLCommandQueue *) d->cmdQueue;
777
778 return true;
779}
780
782{
785
786 for (QMetalShader &s : d->shaderCache)
787 s.destroy();
788 d->shaderCache.clear();
789
790 [d->captureScope release];
791 d->captureScope = nil;
792
793 for (auto *pools : { d->argBufPool, d->bufStagingPool }) {
794 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
795 [pools[i].buf release];
796 pools[i].buf = nil;
797 pools[i].capacity = 0;
798 pools[i].offset = 0;
799 }
800 }
801
802 [d->icbArgumentBuffer release];
803 d->icbArgumentBuffer = nil;
804
805 [d->icbRangeBuffer release];
806 d->icbRangeBuffer = nil;
807
808 [d->icbNoCountBuffer release];
809 d->icbNoCountBuffer = nil;
810
811 [d->icbEncodeFunction release];
812 d->icbEncodeFunction = nil;
813
814 [d->icbEncodeFunctionU32 release];
815 d->icbEncodeFunctionU32 = nil;
816
817 [d->icbEncodeFunctionU16 release];
818 d->icbEncodeFunctionU16 = nil;
819
820 [d->icbEncodePipeline release];
821 d->icbEncodePipeline = nil;
822
823 [d->icbEncodePipelineU32 release];
824 d->icbEncodePipelineU32 = nil;
825
826 [d->icbEncodePipelineU16 release];
827 d->icbEncodePipelineU16 = nil;
828
829 [d->icb release];
830 d->icb = nil;
831
832 d->icbCapacity = 0;
833 d->icbSetupFailed = false;
834
835 [d->binArch release];
836 d->binArch = nil;
837
838 [d->cmdQueue release];
839 if (!importedCmdQueue)
840 d->cmdQueue = nil;
841
842 [d->dev release];
843 if (!importedDevice)
844 d->dev = nil;
845}
846
848{
849 return caps.supportedSampleCounts;
850}
851
853{
854 Q_UNUSED(sampleCount);
855 return { QSize(1, 1) };
856}
857
858QRhiSwapChain *QRhiMetal::createSwapChain()
859{
860 return new QMetalSwapChain(this);
861}
862
863QRhiBuffer *QRhiMetal::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
864{
865 return new QMetalBuffer(this, type, usage, size);
866}
867
869{
870 return 256;
871}
872
874{
875 return false;
876}
877
879{
880 return true;
881}
882
884{
885 return true;
886}
887
889{
890 // depth range 0..1
891 // NB the ctor takes row-major
892 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
893 0.0f, 1.0f, 0.0f, 0.0f,
894 0.0f, 0.0f, 0.5f, 0.5f,
895 0.0f, 0.0f, 0.0f, 1.0f);
896 return m;
897}
898
899bool QRhiMetal::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
900{
901 Q_UNUSED(flags);
902
903 bool supportsFamilyMac2 = false; // needed for BC* formats
904 bool supportsFamilyApple3 = false;
905
906#ifdef Q_OS_MACOS
907 supportsFamilyMac2 = true;
908 if (caps.isAppleGPU)
909 supportsFamilyApple3 = true;
910#else
911 supportsFamilyApple3 = true;
912#endif
913
914 // BC5 is not available for any Apple hardare
915 if (format == QRhiTexture::BC5)
916 return false;
917
918 if (!supportsFamilyApple3) {
919 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
920 return false;
921 if (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12)
922 return false;
923 }
924
925 if (!supportsFamilyMac2)
926 if (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
927 return false;
928
929 return true;
930}
931
932bool QRhiMetal::isFeatureSupported(QRhi::Feature feature) const
933{
934 switch (feature) {
935 case QRhi::MultisampleTexture:
936 return true;
937 case QRhi::MultisampleRenderBuffer:
938 return true;
939 case QRhi::DebugMarkers:
940 return true;
941 case QRhi::Timestamps:
942 return true;
943 case QRhi::Instancing:
944 return true;
945 case QRhi::CustomInstanceStepRate:
946 return true;
947 case QRhi::PrimitiveRestart:
948 return true;
949 case QRhi::NonDynamicUniformBuffers:
950 return true;
951 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
952 return false;
953 case QRhi::NPOTTextureRepeat:
954 return true;
955 case QRhi::RedOrAlpha8IsRed:
956 return true;
957 case QRhi::ElementIndexUint:
958 return true;
959 case QRhi::Compute:
960 return true;
961 case QRhi::FragmentStoresAndAtomics:
962 return caps.fragmentStoresAndAtomics;
963 case QRhi::WideLines:
964 return false;
965 case QRhi::VertexShaderPointSize:
966 return true;
967 case QRhi::BaseVertex:
968 return caps.baseVertexAndInstance;
969 case QRhi::BaseInstance:
970 return caps.baseVertexAndInstance;
971 case QRhi::TriangleFanTopology:
972 return false;
973 case QRhi::ReadBackNonUniformBuffer:
974 return true;
975 case QRhi::ReadBackNonBaseMipLevel:
976 return true;
977 case QRhi::TexelFetch:
978 return true;
979 case QRhi::RenderToNonBaseMipLevel:
980 return true;
981 case QRhi::IntAttributes:
982 return true;
983 case QRhi::ScreenSpaceDerivatives:
984 return true;
985 case QRhi::ReadBackAnyTextureFormat:
986 return true;
987 case QRhi::PipelineCacheDataLoadSave:
989 return false;
990#else
991 return true;
992#endif
993 case QRhi::ImageDataStride:
994 return true;
995 case QRhi::RenderBufferImport:
996 return false;
997 case QRhi::ThreeDimensionalTextures:
998 return true;
999 case QRhi::RenderTo3DTextureSlice:
1000 return true;
1001 case QRhi::TextureArrays:
1002 return true;
1003 case QRhi::Tessellation:
1004 return true;
1005 case QRhi::GeometryShader:
1006 return false;
1007 case QRhi::TextureArrayRange:
1008 return true;
1009 case QRhi::NonFillPolygonMode:
1010 return true;
1011 case QRhi::OneDimensionalTextures:
1012 return true;
1013 case QRhi::OneDimensionalTextureMipmaps:
1014 return false;
1015 case QRhi::HalfAttributes:
1016 return true;
1017 case QRhi::RenderToOneDimensionalTexture:
1018 return false;
1019 case QRhi::ThreeDimensionalTextureMipmaps:
1020 return true;
1021 case QRhi::MultiView:
1022 return caps.multiView;
1023 case QRhi::TextureViewFormat:
1024 return true;
1025 case QRhi::ResolveDepthStencil:
1026 return true;
1027 case QRhi::VariableRateShading:
1028 return false;
1029 case QRhi::VariableRateShadingMap:
1030 return caps.shadingRateMap;
1031 case QRhi::VariableRateShadingMapWithTexture:
1032 return false;
1033 case QRhi::DualSourceBlend:
1034 case QRhi::PerRenderTargetBlending:
1035 case QRhi::SampleVariables:
1036 return true;
1037 case QRhi::InstanceIndexIncludesBaseInstance:
1038 return true;
1039 case QRhi::DepthClamp:
1040 return caps.depthClamp;
1041 case QRhi::DrawIndirect:
1042 return true;
1043 case QRhi::BaseInstanceIndirect:
1044 return caps.baseVertexAndInstance;
1045 case QRhi::DrawIndirectMulti:
1046 return caps.indirectCommandBuffers;
1047 case QRhi::ShaderDrawParameters:
1048 return false;
1049 case QRhi::PushConstants:
1050 return true;
1051 case QRhi::DrawIndirectCount:
1052 return caps.indirectCommandBuffers;
1053 case QRhi::DispatchIndirect:
1054 return true;
1055 case QRhi::BufferToBufferCopy:
1056 return true;
1057 case QRhi::StaticBuffersOnGpuTimeline:
1058 return caps.usePrivateStaticBuffers;
1059 default:
1060 Q_UNREACHABLE();
1061 return false;
1062 }
1063}
1064
1065int QRhiMetal::resourceLimit(QRhi::ResourceLimit limit) const
1066{
1067 switch (limit) {
1068 case QRhi::TextureSizeMin:
1069 return 1;
1070 case QRhi::TextureSizeMax:
1071 return caps.maxTextureSize;
1072 case QRhi::MaxColorAttachments:
1073 return 8;
1074 case QRhi::FramesInFlight:
1075 return QMTL_FRAMES_IN_FLIGHT;
1076 case QRhi::MaxAsyncReadbackFrames:
1077 return QMTL_FRAMES_IN_FLIGHT;
1078 case QRhi::MaxThreadGroupsPerDimension:
1079 return 65535;
1080 case QRhi::MaxThreadsPerThreadGroup:
1081 Q_FALLTHROUGH();
1082 case QRhi::MaxThreadGroupX:
1083 Q_FALLTHROUGH();
1084 case QRhi::MaxThreadGroupY:
1085 Q_FALLTHROUGH();
1086 case QRhi::MaxThreadGroupZ:
1087 return caps.maxThreadGroupSize;
1088 case QRhi::TextureArraySizeMax:
1089 return 2048;
1090 case QRhi::MaxUniformBufferRange:
1091 return 65536;
1092 case QRhi::MaxVertexInputs:
1093 return 31;
1094 case QRhi::MaxVertexOutputs:
1095 return 15; // use the minimum from MTLGPUFamily1/2/3
1096 case QRhi::MaxPushConstantsSize:
1097 return 4096; // the limit for setVertexBytes() and friends
1098 case QRhi::MaxVertexStorageBuffers:
1099 case QRhi::MaxFragmentStorageBuffers:
1100 return 31;
1101 case QRhi::MaxStorageBufferBindings:
1102 case QRhi::MaxStorageImageBindings:
1103 return INT_MAX; // binding numbers are mapped to native slots
1104 case QRhi::ShadingRateImageTileSize:
1105 return 0;
1106 default:
1107 Q_UNREACHABLE();
1108 return 0;
1109 }
1110}
1111
1113{
1114 return &nativeHandlesStruct;
1115}
1116
1118{
1119 return driverInfoStruct;
1120}
1121
1123{
1124 QRhiStats result;
1125 result.totalPipelineCreationTime = totalPipelineCreationTime();
1126 return result;
1127}
1128
1130{
1131 // not applicable
1132 return false;
1133}
1134
1135void QRhiMetal::setQueueSubmitParams(QRhiNativeHandles *)
1136{
1137 // not applicable
1138}
1139
1141{
1142 for (QMetalShader &s : d->shaderCache)
1143 s.destroy();
1144
1145 d->shaderCache.clear();
1146}
1147
1149{
1150 return false;
1151}
1152
1162
1164{
1165 Q_STATIC_ASSERT(sizeof(QMetalPipelineCacheDataHeader) == 256);
1166 QByteArray data;
1167 if (!d->binArch || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1168 return data;
1169
1170 QTemporaryFile tmp;
1171 if (!tmp.open()) {
1172 qCDebug(QRHI_LOG_INFO, "pipelineCacheData: Failed to create temporary file for Metal");
1173 return data;
1174 }
1175 tmp.close(); // the file exists until the tmp dtor runs
1176
1177 const QString fn = QFileInfo(tmp.fileName()).absoluteFilePath();
1178 NSURL *url = QUrl::fromLocalFile(fn).toNSURL();
1179 NSError *err = nil;
1180 if (![d->binArch serializeToURL: url error: &err]) {
1181 const QString msg = QString::fromNSString(err.localizedDescription);
1182 // Some of these "errors" are not actual errors. (think of "Nothing to serialize")
1183 qCDebug(QRHI_LOG_INFO, "Failed to serialize MTLBinaryArchive: %s", qPrintable(msg));
1184 return data;
1185 }
1186
1187 QFile f(fn);
1188 if (!f.open(QIODevice::ReadOnly)) {
1189 qCDebug(QRHI_LOG_INFO, "pipelineCacheData: Failed to reopen temporary file");
1190 return data;
1191 }
1192 const QByteArray blob = f.readAll();
1193 f.close();
1194
1195 const size_t headerSize = sizeof(QMetalPipelineCacheDataHeader);
1196 const quint32 dataSize = quint32(blob.size());
1197
1198 data.resize(headerSize + dataSize);
1199
1201 header.rhiId = pipelineCacheRhiId();
1202 header.arch = quint32(sizeof(void*));
1203 header.dataSize = quint32(dataSize);
1204 header.osMajor = osMajor;
1205 header.osMinor = osMinor;
1206 const size_t driverStrLen = qMin(sizeof(header.driver) - 1, size_t(driverInfoStruct.deviceName.length()));
1207 if (driverStrLen)
1208 memcpy(header.driver, driverInfoStruct.deviceName.constData(), driverStrLen);
1209 header.driver[driverStrLen] = '\0';
1210
1211 memcpy(data.data(), &header, headerSize);
1212 memcpy(data.data() + headerSize, blob.constData(), dataSize);
1213 return data;
1214}
1215
1216void QRhiMetal::setPipelineCacheData(const QByteArray &data)
1217{
1218 if (data.isEmpty())
1219 return;
1220
1221 const size_t headerSize = sizeof(QMetalPipelineCacheDataHeader);
1222 if (data.size() < qsizetype(headerSize)) {
1223 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (header incomplete)");
1224 return;
1225 }
1226
1227 const size_t dataOffset = headerSize;
1229 memcpy(&header, data.constData(), headerSize);
1230
1231 const quint32 rhiId = pipelineCacheRhiId();
1232 if (header.rhiId != rhiId) {
1233 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
1234 rhiId, header.rhiId);
1235 return;
1236 }
1237
1238 const quint32 arch = quint32(sizeof(void*));
1239 if (header.arch != arch) {
1240 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Architecture does not match (%u, %u)",
1241 arch, header.arch);
1242 return;
1243 }
1244
1245 if (header.osMajor != osMajor || header.osMinor != osMinor) {
1246 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: OS version does not match (%u.%u, %u.%u)",
1247 osMajor, osMinor, header.osMajor, header.osMinor);
1248 return;
1249 }
1250
1251 const size_t driverStrLen = qMin(sizeof(header.driver) - 1, size_t(driverInfoStruct.deviceName.length()));
1252 if (strncmp(header.driver, driverInfoStruct.deviceName.constData(), driverStrLen)) {
1253 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Metal device name does not match");
1254 return;
1255 }
1256
1257 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
1258 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (data incomplete)");
1259 return;
1260 }
1261
1262 const char *p = data.constData() + dataOffset;
1263
1264 QTemporaryFile tmp;
1265 if (!tmp.open()) {
1266 qCDebug(QRHI_LOG_INFO, "pipelineCacheData: Failed to create temporary file for Metal");
1267 return;
1268 }
1269 tmp.write(p, header.dataSize);
1270 tmp.close(); // the file exists until the tmp dtor runs
1271
1272 const QString fn = QFileInfo(tmp.fileName()).absoluteFilePath();
1273 NSURL *url = QUrl::fromLocalFile(fn).toNSURL();
1274 if (d->setupBinaryArchive(url))
1275 qCDebug(QRHI_LOG_INFO, "Created MTLBinaryArchive with initial data of %u bytes", header.dataSize);
1276}
1277
1278QRhiRenderBuffer *QRhiMetal::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
1279 int sampleCount, QRhiRenderBuffer::Flags flags,
1280 QRhiTexture::Format backingFormatHint)
1281{
1282 return new QMetalRenderBuffer(this, type, pixelSize, sampleCount, flags, backingFormatHint);
1283}
1284
1285QRhiTexture *QRhiMetal::createTexture(QRhiTexture::Format format,
1286 const QSize &pixelSize, int depth, int arraySize,
1287 int sampleCount, QRhiTexture::Flags flags)
1288{
1289 return new QMetalTexture(this, format, pixelSize, depth, arraySize, sampleCount, flags);
1290}
1291
1292QRhiSampler *QRhiMetal::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
1293 QRhiSampler::Filter mipmapMode,
1294 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1295{
1296 return new QMetalSampler(this, magFilter, minFilter, mipmapMode, u, v, w);
1297}
1298
1299QRhiShadingRateMap *QRhiMetal::createShadingRateMap()
1300{
1301 return new QMetalShadingRateMap(this);
1302}
1303
1304QRhiTextureRenderTarget *QRhiMetal::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
1305 QRhiTextureRenderTarget::Flags flags)
1306{
1307 return new QMetalTextureRenderTarget(this, desc, flags);
1308}
1309
1311{
1312 return new QMetalGraphicsPipeline(this);
1313}
1314
1316{
1317 return new QMetalComputePipeline(this);
1318}
1319
1321{
1322 return new QMetalShaderResourceBindings(this);
1323}
1324
1330
1331static inline int mapBinding(int binding,
1332 int stageIndex,
1333 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
1334 BindingType type)
1335{
1336 const QShader::NativeResourceBindingMap *map = nativeResourceBindingMaps[stageIndex];
1337 if (!map || map->isEmpty())
1338 return binding; // old QShader versions do not have this map, assume 1:1 mapping then
1339
1340 auto it = map->constFind(binding);
1341 if (it != map->cend())
1342 return type == BindingType::Sampler ? it->second : it->first; // may be -1, if the resource is inactive
1343
1344 // Hitting this path is normal too. It is not given that the resource (for
1345 // example, a uniform block) is present in the shaders for all the stages
1346 // specified by the visibility mask in the QRhiShaderResourceBinding.
1347 return -1;
1348}
1349
1350static inline MTLResourceUsage storageImageUsage(QRhiShaderResourceBinding::Type type)
1351{
1352 switch (type) {
1353 case QRhiShaderResourceBinding::ImageLoad:
1354 return MTLResourceUsageRead;
1355 case QRhiShaderResourceBinding::ImageStore:
1356 return MTLResourceUsageWrite;
1357 default:
1358 return MTLResourceUsageRead | MTLResourceUsageWrite;
1359 }
1360}
1361
1363 int encoderStage,
1365{
1366 for (const QMetalShaderResourceBindingsData::Stage::Texture &t : res.textures) {
1367 switch (encoderStage) {
1368 case QMetalShaderResourceBindingsData::VERTEX:
1369 [cbD->d->currentRenderPassEncoder useResource: t.mtltex usage: t.usage stages: MTLRenderStageVertex];
1370 break;
1371 case QMetalShaderResourceBindingsData::FRAGMENT:
1372 [cbD->d->currentRenderPassEncoder useResource: t.mtltex usage: t.usage stages: MTLRenderStageFragment];
1373 break;
1374 case QMetalShaderResourceBindingsData::COMPUTE:
1375 [cbD->d->currentComputePassEncoder useResource: t.mtltex usage: t.usage];
1376 break;
1377 default:
1378 break;
1379 }
1380 }
1381}
1382
1384 int stage,
1385 const QRhiBatchedBindings<id<MTLBuffer>>::Batch &bufferBatch,
1386 const QRhiBatchedBindings<NSUInteger>::Batch &offsetBatch)
1387{
1388 switch (stage) {
1389 case QMetalShaderResourceBindingsData::VERTEX:
1390 [cbD->d->currentRenderPassEncoder setVertexBuffers: bufferBatch.resources.constData()
1391 offsets: offsetBatch.resources.constData()
1392 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1393 break;
1394 case QMetalShaderResourceBindingsData::FRAGMENT:
1395 [cbD->d->currentRenderPassEncoder setFragmentBuffers: bufferBatch.resources.constData()
1396 offsets: offsetBatch.resources.constData()
1397 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1398 break;
1399 case QMetalShaderResourceBindingsData::COMPUTE:
1400 [cbD->d->currentComputePassEncoder setBuffers: bufferBatch.resources.constData()
1401 offsets: offsetBatch.resources.constData()
1402 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1403 break;
1406 // do nothing. These are used later for tessellation
1407 break;
1408 default:
1409 Q_UNREACHABLE();
1410 break;
1411 }
1412}
1413
1415 int stage,
1416 const QRhiBatchedBindings<id<MTLTexture>>::Batch &textureBatch)
1417{
1418 switch (stage) {
1419 case QMetalShaderResourceBindingsData::VERTEX:
1420 [cbD->d->currentRenderPassEncoder setVertexTextures: textureBatch.resources.constData()
1421 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1422 break;
1423 case QMetalShaderResourceBindingsData::FRAGMENT:
1424 [cbD->d->currentRenderPassEncoder setFragmentTextures: textureBatch.resources.constData()
1425 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1426 break;
1427 case QMetalShaderResourceBindingsData::COMPUTE:
1428 [cbD->d->currentComputePassEncoder setTextures: textureBatch.resources.constData()
1429 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1430 break;
1433 // do nothing. These are used later for tessellation
1434 break;
1435 default:
1436 Q_UNREACHABLE();
1437 break;
1438 }
1439}
1440
1442 int encoderStage,
1443 const QRhiBatchedBindings<id<MTLSamplerState>>::Batch &samplerBatch)
1444{
1445 switch (encoderStage) {
1446 case QMetalShaderResourceBindingsData::VERTEX:
1447 [cbD->d->currentRenderPassEncoder setVertexSamplerStates: samplerBatch.resources.constData()
1448 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1449 break;
1450 case QMetalShaderResourceBindingsData::FRAGMENT:
1451 [cbD->d->currentRenderPassEncoder setFragmentSamplerStates: samplerBatch.resources.constData()
1452 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1453 break;
1454 case QMetalShaderResourceBindingsData::COMPUTE:
1455 [cbD->d->currentComputePassEncoder setSamplerStates: samplerBatch.resources.constData()
1456 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1457 break;
1460 // do nothing. These are used later for tessellation
1461 break;
1462 default:
1463 Q_UNREACHABLE();
1464 break;
1465 }
1466}
1467
1468// Helper that is not used during the common vertex+fragment and compute
1469// pipelines, but is necessary when tessellation is involved and so the
1470// graphics pipeline is under the hood a combination of multiple compute and
1471// render pipelines. We need to be able to set the buffers, textures, samplers
1472// when a switching between render and compute encoders.
1473static inline void rebindShaderResources(QMetalCommandBuffer *cbD, int resourceStage, int encoderStage,
1474 const QMetalShaderResourceBindingsData *customBindingState = nullptr)
1475{
1476 const QMetalShaderResourceBindingsData *bindingData = customBindingState ? customBindingState : &cbD->d->currentShaderResourceBindingState;
1477
1478 for (int i = 0, ie = bindingData->res[resourceStage].bufferBatches.batches.count(); i != ie; ++i) {
1479 const auto &bufferBatch(bindingData->res[resourceStage].bufferBatches.batches[i]);
1480 const auto &offsetBatch(bindingData->res[resourceStage].bufferOffsetBatches.batches[i]);
1481 bindStageBuffers(cbD, encoderStage, bufferBatch, offsetBatch);
1482 }
1483
1484 for (int i = 0, ie = bindingData->res[resourceStage].textureBatches.batches.count(); i != ie; ++i) {
1485 const auto &batch(bindingData->res[resourceStage].textureBatches.batches[i]);
1486 bindStageTextures(cbD, encoderStage, batch);
1487 }
1488
1489 for (int i = 0, ie = bindingData->res[resourceStage].samplerBatches.batches.count(); i != ie; ++i) {
1490 const auto &batch(bindingData->res[resourceStage].samplerBatches.batches[i]);
1491 bindStageSamplers(cbD, encoderStage, batch);
1492 }
1493
1494 if (bindingData->res[resourceStage].usesArgumentBuffer)
1495 declareStageArgumentBufferResources(cbD, encoderStage, bindingData->res[resourceStage]);
1496}
1497
1499{
1500 switch (stage) {
1501 case QMetalShaderResourceBindingsData::VERTEX:
1502 return QRhiShaderResourceBinding::StageFlag::VertexStage;
1503 case QMetalShaderResourceBindingsData::TESSCTRL:
1504 return QRhiShaderResourceBinding::StageFlag::TessellationControlStage;
1505 case QMetalShaderResourceBindingsData::TESSEVAL:
1506 return QRhiShaderResourceBinding::StageFlag::TessellationEvaluationStage;
1507 case QMetalShaderResourceBindingsData::FRAGMENT:
1508 return QRhiShaderResourceBinding::StageFlag::FragmentStage;
1509 case QMetalShaderResourceBindingsData::COMPUTE:
1510 return QRhiShaderResourceBinding::StageFlag::ComputeStage;
1511 }
1512
1513 Q_UNREACHABLE_RETURN(QRhiShaderResourceBinding::StageFlag::VertexStage);
1514}
1515
1518 int dynamicOffsetCount,
1519 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets,
1520 bool offsetOnlyChange,
1521 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[SUPPORTED_STAGES],
1522 const QMetalShader *shaders[SUPPORTED_STAGES])
1523{
1525
1526 for (const QRhiShaderResourceBinding &binding : std::as_const(srbD->sortedBindings)) {
1527 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(binding);
1528 switch (b->type()) {
1529 case QRhiShaderResourceBinding::UniformBuffer:
1530 {
1531 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->ubuf().buf);
1532 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
1533 quint32 offset = b->ubuf().offset;
1534 for (int i = 0; i < dynamicOffsetCount; ++i) {
1535 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1536 if (dynOfs.first == b->binding) {
1537 offset = dynOfs.second;
1538 break;
1539 }
1540 }
1541
1542 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1543 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1544 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Buffer);
1545 if (nativeBinding >= 0)
1546 bindingData.res[stage].buffers.append({ nativeBinding, mtlbuf, offset });
1547 }
1548 }
1549 }
1550 break;
1551 case QRhiShaderResourceBinding::SampledTexture:
1552 case QRhiShaderResourceBinding::Texture:
1553 case QRhiShaderResourceBinding::Sampler:
1554 {
1555 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1556 for (int elem = 0; elem < data->count(); ++elem) {
1557 QMetalTexture *texD = QRHI_RES(QMetalTexture, data->texSamplers[elem].tex);
1558 QMetalSampler *samplerD = QRHI_RES(QMetalSampler, data->texSamplers[elem].sampler);
1559
1560 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1561 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1562 // Must handle all three cases (combined, separate, separate):
1563 // first = texture binding, second = sampler binding
1564 // first = texture binding
1565 // first = sampler binding (i.e. BindingType::Texture...)
1566 const int textureBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture);
1567 const int samplerBinding = texD && samplerD ? mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Sampler)
1568 : (samplerD ? mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture) : -1);
1569 if (textureBinding >= 0 && texD)
1570 bindingData.res[stage].textures.append({ textureBinding + elem, texD->d->textureForSampling(), MTLResourceUsageRead });
1571 if (samplerBinding >= 0)
1572 bindingData.res[stage].samplers.append({ samplerBinding + elem, samplerD->d->samplerState });
1573 }
1574 }
1575 }
1576 }
1577 break;
1578 case QRhiShaderResourceBinding::ImageLoad:
1579 case QRhiShaderResourceBinding::ImageStore:
1580 case QRhiShaderResourceBinding::ImageLoadStore:
1581 {
1582 QMetalTexture *texD = QRHI_RES(QMetalTexture, b->simage().tex);
1583 id<MTLTexture> t = texD->d->viewForLevel(b->simage().level);
1584
1585 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1586 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1587 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture);
1588 if (nativeBinding >= 0)
1589 bindingData.res[stage].textures.append({ nativeBinding, t, storageImageUsage(b->type()) });
1590 }
1591 }
1592 }
1593 break;
1594 case QRhiShaderResourceBinding::BufferLoad:
1595 case QRhiShaderResourceBinding::BufferStore:
1596 case QRhiShaderResourceBinding::BufferLoadStore:
1597 {
1598 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->sbuf().buf);
1599 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
1600 quint32 offset = b->sbuf().offset;
1601 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1602 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1603 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Buffer);
1604 if (nativeBinding >= 0)
1605 bindingData.res[stage].buffers.append({ nativeBinding, mtlbuf, offset });
1606 }
1607 }
1608 }
1609 break;
1610 default:
1611 Q_UNREACHABLE();
1612 break;
1613 }
1614 }
1615
1616 // With the argument buffer shader variant the texture and sampler values
1617 // collected above are ids within the argument buffer, so encode them into
1618 // one and bind that instead of binding them individually.
1619 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1620 const QMetalShader *shader = shaders[stage];
1621 if (!shader || !shader->argumentEncoder)
1622 continue;
1623 QMetalShaderResourceBindingsData::Stage &res(bindingData.res[stage]);
1624
1625 // offsetOnlyChange means same srb, same pipeline, and no resource
1626 // changed, so what is in the argument buffer cannot have changed
1627 // either. Carry the encoded one over instead of building it again.
1628 if (offsetOnlyChange) {
1630 cbD->d->currentShaderResourceBindingState.res[stage]);
1631 if (prev.usesArgumentBuffer) {
1632 for (const QMetalShaderResourceBindingsData::Stage::Buffer &b : prev.buffers) {
1633 if (b.nativeBinding == shader->argumentBufferIndex) {
1634 res.samplers.clear();
1635 res.buffers.append(b);
1636 res.usesArgumentBuffer = true;
1637 break;
1638 }
1639 }
1640 if (res.usesArgumentBuffer)
1641 continue;
1642 }
1643 }
1644
1645 // The argument buffer is in the constant address space, and it is bound
1646 // like any other buffer, so the offset must satisfy the same 256 byte
1647 // requirement on macOS that makes ubufAlignment() 256. The encoder's
1648 // own alignment is typically well below that.
1649 const quint32 argBufAlignment = qMax(quint32(shader->argumentEncoder.alignment),
1650 quint32(ubufAlignment()));
1651 quint32 argBufOffset = 0;
1652 id<MTLBuffer> argBuf = d->allocArgumentBuffer(quint32(shader->argumentEncoder.encodedLength),
1653 argBufAlignment, currentFrameSlot, &argBufOffset);
1654 if (!argBuf) {
1655 // Nothing gets bound at the argument buffer's index then, so the
1656 // shader will dereference garbage. Acceptable: failing to
1657 // sub-allocate from a small shared memory buffer means the process
1658 // is out of memory anyway.
1659 qWarning("Failed to allocate Metal argument buffer");
1660 res.textures.clear();
1661 res.samplers.clear();
1662 continue;
1663 }
1664 [shader->argumentEncoder setArgumentBuffer: argBuf offset: argBufOffset];
1665 for (const QMetalShaderResourceBindingsData::Stage::Texture &t : std::as_const(res.textures))
1666 [shader->argumentEncoder setTexture: t.mtltex atIndex: NSUInteger(t.nativeBinding)];
1667 for (const QMetalShaderResourceBindingsData::Stage::Sampler &sm : std::as_const(res.samplers))
1668 [shader->argumentEncoder setSamplerState: sm.mtlsampler atIndex: NSUInteger(sm.nativeBinding)];
1669 res.samplers.clear();
1670 res.buffers.append({ shader->argumentBufferIndex, argBuf, argBufOffset });
1671 res.usesArgumentBuffer = true;
1672 }
1673
1674 for (int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1677 continue;
1679 continue;
1680
1681 // QRhiBatchedBindings works with the native bindings and expects
1682 // sorted input. The pre-sorted QRhiShaderResourceBinding list (based
1683 // on the QRhi (SPIR-V) binding) is not helpful in this regard, so we
1684 // have to sort here every time.
1685
1686 std::sort(bindingData.res[stage].buffers.begin(), bindingData.res[stage].buffers.end(), [](const QMetalShaderResourceBindingsData::Stage::Buffer &a, const QMetalShaderResourceBindingsData::Stage::Buffer &b) {
1687 return a.nativeBinding < b.nativeBinding;
1688 });
1689
1690 for (const QMetalShaderResourceBindingsData::Stage::Buffer &buf : std::as_const(bindingData.res[stage].buffers)) {
1691 bindingData.res[stage].bufferBatches.feed(buf.nativeBinding, buf.mtlbuf);
1692 bindingData.res[stage].bufferOffsetBatches.feed(buf.nativeBinding, buf.offset);
1693 }
1694
1695 bindingData.res[stage].bufferBatches.finish();
1696 bindingData.res[stage].bufferOffsetBatches.finish();
1697
1698 for (int i = 0, ie = bindingData.res[stage].bufferBatches.batches.count(); i != ie; ++i) {
1699 const auto &bufferBatch(bindingData.res[stage].bufferBatches.batches[i]);
1700 const auto &offsetBatch(bindingData.res[stage].bufferOffsetBatches.batches[i]);
1701 // skip setting Buffer binding if the current state is already correct
1702 if (cbD->d->currentShaderResourceBindingState.res[stage].bufferBatches.batches.count() > i
1703 && cbD->d->currentShaderResourceBindingState.res[stage].bufferOffsetBatches.batches.count() > i
1704 && bufferBatch == cbD->d->currentShaderResourceBindingState.res[stage].bufferBatches.batches[i]
1705 && offsetBatch == cbD->d->currentShaderResourceBindingState.res[stage].bufferOffsetBatches.batches[i])
1706 {
1707 continue;
1708 }
1709 bindStageBuffers(cbD, stage, bufferBatch, offsetBatch);
1710 }
1711
1712 if (offsetOnlyChange)
1713 continue;
1714
1715 if (bindingData.res[stage].usesArgumentBuffer) {
1716 declareStageArgumentBufferResources(cbD, stage, bindingData.res[stage]);
1717 continue;
1718 }
1719
1720 std::sort(bindingData.res[stage].textures.begin(), bindingData.res[stage].textures.end(), [](const QMetalShaderResourceBindingsData::Stage::Texture &a, const QMetalShaderResourceBindingsData::Stage::Texture &b) {
1721 return a.nativeBinding < b.nativeBinding;
1722 });
1723
1724 std::sort(bindingData.res[stage].samplers.begin(), bindingData.res[stage].samplers.end(), [](const QMetalShaderResourceBindingsData::Stage::Sampler &a, const QMetalShaderResourceBindingsData::Stage::Sampler &b) {
1725 return a.nativeBinding < b.nativeBinding;
1726 });
1727
1728 for (const QMetalShaderResourceBindingsData::Stage::Texture &t : std::as_const(bindingData.res[stage].textures))
1729 bindingData.res[stage].textureBatches.feed(t.nativeBinding, t.mtltex);
1730
1731 for (const QMetalShaderResourceBindingsData::Stage::Sampler &s : std::as_const(bindingData.res[stage].samplers))
1732 bindingData.res[stage].samplerBatches.feed(s.nativeBinding, s.mtlsampler);
1733
1734 bindingData.res[stage].textureBatches.finish();
1735 bindingData.res[stage].samplerBatches.finish();
1736
1737 for (int i = 0, ie = bindingData.res[stage].textureBatches.batches.count(); i != ie; ++i) {
1738 const auto &batch(bindingData.res[stage].textureBatches.batches[i]);
1739 // skip setting Texture binding if the current state is already correct
1740 if (cbD->d->currentShaderResourceBindingState.res[stage].textureBatches.batches.count() > i
1741 && batch == cbD->d->currentShaderResourceBindingState.res[stage].textureBatches.batches[i])
1742 {
1743 continue;
1744 }
1745 bindStageTextures(cbD, stage, batch);
1746 }
1747
1748 for (int i = 0, ie = bindingData.res[stage].samplerBatches.batches.count(); i != ie; ++i) {
1749 const auto &batch(bindingData.res[stage].samplerBatches.batches[i]);
1750 // skip setting Sampler State if the current state is already correct
1751 if (cbD->d->currentShaderResourceBindingState.res[stage].samplerBatches.batches.count() > i
1752 && batch == cbD->d->currentShaderResourceBindingState.res[stage].samplerBatches.batches[i])
1753 {
1754 continue;
1755 }
1756 bindStageSamplers(cbD, stage, batch);
1757 }
1758 }
1759
1760 cbD->d->currentShaderResourceBindingState = bindingData;
1761}
1762
1764{
1765 const QList<QShaderDescription::PushConstantBlock> blocks = s.desc.pushConstantBlocks();
1766 return blocks.isEmpty() ? 0 : quint32(blocks.first().size);
1767}
1768
1769static inline int mtlPushConstantBufferIndex(const QMetalShader &s)
1770{
1771 return s.nativeShaderInfo.extraBufferBindings.value(QShaderPrivate::MslPushConstantBufferBinding, -1);
1772}
1773
1775{
1776 QRHI_RES_RHI(QRhiMetal);
1777
1778 // Also update the tracked state, so that the callers that reactivate a
1779 // pipeline on a new encoder after interrupting the pass do not have to.
1780 cbD->currentGraphicsPipeline = this;
1781 cbD->currentComputePipeline = nullptr;
1783
1784 [cbD->d->currentRenderPassEncoder setRenderPipelineState: d->ps];
1785
1786 if (cbD->d->currentDepthStencilState != d->ds) {
1787 [cbD->d->currentRenderPassEncoder setDepthStencilState: d->ds];
1788 cbD->d->currentDepthStencilState = d->ds;
1789 }
1790 if (cbD->currentCullMode == -1 || d->cullMode != uint(cbD->currentCullMode)) {
1791 [cbD->d->currentRenderPassEncoder setCullMode: d->cullMode];
1792 cbD->currentCullMode = int(d->cullMode);
1793 }
1794 if (cbD->currentTriangleFillMode == -1 || d->triangleFillMode != uint(cbD->currentTriangleFillMode)) {
1795 [cbD->d->currentRenderPassEncoder setTriangleFillMode: d->triangleFillMode];
1796 cbD->currentTriangleFillMode = int(d->triangleFillMode);
1797 }
1798 if (rhiD->caps.depthClamp) {
1799 if (cbD->currentDepthClipMode == -1 || d->depthClipMode != uint(cbD->currentDepthClipMode)) {
1800 [cbD->d->currentRenderPassEncoder setDepthClipMode: d->depthClipMode];
1801 cbD->currentDepthClipMode = int(d->depthClipMode);
1802 }
1803 }
1804 if (cbD->currentFrontFaceWinding == -1 || d->winding != uint(cbD->currentFrontFaceWinding)) {
1805 [cbD->d->currentRenderPassEncoder setFrontFacingWinding: d->winding];
1806 cbD->currentFrontFaceWinding = int(d->winding);
1807 }
1808 if (!qFuzzyCompare(d->depthBias, cbD->currentDepthBiasValues.first)
1809 || !qFuzzyCompare(d->slopeScaledDepthBias, cbD->currentDepthBiasValues.second))
1810 {
1811 [cbD->d->currentRenderPassEncoder setDepthBias: d->depthBias
1812 slopeScale: d->slopeScaledDepthBias
1813 clamp: 0.0f];
1814 cbD->currentDepthBiasValues = { d->depthBias, d->slopeScaledDepthBias };
1815 }
1816
1817 if (m_stencilTest) {
1818 const quint32 ref = m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1819 ? cbD->currentStencilRef : 0;
1820 if (cbD->appliedStencilRef != ref) {
1821 [cbD->d->currentRenderPassEncoder setStencilReferenceValue: ref];
1822 cbD->appliedStencilRef = ref;
1823 }
1824 }
1825
1826 if (cbD->pushConstantsNeedRebind && !d->tess.enabled) {
1827 const int vsIdx = mtlPushConstantBufferIndex(d->vs);
1828 const int fsIdx = mtlPushConstantBufferIndex(d->fs);
1829 if (vsIdx >= 0 || fsIdx >= 0) {
1830 const quint32 blockSize = qMax(mtlPushConstantBlockSize(d->vs), mtlPushConstantBlockSize(d->fs));
1831 if (quint32(cbD->pushConstantData.size()) < blockSize)
1832 cbD->pushConstantData.resize(int(blockSize), 0);
1833 const NSUInteger total = NSUInteger(cbD->pushConstantData.size());
1834 if (vsIdx >= 0)
1835 [cbD->d->currentRenderPassEncoder setVertexBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(vsIdx)];
1836 if (fsIdx >= 0)
1837 [cbD->d->currentRenderPassEncoder setFragmentBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(fsIdx)];
1838 cbD->pushConstantsNeedRebind = false;
1839 }
1840 }
1841}
1842
1843void QRhiMetal::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
1844{
1845 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
1848
1850 return;
1851
1853 cbD->currentComputePipeline = nullptr;
1855
1856 if (cbD->hasCustomScissorSet && !psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
1858
1859 if (!psD->d->tess.enabled && !psD->d->tess.failed)
1861
1862 // mark work buffers that can now be safely reused as reusable
1863 // NOTE: These are usually empty unless tessellation or mutiview is used.
1864 for (QMetalBuffer *workBuf : psD->d->extraBufMgr.deviceLocalWorkBuffers) {
1865 if (workBuf && workBuf->lastActiveFrameSlot == currentFrameSlot)
1866 workBuf->lastActiveFrameSlot = -1;
1867 }
1868 for (QMetalBuffer *workBuf : psD->d->extraBufMgr.hostVisibleWorkBuffers) {
1869 if (workBuf && workBuf->lastActiveFrameSlot == currentFrameSlot)
1870 workBuf->lastActiveFrameSlot = -1;
1871 }
1872
1873 psD->lastActiveFrameSlot = currentFrameSlot;
1874}
1875
1876void QRhiMetal::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
1877 int dynamicOffsetCount,
1878 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1879{
1880 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
1884
1885 if (!srb) {
1886 if (gfxPsD)
1887 srb = gfxPsD->m_shaderResourceBindings;
1888 else
1889 srb = compPsD->m_shaderResourceBindings;
1890 }
1891
1893 bool hasSlottedResourceInSrb = false;
1894 bool hasDynamicOffsetInSrb = false;
1895 bool resNeedsRebind = false;
1896
1897 bool pipelineChanged = false;
1898 if (gfxPsD) {
1899 pipelineChanged = srbD->lastUsedGraphicsPipeline != gfxPsD;
1900 srbD->lastUsedGraphicsPipeline = gfxPsD;
1901 } else {
1902 pipelineChanged = srbD->lastUsedComputePipeline != compPsD;
1903 srbD->lastUsedComputePipeline = compPsD;
1904 }
1905
1906 // SPIRV-Cross buffer size buffers
1907 // Need to determine storage buffer sizes here as this is the last opportunity for storage
1908 // buffer bindings (offset, size) to be specified before draw / dispatch call
1909 const bool needsBufferSizeBuffer = (compPsD && compPsD->d->bufferSizeBuffer) || (gfxPsD && gfxPsD->d->bufferSizeBuffer);
1910 QMap<QRhiShaderResourceBinding::StageFlag, QMap<int, quint32>> storageBufferSizes;
1911
1912 // do buffer writes, figure out if we need to rebind, and mark as in-use
1913 for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
1914 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
1915 QMetalShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
1916 switch (b->type()) {
1917 case QRhiShaderResourceBinding::UniformBuffer:
1918 {
1919 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->ubuf().buf);
1920 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1921 sanityCheckResourceOwnership(bufD);
1923 if (bufD->d->slotted)
1924 hasSlottedResourceInSrb = true;
1925 if (b->ubuf().hasDynamicOffset)
1926 hasDynamicOffsetInSrb = true;
1927 if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1928 resNeedsRebind = true;
1929 bd.ubuf.id = bufD->m_id;
1930 bd.ubuf.generation = bufD->generation;
1931 }
1932 bufD->lastActiveFrameSlot = currentFrameSlot;
1933 }
1934 break;
1935 case QRhiShaderResourceBinding::SampledTexture:
1936 case QRhiShaderResourceBinding::Texture:
1937 case QRhiShaderResourceBinding::Sampler:
1938 {
1939 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1940 if (bd.stex.d.size() != data->count()) {
1941 bd.stex.d.resize(data->count());
1942 resNeedsRebind = true;
1943 }
1944 for (int elem = 0; elem < data->count(); ++elem) {
1945 QMetalTexture *texD = QRHI_RES(QMetalTexture, data->texSamplers[elem].tex);
1946 QMetalSampler *samplerD = QRHI_RES(QMetalSampler, data->texSamplers[elem].sampler);
1947 Q_ASSERT(texD || samplerD);
1948 sanityCheckResourceOwnership(texD);
1949 sanityCheckResourceOwnership(samplerD);
1950 const quint64 texId = texD ? texD->m_id : 0;
1951 const uint texGen = texD ? texD->generation : 0;
1952 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1953 const uint samplerGen = samplerD ? samplerD->generation : 0;
1954 if (texGen != bd.stex.d[elem].texGeneration
1955 || texId != bd.stex.d[elem].texId
1956 || samplerGen != bd.stex.d[elem].samplerGeneration
1957 || samplerId != bd.stex.d[elem].samplerId)
1958 {
1959 resNeedsRebind = true;
1960 bd.stex.d[elem].texId = texId;
1961 bd.stex.d[elem].texGeneration = texGen;
1962 bd.stex.d[elem].samplerId = samplerId;
1963 bd.stex.d[elem].samplerGeneration = samplerGen;
1964 }
1965 if (texD)
1966 texD->lastActiveFrameSlot = currentFrameSlot;
1967 if (samplerD)
1968 samplerD->lastActiveFrameSlot = currentFrameSlot;
1969 }
1970 }
1971 break;
1972 case QRhiShaderResourceBinding::ImageLoad:
1973 case QRhiShaderResourceBinding::ImageStore:
1974 case QRhiShaderResourceBinding::ImageLoadStore:
1975 {
1976 QMetalTexture *texD = QRHI_RES(QMetalTexture, b->simage().tex);
1977 sanityCheckResourceOwnership(texD);
1978 if (texD->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1979 resNeedsRebind = true;
1980 bd.simage.id = texD->m_id;
1981 bd.simage.generation = texD->generation;
1982 }
1983 texD->lastActiveFrameSlot = currentFrameSlot;
1984 }
1985 break;
1986 case QRhiShaderResourceBinding::BufferLoad:
1987 case QRhiShaderResourceBinding::BufferStore:
1988 case QRhiShaderResourceBinding::BufferLoadStore:
1989 {
1990 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->sbuf().buf);
1991 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
1992 sanityCheckResourceOwnership(bufD);
1993
1994 if (needsBufferSizeBuffer) {
1995 for (int i = 0; i < 6; ++i) {
1996 const QRhiShaderResourceBinding::StageFlag stage =
1997 QRhiShaderResourceBinding::StageFlag(1 << i);
1998 if (b->stage.testFlag(stage)) {
1999 storageBufferSizes[stage][b->binding] = b->sbuf().maybeSize ? b->sbuf().maybeSize : bufD->size();
2000 }
2001 }
2002 }
2003
2005 if (bufD->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
2006 resNeedsRebind = true;
2007 bd.sbuf.id = bufD->m_id;
2008 bd.sbuf.generation = bufD->generation;
2009 }
2010 bufD->lastActiveFrameSlot = currentFrameSlot;
2011 }
2012 break;
2013 default:
2014 Q_UNREACHABLE();
2015 break;
2016 }
2017 }
2018
2019 if (needsBufferSizeBuffer) {
2020 QMetalBuffer *bufD = nullptr;
2021 QVarLengthArray<std::pair<QMetalShader *, QRhiShaderResourceBinding::StageFlag>, 4> shaders;
2022
2023 if (compPsD) {
2024 bufD = compPsD->d->bufferSizeBuffer;
2025 Q_ASSERT(compPsD->d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2026 shaders.append({&compPsD->d->cs, QRhiShaderResourceBinding::StageFlag::ComputeStage});
2027 } else {
2028 bufD = gfxPsD->d->bufferSizeBuffer;
2029 if (gfxPsD->d->tess.enabled) {
2030
2031 // Assumptions
2032 // * We only use one of the compute vertex shader variants in a pipeline at any one time
2033 // * The vertex shader variants all have the same storage block bindings
2034 // * The vertex shader variants all have the same native resource binding map
2035 // * The vertex shader variants all have the same MslBufferSizeBufferBinding requirement
2036 // * The vertex shader variants all have the same MslBufferSizeBufferBinding binding
2037 // => We only need to use one vertex shader variant to generate the identical shader
2038 // resource bindings
2039 Q_ASSERT(gfxPsD->d->tess.compVs[0].desc.storageBlocks() == gfxPsD->d->tess.compVs[1].desc.storageBlocks());
2040 Q_ASSERT(gfxPsD->d->tess.compVs[0].desc.storageBlocks() == gfxPsD->d->tess.compVs[2].desc.storageBlocks());
2041 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD->d->tess.compVs[1].nativeResourceBindingMap);
2042 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD->d->tess.compVs[2].nativeResourceBindingMap);
2043 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)
2044 == gfxPsD->d->tess.compVs[1].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2045 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)
2046 == gfxPsD->d->tess.compVs[2].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2047 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]
2048 == gfxPsD->d->tess.compVs[1].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]);
2049 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]
2050 == gfxPsD->d->tess.compVs[2].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]);
2051
2052 if (gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2053 shaders.append({&gfxPsD->d->tess.compVs[0], QRhiShaderResourceBinding::StageFlag::VertexStage});
2054
2055 if (gfxPsD->d->tess.compTesc.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2056 shaders.append({&gfxPsD->d->tess.compTesc, QRhiShaderResourceBinding::StageFlag::TessellationControlStage});
2057
2058 if (gfxPsD->d->tess.vertTese.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2059 shaders.append({&gfxPsD->d->tess.vertTese, QRhiShaderResourceBinding::StageFlag::TessellationEvaluationStage});
2060
2061 } else {
2062 if (gfxPsD->d->vs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2063 shaders.append({&gfxPsD->d->vs, QRhiShaderResourceBinding::StageFlag::VertexStage});
2064 }
2065 if (gfxPsD->d->fs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2066 shaders.append({&gfxPsD->d->fs, QRhiShaderResourceBinding::StageFlag::FragmentStage});
2067 }
2068
2069 quint32 offset = 0;
2070 for (const auto &shader : shaders) {
2071
2072 const int binding = shader.first->nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
2073
2074 // if we don't have a srb entry for the buffer size buffer
2075 if (!(storageBufferSizes.contains(shader.second) && storageBufferSizes[shader.second].contains(binding))) {
2076
2077 int maxNativeBinding = 0;
2078 for (const QShaderDescription::StorageBlock &block : shader.first->desc.storageBlocks())
2079 maxNativeBinding = qMax(maxNativeBinding, shader.first->nativeResourceBindingMap[block.binding].first);
2080
2081 const int size = (maxNativeBinding + 1) * sizeof(int);
2082
2083 Q_ASSERT(offset + size <= bufD->size());
2084 srbD->sortedBindings.append(QRhiShaderResourceBinding::bufferLoad(binding, shader.second, bufD, offset, size));
2085
2086 QMetalShaderResourceBindings::BoundResourceData bd;
2087 bd.sbuf.id = bufD->m_id;
2088 bd.sbuf.generation = bufD->generation;
2089 srbD->boundResourceData.append(bd);
2090 }
2091
2092 // create the buffer size buffer data
2093 QVarLengthArray<int, 8> bufferSizeBufferData;
2094 Q_ASSERT(storageBufferSizes.contains(shader.second));
2095 const QMap<int, quint32> &sizes(storageBufferSizes[shader.second]);
2096 for (const QShaderDescription::StorageBlock &block : shader.first->desc.storageBlocks()) {
2097 const int index = shader.first->nativeResourceBindingMap[block.binding].first;
2098
2099 // if the native binding is -1, the buffer is present but not accessed in the shader
2100 if (index < 0)
2101 continue;
2102
2103 if (bufferSizeBufferData.size() <= index)
2104 bufferSizeBufferData.resize(index + 1);
2105
2106 Q_ASSERT(sizes.contains(block.binding));
2107 bufferSizeBufferData[index] = sizes[block.binding];
2108 }
2109
2110 QRhiBufferData data;
2111 const quint32 size = bufferSizeBufferData.size() * sizeof(int);
2112 data.assign(reinterpret_cast<const char *>(bufferSizeBufferData.constData()), size);
2113 Q_ASSERT(offset + size <= bufD->size());
2114 bufD->d->pendingUpdates[bufD->d->slotted ? currentFrameSlot : 0].append({ offset, data });
2115
2116 // buffer offsets must be 32byte aligned
2117 offset += ((size + 31) / 32) * 32;
2118 }
2119
2121 bufD->lastActiveFrameSlot = currentFrameSlot;
2122 }
2123
2124 // make sure the resources for the correct slot get bound
2125 const int resSlot = hasSlottedResourceInSrb ? currentFrameSlot : 0;
2126 if (hasSlottedResourceInSrb && cbD->currentResSlot != resSlot)
2127 resNeedsRebind = true;
2128
2129 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srbD) : (cbD->currentComputeSrb != srbD);
2130 const bool srbRebuilt = cbD->currentSrbGeneration != srbD->generation;
2131
2132 // dynamic uniform buffer offsets always trigger a rebind
2133 if (hasDynamicOffsetInSrb || resNeedsRebind || srbChanged || srbRebuilt || pipelineChanged) {
2134 const QShader::NativeResourceBindingMap *resBindMaps[SUPPORTED_STAGES] = { nullptr, nullptr, nullptr, nullptr, nullptr };
2135 const QMetalShader *shaders[SUPPORTED_STAGES] = { nullptr, nullptr, nullptr, nullptr, nullptr };
2136 if (gfxPsD) {
2137 cbD->currentGraphicsSrb = srbD;
2138 cbD->currentComputeSrb = nullptr;
2139 if (gfxPsD->d->tess.enabled) {
2140 // If tessellating, we don't know which compVs shader to use until the draw call is
2141 // made. They should all have the same native resource binding map, so pick one.
2142 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD->d->tess.compVs[1].nativeResourceBindingMap);
2143 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD->d->tess.compVs[2].nativeResourceBindingMap);
2144 resBindMaps[QMetalShaderResourceBindingsData::VERTEX] = &gfxPsD->d->tess.compVs[0].nativeResourceBindingMap;
2145 resBindMaps[QMetalShaderResourceBindingsData::TESSCTRL] = &gfxPsD->d->tess.compTesc.nativeResourceBindingMap;
2146 resBindMaps[QMetalShaderResourceBindingsData::TESSEVAL] = &gfxPsD->d->tess.vertTese.nativeResourceBindingMap;
2147 } else {
2148 resBindMaps[QMetalShaderResourceBindingsData::VERTEX] = &gfxPsD->d->vs.nativeResourceBindingMap;
2149 shaders[QMetalShaderResourceBindingsData::VERTEX] = &gfxPsD->d->vs;
2150 }
2151 resBindMaps[QMetalShaderResourceBindingsData::FRAGMENT] = &gfxPsD->d->fs.nativeResourceBindingMap;
2152 shaders[QMetalShaderResourceBindingsData::FRAGMENT] = &gfxPsD->d->fs;
2153 } else {
2154 cbD->currentGraphicsSrb = nullptr;
2155 cbD->currentComputeSrb = srbD;
2156 resBindMaps[QMetalShaderResourceBindingsData::COMPUTE] = &compPsD->d->cs.nativeResourceBindingMap;
2157 shaders[QMetalShaderResourceBindingsData::COMPUTE] = &compPsD->d->cs;
2158 }
2160 cbD->currentResSlot = resSlot;
2161
2162 const bool offsetOnlyChange = hasDynamicOffsetInSrb && !resNeedsRebind
2163 && !srbChanged && !srbRebuilt && !pipelineChanged;
2164 enqueueShaderResourceBindings(srbD, cbD, dynamicOffsetCount, dynamicOffsets, offsetOnlyChange,
2165 resBindMaps, shaders);
2166 }
2167}
2168
2169void QRhiMetal::setVertexInput(QRhiCommandBuffer *cb,
2170 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
2171 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
2172{
2173 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2175
2176 QRhiBatchedBindings<id<MTLBuffer> > buffers;
2177 QRhiBatchedBindings<NSUInteger> offsets;
2178 for (int i = 0; i < bindingCount; ++i) {
2179 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, bindings[i].first);
2181 bufD->lastActiveFrameSlot = currentFrameSlot;
2182 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
2183 buffers.feed(startBinding + i, mtlbuf);
2184 offsets.feed(startBinding + i, bindings[i].second);
2185 }
2186 buffers.finish();
2187 offsets.finish();
2188
2189 // same binding space for vertex and constant buffers - work it around
2191 // There's nothing guaranteeing setShaderResources() was called before
2192 // setVertexInput()... but whatever srb will get bound will have to be
2193 // layout-compatible anyways so maxBinding is the same.
2194 if (!srbD)
2195 srbD = QRHI_RES(QMetalShaderResourceBindings, cbD->currentGraphicsPipeline->shaderResourceBindings());
2196 const int firstVertexBinding = srbD->maxBinding + 1;
2197
2198 if (firstVertexBinding != cbD->d->currentFirstVertexBinding
2199 || buffers != cbD->d->currentVertexInputsBuffers
2200 || offsets != cbD->d->currentVertexInputOffsets)
2201 {
2202 cbD->d->currentFirstVertexBinding = firstVertexBinding;
2203 cbD->d->currentVertexInputsBuffers = buffers;
2204 cbD->d->currentVertexInputOffsets = offsets;
2205
2206 for (int i = 0, ie = buffers.batches.count(); i != ie; ++i) {
2207 const auto &bufferBatch(buffers.batches[i]);
2208 const auto &offsetBatch(offsets.batches[i]);
2209 [cbD->d->currentRenderPassEncoder setVertexBuffers:
2210 bufferBatch.resources.constData()
2211 offsets: offsetBatch.resources.constData()
2212 withRange: NSMakeRange(uint(firstVertexBinding) + bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
2213 }
2214 }
2215
2216 if (indexBuf) {
2217 QMetalBuffer *ibufD = QRHI_RES(QMetalBuffer, indexBuf);
2219 ibufD->lastActiveFrameSlot = currentFrameSlot;
2220 cbD->currentIndexBuffer = ibufD;
2221 cbD->currentIndexOffset = indexOffset;
2222 cbD->currentIndexFormat = indexFormat;
2223 } else {
2224 cbD->currentIndexBuffer = nullptr;
2225 }
2226}
2227
2228// The size of the coordinate space viewports and scissors are specified in.
2229// Normally this is the pixel size of the render target. When a rasterization
2230// rate map is attached, Metal interprets viewports and scissors in the logical
2231// (screen space) coordinate system of the map, which is typically larger than
2232// the physical texture size. This is what foveated rendering on visionOS uses.
2233QSize QRhiMetal::outputSizeForTarget(QRhiRenderTarget *target)
2234{
2235 QRhiShadingRateMap *srm = nullptr;
2236 switch (target->resourceType()) {
2237 case QRhiResource::TextureRenderTarget:
2238 srm = QRHI_RES(QMetalTextureRenderTarget, target)->m_desc.shadingRateMap();
2239 break;
2240 case QRhiResource::SwapChainRenderTarget:
2241 srm = QRHI_RES(QMetalSwapChainRenderTarget, target)->swapChain()->shadingRateMap();
2242 break;
2243 default:
2244 break;
2245 }
2246
2247 if (srm) {
2248 const QSize logicalSize = srm->logicalSize();
2249 if (logicalSize.isValid())
2250 return logicalSize;
2251 }
2252
2253 return target->pixelSize();
2254}
2255
2257{
2258 cbD->hasCustomScissorSet = false;
2259
2260 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2261 std::array<float, 4> vp = cbD->currentViewport.viewport();
2262 float x = 0, y = 0, w = 0, h = 0;
2263
2264 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
2265 x = 0;
2266 y = 0;
2267 w = outputSize.width();
2268 h = outputSize.height();
2269 } else {
2270 // x,y is top-left in MTLScissorRect but bottom-left in QRhiScissor
2271 qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, vp, &x, &y, &w, &h);
2272 }
2273
2274 MTLScissorRect s;
2275 s.x = NSUInteger(x);
2276 s.y = NSUInteger(y);
2277 s.width = NSUInteger(w);
2278 s.height = NSUInteger(h);
2279 [cbD->d->currentRenderPassEncoder setScissorRect: s];
2280}
2281
2282void QRhiMetal::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
2283{
2284 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2286 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2287
2288 // x,y is top-left in MTLViewportRect but bottom-left in QRhiViewport
2289 float x, y, w, h;
2290 if (!qrhi_toTopLeftRenderTargetRect<UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
2291 return;
2292
2293 MTLViewport vp;
2294 vp.originX = double(x);
2295 vp.originY = double(y);
2296 vp.width = double(w);
2297 vp.height = double(h);
2298 vp.znear = double(viewport.minDepth());
2299 vp.zfar = double(viewport.maxDepth());
2300
2301 [cbD->d->currentRenderPassEncoder setViewport: vp];
2302
2303 cbD->currentViewport = viewport;
2305 && !cbD->currentGraphicsPipeline->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
2306 {
2308 }
2309}
2310
2311void QRhiMetal::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
2312{
2313 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2315 Q_ASSERT(!cbD->currentGraphicsPipeline
2316 || cbD->currentGraphicsPipeline->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor));
2317 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2318
2319 // x,y is top-left in MTLScissorRect but bottom-left in QRhiScissor
2320 int x, y, w, h;
2321 if (!qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
2322 return;
2323
2324 MTLScissorRect s;
2325 s.x = NSUInteger(x);
2326 s.y = NSUInteger(y);
2327 s.width = NSUInteger(w);
2328 s.height = NSUInteger(h);
2329
2330 [cbD->d->currentRenderPassEncoder setScissorRect: s];
2331
2332 cbD->hasCustomScissorSet = true;
2333 cbD->currentScissor = scissor;
2334}
2335
2336void QRhiMetal::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c)
2337{
2338 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2340
2341 [cbD->d->currentRenderPassEncoder setBlendColorRed: c.redF()
2342 green: c.greenF() blue: c.blueF() alpha: c.alphaF()];
2343
2344 cbD->hasBlendConstantsSet = true;
2345 cbD->currentBlendConstants = c;
2346}
2347
2348void QRhiMetal::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
2349{
2350 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2352
2353 [cbD->d->currentRenderPassEncoder setStencilReferenceValue: refValue];
2354
2355 cbD->currentStencilRef = refValue;
2356 cbD->appliedStencilRef = refValue;
2357}
2358
2359void QRhiMetal::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data)
2360{
2361 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2363
2364 // setVertexBytes() and friends take the whole block every time, so a shadow
2365 // copy is needed to honour an update of part of it.
2366 auto patch = [cbD, offset, size, data](quint32 blockSize) {
2367 const quint32 total = qMax(blockSize, offset + size);
2368 if (quint32(cbD->pushConstantData.size()) < total)
2369 cbD->pushConstantData.resize(int(total), 0);
2370 memcpy(cbD->pushConstantData.data() + offset, data, size);
2371 return total;
2372 };
2373
2376 if (!psD)
2377 return;
2378 const int idx = mtlPushConstantBufferIndex(psD->d->cs);
2379 if (idx < 0) {
2380 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
2381 return;
2382 }
2383 const quint32 total = patch(mtlPushConstantBlockSize(psD->d->cs));
2384 [cbD->d->currentComputePassEncoder setBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(idx)];
2385 } else {
2387 if (!psD)
2388 return;
2389 if (psD->d->tess.enabled) {
2390 qWarning("Push constants are not supported with tessellation on Metal");
2391 return;
2392 }
2393 const int vsIdx = mtlPushConstantBufferIndex(psD->d->vs);
2394 const int fsIdx = mtlPushConstantBufferIndex(psD->d->fs);
2395 if (vsIdx < 0 && fsIdx < 0) {
2396 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
2397 return;
2398 }
2399 const quint32 total = patch(qMax(mtlPushConstantBlockSize(psD->d->vs), mtlPushConstantBlockSize(psD->d->fs)));
2400 if (vsIdx >= 0)
2401 [cbD->d->currentRenderPassEncoder setVertexBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(vsIdx)];
2402 if (fsIdx >= 0)
2403 [cbD->d->currentRenderPassEncoder setFragmentBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(fsIdx)];
2404 }
2405}
2406
2407void QRhiMetal::setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize)
2408{
2409 Q_UNUSED(cb);
2410 Q_UNUSED(coarsePixelSize);
2411}
2412
2414{
2415 switch (cbD->currentTarget->resourceType()) {
2416 case QRhiResource::SwapChainRenderTarget:
2417 return QRHI_RES(QMetalSwapChainRenderTarget, cbD->currentTarget)->d;
2418 case QRhiResource::TextureRenderTarget:
2419 return QRHI_RES(QMetalTextureRenderTarget, cbD->currentTarget)->d;
2420 default:
2421 return nullptr;
2422 }
2423}
2424
2425// Memoryless attachments only exist for the duration of a single encoder, there
2426// is nowhere to store them to.
2427static inline bool canStoreAttachment(id<MTLTexture> tex)
2428{
2429 return tex && tex.storageMode != MTLStorageModeMemoryless;
2430}
2431
2432// When the pass continues on a new encoder afterwards, the contents have to be
2433// stored, not just resolved or discarded. An attachment with a resolve texture
2434// can only use the resolving store actions.
2435static inline MTLStoreAction interruptionStoreAction(MTLStoreAction finalAction, bool passIsEnding)
2436{
2437 if (passIsEnding)
2438 return finalAction;
2439 return finalAction == MTLStoreActionDontCare ? MTLStoreActionStore
2440 : MTLStoreActionStoreAndMultisampleResolve;
2441}
2442
2443// Store actions are deferred (MTLStoreActionUnknown) for attachments whose
2444// contents may need to outlive the encoder, so they have to be finalized before
2445// the encoder ends.
2446// Store actions cannot be mutated otherwise, and for a resolve attachment the
2447// only legal choices are the two resolving ones.
2449{
2450 for (const auto &[index, finalAction] : std::as_const(cbD->d->deferredColorStoreActions))
2451 [cbD->d->currentRenderPassEncoder setColorStoreAction:
2452 interruptionStoreAction(finalAction, passIsEnding) atIndex: index];
2453
2454 if (cbD->d->deferredDepthStoreAction != MTLStoreActionUnknown) {
2455 [cbD->d->currentRenderPassEncoder setDepthStoreAction:
2456 interruptionStoreAction(cbD->d->deferredDepthStoreAction, passIsEnding)];
2457 }
2458 if (cbD->d->deferredStencilStoreAction != MTLStoreActionUnknown) {
2459 [cbD->d->currentRenderPassEncoder setStencilStoreAction:
2460 interruptionStoreAction(cbD->d->deferredStencilStoreAction, passIsEnding)];
2461 }
2462}
2463
2464// Ends the render command encoder such that the pass can be continued on a new
2465// encoder afterwards.
2467{
2469 for (qsizetype i = 0; i < cbD->d->openDebugGroups.size(); ++i)
2470 [cbD->d->currentRenderPassEncoder popDebugGroup];
2471 [cbD->d->currentRenderPassEncoder endEncoding];
2472 cbD->d->currentRenderPassEncoder = nil;
2473}
2474
2477 id<MTLComputeCommandEncoder> maybeComputeEncoder)
2478{
2479 if (cbD->d->currentRenderPassEncoder)
2481
2482 if (!maybeComputeEncoder)
2483 maybeComputeEncoder = [cbD->d->cb computeCommandEncoder];
2484
2485 return maybeComputeEncoder;
2486}
2487
2489 id<MTLComputeCommandEncoder> computeEncoder)
2490{
2491 if (computeEncoder) {
2492 [computeEncoder endEncoding];
2493 computeEncoder = nil;
2494 }
2495
2496 // No drawable, see beginPass()
2497 if (!cbD->d->currentPassRpDesc)
2498 return;
2499
2501 Q_ASSERT(rtD);
2502
2503 // A memoryless attachment cannot be loaded, its contents are lost (see
2504 // NoTransientBacking), even when the store action is not DontCare, which is
2505 // the case with a resolve.
2506 const auto canLoad = [](MTLRenderPassAttachmentDescriptor *att) {
2507 return att.storeAction != MTLStoreActionDontCare && canStoreAttachment(att.texture);
2508 };
2509
2510 QVarLengthArray<MTLLoadAction, 4> oldColorLoad;
2511 for (uint i = 0; i < uint(rtD->colorAttCount); ++i) {
2512 oldColorLoad.append(cbD->d->currentPassRpDesc.colorAttachments[i].loadAction);
2513 if (canLoad(cbD->d->currentPassRpDesc.colorAttachments[i]))
2514 cbD->d->currentPassRpDesc.colorAttachments[i].loadAction = MTLLoadActionLoad;
2515 }
2516
2517 MTLLoadAction oldDepthLoad;
2518 MTLLoadAction oldStencilLoad;
2519 if (rtD->dsAttCount) {
2520 oldDepthLoad = cbD->d->currentPassRpDesc.depthAttachment.loadAction;
2521 if (canLoad(cbD->d->currentPassRpDesc.depthAttachment))
2522 cbD->d->currentPassRpDesc.depthAttachment.loadAction = MTLLoadActionLoad;
2523
2524 oldStencilLoad = cbD->d->currentPassRpDesc.stencilAttachment.loadAction;
2525 if (canLoad(cbD->d->currentPassRpDesc.stencilAttachment))
2526 cbD->d->currentPassRpDesc.stencilAttachment.loadAction = MTLLoadActionLoad;
2527 }
2528
2529 // The state below is not tied to the pipeline, so it is not restored by the
2530 // callers when they reactivate it on the new encoder. Preserve it here,
2531 // otherwise the pass would silently continue with a full-target viewport,
2532 // no scissor, and default blend constants and stencil reference.
2533 const QRhiViewport prevViewport = cbD->currentViewport;
2534 const bool prevHasScissor = cbD->hasCustomScissorSet;
2535 const QRhiScissor prevScissor = cbD->currentScissor;
2536 const bool prevHasBlendConstants = cbD->hasBlendConstantsSet;
2537 const QColor prevBlendConstants = cbD->currentBlendConstants;
2538 const quint32 prevStencilRef = cbD->currentStencilRef;
2539 // Whether the pipeline was relying on the viewport-derived default scissor,
2540 // which setViewport() below cannot reapply on its own: it only does so when
2541 // a pipeline is already current, and there is none at that point.
2542 const bool prevHasDefaultScissor = cbD->currentGraphicsPipeline
2543 && !cbD->currentGraphicsPipeline->flags().testFlag(QRhiGraphicsPipeline::UsesScissor);
2544 // Rebound when the callers reactivate the pipeline, or when the next
2545 // pipeline with a push constant block is set.
2546 const QVarLengthArray<char, 128> prevPushConstantData = cbD->pushConstantData;
2547
2548 cbD->d->currentRenderPassEncoder = [cbD->d->cb renderCommandEncoderWithDescriptor: cbD->d->currentPassRpDesc];
2550
2551 for (const QByteArray &name : std::as_const(cbD->d->openDebugGroups))
2552 [cbD->d->currentRenderPassEncoder pushDebugGroup: [NSString stringWithUTF8String: name.constData()]];
2553
2554 cbD->pushConstantData = prevPushConstantData;
2555 cbD->pushConstantsNeedRebind = !prevPushConstantData.isEmpty();
2556
2557 // Must come before the callers reactivate the pipeline: setScissor()
2558 // expects no pipeline to be current yet, and setDefaultScissor() consults
2559 // the viewport.
2560 if (!qFuzzyIsNull(prevViewport.viewport()[2]) || !qFuzzyIsNull(prevViewport.viewport()[3]))
2561 rhiD->setViewport(cbD, prevViewport);
2562 if (prevHasScissor)
2563 rhiD->setScissor(cbD, prevScissor);
2564 else if (prevHasDefaultScissor)
2565 rhiD->setDefaultScissor(cbD);
2566 if (prevHasBlendConstants)
2567 rhiD->setBlendConstants(cbD, prevBlendConstants);
2568 cbD->currentStencilRef = prevStencilRef;
2569
2570 for (uint i = 0; i < uint(rtD->colorAttCount); ++i) {
2571 cbD->d->currentPassRpDesc.colorAttachments[i].loadAction = oldColorLoad[i];
2572 }
2573
2574 if (rtD->dsAttCount) {
2575 cbD->d->currentPassRpDesc.depthAttachment.loadAction = oldDepthLoad;
2576 cbD->d->currentPassRpDesc.stencilAttachment.loadAction = oldStencilLoad;
2577 }
2578
2579}
2580
2582{
2583 QMetalCommandBuffer *cbD = args.cbD;
2585 if (graphicsPipeline->d->tess.failed)
2586 return;
2587
2588 const bool indexed = args.type != TessDrawArgs::NonIndexed;
2589 const quint32 instanceCount = indexed ? args.drawIndexed.instanceCount : args.draw.instanceCount;
2590 const quint32 vertexOrIndexCount = indexed ? args.drawIndexed.indexCount : args.draw.vertexCount;
2591
2592 QMetalGraphicsPipelineData::Tessellation &tess(graphicsPipeline->d->tess);
2593 QMetalGraphicsPipelineData::ExtraBufferManager &extraBufMgr(graphicsPipeline->d->extraBufMgr);
2594 const quint32 patchCount = tess.patchCountForDrawCall(vertexOrIndexCount, instanceCount);
2595 QMetalBuffer *vertOutBuf = nullptr;
2596 QMetalBuffer *tescOutBuf = nullptr;
2597 QMetalBuffer *tescPatchOutBuf = nullptr;
2598 QMetalBuffer *tescFactorBuf = nullptr;
2599 QMetalBuffer *tescParamsBuf = nullptr;
2600 id<MTLComputeCommandEncoder> vertTescComputeEncoder
2601 = tempComputeEncoder(this, cbD, cbD->d->tessellationComputeEncoder);
2602 cbD->d->tessellationComputeEncoder = vertTescComputeEncoder;
2603
2604 // Step 1: vertex shader (as compute)
2605 {
2606 id<MTLComputeCommandEncoder> computeEncoder = vertTescComputeEncoder;
2607 QShader::Variant shaderVariant = QShader::NonIndexedVertexAsComputeShader;
2608 if (args.type == TessDrawArgs::U16Indexed)
2609 shaderVariant = QShader::UInt16IndexedVertexAsComputeShader;
2610 else if (args.type == TessDrawArgs::U32Indexed)
2611 shaderVariant = QShader::UInt32IndexedVertexAsComputeShader;
2612 const int varIndex = QMetalGraphicsPipelineData::Tessellation::vsCompVariantToIndex(shaderVariant);
2613 id<MTLComputePipelineState> computePipelineState = tess.vsCompPipeline(this, shaderVariant);
2614 [computeEncoder setComputePipelineState: computePipelineState];
2615
2616 // Make uniform buffers, textures, and samplers (meant for the
2617 // vertex stage from the client's point of view) visible in the
2618 // "vertex as compute" shader
2619 cbD->d->currentComputePassEncoder = computeEncoder;
2621 cbD->d->currentComputePassEncoder = nil;
2622
2623 const QMap<int, int> &ebb(tess.compVs[varIndex].nativeShaderInfo.extraBufferBindings);
2624 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2625 const int indexBufferBinding = ebb.value(QShaderPrivate::MslTessVertIndicesBufferBinding, -1);
2626
2627 if (outputBufferBinding >= 0) {
2628 const quint32 workBufSize = tess.vsCompOutputBufferSize(vertexOrIndexCount, instanceCount);
2629 vertOutBuf = extraBufMgr.acquireWorkBuffer(this, workBufSize);
2630 if (!vertOutBuf)
2631 return;
2632 [computeEncoder setBuffer: vertOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2633 }
2634
2635 if (indexBufferBinding >= 0)
2636 [computeEncoder setBuffer: (id<MTLBuffer>) args.drawIndexed.indexBuffer offset: 0 atIndex: indexBufferBinding];
2637
2638 for (int i = 0, ie = cbD->d->currentVertexInputsBuffers.batches.count(); i != ie; ++i) {
2639 const auto &bufferBatch(cbD->d->currentVertexInputsBuffers.batches[i]);
2640 const auto &offsetBatch(cbD->d->currentVertexInputOffsets.batches[i]);
2641 [computeEncoder setBuffers: bufferBatch.resources.constData()
2642 offsets: offsetBatch.resources.constData()
2643 withRange: NSMakeRange(uint(cbD->d->currentFirstVertexBinding) + bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
2644 }
2645
2646 if (indexed) {
2647 [computeEncoder setStageInRegion: MTLRegionMake2D(args.drawIndexed.vertexOffset, args.drawIndexed.firstInstance,
2648 args.drawIndexed.indexCount, args.drawIndexed.instanceCount)];
2649 } else {
2650 [computeEncoder setStageInRegion: MTLRegionMake2D(args.draw.firstVertex, args.draw.firstInstance,
2651 args.draw.vertexCount, args.draw.instanceCount)];
2652 }
2653
2654 [computeEncoder dispatchThreads: MTLSizeMake(vertexOrIndexCount, instanceCount, 1)
2655 threadsPerThreadgroup: MTLSizeMake(computePipelineState.threadExecutionWidth, 1, 1)];
2656 }
2657
2658 // Step 2: tessellation control shader (as compute)
2659 {
2660 id<MTLComputeCommandEncoder> computeEncoder = vertTescComputeEncoder;
2661 id<MTLComputePipelineState> computePipelineState = tess.tescCompPipeline(this);
2662 [computeEncoder setComputePipelineState: computePipelineState];
2663
2664 cbD->d->currentComputePassEncoder = computeEncoder;
2666 cbD->d->currentComputePassEncoder = nil;
2667
2668 const QMap<int, int> &ebb(tess.compTesc.nativeShaderInfo.extraBufferBindings);
2669 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2670 const int patchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
2671 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
2672 const int paramsBufferBinding = ebb.value(QShaderPrivate::MslTessTescParamsBufferBinding, -1);
2673 const int inputBufferBinding = ebb.value(QShaderPrivate::MslTessTescInputBufferBinding, -1);
2674
2675 if (outputBufferBinding >= 0) {
2676 const quint32 workBufSize = tess.tescCompOutputBufferSize(patchCount);
2677 tescOutBuf = extraBufMgr.acquireWorkBuffer(this, workBufSize);
2678 if (!tescOutBuf)
2679 return;
2680 [computeEncoder setBuffer: tescOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2681 }
2682
2683 if (patchOutputBufferBinding >= 0) {
2684 const quint32 workBufSize = tess.tescCompPatchOutputBufferSize(patchCount);
2685 tescPatchOutBuf = extraBufMgr.acquireWorkBuffer(this, workBufSize);
2686 if (!tescPatchOutBuf)
2687 return;
2688 [computeEncoder setBuffer: tescPatchOutBuf->d->buf[0] offset: 0 atIndex: patchOutputBufferBinding];
2689 }
2690
2691 if (tessFactorBufferBinding >= 0) {
2692 tescFactorBuf = extraBufMgr.acquireWorkBuffer(this, patchCount * sizeof(MTLQuadTessellationFactorsHalf));
2693 [computeEncoder setBuffer: tescFactorBuf->d->buf[0] offset: 0 atIndex: tessFactorBufferBinding];
2694 }
2695
2696 if (paramsBufferBinding >= 0) {
2697 struct {
2698 quint32 inControlPointCount;
2699 quint32 patchCount;
2700 } params;
2701 tescParamsBuf = extraBufMgr.acquireWorkBuffer(this, sizeof(params), QMetalGraphicsPipelineData::ExtraBufferManager::WorkBufType::HostVisible);
2702 if (!tescParamsBuf)
2703 return;
2704 params.inControlPointCount = tess.inControlPointCount;
2705 params.patchCount = patchCount;
2706 id<MTLBuffer> paramsBuf = tescParamsBuf->d->buf[0];
2707 char *p = reinterpret_cast<char *>([paramsBuf contents]);
2708 memcpy(p, &params, sizeof(params));
2709 [computeEncoder setBuffer: paramsBuf offset: 0 atIndex: paramsBufferBinding];
2710 }
2711
2712 if (vertOutBuf && inputBufferBinding >= 0)
2713 [computeEncoder setBuffer: vertOutBuf->d->buf[0] offset: 0 atIndex: inputBufferBinding];
2714
2715 int sgSize = int(computePipelineState.threadExecutionWidth);
2716 int wgSize = std::lcm(tess.outControlPointCount, sgSize);
2717 while (wgSize > caps.maxThreadGroupSize) {
2718 sgSize /= 2;
2719 wgSize = std::lcm(tess.outControlPointCount, sgSize);
2720 }
2721 [computeEncoder dispatchThreads: MTLSizeMake(patchCount * tess.outControlPointCount, 1, 1)
2722 threadsPerThreadgroup: MTLSizeMake(wgSize, 1, 1)];
2723 }
2724
2725 // Much of the state in the QMetalCommandBuffer is going to be reset
2726 // when we get a new render encoder. Save what we need. (cheaper than
2727 // starting to walk over the srb again)
2728 const QMetalShaderResourceBindingsData resourceBindings = cbD->d->currentShaderResourceBindingState;
2729
2730 endTempComputeEncoding(this, cbD, cbD->d->tessellationComputeEncoder);
2731 cbD->d->tessellationComputeEncoder = nil;
2732
2733 // Step 3: tessellation evaluation (as vertex) + fragment shader
2734 {
2735 // No need to call tess.teseFragRenderPipeline because it was done
2736 // once and we know the result is stored in the standard place
2737 // (graphicsPipeline->d->ps).
2738
2740 id<MTLRenderCommandEncoder> renderEncoder = cbD->d->currentRenderPassEncoder;
2741
2744
2745 const QMap<int, int> &ebb(tess.compTesc.nativeShaderInfo.extraBufferBindings);
2746 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2747 const int patchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
2748 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
2749
2750 if (outputBufferBinding >= 0 && tescOutBuf)
2751 [renderEncoder setVertexBuffer: tescOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2752
2753 if (patchOutputBufferBinding >= 0 && tescPatchOutBuf)
2754 [renderEncoder setVertexBuffer: tescPatchOutBuf->d->buf[0] offset: 0 atIndex: patchOutputBufferBinding];
2755
2756 if (tessFactorBufferBinding >= 0 && tescFactorBuf) {
2757 [renderEncoder setTessellationFactorBuffer: tescFactorBuf->d->buf[0] offset: 0 instanceStride: 0];
2758 [renderEncoder setVertexBuffer: tescFactorBuf->d->buf[0] offset: 0 atIndex: tessFactorBufferBinding];
2759 }
2760
2761 [cbD->d->currentRenderPassEncoder drawPatches: tess.outControlPointCount
2762 patchStart: 0
2763 patchCount: patchCount
2764 patchIndexBuffer: nil
2765 patchIndexBufferOffset: 0
2766 instanceCount: 1
2767 baseInstance: 0];
2768 }
2769}
2770
2771void QRhiMetal::adjustForMultiViewDraw(quint32 *instanceCount, QRhiCommandBuffer *cb)
2772{
2773 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2774 const int multiViewCount = cbD->currentGraphicsPipeline->m_multiViewCount;
2775 if (multiViewCount <= 1)
2776 return;
2777
2778 const QMap<int, int> &ebb(cbD->currentGraphicsPipeline->d->vs.nativeShaderInfo.extraBufferBindings);
2779 const int viewMaskBufBinding = ebb.value(QShaderPrivate::MslMultiViewMaskBufferBinding, -1);
2780 if (viewMaskBufBinding == -1) {
2781 qWarning("No extra buffer for multiview in the vertex shader; was it built with --view-count specified?");
2782 return;
2783 }
2784 struct {
2785 quint32 viewOffset;
2786 quint32 viewCount;
2787 } multiViewInfo;
2788 multiViewInfo.viewOffset = 0;
2789 multiViewInfo.viewCount = quint32(multiViewCount);
2790 QMetalBuffer *buf = cbD->currentGraphicsPipeline->d->extraBufMgr.acquireWorkBuffer(this, sizeof(multiViewInfo),
2792 if (buf) {
2793 id<MTLBuffer> mtlbuf = buf->d->buf[0];
2794 char *p = reinterpret_cast<char *>([mtlbuf contents]);
2795 memcpy(p, &multiViewInfo, sizeof(multiViewInfo));
2796 [cbD->d->currentRenderPassEncoder setVertexBuffer: mtlbuf offset: 0 atIndex: viewMaskBufBinding];
2797 // The instance count is adjusted for layered rendering. The vertex shader is expected to contain something like:
2798 // uint gl_ViewIndex = spvViewMask[0] + (gl_InstanceIndex - gl_BaseInstance) % spvViewMask[1];
2799 // where spvViewMask is the buffer with multiViewInfo passed in above.
2800 *instanceCount *= multiViewCount;
2801 }
2802}
2803
2804void QRhiMetal::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
2805 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
2806{
2807 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2809
2810 if (cbD->currentGraphicsPipeline->d->tess.enabled) {
2811 TessDrawArgs a;
2812 a.cbD = cbD;
2813 a.type = TessDrawArgs::NonIndexed;
2814 a.draw.vertexCount = vertexCount;
2815 a.draw.instanceCount = instanceCount;
2816 a.draw.firstVertex = firstVertex;
2817 a.draw.firstInstance = firstInstance;
2819 return;
2820 }
2821
2822 adjustForMultiViewDraw(&instanceCount, cb);
2823
2824 if (caps.baseVertexAndInstance) {
2825 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2826 vertexStart: firstVertex vertexCount: vertexCount instanceCount: instanceCount baseInstance: firstInstance];
2827 } else {
2828 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2829 vertexStart: firstVertex vertexCount: vertexCount instanceCount: instanceCount];
2830 }
2831}
2832
2833void QRhiMetal::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
2834 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
2835{
2836 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
2838
2839 if (!cbD->currentIndexBuffer)
2840 return;
2841
2842 const quint32 indexOffset = cbD->currentIndexOffset + firstIndex * (cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4);
2843 Q_ASSERT(indexOffset == aligned(indexOffset, 4u));
2844
2846 id<MTLBuffer> mtlibuf = ibufD->d->buf[ibufD->d->slotted ? currentFrameSlot : 0];
2847
2848 if (cbD->currentGraphicsPipeline->d->tess.enabled) {
2849 TessDrawArgs a;
2850 a.cbD = cbD;
2851 a.type = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? TessDrawArgs::U16Indexed : TessDrawArgs::U32Indexed;
2852 a.drawIndexed.indexCount = indexCount;
2853 a.drawIndexed.instanceCount = instanceCount;
2854 a.drawIndexed.firstIndex = firstIndex;
2855 a.drawIndexed.vertexOffset = vertexOffset;
2856 a.drawIndexed.firstInstance = firstInstance;
2857 a.drawIndexed.indexBuffer = mtlibuf;
2859 return;
2860 }
2861
2862 adjustForMultiViewDraw(&instanceCount, cb);
2863
2864 if (caps.baseVertexAndInstance) {
2865 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2866 indexCount: indexCount
2867 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
2868 indexBuffer: mtlibuf
2869 indexBufferOffset: indexOffset
2870 instanceCount: instanceCount
2871 baseVertex: vertexOffset
2872 baseInstance: firstInstance];
2873 } else {
2874 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2875 indexCount: indexCount
2876 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
2877 indexBuffer: mtlibuf
2878 indexBufferOffset: indexOffset
2879 instanceCount: instanceCount];
2880 }
2881}
2882
2883// Returns null when the ICB path is usable, otherwise the reason why not.
2885{
2886 if (!caps.indirectCommandBuffers)
2887 return "indirect command buffers are not supported on this device";
2889 || !cbD->currentGraphicsPipeline->m_flags.testFlag(QRhiGraphicsPipeline::UsesIndirectDraws))
2890 {
2891 return "the current graphics pipeline was not created with UsesIndirectDraws";
2892 }
2893 if (cbD->currentGraphicsPipeline->d->tess.enabled)
2894 return "the current graphics pipeline uses tessellation";
2896 return "the shaders of the current graphics pipeline sample textures but have no "
2897 "argument buffer variant, which Metal requires for a pipeline that supports "
2898 "indirect command buffers; rebuild them with qsb --msl-argument-buffers "
2899 "(or use MSLARGUMENTBUFFERS with qt_add_shaders)";
2900 }
2901 return nullptr;
2902}
2903
2905{
2907 return false;
2908
2909 if (!d->icbEncodePipeline) {
2910 NSError *err = nil;
2911 NSString *src = [NSString stringWithUTF8String:s_icbEncodeMsl];
2912 MTLCompileOptions *opts = [MTLCompileOptions new];
2913 opts.languageVersion = MTLLanguageVersion2_1;
2914 id<MTLLibrary> lib = [d->dev newLibraryWithSource:src options:opts error:&err];
2915 [opts release];
2916 if (!lib) {
2917 qWarning("Failed to compile ICB encode kernel: %s",
2918 qPrintable(QString::fromNSString(err.localizedDescription)));
2919 d->icbSetupFailed = true;
2920 return false;
2921 }
2922 d->icbEncodeFunction = [lib newFunctionWithName:@"encode_icb"];
2923 d->icbEncodeFunctionU32 = [lib newFunctionWithName:@"encode_icb_indexed_u32"];
2924 d->icbEncodeFunctionU16 = [lib newFunctionWithName:@"encode_icb_indexed_u16"];
2925 [lib release];
2926 if (!d->icbEncodeFunction || !d->icbEncodeFunctionU32 || !d->icbEncodeFunctionU16) {
2927 qWarning("ICB encode kernel functions not found");
2928 d->icbSetupFailed = true;
2929 return false;
2930 }
2931 NSError *errU32 = nil;
2932 NSError *errU16 = nil;
2933 d->icbEncodePipeline = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunction error:&err];
2934 d->icbEncodePipelineU32 = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunctionU32 error:&errU32];
2935 d->icbEncodePipelineU16 = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunctionU16 error:&errU16];
2936 if (!d->icbEncodePipeline || !d->icbEncodePipelineU32 || !d->icbEncodePipelineU16) {
2937 NSError *firstErr = !d->icbEncodePipeline ? err
2938 : (!d->icbEncodePipelineU32 ? errU32 : errU16);
2939 qWarning("Failed to create ICB encode compute pipeline: %s",
2940 qPrintable(QString::fromNSString(firstErr.localizedDescription)));
2941 d->icbSetupFailed = true;
2942 return false;
2943 }
2944 }
2945
2946 if (!d->icbRangeBuffer) {
2947 d->icbRangeBuffer = [d->dev newBufferWithLength:sizeof(MTLIndirectCommandBufferExecutionRange)
2948 options:MTLResourceStorageModePrivate];
2949 static constexpr quint32 noCount = 0xFFFFFFFFu;
2950 d->icbNoCountBuffer = [d->dev newBufferWithBytes:&noCount
2951 length:sizeof(noCount)
2952 options:MTLResourceStorageModeShared];
2953 if (!d->icbRangeBuffer || !d->icbNoCountBuffer) {
2954 qWarning("Failed to create ICB helper buffers");
2955 d->icbSetupFailed = true;
2956 return false;
2957 }
2958 }
2959
2960 return true;
2961}
2962
2963bool QRhiMetal::prepareIcb(quint32 maxDrawCount)
2964{
2966 return false;
2967
2968 if (!d->icb || d->icbCapacity < maxDrawCount) {
2969 if (d->icb) {
2972 e.lastActiveFrameSlot = currentFrameSlot;
2973 e.stagingIcbBuffer.icb = d->icb;
2974 e.stagingIcbBuffer.argBuffer = d->icbArgumentBuffer;
2975 d->releaseQueue.append(e);
2976 }
2977 d->icb = nil;
2978 d->icbArgumentBuffer = nil;
2979
2980 MTLIndirectCommandBufferDescriptor *icbDesc = [MTLIndirectCommandBufferDescriptor new];
2981 icbDesc.commandTypes = MTLIndirectCommandTypeDraw | MTLIndirectCommandTypeDrawIndexed;
2982 icbDesc.inheritPipelineState = YES;
2983 icbDesc.inheritBuffers = YES;
2984 icbDesc.maxVertexBufferBindCount = 0;
2985 icbDesc.maxFragmentBufferBindCount = 0;
2986 d->icb = [d->dev newIndirectCommandBufferWithDescriptor:icbDesc
2987 maxCommandCount:maxDrawCount
2988 options:MTLResourceStorageModePrivate];
2989 [icbDesc release];
2990 if (!d->icb) {
2991 qWarning("Failed to create MTLIndirectCommandBuffer");
2992 d->icbCapacity = 0;
2993 return false;
2994 }
2995 d->icbCapacity = maxDrawCount;
2996
2997 id<MTLArgumentEncoder> argEnc = [d->icbEncodeFunction newArgumentEncoderWithBufferIndex:1];
2998 d->icbArgumentBuffer = [d->dev newBufferWithLength:argEnc.encodedLength
2999 options:MTLResourceStorageModeShared];
3000 [argEnc setArgumentBuffer:d->icbArgumentBuffer offset:0];
3001 [argEnc setIndirectCommandBuffer:d->icb atIndex:0];
3002 [argEnc release];
3003 }
3004
3005 return true;
3006}
3007
3008// Encodes maxDrawCount entries of indirectBufMtl into targetIcb on an already
3009// open compute encoder, writing the encoded count to targetRangeBuffer.
3010// countBufMtl is optional: when null all maxDrawCount commands are encoded.
3012 id<MTLComputeCommandEncoder> computeEncoder,
3013 id<MTLIndirectCommandBuffer> targetIcb,
3014 id<MTLBuffer> targetArgBuffer,
3015 id<MTLBuffer> targetRangeBuffer,
3016 bool indexed,
3017 QRhiCommandBuffer::IndexFormat indexFormat,
3018 MTLPrimitiveType primitiveType,
3019 id<MTLBuffer> indirectBufMtl, quint32 indirectBufferOffset,
3020 id<MTLBuffer> indexBufMtl, quint32 indexBufferOffset,
3021 id<MTLBuffer> countBufMtl, quint32 countBufferOffset,
3022 quint32 maxDrawCount, quint32 stride)
3023{
3024 id<MTLComputePipelineState> computePipeline = d->icbEncodePipeline;
3025 if (indexed) {
3026 computePipeline = indexFormat == QRhiCommandBuffer::IndexUInt16
3027 ? d->icbEncodePipelineU16 : d->icbEncodePipelineU32;
3028 }
3029 uint32_t maxDrawCountVal = maxDrawCount;
3030 uint32_t metalPrimType = uint32_t(primitiveType);
3031 uint32_t strideVal = stride;
3032
3033 [computeEncoder setComputePipelineState:computePipeline];
3034 [computeEncoder setBuffer:indirectBufMtl offset:indirectBufferOffset atIndex:0];
3035 [computeEncoder setBuffer:targetArgBuffer offset:0 atIndex:1];
3036 [computeEncoder setBytes:&maxDrawCountVal length:sizeof(uint32_t) atIndex:2];
3037 if (indexed)
3038 [computeEncoder setBuffer:indexBufMtl offset:indexBufferOffset atIndex:3];
3039 [computeEncoder setBytes:&metalPrimType length:sizeof(uint32_t) atIndex:4];
3040 [computeEncoder setBytes:&strideVal length:sizeof(uint32_t) atIndex:5];
3041 [computeEncoder setBuffer:countBufMtl ? countBufMtl : d->icbNoCountBuffer
3042 offset:countBufMtl ? countBufferOffset : 0
3043 atIndex:6];
3044 [computeEncoder setBuffer:targetRangeBuffer offset:0 atIndex:7];
3045 [computeEncoder useResource:targetIcb usage:MTLResourceUsageWrite];
3046 [computeEncoder useResource:indirectBufMtl usage:MTLResourceUsageRead];
3047 if (indexed)
3048 [computeEncoder useResource:indexBufMtl usage:MTLResourceUsageRead];
3049
3050 NSUInteger tw = computePipeline.threadExecutionWidth;
3051 [computeEncoder dispatchThreads:MTLSizeMake(maxDrawCount, 1, 1)
3052 threadsPerThreadgroup:MTLSizeMake(tw, 1, 1)];
3053}
3054
3055// Encodes up to maxDrawCount commands into the shared ICB with a compute
3056// dispatch, then executes them on the render encoder. countBufMtl is optional:
3057// when null, all maxDrawCount commands are executed, otherwise the number of
3058// draws is min(maxDrawCount, <uint32 at countBufferOffset>), computed on the
3059// GPU. Returns false when the ICB could not be set up, in which case nothing
3060// was recorded and the pass is left untouched.
3061bool QRhiMetal::icbDraw(QMetalCommandBuffer *cbD, bool indexed,
3062 QMetalBuffer *indirectBufD, quint32 indirectBufferOffset,
3063 QMetalBuffer *countBufD, quint32 countBufferOffset,
3064 quint32 maxDrawCount, quint32 stride)
3065{
3066 if (!maxDrawCount)
3067 return true;
3068
3069 QMetalBuffer *indexBufD = cbD->currentIndexBuffer;
3070 if (indexed && !indexBufD)
3071 return false;
3072
3073 if (!prepareIcb(maxDrawCount))
3074 return false;
3075
3077 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3078 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3079
3080 id<MTLBuffer> countBufMtl = nil;
3081 if (countBufD) {
3083 countBufD->lastActiveFrameSlot = currentFrameSlot;
3084 countBufMtl = countBufD->d->buf[countBufD->d->slotted ? currentFrameSlot : 0];
3085 }
3086
3087 // Everything below survives the interruption only if saved and restored.
3089 const QMetalShaderResourceBindingsData savedResourceBindings = cbD->d->currentShaderResourceBindingState;
3090 const int savedFirstVertexBinding = cbD->d->currentFirstVertexBinding;
3091 const auto savedVertexBuffers = cbD->d->currentVertexInputsBuffers;
3092 const auto savedVertexOffsets = cbD->d->currentVertexInputOffsets;
3093 const quint32 savedIndexOffset = cbD->currentIndexOffset;
3094 const QRhiCommandBuffer::IndexFormat savedIndexFormat = cbD->currentIndexFormat;
3095 id<MTLBuffer> indexBufMtl = indexed
3096 ? indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0] : nil;
3097
3098 // End the current render encoder to make room for the compute pass.
3100
3101 id<MTLComputeCommandEncoder> computeEncoder = [cbD->d->cb computeCommandEncoder];
3102 encodeIcbWithCompute(d, computeEncoder, d->icb, d->icbArgumentBuffer, d->icbRangeBuffer,
3103 indexed, savedIndexFormat, savedPipeline->d->primitiveType,
3104 indirectBufMtl, indirectBufferOffset,
3105 indexBufMtl, savedIndexOffset,
3106 countBufMtl, countBufferOffset,
3107 maxDrawCount, stride);
3108
3109 // Restart the render pass with Load actions to preserve existing content.
3110 endTempComputeEncoding(this, cbD, computeEncoder);
3111
3112 // Restore pipeline, shader resources, and vertex bindings on the new encoder.
3115 QMetalShaderResourceBindingsData::VERTEX, &savedResourceBindings);
3117 QMetalShaderResourceBindingsData::FRAGMENT, &savedResourceBindings);
3118
3119 if (savedFirstVertexBinding >= 0) {
3120 cbD->d->currentFirstVertexBinding = savedFirstVertexBinding;
3121 cbD->d->currentVertexInputsBuffers = savedVertexBuffers;
3122 cbD->d->currentVertexInputOffsets = savedVertexOffsets;
3123 for (int i = 0, ie = savedVertexBuffers.batches.count(); i != ie; ++i) {
3124 const auto &bufferBatch(savedVertexBuffers.batches[i]);
3125 const auto &offsetBatch(savedVertexOffsets.batches[i]);
3126 [cbD->d->currentRenderPassEncoder setVertexBuffers:
3127 bufferBatch.resources.constData()
3128 offsets: offsetBatch.resources.constData()
3129 withRange: NSMakeRange(uint(savedFirstVertexBinding) + bufferBatch.startBinding,
3130 NSUInteger(bufferBatch.resources.count()))];
3131 }
3132 }
3133
3134 cbD->currentIndexBuffer = indexBufD;
3135 cbD->currentIndexOffset = savedIndexOffset;
3136 cbD->currentIndexFormat = savedIndexFormat;
3137
3138 // Declare buffer dependencies and execute the GPU-encoded ICB. The range to
3139 // execute is read from icbRangeBuffer, which the kernel just wrote.
3140 [cbD->d->currentRenderPassEncoder useResource:indirectBufMtl
3141 usage:MTLResourceUsageRead
3142 stages:MTLRenderStageVertex | MTLRenderStageFragment];
3143 if (indexed) {
3144 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
3145 usage:MTLResourceUsageRead
3146 stages:MTLRenderStageVertex | MTLRenderStageFragment];
3147 }
3148 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:d->icb
3149 indirectBuffer:d->icbRangeBuffer
3150 indirectBufferOffset:0];
3151 return true;
3152}
3153
3154// The ICB (Indirect Command Buffer) path encodes the draw commands on the GPU
3155// and executes them with a single executeCommandsInBuffer, which removes the
3156// per-draw CPU overhead. The encoding needs a compute pass, so the render pass
3157// has to be interrupted and restarted: that costs about 100-150 microseconds,
3158// whereas an individual indirect draw call takes 1-2. Hence only taking this
3159// path for large batches.
3160static constexpr quint32 ICB_DRAW_COUNT_THRESHOLD = 128;
3161
3162void QRhiMetal::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
3163 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
3164{
3165 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3167
3168 QMetalBuffer *indirectBufD = QRHI_RES(QMetalBuffer, indirectBuffer);
3170 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3171 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3172
3173 if (drawCount > ICB_DRAW_COUNT_THRESHOLD && !icbUnavailableReason(cbD)
3174 && icbDraw(cbD, false, indirectBufD, indirectBufferOffset, nullptr, 0, drawCount, stride))
3175 {
3176 return;
3177 }
3178
3179 // CPU-side for-loop fallback: used when ICB is not applicable or setup failed.
3180 NSUInteger offset = indirectBufferOffset;
3181 for (quint32 i = 0; i < drawCount; ++i) {
3182 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
3183 indirectBuffer: indirectBufMtl
3184 indirectBufferOffset: offset];
3185 offset += stride;
3186 }
3187}
3188
3189void QRhiMetal::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
3190 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
3191{
3192 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3194
3195 if (!cbD->currentIndexBuffer)
3196 return;
3197
3198 QMetalBuffer *indexBufD = cbD->currentIndexBuffer;
3199 id<MTLBuffer> indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
3200
3201 QMetalBuffer *indirectBufD = QRHI_RES(QMetalBuffer, indirectBuffer);
3203 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3204 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3205
3206 if (drawCount > ICB_DRAW_COUNT_THRESHOLD && !icbUnavailableReason(cbD)
3207 && icbDraw(cbD, true, indirectBufD, indirectBufferOffset, nullptr, 0, drawCount, stride))
3208 {
3209 return;
3210 }
3211
3212 // CPU-side for-loop fallback: used when ICB is not applicable or setup failed.
3213 NSUInteger offset = indirectBufferOffset;
3214 for (quint32 i = 0; i < drawCount; ++i) {
3215 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
3216 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
3217 indexBuffer: indexBufMtl
3218 indexBufferOffset: cbD->currentIndexOffset
3219 indirectBuffer: indirectBufMtl
3220 indirectBufferOffset: offset];
3221 offset += stride;
3222 }
3223}
3224
3225void QRhiMetal::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
3226{
3227 if (!debugMarkers)
3228 return;
3229
3230 NSString *str = [NSString stringWithUTF8String: name.constData()];
3231 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3232 switch (cbD->recordingPass) {
3233 case QMetalCommandBuffer::RenderPass:
3234 [cbD->d->currentRenderPassEncoder pushDebugGroup: str];
3235 cbD->d->openDebugGroups.append(name);
3236 break;
3237 case QMetalCommandBuffer::ComputePass:
3238 [cbD->d->currentComputePassEncoder pushDebugGroup: str];
3239 break;
3240 default:
3241 [cbD->d->cb pushDebugGroup: str];
3242 break;
3243 }
3244}
3245
3246void QRhiMetal::debugMarkEnd(QRhiCommandBuffer *cb)
3247{
3248 if (!debugMarkers)
3249 return;
3250
3251 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3252 switch (cbD->recordingPass) {
3253 case QMetalCommandBuffer::RenderPass:
3254 [cbD->d->currentRenderPassEncoder popDebugGroup];
3255 if (!cbD->d->openDebugGroups.isEmpty())
3256 cbD->d->openDebugGroups.removeLast();
3257 break;
3258 case QMetalCommandBuffer::ComputePass:
3259 [cbD->d->currentComputePassEncoder popDebugGroup];
3260 break;
3261 default:
3262 [cbD->d->cb popDebugGroup];
3263 break;
3264 }
3265}
3266
3267void QRhiMetal::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
3268{
3269 if (!debugMarkers)
3270 return;
3271
3272 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3273 NSString *str = [NSString stringWithUTF8String: msg.constData()];
3274 switch (cbD->recordingPass) {
3275 case QMetalCommandBuffer::RenderPass:
3276 [cbD->d->currentRenderPassEncoder insertDebugSignpost: str];
3277 break;
3278 case QMetalCommandBuffer::ComputePass:
3279 [cbD->d->currentComputePassEncoder insertDebugSignpost: str];
3280 break;
3281 default:
3282 break;
3283 }
3284}
3285
3286const QRhiNativeHandles *QRhiMetal::nativeHandles(QRhiCommandBuffer *cb)
3287{
3288 return QRHI_RES(QMetalCommandBuffer, cb)->nativeHandles();
3289}
3290
3291void QRhiMetal::beginExternal(QRhiCommandBuffer *cb)
3292{
3293 Q_UNUSED(cb);
3294}
3295
3296void QRhiMetal::endExternal(QRhiCommandBuffer *cb)
3297{
3298 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3300}
3301
3302double QRhiMetal::lastCompletedGpuTime(QRhiCommandBuffer *cb)
3303{
3304 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3305 return cbD->d->lastGpuTime;
3306}
3307
3308QRhi::FrameOpResult QRhiMetal::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
3309{
3310 Q_UNUSED(flags);
3311
3312 QMetalSwapChain *swapChainD = QRHI_RES(QMetalSwapChain, swapChain);
3313 currentSwapChain = swapChainD;
3314 currentFrameSlot = swapChainD->currentFrameSlot;
3315
3316 // If we are too far ahead, block. This is also what ensures that any
3317 // resource used in the previous frame for this slot is now not in use
3318 // anymore by the GPU.
3319 dispatch_semaphore_wait(swapChainD->d->sem[currentFrameSlot], DISPATCH_TIME_FOREVER);
3320
3321 // Do this also for any other swapchain's commands with the same frame slot
3322 // While this reduces concurrency, it keeps resource usage safe: swapchain
3323 // A starting its frame 0, followed by swapchain B starting its own frame 0
3324 // will make B wait for A's frame 0 commands, so if a resource is written
3325 // in B's frame or when B checks for pending resource releases, that won't
3326 // mess up A's in-flight commands (as they are not in flight anymore).
3327 for (QMetalSwapChain *sc : std::as_const(swapchains)) {
3328 if (sc != swapChainD)
3329 sc->waitUntilCompleted(currentFrameSlot); // wait+signal
3330 }
3331
3332 [d->captureScope beginScope];
3333
3334 swapChainD->cbWrapper.d->cb = d->newCommandBuffer();
3335
3337 if (swapChainD->samples > 1) {
3338 colorAtt.tex = swapChainD->d->msaaTex[currentFrameSlot];
3339 colorAtt.needsDrawableForResolveTex = true;
3340 } else {
3341 colorAtt.needsDrawableForTex = true;
3342 }
3343
3344 swapChainD->rtWrapper.d->fb.colorAtt[0] = colorAtt;
3345 swapChainD->rtWrapper.d->fb.dsTex = swapChainD->ds ? swapChainD->ds->d->tex : nil;
3346 swapChainD->rtWrapper.d->fb.dsResolveTex = nil;
3347 swapChainD->rtWrapper.d->fb.hasStencil = swapChainD->ds ? true : false;
3348 swapChainD->rtWrapper.d->fb.depthNeedsStore = false;
3349
3350 if (swapChainD->ds)
3351 swapChainD->ds->lastActiveFrameSlot = currentFrameSlot;
3352
3353 d->argBufPool[currentFrameSlot].offset = 0;
3354 d->resetAndResizeBufferStagingArea(currentFrameSlot);
3355 d->globalFrameId += 1;
3356
3358 swapChainD->cbWrapper.resetState(swapChainD->d->lastGpuTime[currentFrameSlot]);
3359 swapChainD->d->lastGpuTime[currentFrameSlot] = 0;
3361
3362 return QRhi::FrameOpSuccess;
3363}
3364
3365QRhi::FrameOpResult QRhiMetal::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
3366{
3367 QMetalSwapChain *swapChainD = QRHI_RES(QMetalSwapChain, swapChain);
3368 Q_ASSERT(currentSwapChain == swapChainD);
3369
3370 // Keep strong reference to command buffer
3371 id<MTLCommandBuffer> commandBuffer = swapChainD->cbWrapper.d->cb;
3372
3373 __block int thisFrameSlot = currentFrameSlot;
3374 [commandBuffer addCompletedHandler: ^(id<MTLCommandBuffer> cb) {
3375 swapChainD->d->lastGpuTime[thisFrameSlot] += cb.GPUEndTime - cb.GPUStartTime;
3376 dispatch_semaphore_signal(swapChainD->d->sem[thisFrameSlot]);
3377 }];
3378
3380 // When Metal API validation diagnostics is enabled in Xcode the texture is
3381 // released before the command buffer is done with it. Manually keep it alive
3382 // to work around this.
3383 id<MTLTexture> drawableTexture = [swapChainD->d->curDrawable.texture retain];
3384 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>) {
3385 [drawableTexture release];
3386 }];
3387#endif
3388
3389 if (flags.testFlag(QRhi::SkipPresent)) {
3390 // Just need to commit, that's it
3391 [commandBuffer commit];
3392 } else {
3393 if (id<CAMetalDrawable> drawable = swapChainD->d->curDrawable) {
3394 // Got something to present
3395 if (swapChainD->d->layer.presentsWithTransaction) {
3396 [commandBuffer commit];
3397 // Keep strong reference to Metal layer
3398 auto *metalLayer = swapChainD->d->layer;
3399 auto presentWithTransaction = ^{
3400 [commandBuffer waitUntilScheduled];
3401 // If the layer has been resized while we waited to be scheduled we bail out,
3402 // as the drawable is no longer valid for the layer, and we'll get a follow-up
3403 // display with the right size. We know we are on the main thread here, which
3404 // means we can access the layer directly. We also know that the layer is valid,
3405 // since the block keeps a strong reference to it, compared to the QRhiSwapChain
3406 // that can go away under our feet by the time we're scheduled.
3407 const auto surfaceSize = QSizeF::fromCGSize(metalLayer.bounds.size) * metalLayer.contentsScale;
3408 const auto textureSize = QSizeF(drawable.texture.width, drawable.texture.height);
3409 if (textureSize == surfaceSize) {
3410 [drawable present];
3411 } else {
3412 qCDebug(QRHI_LOG_INFO) << "Skipping" << drawable << "due to texture size"
3413 << textureSize << "not matching surface size" << surfaceSize;
3414 }
3415 };
3416
3417 if (NSThread.currentThread == NSThread.mainThread) {
3418 presentWithTransaction();
3419 } else {
3420 auto *qtMetalLayer = qt_objc_cast<QMetalLayer*>(swapChainD->d->layer);
3421 Q_ASSERT(qtMetalLayer);
3422 // Let the main thread present the drawable from displayLayer
3423 qtMetalLayer.mainThreadPresentation = presentWithTransaction;
3424 }
3425 } else {
3426 // Keep strong reference to Metal layer so it's valid in the block
3427 auto *qtMetalLayer = qt_objc_cast<QMetalLayer*>(swapChainD->d->layer);
3428 [commandBuffer addScheduledHandler:^(id<MTLCommandBuffer>) {
3429 if (qtMetalLayer) {
3430 // The schedule handler comes in on the com.Metal.CompletionQueueDispatch
3431 // thread, which means we might be racing against a display cycle on the
3432 // main thread. If the displayLayer is already in progress, we don't want
3433 // to step on its toes.
3434 if (qtMetalLayer.displayLock.tryLockForRead()) {
3435 [drawable present];
3436 qtMetalLayer.displayLock.unlock();
3437 } else {
3438 qCDebug(QRHI_LOG_INFO) << "Skipping" << drawable
3439 << "due to" << qtMetalLayer << "needing display";
3440 }
3441 } else {
3442 [drawable present];
3443 }
3444 }];
3445 [commandBuffer commit];
3446 }
3447 } else {
3448 // Still need to commit, even if we don't have a drawable
3449 [commandBuffer commit];
3450 }
3451
3452 swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QMTL_FRAMES_IN_FLIGHT;
3453 }
3454
3455 // Must not hold on to the drawable, regardless of needsPresent
3456 [swapChainD->d->curDrawable release];
3457 swapChainD->d->curDrawable = nil;
3458
3459 [d->captureScope endScope];
3460
3461 swapChainD->frameCount += 1;
3462 currentSwapChain = nullptr;
3463 return QRhi::FrameOpSuccess;
3464}
3465
3466QRhi::FrameOpResult QRhiMetal::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags)
3467{
3468 Q_UNUSED(flags);
3469
3470 currentFrameSlot = (currentFrameSlot + 1) % QMTL_FRAMES_IN_FLIGHT;
3471
3472 for (QMetalSwapChain *sc : std::as_const(swapchains))
3473 sc->waitUntilCompleted(currentFrameSlot);
3474
3475 d->ofr.active = true;
3476 *cb = &d->ofr.cbWrapper;
3477 d->ofr.cbWrapper.d->cb = d->newCommandBuffer();
3478
3479 d->argBufPool[currentFrameSlot].offset = 0;
3480 d->resetAndResizeBufferStagingArea(currentFrameSlot);
3481 d->globalFrameId += 1;
3482
3484 d->ofr.cbWrapper.resetState(d->ofr.lastGpuTime);
3485 d->ofr.lastGpuTime = 0;
3487
3488 return QRhi::FrameOpSuccess;
3489}
3490
3491QRhi::FrameOpResult QRhiMetal::endOffscreenFrame(QRhi::EndFrameFlags flags)
3492{
3493 Q_UNUSED(flags);
3494 Q_ASSERT(d->ofr.active);
3495 d->ofr.active = false;
3496
3497 id<MTLCommandBuffer> cb = d->ofr.cbWrapper.d->cb;
3498 [cb commit];
3499
3500 // offscreen frames wait for completion, unlike swapchain ones
3501 [cb waitUntilCompleted];
3502
3503 d->ofr.lastGpuTime += cb.GPUEndTime - cb.GPUStartTime;
3504
3506
3507 return QRhi::FrameOpSuccess;
3508}
3509
3511{
3512 id<MTLCommandBuffer> cb = nil;
3513 QMetalSwapChain *swapChainD = nullptr;
3514 if (inFrame) {
3515 if (d->ofr.active) {
3516 Q_ASSERT(!currentSwapChain);
3517 Q_ASSERT(d->ofr.cbWrapper.recordingPass == QMetalCommandBuffer::NoPass);
3518 cb = d->ofr.cbWrapper.d->cb;
3519 } else {
3520 Q_ASSERT(currentSwapChain);
3521 swapChainD = currentSwapChain;
3522 Q_ASSERT(swapChainD->cbWrapper.recordingPass == QMetalCommandBuffer::NoPass);
3523 cb = swapChainD->cbWrapper.d->cb;
3524 }
3525 }
3526
3527 for (QMetalSwapChain *sc : std::as_const(swapchains)) {
3528 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
3529 if (currentSwapChain && sc == currentSwapChain && i == currentFrameSlot) {
3530 // no wait as this is the thing we're going to be commit below and
3531 // beginFrame decremented sem already and going to be signaled by endFrame
3532 continue;
3533 }
3534 sc->waitUntilCompleted(i);
3535 }
3536 }
3537
3538 if (cb) {
3539 [cb commit];
3540 [cb waitUntilCompleted];
3541 }
3542
3543 if (inFrame) {
3544 if (d->ofr.active) {
3545 d->ofr.lastGpuTime += cb.GPUEndTime - cb.GPUStartTime;
3546 d->ofr.cbWrapper.d->cb = d->newCommandBuffer();
3547 } else {
3548 swapChainD->d->lastGpuTime[currentFrameSlot] += cb.GPUEndTime - cb.GPUStartTime;
3549 swapChainD->cbWrapper.d->cb = d->newCommandBuffer();
3550 }
3551 }
3552
3554
3556
3557 return QRhi::FrameOpSuccess;
3558}
3559
3561 const QColor &colorClearValue,
3562 const QRhiDepthStencilClearValue &depthStencilClearValue,
3563 int colorAttCount,
3564 QRhiShadingRateMap *shadingRateMap)
3565{
3566 MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
3567 MTLClearColor c = MTLClearColorMake(colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3568 colorClearValue.alphaF());
3569
3570 for (uint i = 0; i < uint(colorAttCount); ++i) {
3571 rp.colorAttachments[i].loadAction = MTLLoadActionClear;
3572 rp.colorAttachments[i].storeAction = MTLStoreActionStore;
3573 rp.colorAttachments[i].clearColor = c;
3574 }
3575
3576 if (hasDepthStencil) {
3577 rp.depthAttachment.loadAction = MTLLoadActionClear;
3578 rp.depthAttachment.storeAction = MTLStoreActionDontCare;
3579 rp.stencilAttachment.loadAction = MTLLoadActionClear;
3580 rp.stencilAttachment.storeAction = MTLStoreActionDontCare;
3581 rp.depthAttachment.clearDepth = double(depthStencilClearValue.depthClearValue());
3582 rp.stencilAttachment.clearStencil = depthStencilClearValue.stencilClearValue();
3583 }
3584
3585 if (shadingRateMap)
3586 rp.rasterizationRateMap = QRHI_RES(QMetalShadingRateMap, shadingRateMap)->d->rateMap;
3587
3588 return rp;
3589}
3590
3591qsizetype QRhiMetal::subresUploadByteSize(const QRhiTextureSubresourceUploadDescription &subresDesc) const
3592{
3593 qsizetype size = 0;
3594 const qsizetype imageSizeBytes = subresDesc.image().isNull() ?
3595 subresDesc.data().size() : subresDesc.image().sizeInBytes();
3596 if (imageSizeBytes > 0)
3597 size += aligned<qsizetype>(imageSizeBytes, QRhiMetalData::TEXBUF_ALIGN);
3598 return size;
3599}
3600
3601void QRhiMetal::enqueueSubresUpload(QMetalTexture *texD, void *mp, void *blitEncPtr,
3602 int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc,
3603 qsizetype *curOfs)
3604{
3605 const QPoint dp = subresDesc.destinationTopLeft();
3606 const QByteArray rawData = subresDesc.data();
3607 QImage img = subresDesc.image();
3608 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3609 id<MTLBlitCommandEncoder> blitEnc = (id<MTLBlitCommandEncoder>) blitEncPtr;
3610
3611 if (!img.isNull()) {
3612 const qsizetype fullImageSizeBytes = img.sizeInBytes();
3613 QSize size = img.size();
3614 int bpl = img.bytesPerLine();
3615
3616 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
3617 const int sx = subresDesc.sourceTopLeft().x();
3618 const int sy = subresDesc.sourceTopLeft().y();
3619 if (!subresDesc.sourceSize().isEmpty())
3620 size = subresDesc.sourceSize();
3621 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3622 if (size.width() == img.width()) {
3623 const int bpc = qMax(1, img.depth() / 8);
3624 Q_ASSERT(size.height() * img.bytesPerLine() <= fullImageSizeBytes);
3625 memcpy(reinterpret_cast<char *>(mp) + *curOfs,
3626 img.constBits() + sy * img.bytesPerLine() + sx * bpc,
3627 size.height() * img.bytesPerLine());
3628 } else {
3629 img = img.copy(sx, sy, size.width(), size.height());
3630 bpl = img.bytesPerLine();
3631 Q_ASSERT(img.sizeInBytes() <= fullImageSizeBytes);
3632 memcpy(reinterpret_cast<char *>(mp) + *curOfs, img.constBits(), size_t(img.sizeInBytes()));
3633 }
3634 } else {
3635 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3636 memcpy(reinterpret_cast<char *>(mp) + *curOfs, img.constBits(), size_t(fullImageSizeBytes));
3637 }
3638
3639 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3640 sourceOffset: NSUInteger(*curOfs)
3641 sourceBytesPerRow: NSUInteger(bpl)
3642 sourceBytesPerImage: 0
3643 sourceSize: MTLSizeMake(NSUInteger(size.width()), NSUInteger(size.height()), 1)
3644 toTexture: texD->d->tex
3645 destinationSlice: NSUInteger(is3D ? 0 : layer)
3646 destinationLevel: NSUInteger(level)
3647 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(is3D ? layer : 0))
3648 options: MTLBlitOptionNone];
3649
3650 *curOfs += aligned<qsizetype>(fullImageSizeBytes, QRhiMetalData::TEXBUF_ALIGN);
3651 } else if (!rawData.isEmpty() && isCompressedFormat(texD->m_format)) {
3652 const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize);
3653 const int subresw = subresSize.width();
3654 const int subresh = subresSize.height();
3655 int w, h;
3656 if (subresDesc.sourceSize().isEmpty()) {
3657 w = subresw;
3658 h = subresh;
3659 } else {
3660 w = subresDesc.sourceSize().width();
3661 h = subresDesc.sourceSize().height();
3662 }
3663
3664 const QSize clamped = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format,
3665 QSize(w, h),
3666 rawData.size());
3667 if (clamped.height() == 0)
3668 return;
3669 h = clamped.height();
3670
3671 quint32 bpl = 0;
3672 QSize blockDim;
3673 compressedFormatInfo(texD->m_format, QSize(w, h), &bpl, nullptr, &blockDim);
3674
3675 const int dx = aligned(dp.x(), blockDim.width());
3676 const int dy = aligned(dp.y(), blockDim.height());
3677 if (dx + w != subresw)
3678 w = aligned(w, blockDim.width());
3679 if (dy + h != subresh)
3680 h = aligned(h, blockDim.height());
3681
3682 memcpy(reinterpret_cast<char *>(mp) + *curOfs, rawData.constData(), size_t(rawData.size()));
3683
3684 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3685 sourceOffset: NSUInteger(*curOfs)
3686 sourceBytesPerRow: bpl
3687 sourceBytesPerImage: 0
3688 sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1)
3689 toTexture: texD->d->tex
3690 destinationSlice: NSUInteger(is3D ? 0 : layer)
3691 destinationLevel: NSUInteger(level)
3692 destinationOrigin: MTLOriginMake(NSUInteger(dx), NSUInteger(dy), NSUInteger(is3D ? layer : 0))
3693 options: MTLBlitOptionNone];
3694
3695 *curOfs += aligned<qsizetype>(rawData.size(), QRhiMetalData::TEXBUF_ALIGN);
3696 } else if (!rawData.isEmpty()) {
3697 const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize);
3698 const int subresw = subresSize.width();
3699 const int subresh = subresSize.height();
3700 int w, h;
3701 if (subresDesc.sourceSize().isEmpty()) {
3702 w = subresw;
3703 h = subresh;
3704 } else {
3705 w = subresDesc.sourceSize().width();
3706 h = subresDesc.sourceSize().height();
3707 }
3708
3709 QSize size = clampedSubResourceUploadSize(QSize(w, h), dp, level, texD->m_pixelSize);
3710 quint32 bytesPerPixel = 0;
3711 textureFormatInfo(texD->m_format, size, nullptr, nullptr, &bytesPerPixel);
3712 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
3713 bytesPerPixel, rawData.size());
3714 w = size.width();
3715 h = size.height();
3716
3717 quint32 bpl = 0;
3718 if (subresDesc.dataStride())
3719 bpl = subresDesc.dataStride();
3720 else
3721 textureFormatInfo(texD->m_format, QSize(w, h), &bpl, nullptr, nullptr);
3722
3723 memcpy(reinterpret_cast<char *>(mp) + *curOfs, rawData.constData(), size_t(rawData.size()));
3724
3725 if (!size.isEmpty()) {
3726 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3727 sourceOffset: NSUInteger(*curOfs)
3728 sourceBytesPerRow: bpl
3729 sourceBytesPerImage: 0
3730 sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1)
3731 toTexture: texD->d->tex
3732 destinationSlice: NSUInteger(is3D ? 0 : layer)
3733 destinationLevel: NSUInteger(level)
3734 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(is3D ? layer : 0))
3735 options: MTLBlitOptionNone];
3736 }
3737
3738 *curOfs += aligned<qsizetype>(rawData.size(), QRhiMetalData::TEXBUF_ALIGN);
3739 } else {
3740 qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
3741 }
3742}
3743
3744void QRhiMetal::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
3745{
3746 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
3748
3749 id<MTLBlitCommandEncoder> blitEnc = nil;
3750 auto ensureBlit = [&blitEnc, cbD, this]() {
3751 if (!blitEnc) {
3752 blitEnc = [cbD->d->cb blitCommandEncoder];
3753 if (debugMarkers)
3754 [blitEnc pushDebugGroup: @"Resource updates"];
3755 }
3756 };
3757
3758 for (int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
3759 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
3761 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, u.buf);
3762 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
3763 for (int i = 0, ie = bufD->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1; i != ie; ++i) {
3764 if (u.offset == 0 && u.data.size() == bufD->m_size)
3765 bufD->d->pendingUpdates[i].clear();
3766 bufD->d->pendingUpdates[i].append({ u.offset, u.data });
3767 }
3769 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, u.buf);
3770 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
3771 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
3772 if (bufD->d->isDeviceLocal) {
3773 const quint32 size = quint32(u.data.size());
3774 if (size) { // a zero size blit is invalid
3775 quint32 stagingOffset = 0;
3776 id<MTLBuffer> stagingBuf = d->allocBufferStaging(size, currentFrameSlot, &stagingOffset);
3777 if (stagingBuf) {
3778 char *p = reinterpret_cast<char *>([stagingBuf contents]);
3779 memcpy(p + stagingOffset, u.data.constData(), size);
3780 ensureBlit();
3781 [blitEnc copyFromBuffer: stagingBuf
3782 sourceOffset: stagingOffset
3783 toBuffer: bufD->d->buf[0]
3784 destinationOffset: u.offset
3785 size: size];
3786 } else {
3787 qWarning("Failed to allocate staging buffer of size %u for buffer upload", size);
3788 }
3789 }
3790 bufD->lastActiveFrameSlot = currentFrameSlot;
3791 } else {
3792 for (int i = 0, ie = bufD->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1; i != ie; ++i)
3793 bufD->d->pendingUpdates[i].append({ u.offset, u.data });
3794 }
3796 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, u.buf);
3798 const int idx = bufD->d->slotted ? currentFrameSlot : 0;
3799 if (bufD->m_type == QRhiBuffer::Dynamic) {
3800 char *p = reinterpret_cast<char *>([bufD->d->buf[idx] contents]);
3801 if (p) {
3802 u.result->data.resize(u.readSize);
3803 memcpy(u.result->data.data(), p + u.offset, size_t(u.readSize));
3804 }
3805 if (u.result->completed)
3806 u.result->completed();
3807 } else {
3808 // Copy into a dedicated staging buffer, here and now, instead
3809 // of holding on to the buffer and reading it when the readback
3810 // completes. The contents have to be the ones at this point in
3811 // the command stream: a buffer that is not slotted - which is
3812 // every buffer with StorageBuffer usage - has one native buffer
3813 // shared by all frames, so by the time the readback completes a
3814 // later frame may well be writing it.
3815 QRhiMetalData::BufferReadback readback;
3816 readback.activeFrameSlot = currentFrameSlot;
3817 readback.readSize = u.readSize;
3818 readback.result = u.result;
3819 readback.buf = [d->dev newBufferWithLength: u.readSize
3820 options: MTLResourceStorageModeShared];
3821
3822 ensureBlit();
3823 [blitEnc copyFromBuffer: bufD->d->buf[idx]
3824 sourceOffset: u.offset
3825 toBuffer: readback.buf
3826 destinationOffset: 0
3827 size: u.readSize];
3828
3829 d->activeBufferReadbacks.append(readback);
3830 bufD->lastActiveFrameSlot = currentFrameSlot;
3831 }
3833 QMetalBuffer *dstD = QRHI_RES(QMetalBuffer, u.buf);
3834 QMetalBuffer *srcD = QRHI_RES(QMetalBuffer, u.src);
3835 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
3836
3838 const int srcIdx = srcD->d->slotted ? currentFrameSlot : 0;
3839 const int dstSlotCount = dstD->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1;
3840 // With device private buffers dstSlotCount is 1 and there are no
3841 // pending host writes at all, so this is a no-op. On the host
3842 // visible path every slot has to be flushed, not just the current
3843 // one: a partial copy cannot discard the pending writes outside the
3844 // copied range, and leaving them queued would let them land on top
3845 // of the copy in a later frame. Writing the slot that is not the
3846 // current one races a still in-flight frame reading it, which is
3847 // why mixing uploadStaticBuffer() and copyBuffer() on one buffer
3848 // within a frame stays unsupported there.
3849 for (int i = 0; i != dstSlotCount; ++i)
3851
3852 ensureBlit();
3853 for (int i = 0; i != dstSlotCount; ++i) {
3854 [blitEnc copyFromBuffer: srcD->d->buf[srcIdx]
3855 sourceOffset: u.srcOffset
3856 toBuffer: dstD->d->buf[i]
3857 destinationOffset: u.offset
3858 size: u.readSize];
3859 }
3860
3861 srcD->lastActiveFrameSlot = dstD->lastActiveFrameSlot = currentFrameSlot;
3863 QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, u.buf);
3864 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic && !bufD->d->slotted);
3866 ensureBlit();
3867 [blitEnc fillBuffer: bufD->d->buf[0]
3868 range: NSMakeRange(u.offset, u.readSize)
3869 value: u.fillValue];
3870 bufD->lastActiveFrameSlot = currentFrameSlot;
3871 }
3872 }
3873
3874 for (int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
3875 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
3877 QMetalTexture *utexD = QRHI_RES(QMetalTexture, u.dst);
3878 qsizetype stagingSize = 0;
3879 for (const auto &subres : u.subresDesc)
3880 stagingSize += subresUploadByteSize(subres.desc);
3881
3882 ensureBlit();
3883 Q_ASSERT(!utexD->d->stagingBuf[currentFrameSlot]);
3884 utexD->d->stagingBuf[currentFrameSlot] = [d->dev newBufferWithLength: NSUInteger(stagingSize)
3885 options: MTLResourceStorageModeShared];
3886
3887 void *mp = [utexD->d->stagingBuf[currentFrameSlot] contents];
3888 qsizetype curOfs = 0;
3889 for (const auto &subres : u.subresDesc)
3890 enqueueSubresUpload(utexD, mp, blitEnc, subres.layer, subres.level, subres.desc, &curOfs);
3891
3892 utexD->lastActiveFrameSlot = currentFrameSlot;
3893
3896 e.lastActiveFrameSlot = currentFrameSlot;
3897 e.stagingBuffer.buffer = utexD->d->stagingBuf[currentFrameSlot];
3898 utexD->d->stagingBuf[currentFrameSlot] = nil;
3899 d->releaseQueue.append(e);
3901 Q_ASSERT(u.src && u.dst);
3902 QMetalTexture *srcD = QRHI_RES(QMetalTexture, u.src);
3903 QMetalTexture *dstD = QRHI_RES(QMetalTexture, u.dst);
3904 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3905 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3906 const QPoint dp = u.desc.destinationTopLeft();
3907 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
3908 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
3909 const QPoint sp = u.desc.sourceTopLeft();
3910
3911 ensureBlit();
3912 [blitEnc copyFromTexture: srcD->d->tex
3913 sourceSlice: NSUInteger(srcIs3D ? 0 : u.desc.sourceLayer())
3914 sourceLevel: NSUInteger(u.desc.sourceLevel())
3915 sourceOrigin: MTLOriginMake(NSUInteger(sp.x()), NSUInteger(sp.y()), NSUInteger(srcIs3D ? u.desc.sourceLayer() : 0))
3916 sourceSize: MTLSizeMake(NSUInteger(copySize.width()), NSUInteger(copySize.height()), 1)
3917 toTexture: dstD->d->tex
3918 destinationSlice: NSUInteger(dstIs3D ? 0 : u.desc.destinationLayer())
3919 destinationLevel: NSUInteger(u.desc.destinationLevel())
3920 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(dstIs3D ? u.desc.destinationLayer() : 0))];
3921
3922 srcD->lastActiveFrameSlot = dstD->lastActiveFrameSlot = currentFrameSlot;
3925 readback.activeFrameSlot = currentFrameSlot;
3926 readback.desc = u.rb;
3927 readback.result = u.result;
3928
3929 QMetalTexture *texD = QRHI_RES(QMetalTexture, u.rb.texture());
3930 QMetalSwapChain *swapChainD = nullptr;
3931 id<MTLTexture> src;
3932 QRect rect;
3933 bool is3D = false;
3934 if (texD) {
3935 if (texD->samples > 1) {
3936 qWarning("Multisample texture cannot be read back");
3937 continue;
3938 }
3939 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3940 if (u.rb.rect().isValid())
3941 rect = u.rb.rect();
3942 else
3943 rect = QRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
3944 readback.format = texD->m_format;
3945 src = texD->d->tex;
3946 texD->lastActiveFrameSlot = currentFrameSlot;
3947 } else {
3948 Q_ASSERT(currentSwapChain);
3950 if (u.rb.rect().isValid())
3951 rect = u.rb.rect();
3952 else
3953 rect = QRect({0, 0}, swapChainD->pixelSize);
3954 readback.format = swapChainD->d->rhiColorFormat;
3955 // Multisample swapchains need nothing special since resolving
3956 // happens when ending a renderpass.
3957 const QMetalRenderTargetData::ColorAtt &colorAtt(swapChainD->rtWrapper.d->fb.colorAtt[0]);
3958 src = colorAtt.resolveTex ? colorAtt.resolveTex : colorAtt.tex;
3959 }
3960 readback.pixelSize = rect.size();
3961
3962 quint32 bpl = 0;
3963 textureFormatInfo(readback.format, readback.pixelSize, &bpl, &readback.bufSize, nullptr);
3964
3965 // The depth and stencil aspects of a texture with a combined
3966 // depth/stencil Metal pixel format cannot be copied out with
3967 // MTLBlitOptionNone, they need separate blits, each into its own
3968 // densely packed plane of the staging buffer. In addition, the
3969 // layout of what the blit produces does not necessarily match
3970 // what QRhi returns for the format (e.g. D16 and D24 may be backed
3971 // by Depth32Float). The decisions are thus based on the actual Metal
3972 // pixel format. finishActiveReadbacks() then converts the planes
3973 // into the layout of the result.
3974 const MTLPixelFormat mtlFormat = texD ? texD->d->format : MTLPixelFormatInvalid;
3975 const bool isDepthFormat = texD && (readback.format == QRhiTexture::D16
3976 || readback.format == QRhiTexture::D24
3977 || readback.format == QRhiTexture::D24S8
3978 || readback.format == QRhiTexture::D32F
3979 || readback.format == QRhiTexture::D32FS8);
3980 const bool nativeLayout = (readback.format == QRhiTexture::D16 && mtlFormat == MTLPixelFormatDepth16Unorm)
3981 || (readback.format == QRhiTexture::D32F && mtlFormat == MTLPixelFormatDepth32Float);
3982 const bool usePlanes = isDepthFormat && !nativeLayout;
3983 bool combinedMtlFormat = mtlFormat == MTLPixelFormatDepth32Float_Stencil8;
3984#ifdef Q_OS_MACOS
3985 if (mtlFormat == MTLPixelFormatDepth24Unorm_Stencil8)
3986 combinedMtlFormat = true;
3987#endif
3988 const bool hasStencil = isStencilSupportingFormat(readback.format);
3989 quint32 depthPlaneBytesPerRow = 0;
3990 if (usePlanes) {
3991 // The depth blit writes 4 bytes per pixel (a float, or a 24-bit
3992 // unorm value in the low bits), the stencil blit 1 byte per pixel.
3993 depthPlaneBytesPerRow = quint32(rect.width()) * 4;
3994 readback.depthPlaneByteSize = depthPlaneBytesPerRow * quint32(rect.height());
3995 if (hasStencil)
3996 readback.stencilPlaneByteSize = quint32(rect.width()) * quint32(rect.height());
3997 readback.depthPlaneIsFloat = mtlFormat == MTLPixelFormatDepth32Float
3998 || mtlFormat == MTLPixelFormatDepth32Float_Stencil8;
3999 }
4000 const quint32 stagingBufSize = usePlanes
4001 ? readback.depthPlaneByteSize + readback.stencilPlaneByteSize
4002 : readback.bufSize;
4003 readback.buf = [d->dev newBufferWithLength: stagingBufSize options: MTLResourceStorageModeShared];
4004
4005 ensureBlit();
4006 const auto blit = [&](quint32 destinationOffset, quint32 destinationBytesPerRow, MTLBlitOption options) {
4007 [blitEnc copyFromTexture: src
4008 sourceSlice: NSUInteger(is3D ? 0 : u.rb.layer())
4009 sourceLevel: NSUInteger(u.rb.level())
4010 sourceOrigin: MTLOriginMake(NSUInteger(rect.x()), NSUInteger(rect.y()), NSUInteger(is3D ? u.rb.layer() : 0))
4011 sourceSize: MTLSizeMake(NSUInteger(rect.width()), NSUInteger(rect.height()), 1)
4012 toBuffer: readback.buf
4013 destinationOffset: destinationOffset
4014 destinationBytesPerRow: destinationBytesPerRow
4015 destinationBytesPerImage: 0
4016 options: options];
4017 };
4018 if (usePlanes) {
4019 blit(0, depthPlaneBytesPerRow,
4020 combinedMtlFormat ? MTLBlitOptionDepthFromDepthStencil : MTLBlitOptionNone);
4021 if (hasStencil)
4022 blit(readback.depthPlaneByteSize, quint32(rect.width()), MTLBlitOptionStencilFromDepthStencil);
4023 } else {
4024 blit(0, bpl, MTLBlitOptionNone);
4025 }
4026
4027 d->activeTextureReadbacks.append(readback);
4029 QMetalTexture *utexD = QRHI_RES(QMetalTexture, u.dst);
4030 ensureBlit();
4031 [blitEnc generateMipmapsForTexture: utexD->d->tex];
4032 utexD->lastActiveFrameSlot = currentFrameSlot;
4033 }
4034 }
4035
4036 if (blitEnc) {
4037 if (debugMarkers)
4038 [blitEnc popDebugGroup];
4039 [blitEnc endEncoding];
4040 }
4041
4042 ud->free();
4043}
4044
4045// this handles all types of buffers, not just Dynamic
4047{
4048 if (bufD->d->pendingUpdates[slot].isEmpty())
4049 return;
4050
4051 Q_ASSERT(!bufD->d->isDeviceLocal);
4052
4053 void *p = [bufD->d->buf[slot] contents];
4054 quint32 changeBegin = UINT32_MAX;
4055 quint32 changeEnd = 0;
4056 for (const QMetalBufferData::BufferUpdate &u : std::as_const(bufD->d->pendingUpdates[slot])) {
4057 memcpy(static_cast<char *>(p) + u.offset, u.data.constData(), size_t(u.data.size()));
4058 if (u.offset < changeBegin)
4059 changeBegin = u.offset;
4060 if (u.offset + u.data.size() > changeEnd)
4061 changeEnd = u.offset + u.data.size();
4062 }
4063#ifdef Q_OS_MACOS
4064 if (changeBegin < UINT32_MAX && changeBegin < changeEnd && bufD->d->managed)
4065 [bufD->d->buf[slot] didModifyRange: NSMakeRange(NSUInteger(changeBegin), NSUInteger(changeEnd - changeBegin))];
4066#endif
4067
4068 bufD->d->pendingUpdates[slot].clear();
4069}
4070
4072{
4073 executeBufferHostWritesForSlot(bufD, bufD->d->slotted ? currentFrameSlot : 0);
4074}
4075
4076void QRhiMetal::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
4077{
4078 Q_ASSERT(QRHI_RES(QMetalCommandBuffer, cb)->recordingPass == QMetalCommandBuffer::NoPass);
4079
4080 enqueueResourceUpdates(cb, resourceUpdates);
4081}
4082
4083void QRhiMetal::beginPass(QRhiCommandBuffer *cb,
4084 QRhiRenderTarget *rt,
4085 const QColor &colorClearValue,
4086 const QRhiDepthStencilClearValue &depthStencilClearValue,
4087 QRhiResourceUpdateBatch *resourceUpdates,
4089{
4090 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4092
4093 if (resourceUpdates)
4094 enqueueResourceUpdates(cb, resourceUpdates);
4095
4096 QMetalRenderTargetData *rtD = nullptr;
4097 switch (rt->resourceType()) {
4098 case QRhiResource::SwapChainRenderTarget:
4099 {
4101 rtD = rtSc->d;
4102 QRhiShadingRateMap *shadingRateMap = rtSc->swapChain()->shadingRateMap();
4103 cbD->d->currentPassRpDesc = d->createDefaultRenderPass(rtD->dsAttCount,
4104 colorClearValue,
4105 depthStencilClearValue,
4106 rtD->colorAttCount,
4107 shadingRateMap);
4108 if (rtD->colorAttCount) {
4109 QMetalRenderTargetData::ColorAtt &color0(rtD->fb.colorAtt[0]);
4111 Q_ASSERT(currentSwapChain);
4113 if (!swapChainD->d->curDrawable) {
4114 QMacAutoReleasePool pool;
4115 swapChainD->d->curDrawable = [[swapChainD->d->layer nextDrawable] retain];
4116 }
4117 if (!swapChainD->d->curDrawable) {
4118 qWarning("No drawable");
4119 // The pass is still begun, the commands recorded in it go
4120 // to a nil encoder and are dropped.
4121 cbD->d->currentPassRpDesc = nil;
4122 } else {
4123 id<MTLTexture> scTex = swapChainD->d->curDrawable.texture;
4124 if (color0.needsDrawableForTex) {
4125 color0.tex = scTex;
4126 color0.needsDrawableForTex = false;
4127 } else {
4128 color0.resolveTex = scTex;
4129 color0.needsDrawableForResolveTex = false;
4130 }
4131 }
4132 }
4133 }
4134 if (shadingRateMap)
4135 QRHI_RES(QMetalShadingRateMap, shadingRateMap)->lastActiveFrameSlot = currentFrameSlot;
4136 }
4137 break;
4138 case QRhiResource::TextureRenderTarget:
4139 {
4141 rtD = rtTex->d;
4142 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QMetalTexture, QMetalRenderBuffer>(rtTex->description(), rtD->currentResIdList))
4143 rtTex->create();
4144 cbD->d->currentPassRpDesc = d->createDefaultRenderPass(rtD->dsAttCount,
4145 colorClearValue,
4146 depthStencilClearValue,
4147 rtD->colorAttCount,
4148 rtTex->m_desc.shadingRateMap());
4149 if (rtD->fb.preserveColor) {
4150 for (uint i = 0; i < uint(rtD->colorAttCount); ++i)
4151 cbD->d->currentPassRpDesc.colorAttachments[i].loadAction = MTLLoadActionLoad;
4152 }
4153 if (rtD->dsAttCount && rtD->fb.preserveDs) {
4154 cbD->d->currentPassRpDesc.depthAttachment.loadAction = MTLLoadActionLoad;
4155 cbD->d->currentPassRpDesc.stencilAttachment.loadAction = MTLLoadActionLoad;
4156 }
4157 int colorAttCount = 0;
4158 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
4159 it != itEnd; ++it)
4160 {
4161 colorAttCount += 1;
4162 if (it->texture()) {
4163 QRHI_RES(QMetalTexture, it->texture())->lastActiveFrameSlot = currentFrameSlot;
4164 if (it->multiViewCount() >= 2)
4165 cbD->d->currentPassRpDesc.renderTargetArrayLength = NSUInteger(it->multiViewCount());
4166 } else if (it->renderBuffer()) {
4167 QRHI_RES(QMetalRenderBuffer, it->renderBuffer())->lastActiveFrameSlot = currentFrameSlot;
4168 }
4169 if (it->resolveTexture())
4170 QRHI_RES(QMetalTexture, it->resolveTexture())->lastActiveFrameSlot = currentFrameSlot;
4171 }
4172 if (rtTex->m_desc.depthStencilBuffer())
4173 QRHI_RES(QMetalRenderBuffer, rtTex->m_desc.depthStencilBuffer())->lastActiveFrameSlot = currentFrameSlot;
4174 if (rtTex->m_desc.depthTexture()) {
4175 QMetalTexture *depthTexture = QRHI_RES(QMetalTexture, rtTex->m_desc.depthTexture());
4176 depthTexture->lastActiveFrameSlot = currentFrameSlot;
4177 if (depthTexture->arraySize() >= 2) {
4178 const int depthLayer = rtTex->m_desc.depthLayer();
4179 if (depthLayer >= 0) {
4180 cbD->d->currentPassRpDesc.depthAttachment.slice = NSUInteger(depthLayer);
4181 cbD->d->currentPassRpDesc.stencilAttachment.slice = NSUInteger(depthLayer);
4182 if (colorAttCount == 0)
4183 cbD->d->currentPassRpDesc.renderTargetArrayLength = 1;
4184 } else if (colorAttCount == 0) {
4185 cbD->d->currentPassRpDesc.renderTargetArrayLength = NSUInteger(depthTexture->arraySize());
4186 }
4187 }
4188 }
4189 if (rtTex->m_desc.depthResolveTexture())
4190 QRHI_RES(QMetalTexture, rtTex->m_desc.depthResolveTexture())->lastActiveFrameSlot = currentFrameSlot;
4191 if (rtTex->m_desc.shadingRateMap())
4192 QRHI_RES(QMetalShadingRateMap, rtTex->m_desc.shadingRateMap())->lastActiveFrameSlot = currentFrameSlot;
4193 }
4194 break;
4195 default:
4196 Q_UNREACHABLE();
4197 break;
4198 }
4199
4200 cbD->d->deferredColorStoreActions.clear();
4201 cbD->d->deferredDepthStoreAction = MTLStoreActionUnknown;
4202 cbD->d->deferredStencilStoreAction = MTLStoreActionUnknown;
4203 for (uint i = 0; i < uint(rtD->colorAttCount); ++i) {
4204 cbD->d->currentPassRpDesc.colorAttachments[i].texture = rtD->fb.colorAtt[i].tex;
4205 cbD->d->currentPassRpDesc.colorAttachments[i].slice = NSUInteger(rtD->fb.colorAtt[i].arrayLayer);
4206 cbD->d->currentPassRpDesc.colorAttachments[i].depthPlane = NSUInteger(rtD->fb.colorAtt[i].slice);
4207 cbD->d->currentPassRpDesc.colorAttachments[i].level = NSUInteger(rtD->fb.colorAtt[i].level);
4208 if (rtD->fb.colorAtt[i].resolveTex) {
4209 const MTLStoreAction storeAction = rtD->fb.preserveColor ? MTLStoreActionStoreAndMultisampleResolve
4210 : MTLStoreActionMultisampleResolve;
4211 // Defer, so that the multisample contents can be kept if the pass
4212 // ends up being interrupted. finalizeDeferredStoreActions() sets the
4213 // real action before the encoder ends.
4214 cbD->d->currentPassRpDesc.colorAttachments[i].storeAction = MTLStoreActionUnknown;
4215 cbD->d->deferredColorStoreActions.append({ i, storeAction });
4216 cbD->d->currentPassRpDesc.colorAttachments[i].resolveTexture = rtD->fb.colorAtt[i].resolveTex;
4217 cbD->d->currentPassRpDesc.colorAttachments[i].resolveSlice = NSUInteger(rtD->fb.colorAtt[i].resolveLayer);
4218 cbD->d->currentPassRpDesc.colorAttachments[i].resolveLevel = NSUInteger(rtD->fb.colorAtt[i].resolveLevel);
4219 }
4220 }
4221
4222 if (rtD->dsAttCount) {
4223 Q_ASSERT(rtD->fb.dsTex);
4224 cbD->d->currentPassRpDesc.depthAttachment.texture = rtD->fb.dsTex;
4225 cbD->d->currentPassRpDesc.stencilAttachment.texture = rtD->fb.hasStencil ? rtD->fb.dsTex : nil;
4226 if (rtD->fb.depthNeedsStore) { // Depth/Stencil is set to DontCare by default, override if needed
4227 cbD->d->currentPassRpDesc.depthAttachment.storeAction = MTLStoreActionStore;
4228 if (rtD->fb.hasStencil)
4229 cbD->d->currentPassRpDesc.stencilAttachment.storeAction = MTLStoreActionStore;
4230 } else if (canStoreAttachment(rtD->fb.dsTex)) {
4231 // Would be discarded at the end of the pass, but an interruption in
4232 // the middle of it still has to be able to keep the contents. Defer,
4233 // so that nothing is stored unless that actually happens.
4234 cbD->d->currentPassRpDesc.depthAttachment.storeAction = MTLStoreActionUnknown;
4235 cbD->d->deferredDepthStoreAction = MTLStoreActionDontCare;
4236 if (rtD->fb.hasStencil) {
4237 cbD->d->currentPassRpDesc.stencilAttachment.storeAction = MTLStoreActionUnknown;
4238 cbD->d->deferredStencilStoreAction = MTLStoreActionDontCare;
4239 }
4240 }
4241 if (rtD->fb.dsResolveTex) {
4242 const MTLStoreAction dsStoreAction = rtD->fb.depthNeedsStore ? MTLStoreActionStoreAndMultisampleResolve
4243 : MTLStoreActionMultisampleResolve;
4244 // Deferred for the same reason as the color attachments above, but
4245 // only when there is something to defer to: a memoryless
4246 // depth-stencil buffer, which is what a QRhiRenderBuffer is on Apple
4247 // GPUs, cannot be stored at all, and rejects the store-and-resolve
4248 // action that an interruption would need.
4249 const bool deferrable = canStoreAttachment(rtD->fb.dsTex);
4250 cbD->d->currentPassRpDesc.depthAttachment.storeAction = deferrable ? MTLStoreActionUnknown
4251 : dsStoreAction;
4252 if (deferrable)
4253 cbD->d->deferredDepthStoreAction = dsStoreAction;
4254 cbD->d->currentPassRpDesc.depthAttachment.resolveTexture = rtD->fb.dsResolveTex;
4255 if (rtD->fb.hasStencil) {
4256 cbD->d->currentPassRpDesc.stencilAttachment.resolveTexture = rtD->fb.dsResolveTex;
4257 cbD->d->currentPassRpDesc.stencilAttachment.storeAction = deferrable ? MTLStoreActionUnknown
4258 : dsStoreAction;
4259 if (deferrable)
4260 cbD->d->deferredStencilStoreAction = dsStoreAction;
4261 }
4262 }
4263 }
4264
4265 cbD->d->currentRenderPassEncoder = cbD->d->currentPassRpDesc
4266 ? [cbD->d->cb renderCommandEncoderWithDescriptor: cbD->d->currentPassRpDesc]
4267 : nil;
4268
4270
4272 cbD->currentTarget = rt;
4273}
4274
4275void QRhiMetal::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
4276{
4277 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4279
4281 [cbD->d->currentRenderPassEncoder endEncoding];
4282
4284 cbD->currentTarget = nullptr;
4285
4286 if (resourceUpdates)
4287 enqueueResourceUpdates(cb, resourceUpdates);
4288}
4289
4290void QRhiMetal::beginComputePass(QRhiCommandBuffer *cb,
4291 QRhiResourceUpdateBatch *resourceUpdates,
4293{
4294 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4296
4297 if (resourceUpdates)
4298 enqueueResourceUpdates(cb, resourceUpdates);
4299
4300 cbD->d->currentComputePassEncoder = [cbD->d->cb computeCommandEncoder];
4303}
4304
4305void QRhiMetal::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
4306{
4307 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4309
4310 [cbD->d->currentComputePassEncoder endEncoding];
4312
4313 if (resourceUpdates)
4314 enqueueResourceUpdates(cb, resourceUpdates);
4315}
4316
4317void QRhiMetal::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
4318{
4319 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4322
4324 cbD->currentGraphicsPipeline = nullptr;
4325 cbD->currentComputePipeline = psD;
4327
4328 [cbD->d->currentComputePassEncoder setComputePipelineState: psD->d->ps];
4329 }
4330
4331 psD->lastActiveFrameSlot = currentFrameSlot;
4332}
4333
4334void QRhiMetal::dispatch(QRhiCommandBuffer *cb, int x, int y, int z)
4335{
4336 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4339
4340 [cbD->d->currentComputePassEncoder dispatchThreadgroups: MTLSizeMake(NSUInteger(x), NSUInteger(y), NSUInteger(z))
4341 threadsPerThreadgroup: psD->d->localSize];
4342}
4343
4344void QRhiMetal::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
4345 quint32 indirectBufferOffset)
4346{
4347 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4350
4351 QMetalBuffer *indirectBufD = QRHI_RES(QMetalBuffer, indirectBuffer);
4353 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
4354 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
4355
4356 // dispatchThreadgroups still wants threadsPerThreadgroup explicitly; the
4357 // indirect buffer only supplies the grid size in threadgroups. The
4358 // threads-per-threadgroup value comes from the bound compute pipeline
4359 // (set in QMetalComputePipeline::create() from the SPIR-V shader's
4360 // local_size_x/y/z layout qualifiers).
4361 [cbD->d->currentComputePassEncoder
4362 dispatchThreadgroupsWithIndirectBuffer: indirectBufMtl
4363 indirectBufferOffset: indirectBufferOffset
4364 threadsPerThreadgroup: psD->d->localSize];
4365}
4366
4367void QRhiMetal::drawIndirectCount(QRhiCommandBuffer *cb,
4368 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
4369 QRhiBuffer *countBuffer, quint32 countBufferOffset,
4370 quint32 maxDrawCount, quint32 stride)
4371{
4372 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4374
4375 // Implemented on top of indirect command buffers. There can be no CPU-side
4376 // fallback, the count is only known to the device.
4377 if (const char *reason = icbUnavailableReason(cbD)) {
4378 qWarning("drawIndirectCount is not available because %s; skipping", reason);
4379 return;
4380 }
4381
4382 icbDraw(cbD, false, QRHI_RES(QMetalBuffer, indirectBuffer), indirectBufferOffset,
4383 QRHI_RES(QMetalBuffer, countBuffer), countBufferOffset, maxDrawCount, stride);
4384}
4385
4386void QRhiMetal::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
4387 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
4388 QRhiBuffer *countBuffer, quint32 countBufferOffset,
4389 quint32 maxDrawCount, quint32 stride)
4390{
4391 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4393
4394 // Implemented on top of indirect command buffers. There can be no CPU-side
4395 // fallback, the count is only known to the device.
4396 if (const char *reason = icbUnavailableReason(cbD)) {
4397 qWarning("drawIndexedIndirectCount is not available because %s; skipping", reason);
4398 return;
4399 }
4400
4401 if (!cbD->currentIndexBuffer) {
4402 qWarning("drawIndexedIndirectCount called without an index buffer bound; skipping");
4403 return;
4404 }
4405
4406 icbDraw(cbD, true, QRHI_RES(QMetalBuffer, indirectBuffer), indirectBufferOffset,
4407 QRHI_RES(QMetalBuffer, countBuffer), countBufferOffset, maxDrawCount, stride);
4408}
4409
4410static inline MTLPrimitiveType toMetalPrimitiveType(QRhiGraphicsPipeline::Topology t);
4411
4413{
4426 Slot frameSlots[QMTL_FRAMES_IN_FLIGHT];
4427
4428 enum class Fill { None, Cpu, Gpu };
4430 bool slotSetupFailed = false;
4431 bool created = false;
4432
4433 // Set by buildIndirect(), which makes the CPU-side recording irrelevant:
4434 // gpuFilled means the kernel encoded into frameSlots[builtSlot], fallbackBuild
4435 // that there was no ICB to encode into and executeIndirect() has to use the
4436 // plain indirect draw entry points.
4437 bool gpuFilled = false;
4438 bool fallbackBuild = false;
4439 QRhiIndirectCommandBufferBuildInfo buildInfo;
4440 int builtSlot = -1;
4441};
4442
4444{
4445 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
4446 QMetalIndirectCommandBufferData::Slot &slot(icbD->d->frameSlots[i]);
4447 if (slot.icb) {
4451 e.stagingIcbBuffer.icb = slot.icb;
4452 e.stagingIcbBuffer.argBuffer = slot.argBuffer;
4453 rhiD->d->releaseQueue.append(e);
4454 }
4455 if (slot.rangeBuffer) {
4459 e.stagingBuffer.buffer = slot.rangeBuffer;
4460 rhiD->d->releaseQueue.append(e);
4461 }
4462 slot = {};
4463 }
4465}
4466
4469{
4471
4472 if (icbD->d->slotSetupFailed)
4473 return false;
4474
4475 if (icbD->d->fill == fill)
4476 return icbD->d->frameSlots[0].icb != nil;
4477
4480 icbD->d->gpuFilled = false;
4481 icbD->d->builtSlot = -1;
4482 }
4483
4484 if (!rhiD->caps.indirectCommandBuffers)
4485 return false;
4486
4487 const bool gpu = fill == QMetalIndirectCommandBufferData::Fill::Gpu;
4488 if (gpu && !rhiD->prepareIcbKernels())
4489 return false;
4490
4491 MTLIndirectCommandBufferDescriptor *icbDesc = [MTLIndirectCommandBufferDescriptor new];
4492 icbDesc.commandTypes = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws
4493 ? MTLIndirectCommandTypeDrawIndexed : MTLIndirectCommandTypeDraw;
4494 // All state except the primitive type and the index buffer is inherited.
4495 icbDesc.inheritPipelineState = YES;
4496 icbDesc.inheritBuffers = YES;
4497 icbDesc.maxVertexBufferBindCount = 0;
4498 icbDesc.maxFragmentBufferBindCount = 0;
4499
4500 bool ok = true;
4501 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT && ok; ++i) {
4502 QMetalIndirectCommandBufferData::Slot &slot(icbD->d->frameSlots[i]);
4503 slot.icb = [rhiD->d->dev newIndirectCommandBufferWithDescriptor:icbDesc
4504 maxCommandCount:icbD->maxCommandCount()
4505 options:gpu ? MTLResourceStorageModePrivate
4506 : MTLResourceStorageModeShared];
4507 if (!slot.icb) {
4508 qWarning("Failed to create MTLIndirectCommandBuffer");
4509 ok = false;
4510 break;
4511 }
4512 if (gpu) {
4513 slot.rangeBuffer = [rhiD->d->dev newBufferWithLength:sizeof(MTLIndirectCommandBufferExecutionRange)
4514 options:MTLResourceStorageModePrivate];
4515 id<MTLArgumentEncoder> argEnc = [rhiD->d->icbEncodeFunction newArgumentEncoderWithBufferIndex:1];
4516 slot.argBuffer = [rhiD->d->dev newBufferWithLength:argEnc.encodedLength
4517 options:MTLResourceStorageModeShared];
4518 if (slot.rangeBuffer && slot.argBuffer) {
4519 [argEnc setArgumentBuffer:slot.argBuffer offset:0];
4520 [argEnc setIndirectCommandBuffer:slot.icb atIndex:0];
4521 } else {
4522 qWarning("Failed to create MTLIndirectCommandBuffer helper buffers");
4523 ok = false;
4524 }
4525 [argEnc release];
4526 if (!ok)
4527 break;
4528 }
4529 }
4530 [icbDesc release];
4531
4532 if (!ok) {
4533 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
4534 [icbD->d->frameSlots[i].icb release];
4535 [icbD->d->frameSlots[i].rangeBuffer release];
4536 [icbD->d->frameSlots[i].argBuffer release];
4537 icbD->d->frameSlots[i] = {};
4538 }
4539 icbD->d->slotSetupFailed = true;
4540 return false;
4541 }
4542
4543 icbD->d->fill = fill;
4544 return true;
4545}
4546
4548 quint32 maxCommandCount)
4551{
4552}
4553
4559
4561{
4562 clear();
4563
4564 if (!d->created)
4565 return;
4566
4567 d->slotSetupFailed = false;
4568 d->gpuFilled = false;
4569 d->fallbackBuild = false;
4570 d->buildInfo = {};
4571 d->builtSlot = -1;
4572 d->created = false;
4573 m_gpuBuilt = false;
4574 m_gpuBuiltCommandCount = 0;
4575
4576 QRHI_RES_RHI(QRhiMetal);
4577 if (rhiD) {
4579 rhiD->unregisterResource(this);
4580 }
4581}
4582
4584{
4585 if (d->created)
4586 destroy();
4587 else
4588 clear();
4589
4590 if (!m_maxCommandCount) {
4591 qWarning("QRhiIndirectCommandBuffer: maxCommandCount is 0");
4592 return false;
4593 }
4594
4595 QRHI_RES_RHI(QRhiMetal);
4597 d->created = true;
4598 rhiD->registerResource(this);
4599 return true;
4600}
4601
4602QRhiIndirectCommandBuffer *QRhiMetal::createIndirectCommandBuffer(QRhiIndirectCommandBuffer::Type type,
4603 quint32 maxCommandCount)
4604{
4605 return new QMetalIndirectCommandBuffer(this, type, maxCommandCount);
4606}
4607
4608void QRhiMetal::commitIndirectCommandBuffer(QRhiResourceUpdateBatch *u,
4609 QRhiIndirectCommandBuffer *icb)
4610{
4611 // Nothing to upload: executeIndirect() encodes straight into the ICB, and
4612 // only there are the primitive type and index buffer known.
4613 Q_UNUSED(u);
4614 Q_UNUSED(icb);
4615}
4616
4617// True when the slot holds an encoding that is already good for these
4618// contents and this state, and so does not need to be re-encoded.
4621 MTLPrimitiveType primitiveType,
4622 id<MTLBuffer> indexBufMtl, quint32 indexOffset,
4623 QRhiCommandBuffer::IndexFormat indexFormat)
4624{
4625 const bool indexed = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4626
4627 return slot.encoded
4628 && slot.generation == icbD->contentsGeneration()
4629 && slot.primitiveType == primitiveType
4630 && (!indexed || (slot.indexBuf == indexBufMtl
4631 && slot.indexOffset == indexOffset
4632 && slot.indexFormat == indexFormat));
4633}
4634
4635// Re-encodes the CPU-recorded commands unless the slot already matches.
4638 MTLPrimitiveType primitiveType,
4639 id<MTLBuffer> indexBufMtl, quint32 indexOffset,
4640 QRhiCommandBuffer::IndexFormat indexFormat)
4641{
4642 const bool indexed = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4643
4644 if (qrhimtl_icbSlotMatches(icbD, slot, primitiveType, indexBufMtl, indexOffset, indexFormat))
4645 return;
4646
4647 const quint32 count = icbD->recordedCommandCount();
4648 if (indexed) {
4649 const MTLIndexType indexType = indexFormat == QRhiCommandBuffer::IndexUInt16
4650 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
4651 const quint32 indexSize = indexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4;
4653 for (quint32 i = 0; i < count; ++i) {
4654 const QRhiIndexedIndirectDrawCommand &c(cmds[i]);
4655 id<MTLIndirectRenderCommand> rc = [slot.icb indirectRenderCommandAtIndex:i];
4656 [rc drawIndexedPrimitives:primitiveType
4657 indexCount:c.indexCount
4658 indexType:indexType
4659 indexBuffer:indexBufMtl
4660 indexBufferOffset:indexOffset + c.firstIndex * indexSize
4661 instanceCount:c.instanceCount
4662 baseVertex:c.vertexOffset
4663 baseInstance:c.firstInstance];
4664 }
4665 } else {
4666 const QRhiIndirectDrawCommand *cmds = icbD->drawCommands();
4667 for (quint32 i = 0; i < count; ++i) {
4668 const QRhiIndirectDrawCommand &c(cmds[i]);
4669 id<MTLIndirectRenderCommand> rc = [slot.icb indirectRenderCommandAtIndex:i];
4670 [rc drawPrimitives:primitiveType
4671 vertexStart:c.firstVertex
4672 vertexCount:c.vertexCount
4673 instanceCount:c.instanceCount
4674 baseInstance:c.firstInstance];
4675 }
4676 }
4677
4678 // Commands past the current count may be left over from a longer batch.
4679 if (count < icbD->maxCommandCount())
4680 [slot.icb resetWithRange:NSMakeRange(count, icbD->maxCommandCount() - count)];
4681
4682 slot.generation = icbD->contentsGeneration();
4683 slot.primitiveType = primitiveType;
4684 slot.indexBuf = indexBufMtl;
4685 slot.indexOffset = indexOffset;
4686 slot.indexFormat = indexFormat;
4687 slot.encoded = true;
4688}
4689
4690// Fallback for when there is no usable ICB.
4692 quint32 firstCommand, quint32 count,
4693 int currentFrameSlot)
4694{
4695 const MTLPrimitiveType primitiveType = cbD->currentGraphicsPipeline->d->primitiveType;
4696
4697 if (icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws) {
4698 QMetalBuffer *indexBufD = cbD->currentIndexBuffer;
4699 if (!indexBufD)
4700 return;
4701 id<MTLBuffer> indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4702 const MTLIndexType indexType = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16
4703 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
4704 const quint32 indexSize = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4;
4706 for (quint32 i = 0; i < count; ++i) {
4707 const QRhiIndexedIndirectDrawCommand &c(cmds[firstCommand + i]);
4708 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: primitiveType
4709 indexCount: c.indexCount
4710 indexType: indexType
4711 indexBuffer: indexBufMtl
4712 indexBufferOffset: cbD->currentIndexOffset + c.firstIndex * indexSize
4713 instanceCount: c.instanceCount
4714 baseVertex: c.vertexOffset
4715 baseInstance: c.firstInstance];
4716 }
4717 } else {
4718 const QRhiIndirectDrawCommand *cmds = icbD->drawCommands();
4719 for (quint32 i = 0; i < count; ++i) {
4720 const QRhiIndirectDrawCommand &c(cmds[firstCommand + i]);
4721 [cbD->d->currentRenderPassEncoder drawPrimitives: primitiveType
4722 vertexStart: c.firstVertex
4723 vertexCount: c.vertexCount
4724 instanceCount: c.instanceCount
4725 baseInstance: c.firstInstance];
4726 }
4727 }
4728}
4729
4730void QRhiMetal::executeIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb,
4731 quint32 firstCommand, quint32 commandCount)
4732{
4733 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4735
4736 QMetalIndirectCommandBuffer *icbD = QRHI_RES(QMetalIndirectCommandBuffer, icb);
4737 icbD->lastActiveFrameSlot = currentFrameSlot;
4738
4739 const bool indexed = icb->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4740
4741 if (icbD->d->gpuFilled) {
4742 if (icbD->d->buildInfo.topology != cbD->currentGraphicsPipeline->topology()) {
4743 qWarning("executeIndirect: the indirect command buffer was built for a different "
4744 "topology than the current graphics pipeline uses; skipping");
4745 return;
4746 }
4747 QMetalIndirectCommandBufferData::Slot &slot(icbD->d->frameSlots[icbD->d->builtSlot]);
4748
4749 const quint32 total = icbD->commandCount();
4750 const bool deviceCount = icbD->d->buildInfo.countBuffer != nullptr;
4751 NSRange range = NSMakeRange(0, total);
4752 if (deviceCount) {
4753 // The count is only known to the device, and applying it is what
4754 // the compute kernel-written range is for. That form of
4755 // executeCommandsInBuffer takes no CPU-side range, so a subrange
4756 // and a device-side count cannot be combined.
4757 if (firstCommand != 0 || commandCount < total) {
4758 qWarning("executeIndirect: firstCommand and commandCount cannot be honoured "
4759 "together with a device-side count; executing all %u command(s)", total);
4760 }
4761 } else {
4762 if (firstCommand >= total)
4763 return;
4764 const quint32 count = qMin(commandCount, total - firstCommand);
4765 if (!count)
4766 return;
4767 range = NSMakeRange(firstCommand, count);
4768 }
4769
4770 if (indexed && icbD->d->buildInfo.indexBuffer) {
4771 QMetalBuffer *indexBufD = QRHI_RES(QMetalBuffer, icbD->d->buildInfo.indexBuffer);
4772 id<MTLBuffer> indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4773 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
4774 usage:MTLResourceUsageRead
4775 stages:MTLRenderStageVertex | MTLRenderStageFragment];
4776 }
4777 if (deviceCount) {
4778 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb
4779 indirectBuffer:slot.rangeBuffer
4780 indirectBufferOffset:0];
4781 } else {
4782 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb withRange:range];
4783 }
4784 return;
4785 }
4786
4787 if (icbD->d->fallbackBuild) {
4788 const QRhiIndirectCommandBufferBuildInfo &info(icbD->d->buildInfo);
4789 if (info.countBuffer) {
4790 qWarning("executeIndirect: a device-side count needs an indirect command buffer, "
4791 "which is not available here; skipping");
4792 return;
4793 }
4794 const quint32 canonicalStride = indexed ? sizeof(QRhiIndexedIndirectDrawCommand)
4795 : sizeof(QRhiIndirectDrawCommand);
4796 const quint32 stride = info.stride ? info.stride : canonicalStride;
4797 const quint32 total = icbD->commandCount();
4798 if (firstCommand >= total)
4799 return;
4800 const quint32 count = qMin(commandCount, total - firstCommand);
4801 if (!count)
4802 return;
4803 const quint32 offset = info.sourceBufferOffset + firstCommand * stride;
4804 if (indexed)
4805 drawIndexedIndirect(cb, info.sourceBuffer, offset, count, stride);
4806 else
4807 drawIndirect(cb, info.sourceBuffer, offset, count, stride);
4808 return;
4809 }
4810
4811 const quint32 total = icbD->recordedCommandCount();
4812 if (firstCommand >= total)
4813 return;
4814 const quint32 count = qMin(commandCount, total - firstCommand);
4815 if (!count)
4816 return;
4817
4820 {
4821 qrhimtl_replayIcbOnCpu(cbD, icbD, firstCommand, count, currentFrameSlot);
4822 return;
4823 }
4824 QMetalIndirectCommandBufferData::Slot &slot(icbD->d->frameSlots[currentFrameSlot]);
4825
4826 id<MTLBuffer> indexBufMtl = nil;
4827 quint32 indexOffset = 0;
4828 if (indexed) {
4829 QMetalBuffer *indexBufD = cbD->currentIndexBuffer;
4830 if (!indexBufD)
4831 return;
4832 indexBufD->lastActiveFrameSlot = currentFrameSlot;
4833 indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4834 indexOffset = cbD->currentIndexOffset;
4835 }
4836
4837 const MTLPrimitiveType primitiveType = cbD->currentGraphicsPipeline->d->primitiveType;
4838 if (slot.usedInFrameId == d->globalFrameId
4839 && !qrhimtl_icbSlotMatches(icbD, slot, primitiveType, indexBufMtl, indexOffset,
4840 cbD->currentIndexFormat))
4841 {
4842 // An executeCommandsInBuffer recorded earlier in this frame references
4843 // this slot, and re-encoding it now would change what that one executes
4844 // once submitted. Replaying as ordinary draws keeps both correct.
4845 qWarning("executeIndirect: the same indirect command buffer is executed more than once "
4846 "in a frame, with different contents, topology or index buffer state; "
4847 "falling back to individual draw calls");
4848 qrhimtl_replayIcbOnCpu(cbD, icbD, firstCommand, count, currentFrameSlot);
4849 return;
4850 }
4851
4852 qrhimtl_encodeIcbFromCpu(icbD, slot, primitiveType,
4853 indexBufMtl, indexOffset, cbD->currentIndexFormat);
4854
4855 if (indexed) {
4856 // Index buffer is not inherited from the encoder, and the ICB commands reference it directly,
4857 // so it needs the useResource.
4858 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
4859 usage:MTLResourceUsageRead
4860 stages:MTLRenderStageVertex | MTLRenderStageFragment];
4861 }
4862 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb
4863 withRange:NSMakeRange(firstCommand, count)];
4864 slot.usedInFrameId = d->globalFrameId;
4865}
4866
4867void QRhiMetal::buildIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb,
4868 const QRhiIndirectCommandBufferBuildInfo &info)
4869{
4870 QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
4872
4873 QMetalIndirectCommandBuffer *icbD = QRHI_RES(QMetalIndirectCommandBuffer, icb);
4874 icbD->lastActiveFrameSlot = currentFrameSlot;
4875
4876 const bool indexed = icb->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4877
4878 if (indexed && !info.indexBuffer) {
4879 qWarning("buildIndirect: an IndexedDraws indirect command buffer needs an "
4880 "index buffer in QRhiIndirectCommandBufferBuildInfo; skipping");
4881 return;
4882 }
4883
4884 quint32 count = info.commandCount ? info.commandCount : icbD->m_maxCommandCount;
4885 if (count > icbD->m_maxCommandCount) {
4886 qWarning("QRhiIndirectCommandBuffer: buildIndirect() with commandCount %u exceeds "
4887 "maxCommandCount %u; clamping", count, icbD->m_maxCommandCount);
4888 count = icbD->m_maxCommandCount;
4889 }
4890 icbD->m_gpuBuilt = true;
4891 icbD->m_gpuBuiltCommandCount = count;
4892
4894 icbD->d->gpuFilled = false;
4895 icbD->d->fallbackBuild = true;
4896 icbD->d->buildInfo = info;
4897 icbD->d->builtSlot = -1;
4898 return;
4899 }
4900
4901 QMetalIndirectCommandBufferData::Slot &slot(icbD->d->frameSlots[currentFrameSlot]);
4902
4903 QMetalBuffer *srcBufD = QRHI_RES(QMetalBuffer, info.sourceBuffer);
4905 srcBufD->lastActiveFrameSlot = currentFrameSlot;
4906 id<MTLBuffer> srcBufMtl = srcBufD->d->buf[srcBufD->d->slotted ? currentFrameSlot : 0];
4907
4908 id<MTLBuffer> indexBufMtl = nil;
4909 if (indexed) {
4910 QMetalBuffer *indexBufD = QRHI_RES(QMetalBuffer, info.indexBuffer);
4911 indexBufD->lastActiveFrameSlot = currentFrameSlot;
4912 indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4913 }
4914
4915 id<MTLBuffer> countBufMtl = nil;
4916 if (info.countBuffer) {
4917 QMetalBuffer *countBufD = QRHI_RES(QMetalBuffer, info.countBuffer);
4919 countBufD->lastActiveFrameSlot = currentFrameSlot;
4920 countBufMtl = countBufD->d->buf[countBufD->d->slotted ? currentFrameSlot : 0];
4921 }
4922
4923 const quint32 stride = info.stride ? info.stride
4924 : (indexed ? sizeof(QRhiIndexedIndirectDrawCommand)
4925 : sizeof(QRhiIndirectDrawCommand));
4926
4927 // Outside a render pass, so the compute encoder costs no interruption, no
4928 // store action juggling and no per-pass state to restore.
4929 id<MTLComputeCommandEncoder> computeEncoder = [cbD->d->cb computeCommandEncoder];
4930 encodeIcbWithCompute(d, computeEncoder, slot.icb, slot.argBuffer, slot.rangeBuffer,
4931 indexed, info.indexFormat,
4932 toMetalPrimitiveType(info.topology),
4933 srcBufMtl, info.sourceBufferOffset,
4934 indexBufMtl, info.indexBufferOffset,
4935 countBufMtl, info.countBufferOffset,
4936 icbD->commandCount(), stride);
4937 [computeEncoder endEncoding];
4938
4939 icbD->d->gpuFilled = true;
4940 icbD->d->fallbackBuild = false;
4941 icbD->d->buildInfo = info;
4942 icbD->d->builtSlot = currentFrameSlot;
4943 // The CPU-encoded contents of this slot, if any, are gone now.
4944 slot.encoded = false;
4945}
4946
4948{
4949 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
4950 [e.buffer.buffers[i] release];
4951}
4952
4954{
4955 [e.renderbuffer.texture release];
4956}
4957
4959{
4960 [e.texture.texture release];
4961 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
4962 [e.texture.stagingBuffers[i] release];
4963 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
4964 [e.texture.views[i] release];
4965 [e.texture.samplingView release];
4966 [e.texture.writeView release];
4967}
4968
4970{
4971 [e.sampler.samplerState release];
4972}
4973
4975{
4976 qsizetype keepBegin = d->releaseQueue.size();
4977 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
4978 const QRhiMetalData::DeferredReleaseEntry &e(d->releaseQueue[i]);
4979 if (forced || currentFrameSlot == e.lastActiveFrameSlot || e.lastActiveFrameSlot < 0) {
4980 switch (e.type) {
4983 break;
4986 break;
4989 break;
4992 break;
4993 case QRhiMetalData::DeferredReleaseEntry::StagingBuffer:
4994 [e.stagingBuffer.buffer release];
4995 break;
4996 case QRhiMetalData::DeferredReleaseEntry::GraphicsPipeline:
4997 [e.graphicsPipeline.pipelineState release];
4998 [e.graphicsPipeline.depthStencilState release];
4999 [e.graphicsPipeline.tessVertexComputeState[0] release];
5000 [e.graphicsPipeline.tessVertexComputeState[1] release];
5001 [e.graphicsPipeline.tessVertexComputeState[2] release];
5002 [e.graphicsPipeline.tessTessControlComputeState release];
5003 break;
5004 case QRhiMetalData::DeferredReleaseEntry::ComputePipeline:
5005 [e.computePipeline.pipelineState release];
5006 break;
5007 case QRhiMetalData::DeferredReleaseEntry::ShadingRateMap:
5008 [e.shadingRateMap.rateMap release];
5009 break;
5010 case QRhiMetalData::DeferredReleaseEntry::StagingIcbBuffer:
5011 [e.stagingIcbBuffer.icb release];
5012 [e.stagingIcbBuffer.argBuffer release];
5013 break;
5014 default:
5015 break;
5016 }
5017 } else if (--keepBegin != i) {
5018 d->releaseQueue[keepBegin] = std::move(d->releaseQueue[i]);
5019 }
5020 }
5021 if (keepBegin)
5022 d->releaseQueue.remove(0, keepBegin);
5023}
5024
5026{
5027 QVarLengthArray<std::function<void()>, 4> completedCallbacks;
5028
5029 for (int i = d->activeTextureReadbacks.count() - 1; i >= 0; --i) {
5030 const QRhiMetalData::TextureReadback &readback(d->activeTextureReadbacks[i]);
5031 if (forced || currentFrameSlot == readback.activeFrameSlot || readback.activeFrameSlot < 0) {
5032 readback.result->format = readback.format;
5033 readback.result->pixelSize = readback.pixelSize;
5034 readback.result->data.resize(int(readback.bufSize));
5035 const void *p = [readback.buf contents];
5036 if (readback.depthPlaneByteSize) {
5037 // The staging buffer holds a densely packed depth plane, followed
5038 // by a densely packed stencil plane when the format has stencil
5039 // (see enqueueResourceUpdates()). Convert into the layout QRhi
5040 // guarantees: D16 is a 16-bit unorm value, D24 and D24S8 have the
5041 // depth in the upper 24 bits and the stencil (or zero) in the lower
5042 // 8 bits, and D32FS8 is the float depth followed by a 32-bit word
5043 // with the stencil in its low 8 bits.
5044 const quint32 pixelCount = quint32(readback.pixelSize.width()) * quint32(readback.pixelSize.height());
5045 const char *depthPlane = static_cast<const char *>(p);
5046 const quint8 *stencilPlane = reinterpret_cast<const quint8 *>(depthPlane + readback.depthPlaneByteSize);
5047 char *dst = readback.result->data.data();
5048 for (quint32 px = 0; px < pixelCount; ++px) {
5049 const quint32 depthWord = qFromUnaligned<quint32>(depthPlane + px * 4);
5050 const float depthF = readback.depthPlaneIsFloat ? qFromUnaligned<float>(depthPlane + px * 4) : 0.0f;
5051 const quint32 stencil = readback.stencilPlaneByteSize ? stencilPlane[px] : 0;
5052 switch (readback.format) {
5053 case QRhiTexture::D16:
5054 qToUnaligned(quint16(qRound(qBound(0.0f, depthF, 1.0f) * 65535.0f)), dst + px * 2);
5055 break;
5056 case QRhiTexture::D32FS8:
5057 qToUnaligned(depthWord, dst + px * 8);
5058 qToUnaligned(stencil, dst + px * 8 + 4);
5059 break;
5060 default: // D24, D24S8
5061 {
5062 const quint32 depth24 = readback.depthPlaneIsFloat
5063 ? quint32(qBound(0.0f, depthF, 1.0f) * 16777215.0f + 0.5f)
5064 : depthWord & 0x00FFFFFFu;
5065 qToUnaligned((depth24 << 8) | stencil, dst + px * 4);
5066 }
5067 break;
5068 }
5069 }
5070 } else {
5071 memcpy(readback.result->data.data(), p, readback.bufSize);
5072 }
5073 [readback.buf release];
5074
5075 if (readback.result->completed)
5076 completedCallbacks.append(readback.result->completed);
5077
5078 d->activeTextureReadbacks.remove(i);
5079 }
5080 }
5081
5082 for (int i = d->activeBufferReadbacks.count() - 1; i >= 0; --i) {
5083 const QRhiMetalData::BufferReadback &readback(d->activeBufferReadbacks[i]);
5084 if (forced || currentFrameSlot == readback.activeFrameSlot
5085 || readback.activeFrameSlot < 0) {
5086 readback.result->data.resize(readback.readSize);
5087 char *p = reinterpret_cast<char *>([readback.buf contents]);
5088 Q_ASSERT(p);
5089 memcpy(readback.result->data.data(), p, size_t(readback.readSize));
5090 [readback.buf release];
5091
5092 if (readback.result->completed)
5093 completedCallbacks.append(readback.result->completed);
5094
5095 d->activeBufferReadbacks.remove(i);
5096 }
5097 }
5098
5099 for (auto f : completedCallbacks)
5100 f();
5101}
5102
5103QMetalBuffer::QMetalBuffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
5105 d(new QMetalBufferData)
5106{
5107 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
5108 d->buf[i] = nil;
5109}
5110
5112{
5113 destroy();
5114 delete d;
5115}
5116
5118{
5119 if (!d->buf[0])
5120 return;
5121
5125
5126 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
5127 e.buffer.buffers[i] = d->buf[i];
5128 d->buf[i] = nil;
5129 d->pendingUpdates[i].clear();
5130 }
5131
5132 QRHI_RES_RHI(QRhiMetal);
5133 if (rhiD) {
5134 rhiD->d->releaseQueue.append(e);
5135 rhiD->unregisterResource(this);
5136 }
5137}
5138
5140{
5141 if (d->buf[0])
5142 destroy();
5143
5144 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
5145 qWarning("StorageBuffer cannot be combined with Dynamic");
5146 return false;
5147 }
5148
5149 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
5150 const quint32 roundedSize = m_usage.testFlag(QRhiBuffer::UniformBuffer) ? aligned(nonZeroSize, 256u) : nonZeroSize;
5151
5152 d->managed = false;
5153 d->isDeviceLocal = false;
5154 MTLResourceOptions opts = MTLResourceStorageModeShared;
5155
5156 QRHI_RES_RHI(QRhiMetal);
5157
5158 const bool internalHostWritable = (int(m_usage) & (WorkBufPoolUsage | InternalHostWritable)) != 0;
5159
5160 if (m_type != Dynamic && !internalHostWritable && rhiD->caps.usePrivateStaticBuffers) {
5161 opts = MTLResourceStorageModePrivate;
5162 d->isDeviceLocal = true;
5163 d->slotted = false;
5164 } else {
5165#ifdef Q_OS_MACOS
5166 if (!rhiD->caps.isAppleGPU && m_type != Dynamic) {
5167 opts = MTLResourceStorageModeManaged;
5168 d->managed = true;
5169 }
5170#endif
5171 // Have QMTL_FRAMES_IN_FLIGHT versions regardless of the type. This is
5172 // because writing to a host visible buffer is not safe when another
5173 // frame reading from the same buffer is still in flight.
5174 d->slotted = !m_usage.testFlag(QRhiBuffer::StorageBuffer) // except for SSBOs written in the shader
5175 && !internalHostWritable; // and the internal buffers
5176 }
5177
5178 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
5179 if (i == 0 || d->slotted) {
5180 d->buf[i] = [rhiD->d->dev newBufferWithLength: roundedSize options: opts];
5181 if (!m_objectName.isEmpty()) {
5182 if (!d->slotted) {
5183 d->buf[i].label = [NSString stringWithUTF8String: m_objectName.constData()];
5184 } else {
5185 const QByteArray name = m_objectName + '/' + QByteArray::number(i);
5186 d->buf[i].label = [NSString stringWithUTF8String: name.constData()];
5187 }
5188 }
5189 }
5190 }
5191
5193 generation += 1;
5194 rhiD->registerResource(this);
5195 return true;
5196}
5197
5199{
5200 if (d->slotted) {
5201 NativeBuffer b;
5202 Q_ASSERT(sizeof(b.objects) / sizeof(b.objects[0]) >= size_t(QMTL_FRAMES_IN_FLIGHT));
5203 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
5204 QRHI_RES_RHI(QRhiMetal);
5206 b.objects[i] = &d->buf[i];
5207 }
5208 b.slotCount = QMTL_FRAMES_IN_FLIGHT;
5209 return b;
5210 }
5211 if (!d->isDeviceLocal) {
5212 QRHI_RES_RHI(QRhiMetal);
5214 }
5215 return { { &d->buf[0] }, 1 };
5216}
5217
5219{
5220 // Shortcut the entire buffer update mechanism and allow the client to do
5221 // the host writes directly to the buffer. This will lead to unexpected
5222 // results when combined with QRhiResourceUpdateBatch-based updates for the
5223 // buffer, but provides a fast path for dynamic buffers that have all their
5224 // content changed in every frame.
5225 Q_ASSERT(m_type == Dynamic);
5226 Q_ASSERT(!d->isDeviceLocal);
5227 QRHI_RES_RHI(QRhiMetal);
5228 Q_ASSERT(rhiD->inFrame);
5229 const int slot = d->slotted ? rhiD->currentFrameSlot : 0;
5230 void *p = [d->buf[slot] contents];
5231 return static_cast<char *>(p);
5232}
5233
5235{
5236 // Nothing to do: managed is never set for Dynamic buffers, and so there is
5237 // no didModifyRange: to issue.
5238}
5239
5240static inline MTLPixelFormat toMetalTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags, const QRhiMetal *d)
5241{
5242#ifndef Q_OS_MACOS
5243 Q_UNUSED(d);
5244#endif
5245
5246 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
5247 switch (format) {
5248 case QRhiTexture::RGBA8:
5249 return srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm;
5250 case QRhiTexture::BGRA8:
5251 return srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
5252 case QRhiTexture::R8:
5253#ifdef Q_OS_MACOS
5254 return MTLPixelFormatR8Unorm;
5255#else
5256 return srgb ? MTLPixelFormatR8Unorm_sRGB : MTLPixelFormatR8Unorm;
5257#endif
5258 case QRhiTexture::R8SI:
5259 return MTLPixelFormatR8Sint;
5260 case QRhiTexture::R8UI:
5261 return MTLPixelFormatR8Uint;
5262 case QRhiTexture::RG8:
5263#ifdef Q_OS_MACOS
5264 return MTLPixelFormatRG8Unorm;
5265#else
5266 return srgb ? MTLPixelFormatRG8Unorm_sRGB : MTLPixelFormatRG8Unorm;
5267#endif
5268 case QRhiTexture::R16:
5269 return MTLPixelFormatR16Unorm;
5270 case QRhiTexture::RG16:
5271 return MTLPixelFormatRG16Unorm;
5272 case QRhiTexture::RED_OR_ALPHA8:
5273 return MTLPixelFormatR8Unorm;
5274
5275 case QRhiTexture::RGBA16F:
5276 return MTLPixelFormatRGBA16Float;
5277 case QRhiTexture::RGBA32F:
5278 return MTLPixelFormatRGBA32Float;
5279 case QRhiTexture::R16F:
5280 return MTLPixelFormatR16Float;
5281 case QRhiTexture::R32F:
5282 return MTLPixelFormatR32Float;
5283
5284 case QRhiTexture::RGB10A2:
5285 return MTLPixelFormatRGB10A2Unorm;
5286
5287 case QRhiTexture::R32SI:
5288 return MTLPixelFormatR32Sint;
5289 case QRhiTexture::R32UI:
5290 return MTLPixelFormatR32Uint;
5291 case QRhiTexture::RG32SI:
5292 return MTLPixelFormatRG32Sint;
5293 case QRhiTexture::RG32UI:
5294 return MTLPixelFormatRG32Uint;
5295 case QRhiTexture::RGBA32SI:
5296 return MTLPixelFormatRGBA32Sint;
5297 case QRhiTexture::RGBA32UI:
5298 return MTLPixelFormatRGBA32Uint;
5299
5300#ifdef Q_OS_MACOS
5301 case QRhiTexture::D16:
5302 return MTLPixelFormatDepth16Unorm;
5303 case QRhiTexture::D24:
5304 return [d->d->dev isDepth24Stencil8PixelFormatSupported] ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float;
5305 case QRhiTexture::D24S8:
5306 return [d->d->dev isDepth24Stencil8PixelFormatSupported] ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
5307#else
5308 case QRhiTexture::D16:
5309 return MTLPixelFormatDepth32Float;
5310 case QRhiTexture::D24:
5311 return MTLPixelFormatDepth32Float;
5312 case QRhiTexture::D24S8:
5313 return MTLPixelFormatDepth32Float_Stencil8;
5314#endif
5315 case QRhiTexture::D32F:
5316 return MTLPixelFormatDepth32Float;
5317 case QRhiTexture::D32FS8:
5318 return MTLPixelFormatDepth32Float_Stencil8;
5319
5320#ifdef Q_OS_MACOS
5321 case QRhiTexture::BC1:
5322 return srgb ? MTLPixelFormatBC1_RGBA_sRGB : MTLPixelFormatBC1_RGBA;
5323 case QRhiTexture::BC2:
5324 return srgb ? MTLPixelFormatBC2_RGBA_sRGB : MTLPixelFormatBC2_RGBA;
5325 case QRhiTexture::BC3:
5326 return srgb ? MTLPixelFormatBC3_RGBA_sRGB : MTLPixelFormatBC3_RGBA;
5327 case QRhiTexture::BC4:
5328 return MTLPixelFormatBC4_RUnorm;
5329 case QRhiTexture::BC5:
5330 qWarning("QRhiMetal does not support BC5");
5331 return MTLPixelFormatInvalid;
5332 case QRhiTexture::BC6H:
5333 return MTLPixelFormatBC6H_RGBUfloat;
5334 case QRhiTexture::BC7:
5335 return srgb ? MTLPixelFormatBC7_RGBAUnorm_sRGB : MTLPixelFormatBC7_RGBAUnorm;
5336#else
5337 case QRhiTexture::BC1:
5338 case QRhiTexture::BC2:
5339 case QRhiTexture::BC3:
5340 case QRhiTexture::BC4:
5341 case QRhiTexture::BC5:
5342 case QRhiTexture::BC6H:
5343 case QRhiTexture::BC7:
5344 qWarning("QRhiMetal: BCx compression not supported on this platform");
5345 return MTLPixelFormatInvalid;
5346#endif
5347
5348#ifndef Q_OS_MACOS
5349 case QRhiTexture::ETC2_RGB8:
5350 return srgb ? MTLPixelFormatETC2_RGB8_sRGB : MTLPixelFormatETC2_RGB8;
5351 case QRhiTexture::ETC2_RGB8A1:
5352 return srgb ? MTLPixelFormatETC2_RGB8A1_sRGB : MTLPixelFormatETC2_RGB8A1;
5353 case QRhiTexture::ETC2_RGBA8:
5354 return srgb ? MTLPixelFormatEAC_RGBA8_sRGB : MTLPixelFormatEAC_RGBA8;
5355
5356 case QRhiTexture::ASTC_4x4:
5357 return srgb ? MTLPixelFormatASTC_4x4_sRGB : MTLPixelFormatASTC_4x4_LDR;
5358 case QRhiTexture::ASTC_5x4:
5359 return srgb ? MTLPixelFormatASTC_5x4_sRGB : MTLPixelFormatASTC_5x4_LDR;
5360 case QRhiTexture::ASTC_5x5:
5361 return srgb ? MTLPixelFormatASTC_5x5_sRGB : MTLPixelFormatASTC_5x5_LDR;
5362 case QRhiTexture::ASTC_6x5:
5363 return srgb ? MTLPixelFormatASTC_6x5_sRGB : MTLPixelFormatASTC_6x5_LDR;
5364 case QRhiTexture::ASTC_6x6:
5365 return srgb ? MTLPixelFormatASTC_6x6_sRGB : MTLPixelFormatASTC_6x6_LDR;
5366 case QRhiTexture::ASTC_8x5:
5367 return srgb ? MTLPixelFormatASTC_8x5_sRGB : MTLPixelFormatASTC_8x5_LDR;
5368 case QRhiTexture::ASTC_8x6:
5369 return srgb ? MTLPixelFormatASTC_8x6_sRGB : MTLPixelFormatASTC_8x6_LDR;
5370 case QRhiTexture::ASTC_8x8:
5371 return srgb ? MTLPixelFormatASTC_8x8_sRGB : MTLPixelFormatASTC_8x8_LDR;
5372 case QRhiTexture::ASTC_10x5:
5373 return srgb ? MTLPixelFormatASTC_10x5_sRGB : MTLPixelFormatASTC_10x5_LDR;
5374 case QRhiTexture::ASTC_10x6:
5375 return srgb ? MTLPixelFormatASTC_10x6_sRGB : MTLPixelFormatASTC_10x6_LDR;
5376 case QRhiTexture::ASTC_10x8:
5377 return srgb ? MTLPixelFormatASTC_10x8_sRGB : MTLPixelFormatASTC_10x8_LDR;
5378 case QRhiTexture::ASTC_10x10:
5379 return srgb ? MTLPixelFormatASTC_10x10_sRGB : MTLPixelFormatASTC_10x10_LDR;
5380 case QRhiTexture::ASTC_12x10:
5381 return srgb ? MTLPixelFormatASTC_12x10_sRGB : MTLPixelFormatASTC_12x10_LDR;
5382 case QRhiTexture::ASTC_12x12:
5383 return srgb ? MTLPixelFormatASTC_12x12_sRGB : MTLPixelFormatASTC_12x12_LDR;
5384#else
5385 case QRhiTexture::ETC2_RGB8:
5386 if (d->caps.isAppleGPU)
5387 return srgb ? MTLPixelFormatETC2_RGB8_sRGB : MTLPixelFormatETC2_RGB8;
5388 qWarning("QRhiMetal: ETC2 compression not supported on this platform");
5389 return MTLPixelFormatInvalid;
5390 case QRhiTexture::ETC2_RGB8A1:
5391 if (d->caps.isAppleGPU)
5392 return srgb ? MTLPixelFormatETC2_RGB8A1_sRGB : MTLPixelFormatETC2_RGB8A1;
5393 qWarning("QRhiMetal: ETC2 compression not supported on this platform");
5394 return MTLPixelFormatInvalid;
5395 case QRhiTexture::ETC2_RGBA8:
5396 if (d->caps.isAppleGPU)
5397 return srgb ? MTLPixelFormatEAC_RGBA8_sRGB : MTLPixelFormatEAC_RGBA8;
5398 qWarning("QRhiMetal: ETC2 compression not supported on this platform");
5399 return MTLPixelFormatInvalid;
5400 case QRhiTexture::ASTC_4x4:
5401 if (d->caps.isAppleGPU)
5402 return srgb ? MTLPixelFormatASTC_4x4_sRGB : MTLPixelFormatASTC_4x4_LDR;
5403 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5404 return MTLPixelFormatInvalid;
5405 case QRhiTexture::ASTC_5x4:
5406 if (d->caps.isAppleGPU)
5407 return srgb ? MTLPixelFormatASTC_5x4_sRGB : MTLPixelFormatASTC_5x4_LDR;
5408 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5409 return MTLPixelFormatInvalid;
5410 case QRhiTexture::ASTC_5x5:
5411 if (d->caps.isAppleGPU)
5412 return srgb ? MTLPixelFormatASTC_5x5_sRGB : MTLPixelFormatASTC_5x5_LDR;
5413 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5414 return MTLPixelFormatInvalid;
5415 case QRhiTexture::ASTC_6x5:
5416 if (d->caps.isAppleGPU)
5417 return srgb ? MTLPixelFormatASTC_6x5_sRGB : MTLPixelFormatASTC_6x5_LDR;
5418 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5419 return MTLPixelFormatInvalid;
5420 case QRhiTexture::ASTC_6x6:
5421 if (d->caps.isAppleGPU)
5422 return srgb ? MTLPixelFormatASTC_6x6_sRGB : MTLPixelFormatASTC_6x6_LDR;
5423 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5424 return MTLPixelFormatInvalid;
5425 case QRhiTexture::ASTC_8x5:
5426 if (d->caps.isAppleGPU)
5427 return srgb ? MTLPixelFormatASTC_8x5_sRGB : MTLPixelFormatASTC_8x5_LDR;
5428 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5429 return MTLPixelFormatInvalid;
5430 case QRhiTexture::ASTC_8x6:
5431 if (d->caps.isAppleGPU)
5432 return srgb ? MTLPixelFormatASTC_8x6_sRGB : MTLPixelFormatASTC_8x6_LDR;
5433 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5434 return MTLPixelFormatInvalid;
5435 case QRhiTexture::ASTC_8x8:
5436 if (d->caps.isAppleGPU)
5437 return srgb ? MTLPixelFormatASTC_8x8_sRGB : MTLPixelFormatASTC_8x8_LDR;
5438 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5439 return MTLPixelFormatInvalid;
5440 case QRhiTexture::ASTC_10x5:
5441 if (d->caps.isAppleGPU)
5442 return srgb ? MTLPixelFormatASTC_10x5_sRGB : MTLPixelFormatASTC_10x5_LDR;
5443 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5444 return MTLPixelFormatInvalid;
5445 case QRhiTexture::ASTC_10x6:
5446 if (d->caps.isAppleGPU)
5447 return srgb ? MTLPixelFormatASTC_10x6_sRGB : MTLPixelFormatASTC_10x6_LDR;
5448 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5449 return MTLPixelFormatInvalid;
5450 case QRhiTexture::ASTC_10x8:
5451 if (d->caps.isAppleGPU)
5452 return srgb ? MTLPixelFormatASTC_10x8_sRGB : MTLPixelFormatASTC_10x8_LDR;
5453 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5454 return MTLPixelFormatInvalid;
5455 case QRhiTexture::ASTC_10x10:
5456 if (d->caps.isAppleGPU)
5457 return srgb ? MTLPixelFormatASTC_10x10_sRGB : MTLPixelFormatASTC_10x10_LDR;
5458 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5459 return MTLPixelFormatInvalid;
5460 case QRhiTexture::ASTC_12x10:
5461 if (d->caps.isAppleGPU)
5462 return srgb ? MTLPixelFormatASTC_12x10_sRGB : MTLPixelFormatASTC_12x10_LDR;
5463 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5464 return MTLPixelFormatInvalid;
5465 case QRhiTexture::ASTC_12x12:
5466 if (d->caps.isAppleGPU)
5467 return srgb ? MTLPixelFormatASTC_12x12_sRGB : MTLPixelFormatASTC_12x12_LDR;
5468 qWarning("QRhiMetal: ASTC compression not supported on this platform");
5469 return MTLPixelFormatInvalid;
5470#endif
5471
5472 default:
5473 Q_UNREACHABLE();
5474 return MTLPixelFormatInvalid;
5475 }
5476}
5477
5478QMetalRenderBuffer::QMetalRenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize,
5479 int sampleCount, QRhiRenderBuffer::Flags flags,
5480 QRhiTexture::Format backingFormatHint)
5483{
5484}
5485
5487{
5488 destroy();
5489 delete d;
5490}
5491
5493{
5494 if (!d->tex)
5495 return;
5496
5500
5501 e.renderbuffer.texture = d->tex;
5502 d->tex = nil;
5503
5504 QRHI_RES_RHI(QRhiMetal);
5505 if (rhiD) {
5506 rhiD->d->releaseQueue.append(e);
5507 rhiD->unregisterResource(this);
5508 }
5509}
5510
5512{
5513 if (d->tex)
5514 destroy();
5515
5516 if (m_pixelSize.isEmpty())
5517 return false;
5518
5519 QRHI_RES_RHI(QRhiMetal);
5520 samples = rhiD->effectiveSampleCount(m_sampleCount);
5521
5522 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
5523 desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
5524 desc.width = NSUInteger(m_pixelSize.width());
5525 desc.height = NSUInteger(m_pixelSize.height());
5526 if (samples > 1)
5527 desc.sampleCount = NSUInteger(samples);
5528 desc.resourceOptions = MTLResourceStorageModePrivate;
5529 desc.usage = MTLTextureUsageRenderTarget;
5530
5531 // Memoryless contents cannot survive the render pass getting interrupted and
5532 // continued on another command encoder, which is what NoTransientBacking is
5533 // there to avoid.
5534 const bool canBeMemoryless = !m_flags.testFlag(QRhiRenderBuffer::NoTransientBacking);
5535
5536 switch (m_type) {
5537 case DepthStencil:
5538#ifdef Q_OS_MACOS
5539 if (rhiD->caps.isAppleGPU && canBeMemoryless) {
5540 desc.storageMode = MTLStorageModeMemoryless;
5541 d->format = MTLPixelFormatDepth32Float_Stencil8;
5542 } else {
5543 desc.storageMode = MTLStorageModePrivate;
5544 d->format = rhiD->d->dev.depth24Stencil8PixelFormatSupported
5545 ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
5546 }
5547#else
5548 desc.storageMode = canBeMemoryless ? MTLStorageModeMemoryless : MTLStorageModePrivate;
5549 d->format = MTLPixelFormatDepth32Float_Stencil8;
5550#endif
5551 desc.pixelFormat = d->format;
5552 break;
5553 case Color:
5554 desc.storageMode = MTLStorageModePrivate;
5555 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5556 d->format = toMetalTextureFormat(m_backingFormatHint, {}, rhiD);
5557 else
5558 d->format = MTLPixelFormatRGBA8Unorm;
5559 desc.pixelFormat = d->format;
5560 break;
5561 default:
5562 Q_UNREACHABLE();
5563 break;
5564 }
5565
5566 d->tex = [rhiD->d->dev newTextureWithDescriptor: desc];
5567 [desc release];
5568
5569 if (!m_objectName.isEmpty())
5570 d->tex.label = [NSString stringWithUTF8String: m_objectName.constData()];
5571
5573 generation += 1;
5574 rhiD->registerResource(this);
5575 return true;
5576}
5577
5579{
5580 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5581 return m_backingFormatHint;
5582 else
5583 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
5584}
5585
5586QMetalTexture::QMetalTexture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
5587 int arraySize, int sampleCount, Flags flags)
5589 d(new QMetalTextureData(this))
5590{
5591 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
5592 d->stagingBuf[i] = nil;
5593
5594 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
5595 d->perLevelViews[i] = nil;
5596}
5597
5599{
5600 destroy();
5601 delete d;
5602}
5603
5605{
5606 if (!d->tex)
5607 return;
5608
5612
5613 e.texture.texture = d->owns ? d->tex : nil;
5614 d->tex = nil;
5615
5616 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
5617 e.texture.stagingBuffers[i] = d->stagingBuf[i];
5618 d->stagingBuf[i] = nil;
5619 }
5620
5621 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
5622 e.texture.views[i] = d->perLevelViews[i];
5623 d->perLevelViews[i] = nil;
5624 }
5625
5626 e.texture.samplingView = d->samplingView;
5627 d->samplingView = nil;
5628 e.texture.writeView = d->writeView;
5629 d->writeView = nil;
5630
5631 QRHI_RES_RHI(QRhiMetal);
5632 if (rhiD) {
5633 rhiD->d->releaseQueue.append(e);
5634 rhiD->unregisterResource(this);
5635 }
5636}
5637
5638bool QMetalTexture::prepareCreate(QSize *adjustedSize)
5639{
5640 if (d->tex)
5641 destroy();
5642
5643 const bool isCube = m_flags.testFlag(CubeMap);
5644 const bool is3D = m_flags.testFlag(ThreeDimensional);
5645 const bool isArray = m_flags.testFlag(TextureArray);
5646 const bool hasMipMaps = m_flags.testFlag(MipMapped);
5647 const bool is1D = m_flags.testFlag(OneDimensional);
5648
5649 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
5650 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
5651
5652 QRHI_RES_RHI(QRhiMetal);
5653 d->format = toMetalTextureFormat(m_format, m_flags, rhiD);
5654 if (m_writeViewFormat.format != UnknownFormat) {
5655 d->viewFormat = toMetalTextureFormat(m_writeViewFormat.format,
5656 m_writeViewFormat.srgb ? sRGB : Flags(), rhiD);
5657 } else {
5658 d->viewFormat = d->format;
5659 }
5660 if (m_readViewFormat.format != UnknownFormat) {
5661 d->viewFormatForSampling = toMetalTextureFormat(m_readViewFormat.format,
5662 m_readViewFormat.srgb ? sRGB : Flags(), rhiD);
5663 } else {
5664 d->viewFormatForSampling = d->format;
5665 }
5666 mipLevelCount = hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1;
5667 samples = rhiD->effectiveSampleCount(m_sampleCount);
5668 if (samples > 1) {
5669 if (isCube) {
5670 qWarning("Cubemap texture cannot be multisample");
5671 return false;
5672 }
5673 if (is3D) {
5674 qWarning("3D texture cannot be multisample");
5675 return false;
5676 }
5677 if (hasMipMaps) {
5678 qWarning("Multisample texture cannot have mipmaps");
5679 return false;
5680 }
5681 }
5682 if (isCube && is3D) {
5683 qWarning("Texture cannot be both cube and 3D");
5684 return false;
5685 }
5686 if (isArray && is3D) {
5687 qWarning("Texture cannot be both array and 3D");
5688 return false;
5689 }
5690 if (is1D && is3D) {
5691 qWarning("Texture cannot be both 1D and 3D");
5692 return false;
5693 }
5694 if (is1D && isCube) {
5695 qWarning("Texture cannot be both 1D and cube");
5696 return false;
5697 }
5698 if (m_depth > 1 && !is3D) {
5699 qWarning("Texture cannot have a depth of %d when it is not 3D", m_depth);
5700 return false;
5701 }
5702 if (m_arraySize > 0 && !isArray) {
5703 qWarning("Texture cannot have an array size of %d when it is not an array", m_arraySize);
5704 return false;
5705 }
5706 if (m_arraySize < 1 && isArray) {
5707 qWarning("Texture is an array but array size is %d", m_arraySize);
5708 return false;
5709 }
5710
5711 if (!rhiD->textureFormatInfo(m_format, size, nullptr, nullptr, nullptr))
5712 return false;
5713
5714 if (adjustedSize)
5715 *adjustedSize = size;
5716
5717 return true;
5718}
5719
5721{
5722 QSize size;
5723 if (!prepareCreate(&size))
5724 return false;
5725
5726 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
5727
5728 const bool isCube = m_flags.testFlag(CubeMap);
5729 const bool is3D = m_flags.testFlag(ThreeDimensional);
5730 const bool isArray = m_flags.testFlag(TextureArray);
5731 const bool is1D = m_flags.testFlag(OneDimensional);
5732 if (isCube) {
5733 desc.textureType = MTLTextureTypeCube;
5734 } else if (is3D) {
5735 desc.textureType = MTLTextureType3D;
5736 } else if (is1D) {
5737 desc.textureType = isArray ? MTLTextureType1DArray : MTLTextureType1D;
5738 } else if (isArray) {
5739 desc.textureType = samples > 1 ? MTLTextureType2DMultisampleArray : MTLTextureType2DArray;
5740 } else {
5741 desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
5742 }
5743 desc.pixelFormat = d->format;
5744 desc.width = NSUInteger(size.width());
5745 desc.height = NSUInteger(size.height());
5746 desc.depth = is3D ? qMax(1, m_depth) : 1;
5747 desc.mipmapLevelCount = NSUInteger(mipLevelCount);
5748 if (samples > 1)
5749 desc.sampleCount = NSUInteger(samples);
5750 if (isArray)
5751 desc.arrayLength = NSUInteger(qMax(0, m_arraySize));
5752 desc.resourceOptions = MTLResourceStorageModePrivate;
5753 desc.storageMode = MTLStorageModePrivate;
5754 desc.usage = MTLTextureUsageShaderRead;
5755 if (m_flags.testFlag(RenderTarget))
5756 desc.usage |= MTLTextureUsageRenderTarget;
5757 if (m_flags.testFlag(UsedWithLoadStore))
5758 desc.usage |= MTLTextureUsageShaderWrite;
5759
5760 // Metal requires this only when the view changes the component layout, and
5761 // explicitly says not to set it for linear <-> sRGB views. A view of the
5762 // same QRhi format with a different sRGB setting, or over an array slice
5763 // range, therefore does not need it.
5764 const bool writeViewChangesFormat = m_writeViewFormat.format != UnknownFormat
5765 && m_writeViewFormat.format != m_format;
5766 const bool readViewChangesFormat = m_readViewFormat.format != UnknownFormat
5767 && m_readViewFormat.format != m_format;
5768 if (writeViewChangesFormat || readViewChangesFormat)
5769 desc.usage |= MTLTextureUsagePixelFormatView;
5770
5771 QRHI_RES_RHI(QRhiMetal);
5772 d->tex = [rhiD->d->dev newTextureWithDescriptor: desc];
5773 [desc release];
5774
5775 if (!m_objectName.isEmpty())
5776 d->tex.label = [NSString stringWithUTF8String: m_objectName.constData()];
5777
5778 d->owns = true;
5779
5780 if (!d->createViews())
5781 return false;
5782
5784 generation += 1;
5785 rhiD->registerResource(this);
5786 return true;
5787}
5788
5789bool QMetalTexture::createFrom(QRhiTexture::NativeTexture src)
5790{
5791 id<MTLTexture> tex = id<MTLTexture>(src.object);
5792 if (tex == 0)
5793 return false;
5794
5795 if (!prepareCreate())
5796 return false;
5797
5798 d->tex = tex;
5799
5800 d->owns = false;
5801
5802 if (!d->createViews())
5803 return false;
5804
5806 generation += 1;
5807 QRHI_RES_RHI(QRhiMetal);
5808 rhiD->registerResource(this);
5809 return true;
5810}
5811
5813{
5814 return {quint64(d->tex), 0};
5815}
5816
5818{
5819 Q_ASSERT(!samplingView && !writeView);
5820
5821 const bool isCube = q->m_flags.testFlag(QRhiTexture::CubeMap);
5822 const bool isArray = q->m_flags.testFlag(QRhiTexture::TextureArray);
5823 const bool hasArrayRange = isArray && q->m_arrayRangeStart >= 0 && q->m_arrayRangeLength >= 0;
5824 const NSUInteger sliceCount = isCube ? 6 : (isArray ? NSUInteger(qMax(0, q->m_arraySize)) : 1);
5825 const NSRange levels = NSMakeRange(0, NSUInteger(q->mipLevelCount));
5826 const MTLTextureType type = [tex textureType];
5827
5828 id<MTLTexture> newSamplingView = nil;
5829 id<MTLTexture> newWriteView = nil;
5830
5831 if (viewFormatForSampling != format || hasArrayRange) {
5832 const NSRange slices = hasArrayRange
5833 ? NSMakeRange(NSUInteger(q->m_arrayRangeStart), NSUInteger(q->m_arrayRangeLength))
5834 : NSMakeRange(0, sliceCount);
5835 newSamplingView = [tex newTextureViewWithPixelFormat: viewFormatForSampling
5836 textureType: type levels: levels slices: slices];
5837 if (!newSamplingView) {
5838 qWarning("QRhiMetal: Failed to create texture view used for sampling");
5839 return false;
5840 }
5841 }
5842
5843 if (viewFormat != format) {
5844 newWriteView = [tex newTextureViewWithPixelFormat: viewFormat
5845 textureType: type levels: levels
5846 slices: NSMakeRange(0, sliceCount)];
5847 if (!newWriteView) {
5848 qWarning("QRhiMetal: Failed to create texture view used for rendering");
5849 [newSamplingView release];
5850 return false;
5851 }
5852 }
5853
5854 samplingView = newSamplingView;
5855 writeView = newWriteView;
5856 return true;
5857}
5858
5860{
5861 Q_ASSERT(level >= 0 && level < int(q->mipLevelCount));
5862 if (perLevelViews[level])
5863 return perLevelViews[level];
5864
5865 const MTLTextureType type = [tex textureType];
5866 const bool isCube = q->m_flags.testFlag(QRhiTexture::CubeMap);
5867 const bool isArray = q->m_flags.testFlag(QRhiTexture::TextureArray);
5868 id<MTLTexture> view = [tex newTextureViewWithPixelFormat: viewFormat textureType: type
5869 levels: NSMakeRange(NSUInteger(level), 1)
5870 slices: NSMakeRange(0, isCube ? 6 : (isArray ? qMax(0, q->m_arraySize) : 1))];
5871
5872 perLevelViews[level] = view;
5873 return view;
5874}
5875
5876QMetalSampler::QMetalSampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
5877 AddressMode u, AddressMode v, AddressMode w)
5879 d(new QMetalSamplerData)
5880{
5881}
5882
5884{
5885 destroy();
5886 delete d;
5887}
5888
5890{
5891 if (!d->samplerState)
5892 return;
5893
5897
5898 e.sampler.samplerState = d->samplerState;
5899 d->samplerState = nil;
5900
5901 QRHI_RES_RHI(QRhiMetal);
5902 if (rhiD) {
5903 rhiD->d->releaseQueue.append(e);
5904 rhiD->unregisterResource(this);
5905 }
5906}
5907
5908static inline MTLSamplerMinMagFilter toMetalFilter(QRhiSampler::Filter f)
5909{
5910 switch (f) {
5911 case QRhiSampler::Nearest:
5912 return MTLSamplerMinMagFilterNearest;
5913 case QRhiSampler::Linear:
5914 return MTLSamplerMinMagFilterLinear;
5915 default:
5916 Q_UNREACHABLE();
5917 return MTLSamplerMinMagFilterNearest;
5918 }
5919}
5920
5921static inline MTLSamplerMipFilter toMetalMipmapMode(QRhiSampler::Filter f)
5922{
5923 switch (f) {
5924 case QRhiSampler::None:
5925 return MTLSamplerMipFilterNotMipmapped;
5926 case QRhiSampler::Nearest:
5927 return MTLSamplerMipFilterNearest;
5928 case QRhiSampler::Linear:
5929 return MTLSamplerMipFilterLinear;
5930 default:
5931 Q_UNREACHABLE();
5932 return MTLSamplerMipFilterNotMipmapped;
5933 }
5934}
5935
5936static inline MTLSamplerAddressMode toMetalAddressMode(QRhiSampler::AddressMode m)
5937{
5938 switch (m) {
5939 case QRhiSampler::Repeat:
5940 return MTLSamplerAddressModeRepeat;
5941 case QRhiSampler::ClampToEdge:
5942 return MTLSamplerAddressModeClampToEdge;
5943 case QRhiSampler::Mirror:
5944 return MTLSamplerAddressModeMirrorRepeat;
5945 default:
5946 Q_UNREACHABLE();
5947 return MTLSamplerAddressModeClampToEdge;
5948 }
5949}
5950
5951static inline MTLCompareFunction toMetalTextureCompareFunction(QRhiSampler::CompareOp op)
5952{
5953 switch (op) {
5954 case QRhiSampler::Never:
5955 return MTLCompareFunctionNever;
5956 case QRhiSampler::Less:
5957 return MTLCompareFunctionLess;
5958 case QRhiSampler::Equal:
5959 return MTLCompareFunctionEqual;
5960 case QRhiSampler::LessOrEqual:
5961 return MTLCompareFunctionLessEqual;
5962 case QRhiSampler::Greater:
5963 return MTLCompareFunctionGreater;
5964 case QRhiSampler::NotEqual:
5965 return MTLCompareFunctionNotEqual;
5966 case QRhiSampler::GreaterOrEqual:
5967 return MTLCompareFunctionGreaterEqual;
5968 case QRhiSampler::Always:
5969 return MTLCompareFunctionAlways;
5970 default:
5971 Q_UNREACHABLE();
5972 return MTLCompareFunctionNever;
5973 }
5974}
5975
5977{
5978 if (d->samplerState)
5979 destroy();
5980
5981 MTLSamplerDescriptor *desc = [[MTLSamplerDescriptor alloc] init];
5982 desc.minFilter = toMetalFilter(m_minFilter);
5983 desc.magFilter = toMetalFilter(m_magFilter);
5984 desc.mipFilter = toMetalMipmapMode(m_mipmapMode);
5985 desc.sAddressMode = toMetalAddressMode(m_addressU);
5986 desc.tAddressMode = toMetalAddressMode(m_addressV);
5987 desc.rAddressMode = toMetalAddressMode(m_addressW);
5988 desc.compareFunction = toMetalTextureCompareFunction(m_compareOp);
5989 QRHI_RES_RHI(QRhiMetal);
5990 // Whether this sampler ends up in an argument buffer is not known here, and
5991 // a sampler state cannot be changed afterwards. Metal gives no warning when
5992 // one without this is used with an argument buffer, it just faults the GPU.
5993 // So set it always as long as ICBs are supported.
5994 desc.supportArgumentBuffers = rhiD->caps.indirectCommandBuffers ? YES : NO;
5995 d->samplerState = [rhiD->d->dev newSamplerStateWithDescriptor: desc];
5996 [desc release];
5997 if (!d->samplerState) {
5998 // Sampler states with supportArgumentBuffers set draw on a per-process
5999 // quota (MTLDevice.maxArgumentBufferSamplerCount), so mention that as
6000 // the likely reason for a failure that is otherwise hard to explain.
6001 qWarning("Failed to create Metal sampler state. The number of unique sampler "
6002 "states with argument buffer support may have exceeded the limit of %u.",
6003 uint(rhiD->d->dev.maxArgumentBufferSamplerCount));
6004 return false;
6005 }
6006
6008 generation += 1;
6009 rhiD->registerResource(this);
6010 return true;
6011}
6012
6016{
6017}
6018
6020{
6021 destroy();
6022 delete d;
6023}
6024
6026{
6027 if (!d->rateMap)
6028 return;
6029
6033
6034 e.shadingRateMap.rateMap = d->rateMap;
6035 d->rateMap = nil;
6036
6037 QRHI_RES_RHI(QRhiMetal);
6038 if (rhiD) {
6039 rhiD->d->releaseQueue.append(e);
6040 rhiD->unregisterResource(this);
6041 }
6042}
6043
6044bool QMetalShadingRateMap::createFrom(NativeShadingRateMap src)
6045{
6046 if (d->rateMap)
6047 destroy();
6048
6049 d->rateMap = (id<MTLRasterizationRateMap>) (quintptr(src.object));
6050 if (!d->rateMap)
6051 return false;
6052
6053 [d->rateMap retain];
6054
6056 generation += 1;
6057 QRHI_RES_RHI(QRhiMetal);
6058 rhiD->registerResource(this);
6059 return true;
6060}
6061
6063{
6064 if (!d->rateMap)
6065 return QSize();
6066
6067 const MTLSize screenSize = [d->rateMap screenSize];
6068 return QSize(int(screenSize.width), int(screenSize.height));
6069}
6070
6071// dummy, no Vulkan-style RenderPass+Framebuffer concept here.
6072// We do have MTLRenderPassDescriptor of course, but it will be created on the fly for each pass.
6075{
6076 serializedFormatData.reserve(16);
6077}
6078
6083
6085{
6086 QRHI_RES_RHI(QRhiMetal);
6087 if (rhiD)
6088 rhiD->unregisterResource(this);
6089}
6090
6091bool QMetalRenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const
6092{
6093 if (!other)
6094 return false;
6095
6097
6099 return false;
6100
6102 return false;
6103
6104 for (int i = 0; i < colorAttachmentCount; ++i) {
6105 if (colorFormat[i] != o->colorFormat[i])
6106 return false;
6107 }
6108
6109 if (hasDepthStencil) {
6110 if (dsFormat != o->dsFormat)
6111 return false;
6112 }
6113
6115 return false;
6116
6117 return true;
6118}
6119
6121{
6122 serializedFormatData.clear();
6123 auto p = std::back_inserter(serializedFormatData);
6124
6125 *p++ = colorAttachmentCount;
6126 *p++ = hasDepthStencil;
6127 for (int i = 0; i < colorAttachmentCount; ++i)
6128 *p++ = colorFormat[i];
6129 *p++ = hasDepthStencil ? dsFormat : 0;
6130 *p++ = hasShadingRateMap;
6131}
6132
6134{
6135 QMetalRenderPassDescriptor *rpD = new QMetalRenderPassDescriptor(m_rhi);
6138 memcpy(rpD->colorFormat, colorFormat, sizeof(colorFormat));
6139 rpD->dsFormat = dsFormat;
6141
6143
6144 QRHI_RES_RHI(QRhiMetal);
6145 rhiD->registerResource(rpD, false);
6146 return rpD;
6147}
6148
6150{
6151 return serializedFormatData;
6152}
6153
6154QMetalSwapChainRenderTarget::QMetalSwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
6157{
6158}
6159
6165
6167{
6168 // nothing to do here
6169}
6170
6172{
6173 return d->pixelSize;
6174}
6175
6177{
6178 return d->dpr;
6179}
6180
6182{
6183 return d->sampleCount;
6184}
6185
6187 const QRhiTextureRenderTargetDescription &desc,
6188 Flags flags)
6191{
6192}
6193
6199
6201{
6202 QRHI_RES_RHI(QRhiMetal);
6203 if (rhiD)
6204 rhiD->unregisterResource(this);
6205}
6206
6208{
6209 const int colorAttachmentCount = int(m_desc.colorAttachmentCount());
6210 QMetalRenderPassDescriptor *rpD = new QMetalRenderPassDescriptor(m_rhi);
6211 rpD->colorAttachmentCount = colorAttachmentCount;
6212 rpD->hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
6213
6214 for (int i = 0; i < colorAttachmentCount; ++i) {
6215 const QRhiColorAttachment *colorAtt = m_desc.colorAttachmentAt(i);
6216 QMetalTexture *texD = QRHI_RES(QMetalTexture, colorAtt->texture());
6217 QMetalRenderBuffer *rbD = QRHI_RES(QMetalRenderBuffer, colorAtt->renderBuffer());
6218 rpD->colorFormat[i] = int(texD ? texD->d->viewFormat : rbD->d->format);
6219 }
6220
6221 if (m_desc.depthTexture())
6222 rpD->dsFormat = int(QRHI_RES(QMetalTexture, m_desc.depthTexture())->d->viewFormat);
6223 else if (m_desc.depthStencilBuffer())
6224 rpD->dsFormat = int(QRHI_RES(QMetalRenderBuffer, m_desc.depthStencilBuffer())->d->format);
6225
6226 rpD->hasShadingRateMap = m_desc.shadingRateMap() != nullptr;
6227
6229
6230 QRHI_RES_RHI(QRhiMetal);
6231 rhiD->registerResource(rpD, false);
6232 return rpD;
6233}
6234
6236{
6237 QRHI_RES_RHI(QRhiMetal);
6238 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
6239 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
6240 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
6241
6242 d->colorAttCount = 0;
6243 int attIndex = 0;
6244 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
6245 d->colorAttCount += 1;
6246 QMetalTexture *texD = QRHI_RES(QMetalTexture, it->texture());
6247 QMetalRenderBuffer *rbD = QRHI_RES(QMetalRenderBuffer, it->renderBuffer());
6248 Q_ASSERT(texD || rbD);
6249 id<MTLTexture> dst = nil;
6250 bool is3D = false;
6251 if (texD) {
6252 dst = texD->d->textureForWrite();
6253 if (attIndex == 0) {
6254 d->pixelSize = rhiD->q->sizeForMipLevel(it->level(), texD->pixelSize());
6256 }
6257 is3D = texD->flags().testFlag(QRhiTexture::ThreeDimensional);
6258 } else if (rbD) {
6259 dst = rbD->d->tex;
6260 if (attIndex == 0) {
6261 d->pixelSize = rbD->pixelSize();
6263 }
6264 }
6266 colorAtt.tex = dst;
6267 colorAtt.arrayLayer = is3D ? 0 : it->layer();
6268 colorAtt.slice = is3D ? it->layer() : 0;
6269 colorAtt.level = it->level();
6270 QMetalTexture *resTexD = QRHI_RES(QMetalTexture, it->resolveTexture());
6271 colorAtt.resolveTex = resTexD ? resTexD->d->textureForWrite() : nil;
6272 colorAtt.resolveLayer = it->resolveLayer();
6273 colorAtt.resolveLevel = it->resolveLevel();
6274 d->fb.colorAtt[attIndex] = colorAtt;
6275 }
6276 d->dpr = 1;
6277
6278 if (hasDepthStencil) {
6279 if (m_desc.depthTexture()) {
6280 QMetalTexture *depthTexD = QRHI_RES(QMetalTexture, m_desc.depthTexture());
6281 d->fb.dsTex = depthTexD->d->textureForWrite();
6282 d->fb.hasStencil = rhiD->isStencilSupportingFormat(depthTexD->format());
6283 d->fb.depthNeedsStore = !m_flags.testFlag(DoNotStoreDepthStencilContents) && !m_desc.depthResolveTexture();
6284 d->fb.preserveDs = m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
6285 if (d->colorAttCount == 0) {
6286 d->pixelSize = depthTexD->pixelSize();
6287 d->sampleCount = depthTexD->samples;
6288 }
6289 } else {
6290 QMetalRenderBuffer *depthRbD = QRHI_RES(QMetalRenderBuffer, m_desc.depthStencilBuffer());
6291 d->fb.dsTex = depthRbD->d->tex;
6292 d->fb.hasStencil = true;
6293 d->fb.depthNeedsStore = false;
6294 d->fb.preserveDs = false;
6295 if (d->colorAttCount == 0) {
6296 d->pixelSize = depthRbD->pixelSize();
6297 d->sampleCount = depthRbD->samples;
6298 }
6299 }
6300 if (m_desc.depthResolveTexture()) {
6301 QMetalTexture *depthResolveTexD = QRHI_RES(QMetalTexture, m_desc.depthResolveTexture());
6302 d->fb.dsResolveTex = depthResolveTexD->d->textureForWrite();
6303 }
6304 d->dsAttCount = 1;
6305 } else {
6306 d->dsAttCount = 0;
6307 }
6308
6309 if (d->colorAttCount > 0)
6310 d->fb.preserveColor = m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
6311
6312 QRhiRenderTargetAttachmentTracker::updateResIdList<QMetalTexture, QMetalRenderBuffer>(m_desc, &d->currentResIdList);
6313
6314 rhiD->registerResource(this, false);
6315 return true;
6316}
6317
6319{
6320 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QMetalTexture, QMetalRenderBuffer>(m_desc, d->currentResIdList))
6321 const_cast<QMetalTextureRenderTarget *>(this)->create();
6322
6323 return d->pixelSize;
6324}
6325
6327{
6328 return d->dpr;
6329}
6330
6332{
6333 return d->sampleCount;
6334}
6335
6340
6345
6347{
6348 sortedBindings.clear();
6349 maxBinding = -1;
6350
6351 QRHI_RES_RHI(QRhiMetal);
6352 if (rhiD)
6353 rhiD->unregisterResource(this);
6354}
6355
6357{
6358 if (!sortedBindings.isEmpty())
6359 destroy();
6360
6361 QRHI_RES_RHI(QRhiMetal);
6362 if (!rhiD->sanityCheckShaderResourceBindings(this))
6363 return false;
6364
6365 rhiD->updateLayoutDesc(this);
6366
6367 std::copy(m_bindings.cbegin(), m_bindings.cend(), std::back_inserter(sortedBindings));
6368 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
6369 if (!sortedBindings.isEmpty())
6370 maxBinding = QRhiImplementation::shaderResourceBindingData(sortedBindings.last())->binding;
6371 else
6372 maxBinding = -1;
6373
6374 boundResourceData.resize(sortedBindings.count());
6375
6376 for (BoundResourceData &bd : boundResourceData)
6377 bd = {};
6378
6379 generation += 1;
6380 rhiD->registerResource(this, false);
6381 return true;
6382}
6383
6385{
6386 sortedBindings.clear();
6387 std::copy(m_bindings.cbegin(), m_bindings.cend(), std::back_inserter(sortedBindings));
6388 if (!flags.testFlag(BindingsAreSorted))
6389 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
6390
6391 for (BoundResourceData &bd : boundResourceData)
6392 bd = {};
6393
6394 generation += 1;
6395}
6396
6400{
6401 d->q = this;
6402 d->tess.q = d;
6403}
6404
6410
6412{
6413 d->vs.destroy();
6414 d->fs.destroy();
6415
6416 d->icbCapable = false;
6417
6418 d->tess.compVs[0].destroy();
6419 d->tess.compVs[1].destroy();
6420 d->tess.compVs[2].destroy();
6421
6422 d->tess.compTesc.destroy();
6423 d->tess.vertTese.destroy();
6424
6425 qDeleteAll(d->extraBufMgr.deviceLocalWorkBuffers);
6426 d->extraBufMgr.deviceLocalWorkBuffers.clear();
6427 qDeleteAll(d->extraBufMgr.hostVisibleWorkBuffers);
6428 d->extraBufMgr.hostVisibleWorkBuffers.clear();
6429
6430 delete d->bufferSizeBuffer;
6431 d->bufferSizeBuffer = nullptr;
6432
6433 if (!d->ps && !d->ds
6434 && !d->tess.vertexComputeState[0] && !d->tess.vertexComputeState[1] && !d->tess.vertexComputeState[2]
6435 && !d->tess.tessControlComputeState)
6436 {
6437 return;
6438 }
6439
6443 e.graphicsPipeline.pipelineState = d->ps;
6444 e.graphicsPipeline.depthStencilState = d->ds;
6445 e.graphicsPipeline.tessVertexComputeState = d->tess.vertexComputeState;
6446 e.graphicsPipeline.tessTessControlComputeState = d->tess.tessControlComputeState;
6447 d->ps = nil;
6448 d->ds = nil;
6449 d->tess.vertexComputeState = {};
6450 d->tess.tessControlComputeState = nil;
6451
6452 QRHI_RES_RHI(QRhiMetal);
6453 if (rhiD) {
6454 rhiD->d->releaseQueue.append(e);
6455 rhiD->unregisterResource(this);
6456 }
6457}
6458
6459static inline MTLVertexFormat toMetalAttributeFormat(QRhiVertexInputAttribute::Format format)
6460{
6461 switch (format) {
6462 case QRhiVertexInputAttribute::Float4:
6463 return MTLVertexFormatFloat4;
6464 case QRhiVertexInputAttribute::Float3:
6465 return MTLVertexFormatFloat3;
6466 case QRhiVertexInputAttribute::Float2:
6467 return MTLVertexFormatFloat2;
6468 case QRhiVertexInputAttribute::Float:
6469 return MTLVertexFormatFloat;
6470 case QRhiVertexInputAttribute::UNormByte4:
6471 return MTLVertexFormatUChar4Normalized;
6472 case QRhiVertexInputAttribute::UNormByte2:
6473 return MTLVertexFormatUChar2Normalized;
6474 case QRhiVertexInputAttribute::UNormByte:
6475 return MTLVertexFormatUCharNormalized;
6476 case QRhiVertexInputAttribute::UInt4:
6477 return MTLVertexFormatUInt4;
6478 case QRhiVertexInputAttribute::UInt3:
6479 return MTLVertexFormatUInt3;
6480 case QRhiVertexInputAttribute::UInt2:
6481 return MTLVertexFormatUInt2;
6482 case QRhiVertexInputAttribute::UInt:
6483 return MTLVertexFormatUInt;
6484 case QRhiVertexInputAttribute::SInt4:
6485 return MTLVertexFormatInt4;
6486 case QRhiVertexInputAttribute::SInt3:
6487 return MTLVertexFormatInt3;
6488 case QRhiVertexInputAttribute::SInt2:
6489 return MTLVertexFormatInt2;
6490 case QRhiVertexInputAttribute::SInt:
6491 return MTLVertexFormatInt;
6492 case QRhiVertexInputAttribute::Half4:
6493 return MTLVertexFormatHalf4;
6494 case QRhiVertexInputAttribute::Half3:
6495 return MTLVertexFormatHalf3;
6496 case QRhiVertexInputAttribute::Half2:
6497 return MTLVertexFormatHalf2;
6498 case QRhiVertexInputAttribute::Half:
6499 return MTLVertexFormatHalf;
6500 case QRhiVertexInputAttribute::UShort4:
6501 return MTLVertexFormatUShort4;
6502 case QRhiVertexInputAttribute::UShort3:
6503 return MTLVertexFormatUShort3;
6504 case QRhiVertexInputAttribute::UShort2:
6505 return MTLVertexFormatUShort2;
6506 case QRhiVertexInputAttribute::UShort:
6507 return MTLVertexFormatUShort;
6508 case QRhiVertexInputAttribute::SShort4:
6509 return MTLVertexFormatShort4;
6510 case QRhiVertexInputAttribute::SShort3:
6511 return MTLVertexFormatShort3;
6512 case QRhiVertexInputAttribute::SShort2:
6513 return MTLVertexFormatShort2;
6514 case QRhiVertexInputAttribute::SShort:
6515 return MTLVertexFormatShort;
6516 default:
6517 Q_UNREACHABLE();
6518 return MTLVertexFormatFloat4;
6519 }
6520}
6521
6522static inline MTLBlendFactor toMetalBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
6523{
6524 switch (f) {
6525 case QRhiGraphicsPipeline::Zero:
6526 return MTLBlendFactorZero;
6527 case QRhiGraphicsPipeline::One:
6528 return MTLBlendFactorOne;
6529 case QRhiGraphicsPipeline::SrcColor:
6530 return MTLBlendFactorSourceColor;
6531 case QRhiGraphicsPipeline::OneMinusSrcColor:
6532 return MTLBlendFactorOneMinusSourceColor;
6533 case QRhiGraphicsPipeline::DstColor:
6534 return MTLBlendFactorDestinationColor;
6535 case QRhiGraphicsPipeline::OneMinusDstColor:
6536 return MTLBlendFactorOneMinusDestinationColor;
6537 case QRhiGraphicsPipeline::SrcAlpha:
6538 return MTLBlendFactorSourceAlpha;
6539 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
6540 return MTLBlendFactorOneMinusSourceAlpha;
6541 case QRhiGraphicsPipeline::DstAlpha:
6542 return MTLBlendFactorDestinationAlpha;
6543 case QRhiGraphicsPipeline::OneMinusDstAlpha:
6544 return MTLBlendFactorOneMinusDestinationAlpha;
6545 case QRhiGraphicsPipeline::ConstantColor:
6546 return MTLBlendFactorBlendColor;
6547 case QRhiGraphicsPipeline::ConstantAlpha:
6548 return MTLBlendFactorBlendAlpha;
6549 case QRhiGraphicsPipeline::OneMinusConstantColor:
6550 return MTLBlendFactorOneMinusBlendColor;
6551 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
6552 return MTLBlendFactorOneMinusBlendAlpha;
6553 case QRhiGraphicsPipeline::SrcAlphaSaturate:
6554 return MTLBlendFactorSourceAlphaSaturated;
6555 case QRhiGraphicsPipeline::Src1Color:
6556 return MTLBlendFactorSource1Color;
6557 case QRhiGraphicsPipeline::OneMinusSrc1Color:
6558 return MTLBlendFactorOneMinusSource1Color;
6559 case QRhiGraphicsPipeline::Src1Alpha:
6560 return MTLBlendFactorSource1Alpha;
6561 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
6562 return MTLBlendFactorOneMinusSource1Alpha;
6563 default:
6564 Q_UNREACHABLE();
6565 return MTLBlendFactorZero;
6566 }
6567}
6568
6569static inline MTLBlendOperation toMetalBlendOp(QRhiGraphicsPipeline::BlendOp op)
6570{
6571 switch (op) {
6572 case QRhiGraphicsPipeline::Add:
6573 return MTLBlendOperationAdd;
6574 case QRhiGraphicsPipeline::Subtract:
6575 return MTLBlendOperationSubtract;
6576 case QRhiGraphicsPipeline::ReverseSubtract:
6577 return MTLBlendOperationReverseSubtract;
6578 case QRhiGraphicsPipeline::Min:
6579 return MTLBlendOperationMin;
6580 case QRhiGraphicsPipeline::Max:
6581 return MTLBlendOperationMax;
6582 default:
6583 Q_UNREACHABLE();
6584 return MTLBlendOperationAdd;
6585 }
6586}
6587
6588static inline uint toMetalColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
6589{
6590 uint f = 0;
6591 if (c.testFlag(QRhiGraphicsPipeline::R))
6592 f |= MTLColorWriteMaskRed;
6593 if (c.testFlag(QRhiGraphicsPipeline::G))
6594 f |= MTLColorWriteMaskGreen;
6595 if (c.testFlag(QRhiGraphicsPipeline::B))
6596 f |= MTLColorWriteMaskBlue;
6597 if (c.testFlag(QRhiGraphicsPipeline::A))
6598 f |= MTLColorWriteMaskAlpha;
6599 return f;
6600}
6601
6602static inline MTLCompareFunction toMetalCompareOp(QRhiGraphicsPipeline::CompareOp op)
6603{
6604 switch (op) {
6605 case QRhiGraphicsPipeline::Never:
6606 return MTLCompareFunctionNever;
6607 case QRhiGraphicsPipeline::Less:
6608 return MTLCompareFunctionLess;
6609 case QRhiGraphicsPipeline::Equal:
6610 return MTLCompareFunctionEqual;
6611 case QRhiGraphicsPipeline::LessOrEqual:
6612 return MTLCompareFunctionLessEqual;
6613 case QRhiGraphicsPipeline::Greater:
6614 return MTLCompareFunctionGreater;
6615 case QRhiGraphicsPipeline::NotEqual:
6616 return MTLCompareFunctionNotEqual;
6617 case QRhiGraphicsPipeline::GreaterOrEqual:
6618 return MTLCompareFunctionGreaterEqual;
6619 case QRhiGraphicsPipeline::Always:
6620 return MTLCompareFunctionAlways;
6621 default:
6622 Q_UNREACHABLE();
6623 return MTLCompareFunctionAlways;
6624 }
6625}
6626
6627static inline MTLStencilOperation toMetalStencilOp(QRhiGraphicsPipeline::StencilOp op)
6628{
6629 switch (op) {
6630 case QRhiGraphicsPipeline::StencilZero:
6631 return MTLStencilOperationZero;
6632 case QRhiGraphicsPipeline::Keep:
6633 return MTLStencilOperationKeep;
6634 case QRhiGraphicsPipeline::Replace:
6635 return MTLStencilOperationReplace;
6636 case QRhiGraphicsPipeline::IncrementAndClamp:
6637 return MTLStencilOperationIncrementClamp;
6638 case QRhiGraphicsPipeline::DecrementAndClamp:
6639 return MTLStencilOperationDecrementClamp;
6640 case QRhiGraphicsPipeline::Invert:
6641 return MTLStencilOperationInvert;
6642 case QRhiGraphicsPipeline::IncrementAndWrap:
6643 return MTLStencilOperationIncrementWrap;
6644 case QRhiGraphicsPipeline::DecrementAndWrap:
6645 return MTLStencilOperationDecrementWrap;
6646 default:
6647 Q_UNREACHABLE();
6648 return MTLStencilOperationKeep;
6649 }
6650}
6651
6652static inline MTLPrimitiveType toMetalPrimitiveType(QRhiGraphicsPipeline::Topology t)
6653{
6654 switch (t) {
6655 case QRhiGraphicsPipeline::Triangles:
6656 return MTLPrimitiveTypeTriangle;
6657 case QRhiGraphicsPipeline::TriangleStrip:
6658 return MTLPrimitiveTypeTriangleStrip;
6659 case QRhiGraphicsPipeline::Lines:
6660 return MTLPrimitiveTypeLine;
6661 case QRhiGraphicsPipeline::LineStrip:
6662 return MTLPrimitiveTypeLineStrip;
6663 case QRhiGraphicsPipeline::Points:
6664 return MTLPrimitiveTypePoint;
6665 default:
6666 Q_UNREACHABLE();
6667 return MTLPrimitiveTypeTriangle;
6668 }
6669}
6670
6671static inline MTLPrimitiveTopologyClass toMetalPrimitiveTopologyClass(QRhiGraphicsPipeline::Topology t)
6672{
6673 switch (t) {
6674 case QRhiGraphicsPipeline::Triangles:
6675 case QRhiGraphicsPipeline::TriangleStrip:
6676 case QRhiGraphicsPipeline::TriangleFan:
6677 return MTLPrimitiveTopologyClassTriangle;
6678 case QRhiGraphicsPipeline::Lines:
6679 case QRhiGraphicsPipeline::LineStrip:
6680 return MTLPrimitiveTopologyClassLine;
6681 case QRhiGraphicsPipeline::Points:
6682 return MTLPrimitiveTopologyClassPoint;
6683 default:
6684 Q_UNREACHABLE();
6685 return MTLPrimitiveTopologyClassTriangle;
6686 }
6687}
6688
6689static inline MTLCullMode toMetalCullMode(QRhiGraphicsPipeline::CullMode c)
6690{
6691 switch (c) {
6692 case QRhiGraphicsPipeline::None:
6693 return MTLCullModeNone;
6694 case QRhiGraphicsPipeline::Front:
6695 return MTLCullModeFront;
6696 case QRhiGraphicsPipeline::Back:
6697 return MTLCullModeBack;
6698 default:
6699 Q_UNREACHABLE();
6700 return MTLCullModeNone;
6701 }
6702}
6703
6704static inline MTLTriangleFillMode toMetalTriangleFillMode(QRhiGraphicsPipeline::PolygonMode mode)
6705{
6706 switch (mode) {
6707 case QRhiGraphicsPipeline::Fill:
6708 return MTLTriangleFillModeFill;
6709 case QRhiGraphicsPipeline::Line:
6710 return MTLTriangleFillModeLines;
6711 default:
6712 Q_UNREACHABLE();
6713 return MTLTriangleFillModeFill;
6714 }
6715}
6716
6717static inline MTLWinding toMetalTessellationWindingOrder(QShaderDescription::TessellationWindingOrder w)
6718{
6719 switch (w) {
6720 case QShaderDescription::CwTessellationWindingOrder:
6721 return MTLWindingClockwise;
6722 case QShaderDescription::CcwTessellationWindingOrder:
6723 return MTLWindingCounterClockwise;
6724 default:
6725 // this is reachable, consider a tess.eval. shader not declaring it, the value is then Unknown
6726 return MTLWindingCounterClockwise;
6727 }
6728}
6729
6730static inline MTLTessellationPartitionMode toMetalTessellationPartitionMode(QShaderDescription::TessellationPartitioning p)
6731{
6732 switch (p) {
6733 case QShaderDescription::EqualTessellationPartitioning:
6734 return MTLTessellationPartitionModePow2;
6735 case QShaderDescription::FractionalEvenTessellationPartitioning:
6736 return MTLTessellationPartitionModeFractionalEven;
6737 case QShaderDescription::FractionalOddTessellationPartitioning:
6738 return MTLTessellationPartitionModeFractionalOdd;
6739 default:
6740 // this is reachable, consider a tess.eval. shader not declaring it, the value is then Unknown
6741 return MTLTessellationPartitionModePow2;
6742 }
6743}
6744
6745static inline MTLLanguageVersion toMetalLanguageVersion(const QShaderVersion &version)
6746{
6747 int v = version.version();
6748 return MTLLanguageVersion(((v / 10) << 16) + (v % 10));
6749}
6750
6751id<MTLBuffer> QRhiMetalData::allocFromStagingArea(StagingArea *area, quint32 size, quint32 alignment,
6752 int frameSlot, quint32 minBlockSize, quint32 *offset)
6753{
6754 auto &pool(*area);
6755 const quint32 alignedSize = aligned<quint32>(size, alignment);
6756 if (pool.offset + alignedSize > pool.capacity) {
6757 if (pool.buf) {
6758 // Reusing the StagingBuffer entry type: the handler just releases
6759 // the buffer. lastActiveFrameSlot = frameSlot is what keeps the old
6760 // buffer alive for the rest of this frame, since
6761 // executeDeferredReleases() only gets to this slot after the
6762 // semaphore wait in the next beginFrame() for it.
6765 e.lastActiveFrameSlot = frameSlot;
6766 e.stagingBuffer.buffer = pool.buf;
6767 releaseQueue.append(e);
6768 }
6769 pool.capacity = qMax(pool.capacity * 2, qMax(alignedSize, minBlockSize));
6770 pool.buf = [dev newBufferWithLength: pool.capacity options: MTLResourceStorageModeShared];
6771 pool.offset = 0;
6772 if (!pool.buf) {
6773 pool.capacity = 0;
6774 return nil;
6775 }
6776 }
6777 *offset = pool.offset;
6778 pool.offset += alignedSize;
6779 return pool.buf;
6780}
6781
6782id<MTLBuffer> QRhiMetalData::allocArgumentBuffer(quint32 size, quint32 alignment, int frameSlot, quint32 *offset)
6783{
6784 return allocFromStagingArea(&argBufPool[frameSlot], size, alignment, frameSlot, 16384, offset);
6785}
6786
6788{
6789 id<MTLBuffer> buf = [dev newBufferWithLength: size options: MTLResourceStorageModeShared];
6790 if (!buf)
6791 return nil;
6794 e.lastActiveFrameSlot = frameSlot;
6795 e.stagingBuffer.buffer = buf;
6796 releaseQueue.append(e);
6797 return buf;
6798}
6799
6800id<MTLBuffer> QRhiMetalData::allocBufferStaging(quint32 size, int frameSlot, quint32 *offset)
6801{
6802 if (size > LARGE_STAGING_ALLOC) {
6803 *offset = 0;
6804 return newOneShotStagingBuffer(size, frameSlot);
6805 }
6806
6807 StagingArea &area(bufStagingPool[frameSlot]);
6808 // 4 byte alignment is what MTLBlitCommandEncoder wants on non-Apple GPUs.
6809 const quint32 alignedSize = aligned<quint32>(size, 4u);
6810 area.bytesNeeded += alignedSize;
6811
6812 if (area.offset + alignedSize > area.capacity) {
6813 *offset = 0;
6814 return newOneShotStagingBuffer(size, frameSlot);
6815 }
6816
6817 *offset = area.offset;
6818 area.offset += alignedSize;
6819 return area.buf;
6820}
6821
6823{
6824 StagingArea &area(bufStagingPool[frameSlot]);
6825 const quint32 needed = area.bytesNeeded;
6826 area.bytesNeeded = 0;
6827 area.offset = 0;
6828
6829 bool resize = false;
6830 quint32 newCapacity = 0;
6831 if (needed > area.capacity) {
6832 // Fell back to one-shot buffers last time. Only grow once the demand
6833 // has proven to be recurring: a one-time burst, which is what loading a
6834 // scene looks like, would otherwise size the area permanently right at
6835 // the point where it is not needed any more.
6836 area.lowDemandFrames = 0;
6838 newCapacity = qMin(qNextPowerOfTwo(needed), STAGING_AREA_MAX);
6839 resize = true;
6840 }
6841 } else if (needed <= area.capacity / 4 && area.capacity > 0) {
6842 area.highDemandFrames = 0;
6844 area.lowDemandFrames = 0;
6845 // Nothing at all for a while, e.g. an app that only uploads during
6846 // startup: give the memory back entirely.
6847 newCapacity = needed ? qMax(area.capacity / 2, STAGING_AREA_MIN) : 0;
6848 resize = true;
6849 }
6850 } else {
6851 area.lowDemandFrames = 0;
6852 area.highDemandFrames = 0;
6853 }
6854
6855 if (resize && newCapacity != area.capacity) {
6856 if (area.buf) {
6859 e.lastActiveFrameSlot = frameSlot;
6860 e.stagingBuffer.buffer = area.buf;
6861 releaseQueue.append(e);
6862 area.buf = nil;
6863 }
6864 area.capacity = 0;
6865 if (newCapacity) {
6866 area.buf = [dev newBufferWithLength: newCapacity options: MTLResourceStorageModeShared];
6867 if (area.buf)
6868 area.capacity = newCapacity;
6869 }
6870 }
6871}
6872
6873id<MTLLibrary> QRhiMetalData::createMetalLib(const QShader &shader, QShader::Variant shaderVariant,
6874 bool preferArgumentBuffers,
6875 QString *error, QByteArray *entryPoint, QShaderKey *activeKey)
6876{
6877 QVarLengthArray<int, 8> versions;
6878 versions << 30 << 24 << 23 << 22 << 21 << 20 << 12;
6879
6880 // preferArgumentBuffers overrides whatever variant is set in the QShader.
6881 // This is by design, since we cannot expect the client to start specifying
6882 // the ArgumentBuffer variant that is only relevant for Metal. Also not
6883 // compatible with BatchableVertexShader and other variants since
6884 // ArgumentBufferShader is expected to be the argument-buffers version of
6885 // StandardShader, and it cannot be a combination of multiple variants. That
6886 // limitation should be fine for now.
6887
6888 QVarLengthArray<QShader::Variant, 2> variants;
6889 if (preferArgumentBuffers)
6890 variants << QShader::ArgumentBufferShader;
6891 variants << shaderVariant;
6892
6893 const QList<QShaderKey> shaders = shader.availableShaders();
6894
6895 auto findKey = [&shaders, &versions, &variants](QShader::Source source, QShaderKey *result) {
6896 for (const QShader::Variant &variant : variants) {
6897 for (const int &version : versions) {
6898 const QShaderKey key = { source, version, variant };
6899 if (shaders.contains(key)) {
6900 *result = key;
6901 return true;
6902 }
6903 }
6904 }
6905 return false;
6906 };
6907
6908 QShaderKey key;
6909
6910 if (findKey(QShader::Source::MetalLibShader, &key)) {
6911 QShaderCode mtllib = shader.shader(key);
6912 dispatch_data_t data = dispatch_data_create(mtllib.shader().constData(),
6913 size_t(mtllib.shader().size()),
6914 dispatch_get_global_queue(0, 0),
6915 DISPATCH_DATA_DESTRUCTOR_DEFAULT);
6916 NSError *err = nil;
6917 id<MTLLibrary> lib = [dev newLibraryWithData: data error: &err];
6918 dispatch_release(data);
6919 if (!err) {
6920 *entryPoint = mtllib.entryPoint();
6921 *activeKey = key;
6922 return lib;
6923 } else {
6924 const QString msg = QString::fromNSString(err.localizedDescription);
6925 qWarning("Failed to load metallib from baked shader: %s", qPrintable(msg));
6926 }
6927 }
6928
6929 if (!findKey(QShader::Source::MslShader, &key)) {
6930 qWarning() << "No MSL code found in baked shader" << shader;
6931 return nil;
6932 }
6933
6934 QShaderCode mslSource = shader.shader(key);
6935
6936 NSString *src = [NSString stringWithUTF8String: mslSource.shader().constData()];
6937 MTLCompileOptions *opts = [[MTLCompileOptions alloc] init];
6938 opts.languageVersion = toMetalLanguageVersion(key.sourceVersion());
6939 NSError *err = nil;
6940 id<MTLLibrary> lib = [dev newLibraryWithSource: src options: opts error: &err];
6941 [opts release];
6942 // src is autoreleased
6943
6944 // if lib is null and err is non-null, we had errors (fail)
6945 // if lib is non-null and err is non-null, we had warnings (success)
6946 // if lib is non-null and err is null, there were no errors or warnings (success)
6947 if (!lib) {
6948 const QString msg = QString::fromNSString(err.localizedDescription);
6949 *error = msg;
6950 return nil;
6951 }
6952
6953 *entryPoint = mslSource.entryPoint();
6954 *activeKey = key;
6955 return lib;
6956}
6957
6958id<MTLFunction> QRhiMetalData::createMSLShaderFunction(id<MTLLibrary> lib, const QByteArray &entryPoint)
6959{
6960 return [lib newFunctionWithName:[NSString stringWithUTF8String:entryPoint.constData()]];
6961}
6962
6964{
6965 MTLRenderPipelineDescriptor *rpDesc = reinterpret_cast<MTLRenderPipelineDescriptor *>(metalRpDesc);
6966
6967 if (rpD->colorAttachmentCount) {
6968 // defaults when no targetBlends are provided
6969 rpDesc.colorAttachments[0].pixelFormat = MTLPixelFormat(rpD->colorFormat[0]);
6970 rpDesc.colorAttachments[0].writeMask = MTLColorWriteMaskAll;
6971 rpDesc.colorAttachments[0].blendingEnabled = false;
6972
6973 Q_ASSERT(m_targetBlends.count() == rpD->colorAttachmentCount
6974 || (m_targetBlends.isEmpty() && rpD->colorAttachmentCount == 1));
6975
6976 for (uint i = 0, ie = uint(m_targetBlends.count()); i != ie; ++i) {
6977 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[int(i)]);
6978 rpDesc.colorAttachments[i].pixelFormat = MTLPixelFormat(rpD->colorFormat[i]);
6979 rpDesc.colorAttachments[i].blendingEnabled = b.enable;
6980 rpDesc.colorAttachments[i].sourceRGBBlendFactor = toMetalBlendFactor(b.srcColor);
6981 rpDesc.colorAttachments[i].destinationRGBBlendFactor = toMetalBlendFactor(b.dstColor);
6982 rpDesc.colorAttachments[i].rgbBlendOperation = toMetalBlendOp(b.opColor);
6983 rpDesc.colorAttachments[i].sourceAlphaBlendFactor = toMetalBlendFactor(b.srcAlpha);
6984 rpDesc.colorAttachments[i].destinationAlphaBlendFactor = toMetalBlendFactor(b.dstAlpha);
6985 rpDesc.colorAttachments[i].alphaBlendOperation = toMetalBlendOp(b.opAlpha);
6986 rpDesc.colorAttachments[i].writeMask = toMetalColorWriteMask(b.colorWrite);
6987 }
6988 }
6989
6990 if (rpD->hasDepthStencil) {
6991 // Must only be set when a depth-stencil buffer will actually be bound,
6992 // validation blows up otherwise.
6993 MTLPixelFormat fmt = MTLPixelFormat(rpD->dsFormat);
6994 rpDesc.depthAttachmentPixelFormat = fmt;
6995#if defined(Q_OS_MACOS)
6996 if (fmt != MTLPixelFormatDepth16Unorm && fmt != MTLPixelFormatDepth32Float)
6997#else
6998 if (fmt != MTLPixelFormatDepth32Float)
6999#endif
7000 rpDesc.stencilAttachmentPixelFormat = fmt;
7001 }
7002
7003 QRHI_RES_RHI(QRhiMetal);
7004 rpDesc.rasterSampleCount = NSUInteger(rhiD->effectiveSampleCount(m_sampleCount));
7005}
7006
7008{
7009 MTLDepthStencilDescriptor *dsDesc = reinterpret_cast<MTLDepthStencilDescriptor *>(metalDsDesc);
7010
7011 dsDesc.depthCompareFunction = m_depthTest ? toMetalCompareOp(m_depthOp) : MTLCompareFunctionAlways;
7012 dsDesc.depthWriteEnabled = m_depthWrite;
7013 if (m_stencilTest) {
7014 dsDesc.frontFaceStencil = [[MTLStencilDescriptor alloc] init];
7015 dsDesc.frontFaceStencil.stencilFailureOperation = toMetalStencilOp(m_stencilFront.failOp);
7016 dsDesc.frontFaceStencil.depthFailureOperation = toMetalStencilOp(m_stencilFront.depthFailOp);
7017 dsDesc.frontFaceStencil.depthStencilPassOperation = toMetalStencilOp(m_stencilFront.passOp);
7018 dsDesc.frontFaceStencil.stencilCompareFunction = toMetalCompareOp(m_stencilFront.compareOp);
7019 dsDesc.frontFaceStencil.readMask = m_stencilReadMask;
7020 dsDesc.frontFaceStencil.writeMask = m_stencilWriteMask;
7021
7022 dsDesc.backFaceStencil = [[MTLStencilDescriptor alloc] init];
7023 dsDesc.backFaceStencil.stencilFailureOperation = toMetalStencilOp(m_stencilBack.failOp);
7024 dsDesc.backFaceStencil.depthFailureOperation = toMetalStencilOp(m_stencilBack.depthFailOp);
7025 dsDesc.backFaceStencil.depthStencilPassOperation = toMetalStencilOp(m_stencilBack.passOp);
7026 dsDesc.backFaceStencil.stencilCompareFunction = toMetalCompareOp(m_stencilBack.compareOp);
7027 dsDesc.backFaceStencil.readMask = m_stencilReadMask;
7028 dsDesc.backFaceStencil.writeMask = m_stencilWriteMask;
7029 }
7030}
7031
7033{
7034 d->winding = m_frontFace == CCW ? MTLWindingCounterClockwise : MTLWindingClockwise;
7035 d->cullMode = toMetalCullMode(m_cullMode);
7036 d->triangleFillMode = toMetalTriangleFillMode(m_polygonMode);
7037 d->depthClipMode = m_depthClamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
7038 d->depthBias = float(m_depthBias);
7039 d->slopeScaledDepthBias = m_slopeScaledDepthBias;
7040}
7041
7043{
7044 // same binding space for vertex and constant buffers - work it around
7045 // should be in native resource binding not SPIR-V, but this will work anyway
7046 const int firstVertexBinding = QRHI_RES(QMetalShaderResourceBindings, q->shaderResourceBindings())->maxBinding + 1;
7047
7048 QRhiVertexInputLayout vertexInputLayout = q->vertexInputLayout();
7049 for (auto it = vertexInputLayout.cbeginAttributes(), itEnd = vertexInputLayout.cendAttributes();
7050 it != itEnd; ++it)
7051 {
7052 const uint loc = uint(it->location());
7053 desc.attributes[loc].format = decltype(desc.attributes[loc].format)(toMetalAttributeFormat(it->format()));
7054 desc.attributes[loc].offset = NSUInteger(it->offset());
7055 desc.attributes[loc].bufferIndex = NSUInteger(firstVertexBinding + it->binding());
7056 }
7057 int bindingIndex = 0;
7058 const NSUInteger viewCount = qMax<NSUInteger>(1, q->multiViewCount());
7059 for (auto it = vertexInputLayout.cbeginBindings(), itEnd = vertexInputLayout.cendBindings();
7060 it != itEnd; ++it, ++bindingIndex)
7061 {
7062 const uint layoutIdx = uint(firstVertexBinding + bindingIndex);
7063 desc.layouts[layoutIdx].stepFunction =
7064 it->classification() == QRhiVertexInputBinding::PerInstance
7065 ? MTLVertexStepFunctionPerInstance : MTLVertexStepFunctionPerVertex;
7066 desc.layouts[layoutIdx].stepRate = NSUInteger(it->instanceStepRate());
7067 if (desc.layouts[layoutIdx].stepFunction == MTLVertexStepFunctionPerInstance)
7068 desc.layouts[layoutIdx].stepRate *= viewCount;
7069 desc.layouts[layoutIdx].stride = it->stride();
7070 }
7071}
7072
7073void QMetalGraphicsPipelineData::setupStageInputDescriptor(MTLStageInputOutputDescriptor *desc)
7074{
7075 // same binding space for vertex and constant buffers - work it around
7076 // should be in native resource binding not SPIR-V, but this will work anyway
7077 const int firstVertexBinding = QRHI_RES(QMetalShaderResourceBindings, q->shaderResourceBindings())->maxBinding + 1;
7078
7079 QRhiVertexInputLayout vertexInputLayout = q->vertexInputLayout();
7080 for (auto it = vertexInputLayout.cbeginAttributes(), itEnd = vertexInputLayout.cendAttributes();
7081 it != itEnd; ++it)
7082 {
7083 const uint loc = uint(it->location());
7084 desc.attributes[loc].format = decltype(desc.attributes[loc].format)(toMetalAttributeFormat(it->format()));
7085 desc.attributes[loc].offset = NSUInteger(it->offset());
7086 desc.attributes[loc].bufferIndex = NSUInteger(firstVertexBinding + it->binding());
7087 }
7088 int bindingIndex = 0;
7089 for (auto it = vertexInputLayout.cbeginBindings(), itEnd = vertexInputLayout.cendBindings();
7090 it != itEnd; ++it, ++bindingIndex)
7091 {
7092 const uint layoutIdx = uint(firstVertexBinding + bindingIndex);
7093 if (desc.indexBufferIndex) {
7094 desc.layouts[layoutIdx].stepFunction =
7095 it->classification() == QRhiVertexInputBinding::PerInstance
7096 ? MTLStepFunctionThreadPositionInGridY : MTLStepFunctionThreadPositionInGridXIndexed;
7097 } else {
7098 desc.layouts[layoutIdx].stepFunction =
7099 it->classification() == QRhiVertexInputBinding::PerInstance
7100 ? MTLStepFunctionThreadPositionInGridY : MTLStepFunctionThreadPositionInGridX;
7101 }
7102 desc.layouts[layoutIdx].stepRate = NSUInteger(it->instanceStepRate());
7103 desc.layouts[layoutIdx].stride = it->stride();
7104 }
7105}
7106
7107void QRhiMetalData::trySeedingRenderPipelineFromBinaryArchive(MTLRenderPipelineDescriptor *rpDesc)
7108{
7109 if (binArch) {
7110 NSArray *binArchArray = [NSArray arrayWithObjects: binArch, nil];
7111 rpDesc.binaryArchives = binArchArray;
7112 }
7113}
7114
7115void QRhiMetalData::addRenderPipelineToBinaryArchive(MTLRenderPipelineDescriptor *rpDesc)
7116{
7117 if (binArch) {
7118 NSError *err = nil;
7119 if (![binArch addRenderPipelineFunctionsWithDescriptor: rpDesc error: &err]) {
7120 const QString msg = QString::fromNSString(err.localizedDescription);
7121 qWarning("Failed to collect render pipeline functions to binary archive: %s", qPrintable(msg));
7122 }
7123 }
7124}
7125
7126static inline bool usesTextures(const QShaderDescription &desc)
7127{
7128 return !desc.combinedImageSamplers().isEmpty()
7129 || !desc.separateImages().isEmpty()
7130 || !desc.storageImages().isEmpty();
7131}
7132
7133static bool hasArgumentBufferVariant(const QShader &shader)
7134{
7135 for (const QShaderKey &k : shader.availableShaders()) {
7136 if (k.sourceVariant() == QShader::ArgumentBufferShader)
7137 return true;
7138 }
7139 return false;
7140}
7141
7143{
7144 const int index = shader->nativeShaderInfo.extraBufferBindings.value(QShaderPrivate::MslArgumentBufferBinding, -1);
7145 if (index >= 0) {
7146 shader->argumentBufferIndex = index;
7147 shader->argumentEncoder = [shader->func newArgumentEncoderWithBufferIndex: NSUInteger(index)];
7148 }
7149}
7150
7152{
7153 QRHI_RES_RHI(QRhiMetal);
7154
7155 // A pipeline that supports indirect command buffers cannot have textures
7156 // bound directly to its functions, so prefer the shader variant that
7157 // reaches them through an argument buffer.
7158 const bool wantArgumentBuffers = m_flags.testFlag(UsesIndirectDraws) && rhiD->caps.indirectCommandBuffers;
7159
7160 MTLVertexDescriptor *vertexDesc = [MTLVertexDescriptor vertexDescriptor];
7161 d->setupVertexInputDescriptor(vertexDesc);
7162
7163 MTLRenderPipelineDescriptor *rpDesc = [[MTLRenderPipelineDescriptor alloc] init];
7164 rpDesc.vertexDescriptor = vertexDesc;
7165
7166 // Mutability cannot be determined (slotted buffers could be set as
7167 // MTLMutabilityImmutable, but then we potentially need a different
7168 // descriptor for each buffer combination as this depends on the actual
7169 // buffers not just the resource binding layout), so leave
7170 // rpDesc.vertex/fragmentBuffers at the defaults.
7171
7172 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7173 const QShader shader = shaderStage.shader();
7174 const bool argumentBufferBuild = wantArgumentBuffers && hasArgumentBufferVariant(shader);
7175 auto cacheIt = rhiD->d->shaderCache.constFind({ shaderStage, argumentBufferBuild });
7176 if (cacheIt != rhiD->d->shaderCache.constEnd()) {
7177 switch (shaderStage.type()) {
7178 case QRhiShaderStage::Vertex:
7179 d->vs = *cacheIt;
7180 [d->vs.lib retain];
7181 [d->vs.func retain];
7182 [d->vs.argumentEncoder retain];
7183 rpDesc.vertexFunction = d->vs.func;
7184 break;
7185 case QRhiShaderStage::Fragment:
7186 d->fs = *cacheIt;
7187 [d->fs.lib retain];
7188 [d->fs.func retain];
7189 [d->fs.argumentEncoder retain];
7190 rpDesc.fragmentFunction = d->fs.func;
7191 break;
7192 default:
7193 break;
7194 }
7195 } else {
7196 QString error;
7197 QByteArray entryPoint;
7198 QShaderKey activeKey;
7199 id<MTLLibrary> lib = rhiD->d->createMetalLib(shader, shaderStage.shaderVariant(),
7200 argumentBufferBuild,
7201 &error, &entryPoint, &activeKey);
7202 if (!lib) {
7203 qWarning("MSL shader compilation failed: %s", qPrintable(error));
7204 return false;
7205 }
7206 id<MTLFunction> func = rhiD->d->createMSLShaderFunction(lib, entryPoint);
7207 if (!func) {
7208 qWarning("MSL function for entry point %s not found", entryPoint.constData());
7209 [lib release];
7210 return false;
7211 }
7212 if (rhiD->d->shaderCache.count() >= QRhiMetal::MAX_SHADER_CACHE_ENTRIES) {
7213 // Use the simplest strategy: too many cached shaders -> drop them all.
7214 for (QMetalShader &s : rhiD->d->shaderCache)
7215 s.destroy();
7216 rhiD->d->shaderCache.clear();
7217 }
7218 switch (shaderStage.type()) {
7219 case QRhiShaderStage::Vertex:
7220 d->vs.lib = lib;
7221 d->vs.func = func;
7222 d->vs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
7223 d->vs.desc = shader.description();
7224 d->vs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
7225 setupArgumentBufferEncoder(&d->vs);
7226 rhiD->d->shaderCache.insert({ shaderStage, argumentBufferBuild }, d->vs);
7227 [d->vs.lib retain];
7228 [d->vs.func retain];
7229 [d->vs.argumentEncoder retain];
7230 rpDesc.vertexFunction = func;
7231 break;
7232 case QRhiShaderStage::Fragment:
7233 d->fs.lib = lib;
7234 d->fs.func = func;
7235 d->fs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
7236 d->fs.desc = shader.description();
7237 d->fs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
7238 setupArgumentBufferEncoder(&d->fs);
7239 rhiD->d->shaderCache.insert({ shaderStage, argumentBufferBuild }, d->fs);
7240 [d->fs.lib retain];
7241 [d->fs.func retain];
7242 [d->fs.argumentEncoder retain];
7243 rpDesc.fragmentFunction = func;
7244 break;
7245 default:
7246 [func release];
7247 [lib release];
7248 break;
7249 }
7250 }
7251 }
7252
7253 QMetalRenderPassDescriptor *rpD = QRHI_RES(QMetalRenderPassDescriptor, m_renderPassDesc);
7255
7256 // Safe for an indirect command buffer if the stage has no textures at all,
7257 // or reaches them through an argument buffer.
7258 const auto icbSafe = [](const QMetalShader &s) {
7259 return !usesTextures(s.desc) || s.argumentBufferIndex >= 0;
7260 };
7261 d->icbCapable = wantArgumentBuffers && icbSafe(d->vs) && icbSafe(d->fs);
7262 if (d->icbCapable)
7263 rpDesc.supportIndirectCommandBuffers = YES;
7264
7265 if (m_multiViewCount >= 2)
7266 rpDesc.inputPrimitiveTopology = toMetalPrimitiveTopologyClass(m_topology);
7267
7268 rhiD->d->trySeedingRenderPipelineFromBinaryArchive(rpDesc);
7269
7270 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7271 rhiD->d->addRenderPipelineToBinaryArchive(rpDesc);
7272
7273 NSError *err = nil;
7274 d->ps = [rhiD->d->dev newRenderPipelineStateWithDescriptor: rpDesc error: &err];
7275 [rpDesc release];
7276 if (!d->ps) {
7277 const QString msg = QString::fromNSString(err.localizedDescription);
7278 qWarning("Failed to create render pipeline state: %s", qPrintable(msg));
7279 return false;
7280 }
7281
7282 MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init];
7284 d->ds = [rhiD->d->dev newDepthStencilStateWithDescriptor: dsDesc];
7285 [dsDesc release];
7286
7287 d->primitiveType = toMetalPrimitiveType(m_topology);
7289
7290 return true;
7291}
7292
7293int QMetalGraphicsPipelineData::Tessellation::vsCompVariantToIndex(QShader::Variant vertexCompVariant)
7294{
7295 switch (vertexCompVariant) {
7296 case QShader::NonIndexedVertexAsComputeShader:
7297 return 0;
7298 case QShader::UInt32IndexedVertexAsComputeShader:
7299 return 1;
7300 case QShader::UInt16IndexedVertexAsComputeShader:
7301 return 2;
7302 default:
7303 break;
7304 }
7305 return -1;
7306}
7307
7309{
7310 const int varIndex = vsCompVariantToIndex(vertexCompVariant);
7311 if (varIndex >= 0 && vertexComputeState[varIndex])
7312 return vertexComputeState[varIndex];
7313
7314 id<MTLFunction> func = nil;
7315 if (varIndex >= 0)
7316 func = compVs[varIndex].func;
7317
7318 if (!func) {
7319 qWarning("No compute function found for vertex shader translated for tessellation, this should not happen");
7320 return nil;
7321 }
7322
7323 const QMap<int, int> &ebb(compVs[varIndex].nativeShaderInfo.extraBufferBindings);
7324 const int indexBufferBinding = ebb.value(QShaderPrivate::MslTessVertIndicesBufferBinding, -1);
7325
7326 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor new];
7327 cpDesc.computeFunction = func;
7328 cpDesc.threadGroupSizeIsMultipleOfThreadExecutionWidth = YES;
7329 cpDesc.stageInputDescriptor = [MTLStageInputOutputDescriptor stageInputOutputDescriptor];
7330 if (indexBufferBinding >= 0) {
7331 if (vertexCompVariant == QShader::UInt32IndexedVertexAsComputeShader) {
7332 cpDesc.stageInputDescriptor.indexType = MTLIndexTypeUInt32;
7333 cpDesc.stageInputDescriptor.indexBufferIndex = indexBufferBinding;
7334 } else if (vertexCompVariant == QShader::UInt16IndexedVertexAsComputeShader) {
7335 cpDesc.stageInputDescriptor.indexType = MTLIndexTypeUInt16;
7336 cpDesc.stageInputDescriptor.indexBufferIndex = indexBufferBinding;
7337 }
7338 }
7339 q->setupStageInputDescriptor(cpDesc.stageInputDescriptor);
7340
7341 rhiD->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
7342
7343 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7344 rhiD->d->addComputePipelineToBinaryArchive(cpDesc);
7345
7346 NSError *err = nil;
7347 id<MTLComputePipelineState> ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
7348 options: MTLPipelineOptionNone
7349 reflection: nil
7350 error: &err];
7351 [cpDesc release];
7352 if (!ps) {
7353 const QString msg = QString::fromNSString(err.localizedDescription);
7354 qWarning("Failed to create compute pipeline state: %s", qPrintable(msg));
7355 } else {
7356 vertexComputeState[varIndex] = ps;
7357 }
7358 // not retained, the only owner is vertexComputeState and so the QRhiGraphicsPipeline
7359 return ps;
7360}
7361
7363{
7364 if (tessControlComputeState)
7365 return tessControlComputeState;
7366
7367 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor new];
7368 cpDesc.computeFunction = compTesc.func;
7369
7370 rhiD->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
7371
7372 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7373 rhiD->d->addComputePipelineToBinaryArchive(cpDesc);
7374
7375 NSError *err = nil;
7376 id<MTLComputePipelineState> ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
7377 options: MTLPipelineOptionNone
7378 reflection: nil
7379 error: &err];
7380 [cpDesc release];
7381 if (!ps) {
7382 const QString msg = QString::fromNSString(err.localizedDescription);
7383 qWarning("Failed to create compute pipeline state: %s", qPrintable(msg));
7384 } else {
7385 tessControlComputeState = ps;
7386 }
7387 // not retained, the only owner is tessControlComputeState and so the QRhiGraphicsPipeline
7388 return ps;
7389}
7390
7391static inline bool indexTaken(quint32 index, quint64 indices)
7392{
7393 return (indices >> index) & 0x1;
7394}
7395
7396static inline void takeIndex(quint32 index, quint64 &indices)
7397{
7398 indices |= 1 << index;
7399}
7400
7401static inline int nextAttributeIndex(quint64 indices)
7402{
7403 // Maximum number of vertex attributes per vertex descriptor. There does
7404 // not appear to be a way to query this from the implementation.
7405 // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf indicates
7406 // that all GPU families have a value of 31.
7407 static const int maxVertexAttributes = 31;
7408
7409 for (int index = 0; index < maxVertexAttributes; ++index) {
7410 if (!indexTaken(index, indices))
7411 return index;
7412 }
7413
7414 Q_UNREACHABLE_RETURN(-1);
7415}
7416
7417static inline int aligned(quint32 offset, quint32 alignment)
7418{
7419 return ((offset + alignment - 1) / alignment) * alignment;
7420}
7421
7422template<typename T>
7423static void addUnusedVertexAttribute(const T &variable, QRhiMetal *rhiD, quint32 &offset, quint32 &vertexAlignment)
7424{
7425
7426 int elements = 1;
7427 for (const int dim : variable.arrayDims)
7428 elements *= dim;
7429
7430 if (variable.type == QShaderDescription::VariableType::Struct) {
7431 for (int element = 0; element < elements; ++element) {
7432 for (const auto &member : variable.structMembers) {
7433 addUnusedVertexAttribute(member, rhiD, offset, vertexAlignment);
7434 }
7435 }
7436 } else {
7437 const QRhiVertexInputAttribute::Format format = rhiD->shaderDescVariableFormatToVertexInputFormat(variable.type);
7438 const quint32 size = rhiD->byteSizePerVertexForVertexInputFormat(format);
7439
7440 // MSL specification 3.0 says alignment = size for non packed scalars and vectors
7441 const quint32 alignment = size;
7442 vertexAlignment = std::max(vertexAlignment, alignment);
7443
7444 for (int element = 0; element < elements; ++element) {
7445 // adjust alignment
7446 offset = aligned(offset, alignment);
7447 offset += size;
7448 }
7449 }
7450}
7451
7452template<typename T>
7453static void addVertexAttribute(const T &variable, int binding, QRhiMetal *rhiD, int &index, quint32 &offset, MTLVertexAttributeDescriptorArray *attributes, quint64 &indices, quint32 &vertexAlignment)
7454{
7455
7456 int elements = 1;
7457 for (const int dim : variable.arrayDims)
7458 elements *= dim;
7459
7460 if (variable.type == QShaderDescription::VariableType::Struct) {
7461 for (int element = 0; element < elements; ++element) {
7462 for (const auto &member : variable.structMembers) {
7463 addVertexAttribute(member, binding, rhiD, index, offset, attributes, indices, vertexAlignment);
7464 }
7465 }
7466 } else {
7467 const QRhiVertexInputAttribute::Format format = rhiD->shaderDescVariableFormatToVertexInputFormat(variable.type);
7468 const quint32 size = rhiD->byteSizePerVertexForVertexInputFormat(format);
7469
7470 // MSL specification 3.0 says alignment = size for non packed scalars and vectors
7471 const quint32 alignment = size;
7472 vertexAlignment = std::max(vertexAlignment, alignment);
7473
7474 for (int element = 0; element < elements; ++element) {
7475 Q_ASSERT(!indexTaken(index, indices));
7476
7477 // adjust alignment
7478 offset = aligned(offset, alignment);
7479
7480 attributes[index].bufferIndex = binding;
7481 attributes[index].format = toMetalAttributeFormat(format);
7482 attributes[index].offset = offset;
7483
7484 takeIndex(index, indices);
7485 index++;
7486 if (indexTaken(index, indices))
7487 index = nextAttributeIndex(indices);
7488
7489 offset += size;
7490 }
7491 }
7492}
7493
7494static inline bool matches(const QList<QShaderDescription::BlockVariable> &a, const QList<QShaderDescription::BlockVariable> &b)
7495{
7496 if (a.size() == b.size()) {
7497 bool match = true;
7498 for (int i = 0; i < a.size() && match; ++i) {
7499 match &= a[i].type == b[i].type
7500 && a[i].arrayDims == b[i].arrayDims
7501 && matches(a[i].structMembers, b[i].structMembers);
7502 }
7503 return match;
7504 }
7505
7506 return false;
7507}
7508
7509static inline bool matches(const QShaderDescription::InOutVariable &a, const QShaderDescription::InOutVariable &b)
7510{
7511 return a.location == b.location
7512 && a.type == b.type
7513 && a.perPatch == b.perPatch
7514 && matches(a.structMembers, b.structMembers);
7515}
7516
7517//
7518// Create the tessellation evaluation render pipeline state
7519//
7520// The tesc runs as a compute shader in a compute pipeline and writes per patch and per patch
7521// control point data into separate storage buffers. The tese runs as a vertex shader in a render
7522// pipeline. Our task is to generate a render pipeline descriptor for the tese that pulls vertices
7523// from these buffers.
7524//
7525// As the buffers we are pulling vertices from are written by a compute pipeline, they follow the
7526// MSL alignment conventions which we must take into account when generating our
7527// MTLVertexDescriptor. We must include the user defined tese input attributes, and any builtins
7528// that were used.
7529//
7530// SPIRV-Cross generates the MSL tese shader code with input attribute indices that reflect the
7531// specified GLSL locations. Interface blocks are flattened with each member having an incremented
7532// attribute index. SPIRV-Cross reports an error on compilation if there are clashes in the index
7533// address space.
7534//
7535// After the user specified attributes are processed, SPIRV-Cross places the in-use builtins at the
7536// next available (lowest value) attribute index. Tese builtins are processed in the following
7537// order:
7538//
7539// in gl_PerVertex
7540// {
7541// vec4 gl_Position;
7542// float gl_PointSize;
7543// float gl_ClipDistance[];
7544// };
7545//
7546// patch in float gl_TessLevelOuter[4];
7547// patch in float gl_TessLevelInner[2];
7548//
7549// Enumerations in QShaderDescription::BuiltinType are defined in this order.
7550//
7551// For quads, SPIRV-Cross places MTLQuadTessellationFactorsHalf per patch in the tessellation
7552// factor buffer. For triangles it uses MTLTriangleTessellationFactorsHalf.
7553//
7554// It should be noted that SPIRV-Cross handles the following builtin inputs internally, with no
7555// host side support required.
7556//
7557// in vec3 gl_TessCoord;
7558// in int gl_PatchVerticesIn;
7559// in int gl_PrimitiveID;
7560//
7562{
7563 if (pipeline->d->ps)
7564 return pipeline->d->ps;
7565
7566 MTLRenderPipelineDescriptor *rpDesc = [[MTLRenderPipelineDescriptor alloc] init];
7567 MTLVertexDescriptor *vertexDesc = [MTLVertexDescriptor vertexDescriptor];
7568
7569 // tesc output buffers
7570 const QMap<int, int> &ebb(compTesc.nativeShaderInfo.extraBufferBindings);
7571 const int tescOutputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
7572 const int tescPatchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
7573 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
7574 quint32 offsetInTescOutput = 0;
7575 quint32 offsetInTescPatchOutput = 0;
7576 quint32 offsetInTessFactorBuffer = 0;
7577 quint32 tescOutputAlignment = 0;
7578 quint32 tescPatchOutputAlignment = 0;
7579 quint32 tessFactorAlignment = 0;
7580 QSet<int> usedBuffers;
7581
7582 // tesc output variables in ascending location order
7583 QMap<int, QShaderDescription::InOutVariable> tescOutVars;
7584 for (const auto &tescOutVar : compTesc.desc.outputVariables())
7585 tescOutVars[tescOutVar.location] = tescOutVar;
7586
7587 // tese input variables in ascending location order
7588 QMap<int, QShaderDescription::InOutVariable> teseInVars;
7589 for (const auto &teseInVar : vertTese.desc.inputVariables())
7590 teseInVars[teseInVar.location] = teseInVar;
7591
7592 // bit mask tracking usage of vertex attribute indices
7593 quint64 indices = 0;
7594
7595 for (QShaderDescription::InOutVariable &tescOutVar : tescOutVars) {
7596
7597 int index = tescOutVar.location;
7598 int binding = -1;
7599 quint32 *offset = nullptr;
7600 quint32 *alignment = nullptr;
7601
7602 if (tescOutVar.perPatch) {
7603 binding = tescPatchOutputBufferBinding;
7604 offset = &offsetInTescPatchOutput;
7605 alignment = &tescPatchOutputAlignment;
7606 } else {
7607 tescOutVar.arrayDims.removeLast();
7608 binding = tescOutputBufferBinding;
7609 offset = &offsetInTescOutput;
7610 alignment = &tescOutputAlignment;
7611 }
7612
7613 if (teseInVars.contains(index)) {
7614
7615 if (!matches(teseInVars[index], tescOutVar)) {
7616 qWarning() << "mismatched tessellation control output -> tesssellation evaluation input at location" << index;
7617 qWarning() << " tesc out:" << tescOutVar;
7618 qWarning() << " tese in:" << teseInVars[index];
7619 }
7620
7621 if (binding != -1) {
7622 addVertexAttribute(tescOutVar, binding, rhiD, index, *offset, vertexDesc.attributes, indices, *alignment);
7623 usedBuffers << binding;
7624 } else {
7625 qWarning() << "baked tessellation control shader missing output buffer binding information";
7626 addUnusedVertexAttribute(tescOutVar, rhiD, *offset, *alignment);
7627 }
7628
7629 } else {
7630 qWarning() << "missing tessellation evaluation input for tessellation control output:" << tescOutVar;
7631 addUnusedVertexAttribute(tescOutVar, rhiD, *offset, *alignment);
7632 }
7633
7634 teseInVars.remove(tescOutVar.location);
7635 }
7636
7637 for (const QShaderDescription::InOutVariable &teseInVar : teseInVars)
7638 qWarning() << "missing tessellation control output for tessellation evaluation input:" << teseInVar;
7639
7640 // tesc output builtins in ascending location order
7641 QMap<QShaderDescription::BuiltinType, QShaderDescription::BuiltinVariable> tescOutBuiltins;
7642 for (const auto &tescOutBuiltin : compTesc.desc.outputBuiltinVariables())
7643 tescOutBuiltins[tescOutBuiltin.type] = tescOutBuiltin;
7644
7645 // tese input builtins in ascending location order
7646 QMap<QShaderDescription::BuiltinType, QShaderDescription::BuiltinVariable> teseInBuiltins;
7647 for (const auto &teseInBuiltin : vertTese.desc.inputBuiltinVariables())
7648 teseInBuiltins[teseInBuiltin.type] = teseInBuiltin;
7649
7650 const bool trianglesMode = vertTese.desc.tessellationMode() == QShaderDescription::TrianglesTessellationMode;
7651 bool tessLevelAdded = false;
7652
7653 for (const QShaderDescription::BuiltinVariable &builtin : tescOutBuiltins) {
7654
7655 QShaderDescription::InOutVariable variable;
7656 int binding = -1;
7657 quint32 *offset = nullptr;
7658 quint32 *alignment = nullptr;
7659
7660 switch (builtin.type) {
7661 case QShaderDescription::BuiltinType::PositionBuiltin:
7662 variable.type = QShaderDescription::VariableType::Vec4;
7663 binding = tescOutputBufferBinding;
7664 offset = &offsetInTescOutput;
7665 alignment = &tescOutputAlignment;
7666 break;
7667 case QShaderDescription::BuiltinType::PointSizeBuiltin:
7668 variable.type = QShaderDescription::VariableType::Float;
7669 binding = tescOutputBufferBinding;
7670 offset = &offsetInTescOutput;
7671 alignment = &tescOutputAlignment;
7672 break;
7673 case QShaderDescription::BuiltinType::ClipDistanceBuiltin:
7674 variable.type = QShaderDescription::VariableType::Float;
7675 variable.arrayDims = builtin.arrayDims;
7676 binding = tescOutputBufferBinding;
7677 offset = &offsetInTescOutput;
7678 alignment = &tescOutputAlignment;
7679 break;
7680 case QShaderDescription::BuiltinType::TessLevelOuterBuiltin:
7681 variable.type = QShaderDescription::VariableType::Half4;
7682 binding = tessFactorBufferBinding;
7683 offset = &offsetInTessFactorBuffer;
7684 tessLevelAdded = trianglesMode;
7685 alignment = &tessFactorAlignment;
7686 break;
7687 case QShaderDescription::BuiltinType::TessLevelInnerBuiltin:
7688 if (trianglesMode) {
7689 if (!tessLevelAdded) {
7690 variable.type = QShaderDescription::VariableType::Half4;
7691 binding = tessFactorBufferBinding;
7692 offsetInTessFactorBuffer = 0;
7693 offset = &offsetInTessFactorBuffer;
7694 alignment = &tessFactorAlignment;
7695 tessLevelAdded = true;
7696 } else {
7697 teseInBuiltins.remove(builtin.type);
7698 continue;
7699 }
7700 } else {
7701 variable.type = QShaderDescription::VariableType::Half2;
7702 binding = tessFactorBufferBinding;
7703 offsetInTessFactorBuffer = 8;
7704 offset = &offsetInTessFactorBuffer;
7705 alignment = &tessFactorAlignment;
7706 }
7707 break;
7708 default:
7709 Q_UNREACHABLE();
7710 break;
7711 }
7712
7713 if (teseInBuiltins.contains(builtin.type)) {
7714 if (binding != -1) {
7715 int index = nextAttributeIndex(indices);
7716 addVertexAttribute(variable, binding, rhiD, index, *offset, vertexDesc.attributes, indices, *alignment);
7717 usedBuffers << binding;
7718 } else {
7719 qWarning() << "baked tessellation control shader missing output buffer binding information";
7720 addUnusedVertexAttribute(variable, rhiD, *offset, *alignment);
7721 }
7722 } else {
7723 addUnusedVertexAttribute(variable, rhiD, *offset, *alignment);
7724 }
7725
7726 teseInBuiltins.remove(builtin.type);
7727 }
7728
7729 for (const QShaderDescription::BuiltinVariable &builtin : teseInBuiltins) {
7730 switch (builtin.type) {
7731 case QShaderDescription::BuiltinType::PositionBuiltin:
7732 case QShaderDescription::BuiltinType::PointSizeBuiltin:
7733 case QShaderDescription::BuiltinType::ClipDistanceBuiltin:
7734 qWarning() << "missing tessellation control output for tessellation evaluation builtin input:" << builtin;
7735 break;
7736 default:
7737 break;
7738 }
7739 }
7740
7741 if (usedBuffers.contains(tescOutputBufferBinding)) {
7742 vertexDesc.layouts[tescOutputBufferBinding].stepFunction = MTLVertexStepFunctionPerPatchControlPoint;
7743 vertexDesc.layouts[tescOutputBufferBinding].stride = aligned(offsetInTescOutput, tescOutputAlignment);
7744 }
7745
7746 if (usedBuffers.contains(tescPatchOutputBufferBinding)) {
7747 vertexDesc.layouts[tescPatchOutputBufferBinding].stepFunction = MTLVertexStepFunctionPerPatch;
7748 vertexDesc.layouts[tescPatchOutputBufferBinding].stride = aligned(offsetInTescPatchOutput, tescPatchOutputAlignment);
7749 }
7750
7751 if (usedBuffers.contains(tessFactorBufferBinding)) {
7752 vertexDesc.layouts[tessFactorBufferBinding].stepFunction = MTLVertexStepFunctionPerPatch;
7753 vertexDesc.layouts[tessFactorBufferBinding].stride = trianglesMode ? sizeof(MTLTriangleTessellationFactorsHalf) : sizeof(MTLQuadTessellationFactorsHalf);
7754 }
7755
7756 rpDesc.vertexDescriptor = vertexDesc;
7757 rpDesc.vertexFunction = vertTese.func;
7758 rpDesc.fragmentFunction = pipeline->d->fs.func;
7759
7760 // The portable, cross-API approach is to use CCW, the results are then
7761 // identical (assuming the applied clipSpaceCorrMatrix) for all the 3D
7762 // APIs. The tess.eval. GLSL shader is thus expected to specify ccw. If it
7763 // doesn't, things may not work as expected.
7764 rpDesc.tessellationOutputWindingOrder = toMetalTessellationWindingOrder(vertTese.desc.tessellationWindingOrder());
7765
7766 rpDesc.tessellationPartitionMode = toMetalTessellationPartitionMode(vertTese.desc.tessellationPartitioning());
7767
7768 QMetalRenderPassDescriptor *rpD = QRHI_RES(QMetalRenderPassDescriptor, pipeline->renderPassDescriptor());
7770
7771 rhiD->d->trySeedingRenderPipelineFromBinaryArchive(rpDesc);
7772
7773 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7774 rhiD->d->addRenderPipelineToBinaryArchive(rpDesc);
7775
7776 NSError *err = nil;
7777 id<MTLRenderPipelineState> ps = [rhiD->d->dev newRenderPipelineStateWithDescriptor: rpDesc error: &err];
7778 [rpDesc release];
7779 if (!ps) {
7780 const QString msg = QString::fromNSString(err.localizedDescription);
7781 qWarning("Failed to create render pipeline state for tessellation: %s", qPrintable(msg));
7782 } else {
7783 // ps is stored in the QMetalGraphicsPipelineData so the end result in this
7784 // regard is no different from what createVertexFragmentPipeline does
7785 pipeline->d->ps = ps;
7786 }
7787 return ps;
7788}
7789
7791{
7792 QVector<QMetalBuffer *> *workBuffers = type == WorkBufType::DeviceLocal ? &deviceLocalWorkBuffers : &hostVisibleWorkBuffers;
7793
7794 // Check if something is reusable as-is.
7795 for (QMetalBuffer *workBuf : *workBuffers) {
7796 if (workBuf && workBuf->lastActiveFrameSlot == -1 && workBuf->size() >= size) {
7797 workBuf->lastActiveFrameSlot = rhiD->currentFrameSlot;
7798 return workBuf;
7799 }
7800 }
7801
7802 // Once the pool is above a certain threshold, see if there is something
7803 // unused (but too small) and recreate that our size.
7804 if (workBuffers->count() > QMTL_FRAMES_IN_FLIGHT * 8) {
7805 for (QMetalBuffer *workBuf : *workBuffers) {
7806 if (workBuf && workBuf->lastActiveFrameSlot == -1) {
7807 workBuf->setSize(size);
7808 if (workBuf->create()) {
7809 workBuf->lastActiveFrameSlot = rhiD->currentFrameSlot;
7810 return workBuf;
7811 }
7812 }
7813 }
7814 }
7815
7816 // Add a new buffer to the pool.
7817 QMetalBuffer *buf;
7818 if (type == WorkBufType::DeviceLocal) {
7819 // for GPU->GPU data (non-slotted, not necessarily host writable)
7820 buf = new QMetalBuffer(rhiD, QRhiBuffer::Static, QRhiBuffer::UsageFlags(QMetalBuffer::WorkBufPoolUsage), size);
7821 } else {
7822 // for CPU->GPU (non-slotted, host writable/coherent)
7823 buf = new QMetalBuffer(rhiD, QRhiBuffer::Dynamic, QRhiBuffer::UsageFlags(QMetalBuffer::WorkBufPoolUsage), size);
7824 }
7825 if (buf->create()) {
7826 buf->lastActiveFrameSlot = rhiD->currentFrameSlot;
7827 workBuffers->append(buf);
7828 return buf;
7829 }
7830
7831 qWarning("Failed to acquire work buffer of size %u", size);
7832 return nullptr;
7833}
7834
7835bool QMetalGraphicsPipeline::createTessellationPipelines(const QShader &tessVert, const QShader &tesc, const QShader &tese, const QShader &tessFrag)
7836{
7837 QRHI_RES_RHI(QRhiMetal);
7838 QString error;
7839 QByteArray entryPoint;
7840 QShaderKey activeKey;
7841
7842 const QShaderDescription tescDesc = tesc.description();
7843 const QShaderDescription teseDesc = tese.description();
7844 d->tess.inControlPointCount = uint(m_patchControlPointCount);
7845 d->tess.outControlPointCount = tescDesc.tessellationOutputVertexCount();
7846 if (!d->tess.outControlPointCount)
7847 d->tess.outControlPointCount = teseDesc.tessellationOutputVertexCount();
7848
7849 if (!d->tess.outControlPointCount) {
7850 qWarning("Failed to determine output vertex count from the tessellation control or evaluation shader, cannot tessellate");
7851 d->tess.enabled = false;
7852 d->tess.failed = true;
7853 return false;
7854 }
7855
7856 if (m_multiViewCount >= 2)
7857 qWarning("Multiview is not supported with tessellation");
7858
7859 // Now the vertex shader is a compute shader.
7860 // It should have three dedicated *VertexAsComputeShader variants.
7861 // What the requested variant was (Standard or Batchable) plays no role here.
7862 // (the Qt Quick scenegraph does not use tessellation with its materials)
7863 // Create all three versions.
7864
7865 bool variantsPresent[3] = {};
7866 const QVector<QShaderKey> tessVertKeys = tessVert.availableShaders();
7867 for (const QShaderKey &k : tessVertKeys) {
7868 switch (k.sourceVariant()) {
7869 case QShader::NonIndexedVertexAsComputeShader:
7870 variantsPresent[0] = true;
7871 break;
7872 case QShader::UInt32IndexedVertexAsComputeShader:
7873 variantsPresent[1] = true;
7874 break;
7875 case QShader::UInt16IndexedVertexAsComputeShader:
7876 variantsPresent[2] = true;
7877 break;
7878 default:
7879 break;
7880 }
7881 }
7882 if (!(variantsPresent[0] && variantsPresent[1] && variantsPresent[2])) {
7883 qWarning("Vertex shader is not prepared for Metal tessellation. Cannot tessellate. "
7884 "Perhaps the relevant variants (UInt32IndexedVertexAsComputeShader et al) were not generated? "
7885 "Try passing --msltess to qsb.");
7886 d->tess.enabled = false;
7887 d->tess.failed = true;
7888 return false;
7889 }
7890
7891 int varIndex = 0; // Will map NonIndexed as 0, UInt32 as 1, UInt16 as 2. Do not change this ordering.
7892 for (QShader::Variant variant : {
7893 QShader::NonIndexedVertexAsComputeShader,
7894 QShader::UInt32IndexedVertexAsComputeShader,
7895 QShader::UInt16IndexedVertexAsComputeShader })
7896 {
7897 id<MTLLibrary> lib = rhiD->d->createMetalLib(tessVert, variant, false, &error, &entryPoint, &activeKey);
7898 if (!lib) {
7899 qWarning("MSL shader compilation failed for vertex-as-compute shader %d: %s", int(variant), qPrintable(error));
7900 d->tess.enabled = false;
7901 d->tess.failed = true;
7902 return false;
7903 }
7904 id<MTLFunction> func = rhiD->d->createMSLShaderFunction(lib, entryPoint);
7905 if (!func) {
7906 qWarning("MSL function for entry point %s not found", entryPoint.constData());
7907 [lib release];
7908 d->tess.enabled = false;
7909 d->tess.failed = true;
7910 return false;
7911 }
7912 QMetalShader &compVs(d->tess.compVs[varIndex]);
7913 compVs.lib = lib;
7914 compVs.func = func;
7915 compVs.desc = tessVert.description();
7916 compVs.nativeResourceBindingMap = tessVert.nativeResourceBindingMap(activeKey);
7917 compVs.nativeShaderInfo = tessVert.nativeShaderInfo(activeKey);
7918
7919 // pre-create all three MTLComputePipelineStates
7920 if (!d->tess.vsCompPipeline(rhiD, variant)) {
7921 qWarning("Failed to pre-generate compute pipeline for vertex compute shader (tessellation variant %d)", int(variant));
7922 d->tess.enabled = false;
7923 d->tess.failed = true;
7924 return false;
7925 }
7926
7927 ++varIndex;
7928 }
7929
7930 // Pipeline #2 is a compute that runs the tessellation control (compute) shader
7931 id<MTLLibrary> tessControlLib = rhiD->d->createMetalLib(tesc, QShader::StandardShader, false, &error, &entryPoint, &activeKey);
7932 if (!tessControlLib) {
7933 qWarning("MSL shader compilation failed for tessellation control compute shader: %s", qPrintable(error));
7934 d->tess.enabled = false;
7935 d->tess.failed = true;
7936 return false;
7937 }
7938 id<MTLFunction> tessControlFunc = rhiD->d->createMSLShaderFunction(tessControlLib, entryPoint);
7939 if (!tessControlFunc) {
7940 qWarning("MSL function for entry point %s not found", entryPoint.constData());
7941 [tessControlLib release];
7942 d->tess.enabled = false;
7943 d->tess.failed = true;
7944 return false;
7945 }
7946 d->tess.compTesc.lib = tessControlLib;
7947 d->tess.compTesc.func = tessControlFunc;
7948 d->tess.compTesc.desc = tesc.description();
7949 d->tess.compTesc.nativeResourceBindingMap = tesc.nativeResourceBindingMap(activeKey);
7950 d->tess.compTesc.nativeShaderInfo = tesc.nativeShaderInfo(activeKey);
7951 if (!d->tess.tescCompPipeline(rhiD)) {
7952 qWarning("Failed to pre-generate compute pipeline for tessellation control shader");
7953 d->tess.enabled = false;
7954 d->tess.failed = true;
7955 return false;
7956 }
7957
7958 // Pipeline #3 is a render pipeline with the tessellation evaluation (vertex) + the fragment shader
7959 id<MTLLibrary> tessEvalLib = rhiD->d->createMetalLib(tese, QShader::StandardShader, false, &error, &entryPoint, &activeKey);
7960 if (!tessEvalLib) {
7961 qWarning("MSL shader compilation failed for tessellation evaluation vertex shader: %s", qPrintable(error));
7962 d->tess.enabled = false;
7963 d->tess.failed = true;
7964 return false;
7965 }
7966 id<MTLFunction> tessEvalFunc = rhiD->d->createMSLShaderFunction(tessEvalLib, entryPoint);
7967 if (!tessEvalFunc) {
7968 qWarning("MSL function for entry point %s not found", entryPoint.constData());
7969 [tessEvalLib release];
7970 d->tess.enabled = false;
7971 d->tess.failed = true;
7972 return false;
7973 }
7974 d->tess.vertTese.lib = tessEvalLib;
7975 d->tess.vertTese.func = tessEvalFunc;
7976 d->tess.vertTese.desc = tese.description();
7977 d->tess.vertTese.nativeResourceBindingMap = tese.nativeResourceBindingMap(activeKey);
7978 d->tess.vertTese.nativeShaderInfo = tese.nativeShaderInfo(activeKey);
7979
7980 id<MTLLibrary> fragLib = rhiD->d->createMetalLib(tessFrag, QShader::StandardShader, false, &error, &entryPoint, &activeKey);
7981 if (!fragLib) {
7982 qWarning("MSL shader compilation failed for fragment shader: %s", qPrintable(error));
7983 d->tess.enabled = false;
7984 d->tess.failed = true;
7985 return false;
7986 }
7987 id<MTLFunction> fragFunc = rhiD->d->createMSLShaderFunction(fragLib, entryPoint);
7988 if (!fragFunc) {
7989 qWarning("MSL function for entry point %s not found", entryPoint.constData());
7990 [fragLib release];
7991 d->tess.enabled = false;
7992 d->tess.failed = true;
7993 return false;
7994 }
7995 d->fs.lib = fragLib;
7996 d->fs.func = fragFunc;
7997 d->fs.desc = tessFrag.description();
7998 d->fs.nativeShaderInfo = tessFrag.nativeShaderInfo(activeKey);
7999 d->fs.nativeResourceBindingMap = tessFrag.nativeResourceBindingMap(activeKey);
8000
8001 if (!d->tess.teseFragRenderPipeline(rhiD, this)) {
8002 qWarning("Failed to pre-generate render pipeline for tessellation evaluation + fragment shader");
8003 d->tess.enabled = false;
8004 d->tess.failed = true;
8005 return false;
8006 }
8007
8008 MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init];
8010 d->ds = [rhiD->d->dev newDepthStencilStateWithDescriptor: dsDesc];
8011 [dsDesc release];
8012
8013 // no primitiveType
8015
8016 return true;
8017}
8018
8020{
8021 destroy(); // no early test, always invoke and leave it to destroy to decide what to clean up
8022
8023 QRHI_RES_RHI(QRhiMetal);
8024 rhiD->pipelineCreationStart();
8025 if (!rhiD->sanityCheckGraphicsPipeline(this))
8026 return false;
8027
8028 // See if tessellation is involved. Things will be very different, if so.
8029 QShader tessVert;
8030 QShader tesc;
8031 QShader tese;
8032 QShader tessFrag;
8033 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
8034 switch (shaderStage.type()) {
8035 case QRhiShaderStage::Vertex:
8036 tessVert = shaderStage.shader();
8037 break;
8038 case QRhiShaderStage::TessellationControl:
8039 tesc = shaderStage.shader();
8040 break;
8041 case QRhiShaderStage::TessellationEvaluation:
8042 tese = shaderStage.shader();
8043 break;
8044 case QRhiShaderStage::Fragment:
8045 tessFrag = shaderStage.shader();
8046 break;
8047 default:
8048 break;
8049 }
8050 }
8051 d->tess.enabled = tesc.isValid() && tese.isValid() && m_topology == Patches && m_patchControlPointCount > 0;
8052 d->tess.failed = false;
8053
8054 bool ok = d->tess.enabled ? createTessellationPipelines(tessVert, tesc, tese, tessFrag) : createVertexFragmentPipeline();
8055 if (!ok)
8056 return false;
8057
8058 // SPIRV-Cross buffer size buffers
8059 int buffers = 0;
8060 QVarLengthArray<QMetalShader *, 6> shaders;
8061 if (d->tess.enabled) {
8062 shaders.append(&d->tess.compVs[0]);
8063 shaders.append(&d->tess.compVs[1]);
8064 shaders.append(&d->tess.compVs[2]);
8065 shaders.append(&d->tess.compTesc);
8066 shaders.append(&d->tess.vertTese);
8067 } else {
8068 shaders.append(&d->vs);
8069 }
8070 shaders.append(&d->fs);
8071
8072 for (QMetalShader *shader : shaders) {
8073 if (shader->nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8074 const int binding = shader->nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
8075 shader->nativeResourceBindingMap[binding] = {binding, -1};
8076 int maxNativeBinding = 0;
8077 for (const QShaderDescription::StorageBlock &block : shader->desc.storageBlocks())
8078 maxNativeBinding = qMax(maxNativeBinding, shader->nativeResourceBindingMap[block.binding].first);
8079
8080 // we use one buffer to hold data for all graphics shader stages, each with a different offset.
8081 // buffer offsets must be 32byte aligned - adjust buffer count accordingly
8082 buffers += ((maxNativeBinding + 1 + 7) / 8) * 8;
8083 }
8084 }
8085
8086 if (buffers) {
8088 d->bufferSizeBuffer = new QMetalBuffer(rhiD, QRhiBuffer::Static,
8089 QRhiBuffer::UsageFlags(int(QRhiBuffer::StorageBuffer)
8090 | QMetalBuffer::InternalHostWritable),
8091 buffers * sizeof(int));
8092
8093 d->bufferSizeBuffer->setSize(buffers * sizeof(int));
8095 }
8096
8097 rhiD->pipelineCreationEnd();
8099 generation += 1;
8100 rhiD->registerResource(this);
8101 return true;
8102}
8103
8109
8111{
8112 destroy();
8113 delete d;
8114}
8115
8117{
8118 d->cs.destroy();
8119
8120 if (!d->ps)
8121 return;
8122
8123 delete d->bufferSizeBuffer;
8124 d->bufferSizeBuffer = nullptr;
8125
8129 e.computePipeline.pipelineState = d->ps;
8130 d->ps = nil;
8131
8132 QRHI_RES_RHI(QRhiMetal);
8133 if (rhiD) {
8134 rhiD->d->releaseQueue.append(e);
8135 rhiD->unregisterResource(this);
8136 }
8137}
8138
8139void QRhiMetalData::trySeedingComputePipelineFromBinaryArchive(MTLComputePipelineDescriptor *cpDesc)
8140{
8141 if (binArch) {
8142 NSArray *binArchArray = [NSArray arrayWithObjects: binArch, nil];
8143 cpDesc.binaryArchives = binArchArray;
8144 }
8145}
8146
8147void QRhiMetalData::addComputePipelineToBinaryArchive(MTLComputePipelineDescriptor *cpDesc)
8148{
8149 if (binArch) {
8150 NSError *err = nil;
8151 if (![binArch addComputePipelineFunctionsWithDescriptor: cpDesc error: &err]) {
8152 const QString msg = QString::fromNSString(err.localizedDescription);
8153 qWarning("Failed to collect compute pipeline functions to binary archive: %s", qPrintable(msg));
8154 }
8155 }
8156}
8157
8159{
8160 if (d->ps)
8161 destroy();
8162
8163 QRHI_RES_RHI(QRhiMetal);
8164 rhiD->pipelineCreationStart();
8165
8166 auto cacheIt = rhiD->d->shaderCache.constFind({ m_shaderStage, false });
8167 if (cacheIt != rhiD->d->shaderCache.constEnd()) {
8168 d->cs = *cacheIt;
8169 } else {
8170 const QShader shader = m_shaderStage.shader();
8171 QString error;
8172 QByteArray entryPoint;
8173 QShaderKey activeKey;
8174 id<MTLLibrary> lib = rhiD->d->createMetalLib(shader, m_shaderStage.shaderVariant(), false,
8175 &error, &entryPoint, &activeKey);
8176 if (!lib) {
8177 qWarning("MSL shader compilation failed: %s", qPrintable(error));
8178 return false;
8179 }
8180 id<MTLFunction> func = rhiD->d->createMSLShaderFunction(lib, entryPoint);
8181 if (!func) {
8182 qWarning("MSL function for entry point %s not found", entryPoint.constData());
8183 [lib release];
8184 return false;
8185 }
8186 d->cs.lib = lib;
8187 d->cs.func = func;
8188 d->cs.localSize = shader.description().computeShaderLocalSize();
8189 d->cs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
8190 d->cs.desc = shader.description();
8191 d->cs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
8192
8193 // Compute never needs argument buffers on its own (they are there for
8194 // indirect command buffers, which are graphics-only), hence not asking
8195 // for that shader variant above. It can still be requested explicitly
8196 // via the QRhiShaderStage, in which case the textures and samplers have
8197 // to go through an argument buffer here as well.
8198 setupArgumentBufferEncoder(&d->cs);
8199
8200 // SPIRV-Cross buffer size buffers
8201 if (d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8202 const int binding = d->cs.nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
8203 d->cs.nativeResourceBindingMap[binding] = {binding, -1};
8204 }
8205
8206 if (rhiD->d->shaderCache.count() >= QRhiMetal::MAX_SHADER_CACHE_ENTRIES) {
8207 for (QMetalShader &s : rhiD->d->shaderCache)
8208 s.destroy();
8209 rhiD->d->shaderCache.clear();
8210 }
8211 rhiD->d->shaderCache.insert({ m_shaderStage, false }, d->cs);
8212 }
8213
8214 [d->cs.lib retain];
8215 [d->cs.func retain];
8216 [d->cs.argumentEncoder retain];
8217
8218 if (d->cs.argumentBufferIndex >= 0 && !rhiD->caps.indirectCommandBuffers) {
8219 // Sampler states are created with supportArgumentBuffers only when this
8220 // cap is present, and Metal faults the GPU without any warning when one
8221 // that lacks it is used with an argument buffer.
8222 qWarning("The ArgumentBufferShader variant of a compute shader cannot be used on this device");
8223 return false;
8224 }
8225
8226 d->localSize = MTLSizeMake(d->cs.localSize[0], d->cs.localSize[1], d->cs.localSize[2]);
8227
8228 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor new];
8229 cpDesc.computeFunction = d->cs.func;
8230
8231 rhiD->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
8232
8233 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
8234 rhiD->d->addComputePipelineToBinaryArchive(cpDesc);
8235
8236 NSError *err = nil;
8237 d->ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
8238 options: MTLPipelineOptionNone
8239 reflection: nil
8240 error: &err];
8241 [cpDesc release];
8242 if (!d->ps) {
8243 const QString msg = QString::fromNSString(err.localizedDescription);
8244 qWarning("Failed to create compute pipeline state: %s", qPrintable(msg));
8245 return false;
8246 }
8247
8248 // SPIRV-Cross buffer size buffers
8249 if (d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8250 int buffers = 0;
8251 for (const QShaderDescription::StorageBlock &block : d->cs.desc.storageBlocks())
8252 buffers = qMax(buffers, d->cs.nativeResourceBindingMap[block.binding].first);
8253
8254 buffers += 1;
8255
8256 if (!d->bufferSizeBuffer)
8257 d->bufferSizeBuffer = new QMetalBuffer(rhiD, QRhiBuffer::Static,
8258 QRhiBuffer::UsageFlags(int(QRhiBuffer::StorageBuffer)
8259 | QMetalBuffer::InternalHostWritable),
8260 buffers * sizeof(int));
8261
8262 d->bufferSizeBuffer->setSize(buffers * sizeof(int));
8264 }
8265
8266 rhiD->pipelineCreationEnd();
8268 generation += 1;
8269 rhiD->registerResource(this);
8270 return true;
8271}
8272
8276{
8278}
8279
8281{
8282 destroy();
8283 delete d;
8284}
8285
8287{
8288 // nothing to do here, we do not own the MTL cb object
8289}
8290
8292{
8293 nativeHandlesStruct.commandBuffer = (MTLCommandBuffer *) d->cb;
8294 nativeHandlesStruct.encoder = (MTLRenderCommandEncoder *) d->currentRenderPassEncoder;
8295 return &nativeHandlesStruct;
8296}
8297
8298void QMetalCommandBuffer::resetState(double lastGpuTime)
8299{
8300 d->lastGpuTime = lastGpuTime;
8301 d->currentRenderPassEncoder = nil;
8302 d->currentComputePassEncoder = nil;
8303 d->tessellationComputeEncoder = nil;
8304 d->currentPassRpDesc = nil;
8306}
8307
8309{
8311 currentTarget = nullptr;
8312 d->openDebugGroups.clear();
8314}
8315
8317{
8318 currentGraphicsPipeline = nullptr;
8319 currentComputePipeline = nullptr;
8321 pushConstantData.clear();
8323 currentGraphicsSrb = nullptr;
8324 currentComputeSrb = nullptr;
8326 currentResSlot = -1;
8327 currentIndexBuffer = nullptr;
8328 currentIndexOffset = 0;
8329 currentIndexFormat = QRhiCommandBuffer::IndexUInt16;
8330 currentCullMode = -1;
8334 currentDepthBiasValues = { 0.0f, 0.0f };
8335 hasCustomScissorSet = false;
8336 currentScissor = {};
8337 currentViewport = {};
8338 hasBlendConstantsSet = false;
8339 currentBlendConstants = {};
8340 currentStencilRef = 0;
8341 appliedStencilRef.reset();
8342
8343 d->currentShaderResourceBindingState = {};
8344 d->currentDepthStencilState = nil;
8346 d->currentVertexInputsBuffers.clear();
8347 d->currentVertexInputOffsets.clear();
8348}
8349
8350QMetalSwapChain::QMetalSwapChain(QRhiImplementation *rhi)
8351 : QRhiSwapChain(rhi),
8352 rtWrapper(rhi, this),
8353 cbWrapper(rhi),
8355{
8356 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
8357 d->sem[i] = nullptr;
8358 d->msaaTex[i] = nil;
8359 }
8360}
8361
8363{
8364 destroy();
8365 delete d;
8366}
8367
8369{
8370 if (!d->layer)
8371 return;
8372
8373 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
8374 if (d->sem[i]) {
8375 // the semaphores cannot be released if they do not have the initial value
8377
8378 dispatch_release(d->sem[i]);
8379 d->sem[i] = nullptr;
8380 }
8381 }
8382
8383 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
8384 [d->msaaTex[i] release];
8385 d->msaaTex[i] = nil;
8386 }
8387
8388 d->layer = nullptr;
8389 m_proxyData = {};
8390
8391 [d->curDrawable release];
8392 d->curDrawable = nil;
8393
8394 QRHI_RES_RHI(QRhiMetal);
8395 if (rhiD) {
8396 rhiD->swapchains.remove(this);
8397 rhiD->unregisterResource(this);
8398 }
8399}
8400
8402{
8403 return &cbWrapper;
8404}
8405
8410
8411// view.layer should ideally be called on the main thread, otherwise the UI
8412// Thread Checker in Xcode drops a warning. Hence trying to proxy it through
8413// QRhiSwapChainProxyData instead of just calling this function directly.
8414static inline CAMetalLayer *layerForWindow(QWindow *window)
8415{
8416 Q_ASSERT(window);
8417 CALayer *layer = nullptr;
8418#ifdef Q_OS_MACOS
8419 if (auto *cocoaWindow = window->nativeInterface<QNativeInterface::Private::QCocoaWindow>())
8420 layer = cocoaWindow->contentLayer();
8421#else
8422 layer = reinterpret_cast<UIView *>(window->winId()).layer;
8423#endif
8424 Q_ASSERT(layer);
8425 return static_cast<CAMetalLayer *>(layer);
8426}
8427
8428// If someone calls this, it is hopefully from the main thread, and they will
8429// then set the returned data on the QRhiSwapChain, so it won't need to query
8430// the layer on its own later on.
8432{
8434 d.reserved[0] = layerForWindow(window);
8435 return d;
8436}
8437
8439{
8440 Q_ASSERT(m_window);
8441 CAMetalLayer *layer = d->layer;
8442 if (!layer)
8443 layer = qrhi_objectFromProxyData<CAMetalLayer>(&m_proxyData, m_window, QRhi::Metal, 0);
8444
8445 Q_ASSERT(layer);
8446 int height = (int)layer.bounds.size.height;
8447 int width = (int)layer.bounds.size.width;
8448 width *= layer.contentsScale;
8449 height *= layer.contentsScale;
8450 return QSize(width, height);
8451}
8452
8454{
8455 if (f == HDRExtendedSrgbLinear) {
8456 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8457 } else if (f == HDR10) {
8458 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8459 } else if (f == HDRExtendedDisplayP3Linear) {
8460 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8461 }
8462 return f == SDR;
8463}
8464
8466{
8467 QRHI_RES_RHI(QRhiMetal);
8468
8469 chooseFormats(); // ensure colorFormat and similar are filled out
8470
8471 QMetalRenderPassDescriptor *rpD = new QMetalRenderPassDescriptor(m_rhi);
8473 rpD->hasDepthStencil = m_depthStencil != nullptr;
8474
8475 rpD->colorFormat[0] = int(d->colorFormat);
8476
8477#ifdef Q_OS_MACOS
8478 // m_depthStencil may not be built yet so cannot rely on computed fields in it
8479 rpD->dsFormat = rhiD->d->dev.depth24Stencil8PixelFormatSupported
8480 ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
8481#else
8482 rpD->dsFormat = MTLPixelFormatDepth32Float_Stencil8;
8483#endif
8484
8485 rpD->hasShadingRateMap = m_shadingRateMap != nullptr;
8486
8488
8489 rhiD->registerResource(rpD, false);
8490 return rpD;
8491}
8492
8494{
8495 QRHI_RES_RHI(QRhiMetal);
8496 samples = rhiD->effectiveSampleCount(m_sampleCount);
8497 // pick a format that is allowed for CAMetalLayer.pixelFormat
8498 if (m_format == HDRExtendedSrgbLinear || m_format == HDRExtendedDisplayP3Linear) {
8499 d->colorFormat = MTLPixelFormatRGBA16Float;
8500 d->rhiColorFormat = QRhiTexture::RGBA16F;
8501 return;
8502 }
8503 if (m_format == HDR10) {
8504 d->colorFormat = MTLPixelFormatRGB10A2Unorm;
8505 d->rhiColorFormat = QRhiTexture::RGB10A2;
8506 return;
8507 }
8508 d->colorFormat = m_flags.testFlag(sRGB) ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
8509 d->rhiColorFormat = QRhiTexture::BGRA8;
8510}
8511
8513{
8514 // wait+signal is the general pattern to ensure the commands for a
8515 // given frame slot have completed (if sem is 1, we go 0 then 1; if
8516 // sem is 0 we go -1, block, completion increments to 0, then us to 1)
8517
8518 dispatch_semaphore_t sem = d->sem[slot];
8519 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
8520 dispatch_semaphore_signal(sem);
8521}
8522
8524{
8525 Q_ASSERT(m_window);
8526
8527 const bool needsRegistration = !window || window != m_window;
8528
8529 if (window && window != m_window)
8530 destroy();
8531 // else no destroy(), this is intentional
8532
8533 QRHI_RES_RHI(QRhiMetal);
8534 if (needsRegistration || !rhiD->swapchains.contains(this))
8535 rhiD->swapchains.insert(this);
8536
8537 window = m_window;
8538
8539 if (window->surfaceType() != QSurface::MetalSurface) {
8540 qWarning("QMetalSwapChain only supports MetalSurface windows");
8541 return false;
8542 }
8543
8544 d->layer = qrhi_objectFromProxyData<CAMetalLayer>(&m_proxyData, window, QRhi::Metal, 0);
8545 Q_ASSERT(d->layer);
8546
8548 if (d->colorFormat != d->layer.pixelFormat)
8549 d->layer.pixelFormat = d->colorFormat;
8550
8551 if (m_format == HDRExtendedSrgbLinear) {
8552 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);
8553 d->layer.wantsExtendedDynamicRangeContent = YES;
8554 } else if (m_format == HDR10) {
8555 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceITUR_2100_PQ);
8556 d->layer.wantsExtendedDynamicRangeContent = YES;
8557 } else if (m_format == HDRExtendedDisplayP3Linear) {
8558 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearDisplayP3);
8559 d->layer.wantsExtendedDynamicRangeContent = YES;
8560 }
8561
8562 if (m_flags.testFlag(UsedAsTransferSource))
8563 d->layer.framebufferOnly = NO;
8564
8565#ifdef Q_OS_MACOS
8566 if (m_flags.testFlag(NoVSync))
8567 d->layer.displaySyncEnabled = NO;
8568#endif
8569
8570 if (m_flags.testFlag(SurfaceHasPreMulAlpha)) {
8571 d->layer.opaque = NO;
8572 } else if (m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
8573 // The CoreAnimation compositor is said to expect premultiplied alpha,
8574 // so this is then wrong when it comes to the blending operations but
8575 // there's nothing we can do. Fortunately Qt Quick always outputs
8576 // premultiplied alpha so it is not a problem there.
8577 d->layer.opaque = NO;
8578 } else {
8579 d->layer.opaque = YES;
8580 }
8581
8582 // Now set the layer's drawableSize which will stay set to the same value
8583 // until the next createOrResize(), thus ensuring atomicity with regards to
8584 // the drawable size in frames.
8585 int width = (int)d->layer.bounds.size.width;
8586 int height = (int)d->layer.bounds.size.height;
8587 CGSize layerSize = CGSizeMake(width, height);
8588 const float scaleFactor = d->layer.contentsScale;
8589 layerSize.width *= scaleFactor;
8590 layerSize.height *= scaleFactor;
8591 d->layer.drawableSize = layerSize;
8592
8593 m_currentPixelSize = QSizeF::fromCGSize(layerSize).toSize();
8594 pixelSize = m_currentPixelSize;
8595
8596 [d->layer setDevice: rhiD->d->dev];
8597
8598 [d->curDrawable release];
8599 d->curDrawable = nil;
8600
8601 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
8602 d->lastGpuTime[i] = 0;
8603 if (!d->sem[i])
8604 d->sem[i] = dispatch_semaphore_create(QMTL_FRAMES_IN_FLIGHT - 1);
8605 }
8606
8607 currentFrameSlot = 0;
8608 frameCount = 0;
8609
8610 ds = m_depthStencil ? QRHI_RES(QMetalRenderBuffer, m_depthStencil) : nullptr;
8611 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
8612 qWarning("Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
8613 m_depthStencil->sampleCount(), m_sampleCount);
8614 }
8615 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
8616 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
8617 m_depthStencil->setPixelSize(pixelSize);
8618 if (!m_depthStencil->create())
8619 qWarning("Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
8620 pixelSize.width(), pixelSize.height());
8621 } else {
8622 qWarning("Depth-stencil buffer's size (%dx%d) does not match the layer size (%dx%d). Expect problems.",
8623 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
8624 pixelSize.width(), pixelSize.height());
8625 }
8626 }
8627
8628 rtWrapper.setRenderPassDescriptor(m_renderPassDesc); // for the public getter in QRhiRenderTarget
8629 rtWrapper.d->pixelSize = pixelSize;
8630 rtWrapper.d->dpr = scaleFactor;
8633 rtWrapper.d->dsAttCount = ds ? 1 : 0;
8634
8635 qCDebug(QRHI_LOG_INFO, "got CAMetalLayer, pixel size %dx%d (scale %.2f)",
8636 pixelSize.width(), pixelSize.height(), scaleFactor);
8637
8638 if (samples > 1) {
8639 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
8640 desc.textureType = MTLTextureType2DMultisample;
8641 desc.pixelFormat = d->colorFormat;
8642 desc.width = NSUInteger(pixelSize.width());
8643 desc.height = NSUInteger(pixelSize.height());
8644 desc.sampleCount = NSUInteger(samples);
8645 desc.resourceOptions = MTLResourceStorageModePrivate;
8646 desc.storageMode = MTLStorageModePrivate;
8647 desc.usage = MTLTextureUsageRenderTarget;
8648 for (int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
8649 if (d->msaaTex[i]) {
8652 e.lastActiveFrameSlot = 1; // because currentFrameSlot is reset to 0
8653 e.renderbuffer.texture = d->msaaTex[i];
8654 rhiD->d->releaseQueue.append(e);
8655 }
8656 d->msaaTex[i] = [rhiD->d->dev newTextureWithDescriptor: desc];
8657 }
8658 [desc release];
8659 }
8660
8661 rhiD->registerResource(this);
8662
8663 return true;
8664}
8665
8667{
8670 info.limits.colorComponentValue.maxColorComponentValue = 1;
8671 info.limits.colorComponentValue.maxPotentialColorComponentValue = 1;
8673 info.sdrWhiteLevel = 200; // typical value, but dummy (don't know the real one); won't matter due to being display-referred
8674
8675 if (m_window) {
8676 // Must use m_window, not window, given this may be called before createOrResize().
8677#if defined(Q_OS_MACOS)
8678 NSView *view = reinterpret_cast<NSView *>(m_window->winId());
8679 NSScreen *screen = view.window.screen;
8680 info.limits.colorComponentValue.maxColorComponentValue = screen.maximumExtendedDynamicRangeColorComponentValue;
8681 info.limits.colorComponentValue.maxPotentialColorComponentValue = screen.maximumPotentialExtendedDynamicRangeColorComponentValue;
8682#elif defined(Q_OS_IOS)
8683 UIView *view = reinterpret_cast<UIView *>(m_window->winId());
8684 UIScreen *screen = view.window.windowScene.screen;
8685 info.limits.colorComponentValue.maxColorComponentValue =
8686 view.window.windowScene.screen.currentEDRHeadroom;
8687 info.limits.colorComponentValue.maxPotentialColorComponentValue =
8688 screen.potentialEDRHeadroom;
8689#endif
8690 }
8691
8692 return info;
8693}
8694
8695QT_END_NAMESPACE
void buildIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb, const QRhiIndirectCommandBufferBuildInfo &info) override
void drawIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
static QRhiSwapChainProxyData updateSwapChainProxyData(QWindow *window)
QMetalSwapChain * currentSwapChain
bool isDeviceLost() const override
void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override
QRhiStats statistics() override
void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance) override
void executeBufferHostWritesForCurrentFrame(QMetalBuffer *bufD)
int ubufAlignment() const override
Definition qrhimetal.mm:868
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override
Definition qrhimetal.mm:899
void endExternal(QRhiCommandBuffer *cb) override
QRhiMetalData * d
void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
QRhiMetal(QRhiMetalInitParams *params, QRhiMetalNativeHandles *importDevice=nullptr)
Definition qrhimetal.mm:577
void beginPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
qsizetype subresUploadByteSize(const QRhiTextureSubresourceUploadDescription &subresDesc) const
void beginExternal(QRhiCommandBuffer *cb) override
void adjustForMultiViewDraw(quint32 *instanceCount, QRhiCommandBuffer *cb)
void setDefaultScissor(QMetalCommandBuffer *cbD)
void enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD, QMetalCommandBuffer *cbD, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets, bool offsetOnlyChange, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[SUPPORTED_STAGES], const QMetalShader *shaders[SUPPORTED_STAGES])
QRhiSwapChain * createSwapChain() override
Definition qrhimetal.mm:858
QRhiGraphicsPipeline * createGraphicsPipeline() override
const char * icbUnavailableReason(QMetalCommandBuffer *cbD) const
bool create(QRhi::Flags flags) override
Definition qrhimetal.mm:653
QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override
void dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset) override
void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override
void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QRhiSampler * createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w) override
void setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data) override
static const int SUPPORTED_STAGES
void setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps) override
bool isYUpInNDC() const override
Definition qrhimetal.mm:878
void commitIndirectCommandBuffer(QRhiResourceUpdateBatch *u, QRhiIndirectCommandBuffer *icb) override
int resourceLimit(QRhi::ResourceLimit limit) const override
QRhiShaderResourceBindings * createShaderResourceBindings() override
void executeBufferHostWritesForSlot(QMetalBuffer *bufD, int slot)
QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override
QMatrix4x4 clipSpaceCorrMatrix() const override
Definition qrhimetal.mm:888
void drawIndexedIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
const QRhiNativeHandles * nativeHandles() override
void interruptRenderPass(QMetalCommandBuffer *cbD)
void executeDeferredReleases(bool forced=false)
void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QRhiComputePipeline * createComputePipeline() override
void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
bool isClipDepthZeroToOne() const override
Definition qrhimetal.mm:883
QList< int > supportedSampleCounts() const override
Definition qrhimetal.mm:847
QRhiTextureRenderTarget * createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags) override
bool isYUpInFramebuffer() const override
Definition qrhimetal.mm:873
bool prepareIcbKernels()
QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override
const QRhiNativeHandles * nativeHandles(QRhiCommandBuffer *cb) override
void enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
void setPipelineCacheData(const QByteArray &data) override
void finalizeDeferredStoreActions(QMetalCommandBuffer *cbD, bool passIsEnding)
QByteArray pipelineCacheData() override
void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override
void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override
void setVertexInput(QRhiCommandBuffer *cb, int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings, QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat) override
void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override
bool importedDevice
void tessellatedDraw(const TessDrawArgs &args)
void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override
void debugMarkEnd(QRhiCommandBuffer *cb) override
QRhi::FrameOpResult finish() override
QRhiShadingRateMap * createShadingRateMap() override
bool importedCmdQueue
QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override
bool makeThreadLocalNativeContextCurrent() override
QRhiTexture * createTexture(QRhiTexture::Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, QRhiTexture::Flags flags) override
void setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override
void releaseCachedResources() override
bool icbDraw(QMetalCommandBuffer *cbD, bool indexed, QMetalBuffer *indirectBufD, quint32 indirectBufferOffset, QMetalBuffer *countBufD, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride)
void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override
void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override
void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QRhiDriverInfo driverInfo() const override
double lastCompletedGpuTime(QRhiCommandBuffer *cb) override
void draw(QRhiCommandBuffer *cb, quint32 vertexCount, quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override
void executeIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb, quint32 firstCommand, quint32 commandCount) override
bool prepareIcb(quint32 maxDrawCount)
void finishActiveReadbacks(bool forced=false)
void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override
bool isFeatureSupported(QRhi::Feature feature) const override
Definition qrhimetal.mm:932
void enqueueSubresUpload(QMetalTexture *texD, void *mp, void *blitEncPtr, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc, qsizetype *curOfs)
void destroy() override
Definition qrhimetal.mm:781
QList< QSize > supportedShadingRates(int sampleCount) const override
Definition qrhimetal.mm:852
void beginComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
Definition qrhi_p.h:756
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:326
\inmodule QtGui
Definition qshader.h:81
Combined button and popup list for selecting options.
#define __has_feature(x)
@ UnBounded
Definition qrhi_p.h:392
@ Bounded
Definition qrhi_p.h:393
#define QRHI_RES_RHI(t)
Definition qrhi_p.h:33
#define QRHI_RES(t, x)
Definition qrhi_p.h:32
Int aligned(Int v, Int byteAlign)
\variable QRhiVulkanQueueSubmitParams::waitSemaphoreCount
static int mtlPushConstantBufferIndex(const QMetalShader &s)
static bool usesTextures(const QShaderDescription &desc)
static MTLStencilOperation toMetalStencilOp(QRhiGraphicsPipeline::StencilOp op)
static void qrhimtl_releaseIcbSlots(QRhiMetal *rhiD, QMetalIndirectCommandBuffer *icbD)
static MTLLanguageVersion toMetalLanguageVersion(const QShaderVersion &version)
static MTLPrimitiveTopologyClass toMetalPrimitiveTopologyClass(QRhiGraphicsPipeline::Topology t)
static CAMetalLayer * layerForWindow(QWindow *window)
static void addVertexAttribute(const T &variable, int binding, QRhiMetal *rhiD, int &index, quint32 &offset, MTLVertexAttributeDescriptorArray *attributes, quint64 &indices, quint32 &vertexAlignment)
static void qrhimtl_releaseRenderBuffer(const QRhiMetalData::DeferredReleaseEntry &e)
static void qrhimtl_encodeIcbFromCpu(QMetalIndirectCommandBuffer *icbD, QMetalIndirectCommandBufferData::Slot &slot, MTLPrimitiveType primitiveType, id< MTLBuffer > indexBufMtl, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
static bool hasArgumentBufferVariant(const QShader &shader)
static bool matches(const QList< QShaderDescription::BlockVariable > &a, const QList< QShaderDescription::BlockVariable > &b)
Q_DECLARE_TYPEINFO(QRhiMetalData::TextureReadback, Q_RELOCATABLE_TYPE)
static MTLBlendOperation toMetalBlendOp(QRhiGraphicsPipeline::BlendOp op)
static QMetalRenderTargetData * currentRenderTargetData(QMetalCommandBuffer *cbD)
static MTLBlendFactor toMetalBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
static MTLWinding toMetalTessellationWindingOrder(QShaderDescription::TessellationWindingOrder w)
static MTLPrimitiveType toMetalPrimitiveType(QRhiGraphicsPipeline::Topology t)
static MTLCompareFunction toMetalCompareOp(QRhiGraphicsPipeline::CompareOp op)
static MTLVertexFormat toMetalAttributeFormat(QRhiVertexInputAttribute::Format format)
static constexpr quint32 ICB_DRAW_COUNT_THRESHOLD
BindingType
static MTLTriangleFillMode toMetalTriangleFillMode(QRhiGraphicsPipeline::PolygonMode mode)
static quint32 mtlPushConstantBlockSize(const QMetalShader &s)
static MTLSamplerMinMagFilter toMetalFilter(QRhiSampler::Filter f)
static MTLCullMode toMetalCullMode(QRhiGraphicsPipeline::CullMode c)
static void qrhimtl_releaseBuffer(const QRhiMetalData::DeferredReleaseEntry &e)
static void endTempComputeEncoding(QRhiMetal *rhiD, QMetalCommandBuffer *cbD, id< MTLComputeCommandEncoder > computeEncoder)
static void takeIndex(quint32 index, quint64 &indices)
static int mapBinding(int binding, int stageIndex, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[], BindingType type)
static id< MTLComputeCommandEncoder > tempComputeEncoder(QRhiMetal *rhiD, QMetalCommandBuffer *cbD, id< MTLComputeCommandEncoder > maybeComputeEncoder)
static void rebindShaderResources(QMetalCommandBuffer *cbD, int resourceStage, int encoderStage, const QMetalShaderResourceBindingsData *customBindingState=nullptr)
static void qrhimtl_releaseSampler(const QRhiMetalData::DeferredReleaseEntry &e)
static MTLPixelFormat toMetalTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags, const QRhiMetal *d)
static QRhiShaderResourceBinding::StageFlag toRhiSrbStage(int stage)
static void setupArgumentBufferEncoder(QMetalShader *shader)
static void addUnusedVertexAttribute(const T &variable, QRhiMetal *rhiD, quint32 &offset, quint32 &vertexAlignment)
static uint toMetalColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
static MTLStoreAction interruptionStoreAction(MTLStoreAction finalAction, bool passIsEnding)
#define QRHI_METAL_COMMAND_BUFFERS_WITH_UNRETAINED_REFERENCES
Definition qrhimetal.mm:62
static void qrhimtl_replayIcbOnCpu(QMetalCommandBuffer *cbD, QMetalIndirectCommandBuffer *icbD, quint32 firstCommand, quint32 count, int currentFrameSlot)
static bool qrhimtl_ensureIcbSlots(QRhiMetal *rhiD, QMetalIndirectCommandBuffer *icbD, QMetalIndirectCommandBufferData::Fill fill)
static MTLSamplerMipFilter toMetalMipmapMode(QRhiSampler::Filter f)
static MTLTessellationPartitionMode toMetalTessellationPartitionMode(QShaderDescription::TessellationPartitioning p)
static MTLCompareFunction toMetalTextureCompareFunction(QRhiSampler::CompareOp op)
static int aligned(quint32 offset, quint32 alignment)
static void declareStageArgumentBufferResources(QMetalCommandBuffer *cbD, int encoderStage, const QMetalShaderResourceBindingsData::Stage &res)
static bool canStoreAttachment(id< MTLTexture > tex)
Q_DECLARE_TYPEINFO(QRhiMetalData::DeferredReleaseEntry, Q_RELOCATABLE_TYPE)
static MTLResourceUsage storageImageUsage(QRhiShaderResourceBinding::Type type)
static bool qrhimtl_icbSlotMatches(const QMetalIndirectCommandBuffer *icbD, const QMetalIndirectCommandBufferData::Slot &slot, MTLPrimitiveType primitiveType, id< MTLBuffer > indexBufMtl, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
static MTLSamplerAddressMode toMetalAddressMode(QRhiSampler::AddressMode m)
static void bindStageBuffers(QMetalCommandBuffer *cbD, int stage, const QRhiBatchedBindings< id< MTLBuffer > >::Batch &bufferBatch, const QRhiBatchedBindings< NSUInteger >::Batch &offsetBatch)
static void qrhimtl_releaseTexture(const QRhiMetalData::DeferredReleaseEntry &e)
static void encodeIcbWithCompute(QRhiMetalData *d, id< MTLComputeCommandEncoder > computeEncoder, id< MTLIndirectCommandBuffer > targetIcb, id< MTLBuffer > targetArgBuffer, id< MTLBuffer > targetRangeBuffer, bool indexed, QRhiCommandBuffer::IndexFormat indexFormat, MTLPrimitiveType primitiveType, id< MTLBuffer > indirectBufMtl, quint32 indirectBufferOffset, id< MTLBuffer > indexBufMtl, quint32 indexBufferOffset, id< MTLBuffer > countBufMtl, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride)
static bool indexTaken(quint32 index, quint64 indices)
static void bindStageTextures(QMetalCommandBuffer *cbD, int stage, const QRhiBatchedBindings< id< MTLTexture > >::Batch &textureBatch)
#define QRHI_METAL_DISABLE_BINARY_ARCHIVE
Definition qrhimetal.mm:57
static void bindStageSamplers(QMetalCommandBuffer *cbD, int encoderStage, const QRhiBatchedBindings< id< MTLSamplerState > >::Batch &samplerBatch)
static int nextAttributeIndex(quint64 indices)
static QT_BEGIN_NAMESPACE const int QMTL_FRAMES_IN_FLIGHT
Definition qrhimetal_p.h:26
void f(int c)
[26]
QVarLengthArray< BufferUpdate, 16 > pendingUpdates[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:365
id< MTLBuffer > buf[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:360
char * beginFullDynamicBufferUpdateForCurrentFrame() override
QMetalBufferData * d
Definition qrhimetal_p.h:41
QMetalBuffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
int lastActiveFrameSlot
Definition qrhimetal_p.h:43
QRhiBuffer::NativeBuffer nativeBuffer() override
void endFullDynamicBufferUpdateForCurrentFrame() override
To be called when the entire contents of the buffer data has been updated in the memory block returne...
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool create() override
Creates the corresponding native graphics resources.
MTLRenderPassDescriptor * currentPassRpDesc
Definition qrhimetal.mm:441
id< MTLDepthStencilState > currentDepthStencilState
Definition qrhimetal.mm:445
QMetalShaderResourceBindingsData currentShaderResourceBindingState
Definition qrhimetal.mm:446
MTLStoreAction deferredStencilStoreAction
Definition qrhimetal.mm:454
QVarLengthArray< std::pair< uint, MTLStoreAction >, 4 > deferredColorStoreActions
Definition qrhimetal.mm:452
MTLStoreAction deferredDepthStoreAction
Definition qrhimetal.mm:453
id< MTLComputeCommandEncoder > tessellationComputeEncoder
Definition qrhimetal.mm:440
QRhiBatchedBindings< id< MTLBuffer > > currentVertexInputsBuffers
Definition qrhimetal.mm:443
id< MTLRenderCommandEncoder > currentRenderPassEncoder
Definition qrhimetal.mm:438
id< MTLCommandBuffer > cb
Definition qrhimetal.mm:436
QRhiBatchedBindings< NSUInteger > currentVertexInputOffsets
Definition qrhimetal.mm:444
QVarLengthArray< QByteArray, 4 > openDebugGroups
Definition qrhimetal.mm:447
id< MTLComputeCommandEncoder > currentComputePassEncoder
Definition qrhimetal.mm:439
QMetalBuffer * currentIndexBuffer
const QRhiNativeHandles * nativeHandles()
QMetalShaderResourceBindings * currentComputeSrb
QMetalComputePipeline * currentComputePipeline
QMetalShaderResourceBindings * currentGraphicsSrb
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalCommandBuffer(QRhiImplementation *rhi)
void resetPerPassCachedState()
QMetalCommandBufferData * d
QMetalGraphicsPipeline * currentGraphicsPipeline
void resetState(double lastGpuTime=0)
id< MTLComputePipelineState > ps
Definition qrhimetal.mm:557
QMetalBuffer * bufferSizeBuffer
Definition qrhimetal.mm:562
QMetalComputePipeline(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalComputePipelineData * d
bool create() override
QVector< QMetalBuffer * > deviceLocalWorkBuffers
Definition qrhimetal.mm:511
QMetalBuffer * acquireWorkBuffer(QRhiMetal *rhiD, quint32 size, WorkBufType type=WorkBufType::DeviceLocal)
QVector< QMetalBuffer * > hostVisibleWorkBuffers
Definition qrhimetal.mm:512
quint32 tescCompOutputBufferSize(quint32 patchCount) const
Definition qrhimetal.mm:530
std::array< id< MTLComputePipelineState >, 3 > vertexComputeState
Definition qrhimetal.mm:521
quint32 tescCompPatchOutputBufferSize(quint32 patchCount) const
Definition qrhimetal.mm:534
static int vsCompVariantToIndex(QShader::Variant vertexCompVariant)
id< MTLComputePipelineState > tescCompPipeline(QRhiMetal *rhiD)
id< MTLRenderPipelineState > teseFragRenderPipeline(QRhiMetal *rhiD, QMetalGraphicsPipeline *pipeline)
QMetalGraphicsPipelineData * q
Definition qrhimetal.mm:515
id< MTLComputePipelineState > vsCompPipeline(QRhiMetal *rhiD, QShader::Variant vertexCompVariant)
quint32 patchCountForDrawCall(quint32 vertexOrIndexCount, quint32 instanceCount) const
Definition qrhimetal.mm:539
quint32 vsCompOutputBufferSize(quint32 vertexOrIndexCount, quint32 instanceCount) const
Definition qrhimetal.mm:525
id< MTLComputePipelineState > tessControlComputeState
Definition qrhimetal.mm:522
QMetalGraphicsPipeline * q
Definition qrhimetal.mm:492
MTLDepthClipMode depthClipMode
Definition qrhimetal.mm:500
MTLPrimitiveType primitiveType
Definition qrhimetal.mm:496
id< MTLRenderPipelineState > ps
Definition qrhimetal.mm:493
QMetalBuffer * bufferSizeBuffer
Definition qrhimetal.mm:552
void setupVertexInputDescriptor(MTLVertexDescriptor *desc)
void setupStageInputDescriptor(MTLStageInputOutputDescriptor *desc)
id< MTLDepthStencilState > ds
Definition qrhimetal.mm:494
MTLTriangleFillMode triangleFillMode
Definition qrhimetal.mm:499
QMetalGraphicsPipelineData * d
bool createVertexFragmentPipeline()
QMetalGraphicsPipeline(QRhiImplementation *rhi)
void setupAttachmentsInMetalRenderPassDescriptor(void *metalRpDesc, QMetalRenderPassDescriptor *rpD)
void makeActiveForCurrentRenderPassEncoder(QMetalCommandBuffer *cbD)
bool create() override
Creates the corresponding native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
void setupMetalDepthStencilDescriptor(void *metalDsDesc)
bool createTessellationPipelines(const QShader &tessVert, const QShader &tesc, const QShader &tese, const QShader &tessFrag)
QRhiCommandBuffer::IndexFormat indexFormat
id< MTLIndirectCommandBuffer > icb
QRhiIndirectCommandBufferBuildInfo buildInfo
Slot frameSlots[QMTL_FRAMES_IN_FLIGHT]
QMetalIndirectCommandBuffer(QRhiImplementation *rhi, Type type, quint32 maxCommandCount)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalIndirectCommandBufferData * d
const QRhiIndexedIndirectDrawCommand * indexedDrawCommands() const
bool create() override
Creates the corresponding native objects.
id< MTLTexture > tex
Definition qrhimetal.mm:371
MTLPixelFormat format
Definition qrhimetal.mm:370
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalRenderBufferData * d
Definition qrhimetal_p.h:69
QRhiTexture::Format backingFormat() const override
bool create() override
Creates the corresponding native graphics resources.
QMetalRenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags, QRhiTexture::Format backingFormatHint)
QMetalRenderPassDescriptor(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVector< quint32 > serializedFormat() const override
bool isCompatible(const QRhiRenderPassDescriptor *other) const override
int colorFormat[MAX_COLOR_ATTACHMENTS]
static const int MAX_COLOR_ATTACHMENTS
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() const override
QRhiRenderTargetAttachmentTracker::ResIdList currentResIdList
Definition qrhimetal.mm:487
id< MTLSamplerState > samplerState
Definition qrhimetal.mm:398
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalSampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode, AddressMode u, AddressMode v, AddressMode w)
QMetalSamplerData * d
int lastActiveFrameSlot
bool create() override
QVarLengthArray< Buffer, 8 > buffers
Definition qrhimetal.mm:422
QVarLengthArray< Sampler, 8 > samplers
Definition qrhimetal.mm:424
QRhiBatchedBindings< NSUInteger > bufferOffsetBatches
Definition qrhimetal.mm:426
QVarLengthArray< Texture, 8 > textures
Definition qrhimetal.mm:423
QRhiBatchedBindings< id< MTLSamplerState > > samplerBatches
Definition qrhimetal.mm:428
QRhiBatchedBindings< id< MTLTexture > > textureBatches
Definition qrhimetal.mm:427
QRhiBatchedBindings< id< MTLBuffer > > bufferBatches
Definition qrhimetal.mm:425
bool create() override
Creates the corresponding resource binding set.
QMetalComputePipeline * lastUsedComputePipeline
QMetalShaderResourceBindings(QRhiImplementation *rhi)
QMetalGraphicsPipeline * lastUsedGraphicsPipeline
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
void updateResources(UpdateFlags flags) override
\variable QRhiMetalCommandBufferNativeHandles::commandBuffer
Definition qrhimetal.mm:157
void destroy()
Definition qrhimetal.mm:168
id< MTLLibrary > lib
Definition qrhimetal.mm:158
uint outputVertexCount
Definition qrhimetal.mm:161
std::array< uint, 3 > localSize
Definition qrhimetal.mm:160
QShaderDescription desc
Definition qrhimetal.mm:162
id< MTLFunction > func
Definition qrhimetal.mm:159
int argumentBufferIndex
Definition qrhimetal.mm:166
id< MTLArgumentEncoder > argumentEncoder
Definition qrhimetal.mm:165
id< MTLRasterizationRateMap > rateMap
Definition qrhimetal.mm:403
QMetalShadingRateMapData * d
QMetalShadingRateMap(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QSize logicalSize() const override
bool createFrom(NativeShadingRateMap src) override
Sets up the shading rate map to use a native 3D API shading rate object src.
id< CAMetalDrawable > curDrawable
Definition qrhimetal.mm:568
dispatch_semaphore_t sem[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:569
MTLPixelFormat colorFormat
Definition qrhimetal.mm:574
MTLRenderPassDescriptor * rp
Definition qrhimetal.mm:571
CAMetalLayer * layer
Definition qrhimetal.mm:567
double lastGpuTime[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:570
id< MTLTexture > msaaTex[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:572
QRhiTexture::Format rhiColorFormat
Definition qrhimetal.mm:573
QMetalRenderTargetData * d
QMetalSwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
QSize pixelSize() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
float devicePixelRatio() const override
int sampleCount() const override
QWindow * window
void waitUntilCompleted(int slot)
bool createOrResize() override
Creates the swapchain if not already done and resizes the swapchain buffers to match the current size...
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiCommandBuffer * currentFrameCommandBuffer() override
QMetalSwapChain(QRhiImplementation *rhi)
virtual QRhiSwapChainHdrInfo hdrInfo() override
\variable QRhiSwapChainHdrInfo::limitsType
QMetalRenderBuffer * ds
QMetalSwapChainRenderTarget rtWrapper
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
QMetalSwapChainData * d
bool isFormatSupported(Format f) override
QSize surfacePixelSize() override
QRhiRenderTarget * currentFrameRenderTarget() override
MTLPixelFormat viewFormat
Definition qrhimetal.mm:380
id< MTLTexture > tex
Definition qrhimetal.mm:382
MTLPixelFormat viewFormatForSampling
Definition qrhimetal.mm:381
id< MTLTexture > viewForLevel(int level)
QMetalTexture * q
Definition qrhimetal.mm:378
id< MTLTexture > perLevelViews[QRhi::MAX_MIP_LEVELS]
Definition qrhimetal.mm:387
id< MTLBuffer > stagingBuf[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:385
id< MTLTexture > writeView
Definition qrhimetal.mm:384
QMetalTextureData(QMetalTexture *t)
Definition qrhimetal.mm:376
id< MTLTexture > samplingView
Definition qrhimetal.mm:383
id< MTLTexture > textureForWrite() const
Definition qrhimetal.mm:390
MTLPixelFormat format
Definition qrhimetal.mm:379
id< MTLTexture > textureForSampling() const
Definition qrhimetal.mm:389
float devicePixelRatio() const override
QMetalRenderTargetData * d
QMetalTextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
bool create() override
Creates the corresponding native graphics resources.
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
int sampleCount() const override
QSize pixelSize() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalTexture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, Flags flags)
bool prepareCreate(QSize *adjustedSize=nullptr)
NativeTexture nativeTexture() override
QMetalTextureData * d
Definition qrhimetal_p.h:90
bool create() override
Creates the corresponding native graphics resources.
int lastActiveFrameSlot
Definition qrhimetal_p.h:94
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
\variable QRhiIndirectDrawCommand::vertexCount
Definition qrhi.h:1768
QRhiReadbackResult * result
Definition qrhimetal.mm:290
QMetalCommandBuffer cbWrapper
Definition qrhimetal.mm:263
OffscreenFrame(QRhiImplementation *rhi)
Definition qrhimetal.mm:260
QRhiReadbackDescription desc
Definition qrhimetal.mm:268
QRhiReadbackResult * result
Definition qrhimetal.mm:269
QRhiTexture::Format format
Definition qrhimetal.mm:273
void trySeedingRenderPipelineFromBinaryArchive(MTLRenderPipelineDescriptor *rpDesc)
id< MTLComputePipelineState > icbEncodePipelineU32
Definition qrhimetal.mm:304
static constexpr quint32 STAGING_AREA_MIN
Definition qrhimetal.mm:342
QRhiMetalData(QRhiMetal *rhi)
Definition qrhimetal.mm:182
QVarLengthArray< BufferReadback, 2 > activeBufferReadbacks
Definition qrhimetal.mm:295
QHash< ShaderCacheKey, QMetalShader > shaderCache
Definition qrhimetal.mm:319
bool setupBinaryArchive(NSURL *sourceFileUrl=nil)
Definition qrhimetal.mm:633
bool icbSetupFailed
Definition qrhimetal.mm:314
id< MTLFunction > icbEncodeFunctionU16
Definition qrhimetal.mm:308
void addRenderPipelineToBinaryArchive(MTLRenderPipelineDescriptor *rpDesc)
id< MTLFunction > icbEncodeFunctionU32
Definition qrhimetal.mm:307
MTLCaptureManager * captureMgr
Definition qrhimetal.mm:297
id< MTLBuffer > icbArgumentBuffer
Definition qrhimetal.mm:309
static constexpr quint32 LARGE_STAGING_ALLOC
Definition qrhimetal.mm:341
NSUInteger icbCapacity
Definition qrhimetal.mm:302
void trySeedingComputePipelineFromBinaryArchive(MTLComputePipelineDescriptor *cpDesc)
id< MTLIndirectCommandBuffer > icb
Definition qrhimetal.mm:301
QVector< DeferredReleaseEntry > releaseQueue
Definition qrhimetal.mm:257
id< MTLBuffer > allocArgumentBuffer(quint32 size, quint32 alignment, int frameSlot, quint32 *offset)
static constexpr quint32 STAGING_AREA_MAX
Definition qrhimetal.mm:343
id< MTLLibrary > createMetalLib(const QShader &shader, QShader::Variant shaderVariant, bool preferArgumentBuffers, QString *error, QByteArray *entryPoint, QShaderKey *activeKey)
id< MTLFunction > createMSLShaderFunction(id< MTLLibrary > lib, const QByteArray &entryPoint)
id< MTLBuffer > allocBufferStaging(quint32 size, int frameSlot, quint32 *offset)
id< MTLCaptureScope > captureScope
Definition qrhimetal.mm:298
void resetAndResizeBufferStagingArea(int frameSlot)
MTLRenderPassDescriptor * createDefaultRenderPass(bool hasDepthStencil, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, int colorAttCount, QRhiShadingRateMap *shadingRateMap)
id< MTLBuffer > newOneShotStagingBuffer(quint32 size, int frameSlot)
QRhiMetal * q
Definition qrhimetal.mm:184
id< MTLComputePipelineState > icbEncodePipeline
Definition qrhimetal.mm:303
static constexpr int STAGING_AREA_HIGH_DEMAND_FRAMES
Definition qrhimetal.mm:345
id< MTLFunction > icbEncodeFunction
Definition qrhimetal.mm:306
id< MTLComputePipelineState > icbEncodePipelineU16
Definition qrhimetal.mm:305
static const int TEXBUF_ALIGN
Definition qrhimetal.mm:316
id< MTLBuffer > icbRangeBuffer
Definition qrhimetal.mm:311
id< MTLBuffer > allocFromStagingArea(StagingArea *area, quint32 size, quint32 alignment, int frameSlot, quint32 minBlockSize, quint32 *offset)
StagingArea bufStagingPool[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:330
id< MTLBinaryArchive > binArch
Definition qrhimetal.mm:187
id< MTLCommandBuffer > newCommandBuffer()
Definition qrhimetal.mm:621
QVarLengthArray< TextureReadback, 2 > activeTextureReadbacks
Definition qrhimetal.mm:285
StagingArea argBufPool[QMTL_FRAMES_IN_FLIGHT]
Definition qrhimetal.mm:329
id< MTLDevice > dev
Definition qrhimetal.mm:185
quint64 globalFrameId
Definition qrhimetal.mm:349
static constexpr int STAGING_AREA_LOW_DEMAND_FRAMES
Definition qrhimetal.mm:344
void addComputePipelineToBinaryArchive(MTLComputePipelineDescriptor *cpDesc)
id< MTLCommandQueue > cmdQueue
Definition qrhimetal.mm:186
id< MTLBuffer > icbNoCountBuffer
Definition qrhimetal.mm:313
QMetalCommandBuffer * cbD
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:2016
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1616
LimitsType limitsType
Definition qrhi.h:1627
LuminanceBehavior luminanceBehavior
Definition qrhi.h:1638
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1649
void * reserved[2]
Definition qrhi.h:1650