qrhimetal.mm 110 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt RHI module
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qrhimetal_p.h"
Laszlo Agocs's avatar
Laszlo Agocs committed
38
#include "qrhirsh_p.h"
39 40
#include <QGuiApplication>
#include <QWindow>
Laszlo Agocs's avatar
Laszlo Agocs committed
41
#include <qmath.h>
42 43 44 45 46 47 48 49
#include <QBakedShader>
#include <AppKit/AppKit.h>
#include <Metal/Metal.h>
#include <QuartzCore/CAMetalLayer.h>

QT_BEGIN_NAMESPACE

/*
Laszlo Agocs's avatar
Laszlo Agocs committed
50
    Metal backend. Double buffers and throttles to vsync. "Dynamic" buffers are
Laszlo Agocs's avatar
Laszlo Agocs committed
51 52 53
    Shared (host visible) and duplicated (due to 2 frames in flight), "static"
    are Managed on macOS and Shared on iOS/tvOS, and still duplicated.
    "Immutable" is like "static" but with only one native buffer underneath.
Laszlo Agocs's avatar
Laszlo Agocs committed
54
    Textures are Private (device local) and a host visible staging buffer is
Laszlo Agocs's avatar
Laszlo Agocs committed
55 56 57 58
    used to upload data to them. Does not rely on strong objects refs from
    command buffers (hence uses commandBufferWithUnretainedReferences), but
    does rely on automatic dependency tracking between encoders (hence no
    MTLResourceHazardTrackingModeUntracked atm).
59 60 61 62 63 64
*/

#if __has_feature(objc_arc)
#error ARC not supported
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
65 66 67
// Note: we expect everything here pass the Metal API validation when running
// in Debug mode in XCode. Some of the issues that break validation are not
// obvious and not visible when running outside XCode.
Laszlo Agocs's avatar
Laszlo Agocs committed
68 69 70
//
// An exception is the nextDrawable Called Early blah blah warning, which is
// plain and simply false.
Laszlo Agocs's avatar
Laszlo Agocs committed
71

Laszlo Agocs's avatar
Laszlo Agocs committed
72 73 74
/*!
    \class QRhiMetalInitParams
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    \brief Metal specific initialization parameters.

    A Metal-based QRhi needs no special parameters for initialization.

    \badcode
        QRhiMetalInitParams params;
        rhi = QRhi::create(QRhi::Metal, &params);
    \endcode

    \note Metal API validation cannot be enabled by the application. Instead,
    run the debug build of the application in XCode. Generating a
    \c{.xcodeproj} file via \c{qmake -spec macx-xcode} provides a convenient
    way to enable this.

    \note QRhiSwapChain can only target QWindow instances that have their
    surface type set to QSurface::MetalSurface.

    \section2 Working with existing Metal devices

    When interoperating with another graphics engine, it may be necessary to
    get a QRhi instance that uses the same Metal device. This can be achieved
96 97 98
    by passing a pointer to a QRhiMetalNativeHandles to QRhi::create(). The
    device must be set to a non-null value then. Optionally, a command queue
    object can be specified as well.
Laszlo Agocs's avatar
Laszlo Agocs committed
99 100

    The QRhi does not take ownership of any of the external objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
101 102 103 104 105
 */

/*!
    \class QRhiMetalNativeHandles
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
106
    \brief Holds the Metal device used by the QRhi.
107 108 109 110

    \note The class uses \c{void *} as the type since including the Objective C
    headers is not acceptable here. The actual types are \c{id<MTLDevice>} and
    \c{id<MTLCommandQueue>}.
Laszlo Agocs's avatar
Laszlo Agocs committed
111 112 113 114 115
 */

/*!
    \class QRhiMetalTextureNativeHandles
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
116
    \brief Holds the Metal texture object that is backing a QRhiTexture instance.
117 118 119

    \note The class uses \c{void *} as the type since including the Objective C
    headers is not acceptable here. The actual type is \c{id<MTLTexture>}.
Laszlo Agocs's avatar
Laszlo Agocs committed
120 121
 */

122 123
struct QRhiMetalData
{
124 125
    QRhiMetalData(QRhiImplementation *rhi) : ofr(rhi) { }

126 127
    id<MTLDevice> dev = nil;
    id<MTLCommandQueue> cmdQueue = nil;
128 129 130 131

    MTLRenderPassDescriptor *createDefaultRenderPass(bool hasDepthStencil,
                                                     const QRhiColorClearValue &colorClearValue,
                                                     const QRhiDepthStencilClearValue &depthStencilClearValue);
132 133
    id<MTLLibrary> createMetalLib(const QBakedShader &shader, QBakedShaderKey::ShaderVariant shaderVariant,
                                  QString *error, QByteArray *entryPoint);
134 135 136 137 138
    id<MTLFunction> createMSLShaderFunction(id<MTLLibrary> lib, const QByteArray &entryPoint);

    struct DeferredReleaseEntry {
        enum Type {
            Buffer,
Laszlo Agocs's avatar
Laszlo Agocs committed
139
            RenderBuffer,
Laszlo Agocs's avatar
Laszlo Agocs committed
140
            Texture,
141 142
            Sampler,
            StagingBuffer
143 144 145 146 147 148 149
        };
        Type type;
        int lastActiveFrameSlot; // -1 if not used otherwise 0..FRAMES_IN_FLIGHT-1
        union {
            struct {
                id<MTLBuffer> buffers[QMTL_FRAMES_IN_FLIGHT];
            } buffer;
Laszlo Agocs's avatar
Laszlo Agocs committed
150 151 152
            struct {
                id<MTLTexture> texture;
            } renderbuffer;
Laszlo Agocs's avatar
Laszlo Agocs committed
153 154
            struct {
                id<MTLTexture> texture;
155
                id<MTLBuffer> stagingBuffers[QMTL_FRAMES_IN_FLIGHT];
Laszlo Agocs's avatar
Laszlo Agocs committed
156
            } texture;
Laszlo Agocs's avatar
Laszlo Agocs committed
157 158 159
            struct {
                id<MTLSamplerState> samplerState;
            } sampler;
160 161 162
            struct {
                id<MTLBuffer> buffer;
            } stagingBuffer;
163 164 165
        };
    };
    QVector<DeferredReleaseEntry> releaseQueue;
166

167 168
    static void executeDeferredReleasesOnRshNow(QVector<DeferredReleaseEntry> *rshRelQueue);

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    struct OffscreenFrame {
        OffscreenFrame(QRhiImplementation *rhi) : cbWrapper(rhi) { }
        bool active = false;
        QMetalCommandBuffer cbWrapper;
    } ofr;

    struct ActiveReadback {
        int activeFrameSlot = -1;
        QRhiReadbackDescription desc;
        QRhiReadbackResult *result;
        id<MTLBuffer> buf;
        quint32 bufSize;
        QSize pixelSize;
        QRhiTexture::Format format;
    };
    QVector<ActiveReadback> activeReadbacks;
Laszlo Agocs's avatar
Laszlo Agocs committed
185 186 187

    API_AVAILABLE(macos(10.13), ios(11.0)) MTLCaptureManager *captureMgr;
    API_AVAILABLE(macos(10.13), ios(11.0)) id<MTLCaptureScope> captureScope = nil;
188 189
};

190 191 192
Q_DECLARE_TYPEINFO(QRhiMetalData::DeferredReleaseEntry, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiMetalData::ActiveReadback, Q_MOVABLE_TYPE);

193 194
struct QMetalBufferData
{
Laszlo Agocs's avatar
Laszlo Agocs committed
195
    bool managed;
196
    id<MTLBuffer> buf[QMTL_FRAMES_IN_FLIGHT];
Laszlo Agocs's avatar
Laszlo Agocs committed
197
    QVector<QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate> pendingUpdates[QMTL_FRAMES_IN_FLIGHT];
198 199
};

Laszlo Agocs's avatar
Laszlo Agocs committed
200 201
struct QMetalRenderBufferData
{
202
    MTLPixelFormat format;
Laszlo Agocs's avatar
Laszlo Agocs committed
203 204 205
    id<MTLTexture> tex = nil;
};

Laszlo Agocs's avatar
Laszlo Agocs committed
206 207
struct QMetalTextureData
{
208
    MTLPixelFormat format;
Laszlo Agocs's avatar
Laszlo Agocs committed
209
    id<MTLTexture> tex = nil;
210
    id<MTLBuffer> stagingBuf[QMTL_FRAMES_IN_FLIGHT];
211
    bool owns = true;
Laszlo Agocs's avatar
Laszlo Agocs committed
212 213
};

Laszlo Agocs's avatar
Laszlo Agocs committed
214 215 216 217 218
struct QMetalSamplerData
{
    id<MTLSamplerState> samplerState = nil;
};

219 220 221
struct QMetalCommandBufferData
{
    id<MTLCommandBuffer> cb;
222 223
    id<MTLRenderCommandEncoder> currentPassEncoder;
    MTLRenderPassDescriptor *currentPassRpDesc;
224 225 226
    int currentFirstVertexBinding;
    QRhiBatchedBindings<id<MTLBuffer> > currentVertexInputsBuffers;
    QRhiBatchedBindings<NSUInteger> currentVertexInputOffsets;
227 228 229 230 231
};

struct QMetalRenderTargetData
{
    QSize pixelSize;
Laszlo Agocs's avatar
Laszlo Agocs committed
232
    float dpr = 1;
233 234
    int colorAttCount = 0;
    int dsAttCount = 0;
235 236

    struct ColorAtt {
Laszlo Agocs's avatar
Laszlo Agocs committed
237
        bool needsDrawableForTex = false;
238 239 240
        id<MTLTexture> tex = nil;
        int layer = 0;
        int level = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
241
        bool needsDrawableForResolveTex = false;
242 243 244 245 246
        id<MTLTexture> resolveTex = nil;
        int resolveLayer = 0;
        int resolveLevel = 0;
    };

247
    struct {
248
        ColorAtt colorAtt[QMetalRenderPassDescriptor::MAX_COLOR_ATTACHMENTS];
249
        id<MTLTexture> dsTex = nil;
Laszlo Agocs's avatar
Laszlo Agocs committed
250
        bool hasStencil = false;
251
    } fb;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
};

struct QMetalGraphicsPipelineData
{
    id<MTLRenderPipelineState> ps = nil;
    id<MTLDepthStencilState> ds = nil;
    MTLPrimitiveType primitiveType;
    MTLWinding winding;
    MTLCullMode cullMode;
    id<MTLLibrary> vsLib = nil;
    id<MTLFunction> vsFunc = nil;
    id<MTLLibrary> fsLib = nil;
    id<MTLFunction> fsFunc = nil;
};

struct QMetalSwapChainData
{
    CAMetalLayer *layer = nullptr;
    id<CAMetalDrawable> curDrawable;
Laszlo Agocs's avatar
Laszlo Agocs committed
271
    dispatch_semaphore_t sem[QMTL_FRAMES_IN_FLIGHT];
272
    MTLRenderPassDescriptor *rp = nullptr;
273
    id<MTLTexture> msaaTex[QMTL_FRAMES_IN_FLIGHT];
274
    QRhiTexture::Format rhiColorFormat;
275
    MTLPixelFormat colorFormat;
276 277
};

278
QRhiMetal::QRhiMetal(QRhiMetalInitParams *params, QRhiMetalNativeHandles *importDevice)
279
{
280
    d = new QRhiMetalData(this);
281

Laszlo Agocs's avatar
Laszlo Agocs committed
282 283
    if (params->resourceSharingHost)
        rsh = QRhiResourceSharingHostPrivate::get(params->resourceSharingHost);
284 285

    importedDevice = importDevice != nullptr;
286
    if (importedDevice) {
287 288 289 290 291 292 293 294 295
        if (d->dev) {
            d->dev = (id<MTLDevice>) importDevice->dev;
            importedCmdQueue = importDevice->cmdQueue != nullptr;
            if (importedCmdQueue)
                d->cmdQueue = (id<MTLCommandQueue>) importDevice->cmdQueue;
        } else {
            qWarning("No MTLDevice given, cannot import");
            importedDevice = false;
        }
296 297 298 299 300 301 302 303 304 305 306 307 308
    }
}

QRhiMetal::~QRhiMetal()
{
    delete d;
}

static inline uint aligned(uint v, uint byteAlign)
{
    return (v + byteAlign - 1) & ~(byteAlign - 1);
}

309
bool QRhiMetal::create(QRhi::Flags flags)
310
{
311 312
    Q_UNUSED(flags);

Laszlo Agocs's avatar
Laszlo Agocs committed
313 314 315
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

    if (importedDevice) {
316
        [d->dev retain];
Laszlo Agocs's avatar
Laszlo Agocs committed
317 318 319 320 321 322 323 324 325 326 327 328
    } else {
        if (!rsh || !rsh->d_metal.dev) {
            d->dev = MTLCreateSystemDefaultDevice();
            if (rsh) {
                rsh->d_metal.dev = d->dev;
                [d->dev retain];
            }
        } else {
            d->dev = (id<MTLDevice>) rsh->d_metal.dev;
            [d->dev retain];
        }
    }
329 330 331

    qDebug("Metal device: %s", qPrintable(QString::fromNSString([d->dev name])));

Laszlo Agocs's avatar
Laszlo Agocs committed
332
    if (importedCmdQueue) {
333
        [d->cmdQueue retain];
Laszlo Agocs's avatar
Laszlo Agocs committed
334
    } else {
335 336 337 338 339
        // We could use the existing MTLCommandQueue when rsh is enabled. We
        // choose not to share the queue however, in order avoid performance
        // surprises with multiple windows and QRhis severly limiting each
        // other's rendering rate.
        d->cmdQueue = [d->dev newCommandQueue];
Laszlo Agocs's avatar
Laszlo Agocs committed
340
    }
341

Laszlo Agocs's avatar
Laszlo Agocs committed
342 343
    if (@available(macOS 10.13, iOS 11.0, *)) {
        d->captureMgr = [MTLCaptureManager sharedCaptureManager];
344 345 346
        // Have a custom capture scope as well which then shows up in XCode as
        // an option when capturing, and becomes especially useful when having
        // multiple windows with multiple QRhis.
Laszlo Agocs's avatar
Laszlo Agocs committed
347
        d->captureScope = [d->captureMgr newCaptureScopeWithCommandQueue: d->cmdQueue];
348 349
        const QString label = QString::asprintf("Qt capture scope for QRhi %p", this);
        d->captureScope.label = label.toNSString();
Laszlo Agocs's avatar
Laszlo Agocs committed
350 351
    }

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
#if defined(Q_OS_MACOS)
    caps.maxTextureSize = 16384;
#elif defined(Q_OS_TVOS)
    if ([d->dev supportsFeatureSet: MTLFeatureSet(30003)]) // MTLFeatureSet_tvOS_GPUFamily2_v1
        caps.maxTextureSize = 16384;
    else
        caps.maxTextureSize = 8192;
#elif defined(Q_OS_IOS)
    // welcome to feature set hell
    if ([d->dev supportsFeatureSet: MTLFeatureSet(16)] // MTLFeatureSet_iOS_GPUFamily5_v1
            || [d->dev supportsFeatureSet: MTLFeatureSet(11)] // MTLFeatureSet_iOS_GPUFamily4_v1
            || [d->dev supportsFeatureSet: MTLFeatureSet(4)]) // MTLFeatureSet_iOS_GPUFamily3_v1
    {
        caps.maxTextureSize = 16384;
    } else if ([d->dev supportsFeatureSet: MTLFeatureSet(3)] // MTLFeatureSet_iOS_GPUFamily2_v2
            || [d->dev supportsFeatureSet: MTLFeatureSet(2)]) // MTLFeatureSet_iOS_GPUFamily1_v2
    {
        caps.maxTextureSize = 8192;
    } else {
        caps.maxTextureSize = 4096;
    }
#endif

375 376 377
    nativeHandlesStruct.dev = d->dev;
    nativeHandlesStruct.cmdQueue = d->cmdQueue;

Laszlo Agocs's avatar
Laszlo Agocs committed
378 379 380 381 382 383
    if (rsh) {
        qDebug("Attached to QRhiResourceSharingHost %p, currently %d other QRhi instances on MTLDevice %p",
               rsh, rsh->rhiCount, (void *) d->dev);
        rsh->rhiCount += 1;
    }

384
    return true;
385 386 387 388 389
}

void QRhiMetal::destroy()
{
    executeDeferredReleases(true);
390
    finishActiveReadbacks(true);
391

Laszlo Agocs's avatar
Laszlo Agocs committed
392 393
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

Laszlo Agocs's avatar
Laszlo Agocs committed
394
    if (@available(macOS 10.13, iOS 11.0, *)) {
395 396
        [d->captureScope release];
        d->captureScope = nil;
Laszlo Agocs's avatar
Laszlo Agocs committed
397 398
    }

399 400
    [d->cmdQueue release];
    if (!importedCmdQueue)
401 402
        d->cmdQueue = nil;

403 404
    [d->dev release];
    if (!importedDevice)
405
        d->dev = nil;
Laszlo Agocs's avatar
Laszlo Agocs committed
406 407 408

    if (rsh) {
        if (--rsh->rhiCount == 0) {
409 410 411 412 413
            if (rsh->d_metal.releaseQueue) {
                auto rshRelQueue = static_cast<QVector<QRhiMetalData::DeferredReleaseEntry> *>(rsh->d_metal.releaseQueue);
                QRhiMetalData::executeDeferredReleasesOnRshNow(rshRelQueue);
                delete rshRelQueue;
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
414 415
            [(id<MTLDevice>) rsh->d_metal.dev release];
            rsh->d_metal.dev = nullptr;
416
            rsh->d_metal.releaseQueue = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
417 418
        }
    }
419 420 421 422
}

QVector<int> QRhiMetal::supportedSampleCounts() const
{
423 424 425 426 427 428 429 430 431 432 433 434
    return { 1, 2, 4, 8 };
}

int QRhiMetal::effectiveSampleCount(int sampleCount) const
{
    // Stay compatible with QSurfaceFormat and friends where samples == 0 means the same as 1.
    const int s = qBound(1, sampleCount, 64);
    if (!supportedSampleCounts().contains(s)) {
        qWarning("Attempted to set unsupported sample count %d", sampleCount);
        return 1;
    }
    return s;
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
}

QRhiSwapChain *QRhiMetal::createSwapChain()
{
    return new QMetalSwapChain(this);
}

QRhiBuffer *QRhiMetal::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, int size)
{
    return new QMetalBuffer(this, type, usage, size);
}

int QRhiMetal::ubufAlignment() const
{
    return 256;
}

bool QRhiMetal::isYUpInFramebuffer() const
{
    return false;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
457 458 459 460 461
bool QRhiMetal::isYUpInNDC() const
{
    return true;
}

462 463
QMatrix4x4 QRhiMetal::clipSpaceCorrMatrix() const
{
Laszlo Agocs's avatar
Laszlo Agocs committed
464 465 466 467 468 469 470 471 472 473
    // depth range 0..1
    static QMatrix4x4 m;
    if (m.isIdentity()) {
        // NB the ctor takes row-major
        m = QMatrix4x4(1.0f, 0.0f, 0.0f, 0.0f,
                       0.0f, 1.0f, 0.0f, 0.0f,
                       0.0f, 0.0f, 0.5f, 0.5f,
                       0.0f, 0.0f, 0.0f, 1.0f);
    }
    return m;
474 475
}

476
bool QRhiMetal::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
477
{
478 479
    Q_UNUSED(flags);

480 481 482 483 484
#ifdef Q_OS_MACOS
    if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
        return false;
    if (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12)
        return false;
Laszlo Agocs's avatar
Laszlo Agocs committed
485 486 487
#else
    if (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
        return false;
488
#endif
489 490 491 492

    return true;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
493 494 495 496
bool QRhiMetal::isFeatureSupported(QRhi::Feature feature) const
{
    switch (feature) {
    case QRhi::MultisampleTexture:
497
        return true;
Laszlo Agocs's avatar
Laszlo Agocs committed
498
    case QRhi::MultisampleRenderBuffer:
499
        return true;
500
    case QRhi::DebugMarkers:
Laszlo Agocs's avatar
Laszlo Agocs committed
501
        return true;
502 503
    case QRhi::Timestamps:
        return false;
504 505 506 507
    case QRhi::Instancing:
        return true;
    case QRhi::CustomInstanceStepRate:
        return true;
508 509
    case QRhi::PrimitiveRestart:
        return true;
510 511 512 513
    case QRhi::GeometryShaders:
        return false;
    case QRhi::TessellationShaders:
        return false; // for now
514 515
    case QRhi::NonDynamicUniformBuffers:
        return true;
516 517
    case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
        return false;
518 519
    case QRhi::NPOTTextureRepeat:
        return true;
520 521
    case QRhi::RedOrAlpha8IsRed:
        return true;
Laszlo Agocs's avatar
Laszlo Agocs committed
522 523 524 525 526 527
    default:
        Q_UNREACHABLE();
        return false;
    }
}

528 529 530 531 532 533
int QRhiMetal::resourceSizeLimit(QRhi::ResourceSizeLimit limit) const
{
    switch (limit) {
    case QRhi::TextureSizeMin:
        return 1;
    case QRhi::TextureSizeMax:
534
        return caps.maxTextureSize;
535 536 537 538 539 540
    default:
        Q_UNREACHABLE();
        return 0;
    }
}

541
const QRhiNativeHandles *QRhiMetal::nativeHandles()
542 543 544 545
{
    return &nativeHandlesStruct;
}

546
QRhiRenderBuffer *QRhiMetal::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
547
                                                int sampleCount, QRhiRenderBuffer::Flags flags)
548
{
Laszlo Agocs's avatar
Laszlo Agocs committed
549
    return new QMetalRenderBuffer(this, type, pixelSize, sampleCount, flags);
550 551
}

Laszlo Agocs's avatar
Laszlo Agocs committed
552 553
QRhiTexture *QRhiMetal::createTexture(QRhiTexture::Format format, const QSize &pixelSize,
                                      int sampleCount, QRhiTexture::Flags flags)
554
{
Laszlo Agocs's avatar
Laszlo Agocs committed
555
    return new QMetalTexture(this, format, pixelSize, sampleCount, flags);
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
}

QRhiSampler *QRhiMetal::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                                      QRhiSampler::Filter mipmapMode,
                                      QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
{
    return new QMetalSampler(this, magFilter, minFilter, mipmapMode, u, v, w);
}

QRhiTextureRenderTarget *QRhiMetal::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                              QRhiTextureRenderTarget::Flags flags)
{
    return new QMetalTextureRenderTarget(this, desc, flags);
}

QRhiGraphicsPipeline *QRhiMetal::createGraphicsPipeline()
{
    return new QMetalGraphicsPipeline(this);
}

QRhiShaderResourceBindings *QRhiMetal::createShaderResourceBindings()
{
    return new QMetalShaderResourceBindings(this);
}

581 582 583
void QRhiMetal::enqueueShaderResourceBindings(QMetalShaderResourceBindings *srbD, QMetalCommandBuffer *cbD,
                                              const QVector<QRhiCommandBuffer::DynamicOffset> &dynamicOffsets,
                                              bool offsetOnlyChange)
Laszlo Agocs's avatar
Laszlo Agocs committed
584
{
585 586 587 588 589 590 591 592
    static const int KNOWN_STAGES = 2;
    struct {
        QRhiBatchedBindings<id<MTLBuffer> > buffers;
        QRhiBatchedBindings<NSUInteger> bufferOffsets;
        QRhiBatchedBindings<id<MTLTexture> > textures;
        QRhiBatchedBindings<id<MTLSamplerState> > samplers;
    } res[KNOWN_STAGES];

593 594 595
    for (const QRhiShaderResourceBinding &binding : qAsConst(srbD->sortedBindings)) {
        const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&binding);
        switch (b->type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
596 597
        case QRhiShaderResourceBinding::UniformBuffer:
        {
598
            QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->u.ubuf.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
599
            id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->m_type == QRhiBuffer::Immutable ? 0 : currentFrameSlot];
600 601 602 603 604 605 606 607 608
            uint offset = b->u.ubuf.offset;
            if (!dynamicOffsets.isEmpty()) {
                for (const QRhiCommandBuffer::DynamicOffset &dynOfs : dynamicOffsets) {
                    if (dynOfs.first == b->binding) {
                        offset = dynOfs.second;
                        break;
                    }
                }
            }
609 610
            if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
                res[0].buffers.feed(b->binding, mtlbuf);
611
                res[0].bufferOffsets.feed(b->binding, offset);
612
            }
613 614
            if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
                res[1].buffers.feed(b->binding, mtlbuf);
615
                res[1].bufferOffsets.feed(b->binding, offset);
616
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
617 618 619 620
        }
            break;
        case QRhiShaderResourceBinding::SampledTexture:
        {
621 622 623 624 625
            QMetalTexture *texD = QRHI_RES(QMetalTexture, b->u.stex.tex);
            QMetalSampler *samplerD = QRHI_RES(QMetalSampler, b->u.stex.sampler);
            if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
                res[0].textures.feed(b->binding, texD->d->tex);
                res[0].samplers.feed(b->binding, samplerD->d->samplerState);
Laszlo Agocs's avatar
Laszlo Agocs committed
626
            }
627 628 629
            if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
                res[1].textures.feed(b->binding, texD->d->tex);
                res[1].samplers.feed(b->binding, samplerD->d->samplerState);
Laszlo Agocs's avatar
Laszlo Agocs committed
630 631 632 633 634 635 636 637
            }
        }
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }
638 639 640 641

    for (int idx = 0; idx < KNOWN_STAGES; ++idx) {
        res[idx].buffers.finish();
        res[idx].bufferOffsets.finish();
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
        for (int i = 0, ie = res[idx].buffers.batches.count(); i != ie; ++i) {
            const auto &bufferBatch(res[idx].buffers.batches[i]);
            const auto &offsetBatch(res[idx].bufferOffsets.batches[i]);
            switch (idx) {
            case 0:
                [cbD->d->currentPassEncoder setVertexBuffers: bufferBatch.resources.constData()
                  offsets: offsetBatch.resources.constData()
                  withRange: NSMakeRange(bufferBatch.startBinding, bufferBatch.resources.count())];
                break;
            case 1:
                [cbD->d->currentPassEncoder setFragmentBuffers: bufferBatch.resources.constData()
                  offsets: offsetBatch.resources.constData()
                  withRange: NSMakeRange(bufferBatch.startBinding, bufferBatch.resources.count())];
                break;
            default:
                Q_UNREACHABLE();
                break;
            }
        }
662 663 664 665 666 667 668

        if (offsetOnlyChange)
            continue;

        res[idx].textures.finish();
        res[idx].samplers.finish();

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
        for (int i = 0, ie = res[idx].textures.batches.count(); i != ie; ++i) {
            const auto &batch(res[idx].textures.batches[i]);
            switch (idx) {
            case 0:
                [cbD->d->currentPassEncoder setVertexTextures: batch.resources.constData()
                  withRange: NSMakeRange(batch.startBinding, batch.resources.count())];
                break;
            case 1:
                [cbD->d->currentPassEncoder setFragmentTextures: batch.resources.constData()
                  withRange: NSMakeRange(batch.startBinding, batch.resources.count())];
                break;
            default:
                Q_UNREACHABLE();
                break;
            }
        }
        for (int i = 0, ie = res[idx].samplers.batches.count(); i != ie; ++i) {
            const auto &batch(res[idx].samplers.batches[i]);
            switch (idx) {
            case 0:
                [cbD->d->currentPassEncoder setVertexSamplerStates: batch.resources.constData()
                  withRange: NSMakeRange(batch.startBinding, batch.resources.count())];
                break;
            case 1:
                [cbD->d->currentPassEncoder setFragmentSamplerStates: batch.resources.constData()
                  withRange: NSMakeRange(batch.startBinding, batch.resources.count())];
                break;
            default:
                Q_UNREACHABLE();
                break;
            }
        }
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
702 703
}

704
void QRhiMetal::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
705 706 707
{
    Q_ASSERT(inPass);

708
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
Laszlo Agocs's avatar
Laszlo Agocs committed
709
    QMetalGraphicsPipeline *psD = QRHI_RES(QMetalGraphicsPipeline, ps);
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

    if (cbD->currentPipeline != ps || cbD->currentPipelineGeneration != psD->generation) {
        cbD->currentPipeline = ps;
        cbD->currentPipelineGeneration = psD->generation;

        [cbD->d->currentPassEncoder setRenderPipelineState: psD->d->ps];
        [cbD->d->currentPassEncoder setDepthStencilState: psD->d->ds];
        [cbD->d->currentPassEncoder setCullMode: psD->d->cullMode];
        [cbD->d->currentPassEncoder setFrontFacingWinding: psD->d->winding];
    }

    psD->lastActiveFrameSlot = currentFrameSlot;
}

void QRhiMetal::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
                                   const QVector<QRhiCommandBuffer::DynamicOffset> &dynamicOffsets)
{
    Q_ASSERT(inPass);

    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
    Q_ASSERT(cbD->currentPipeline);
731
    if (!srb)
732
        srb = QRHI_RES(QMetalGraphicsPipeline, cbD->currentPipeline)->m_shaderResourceBindings;
733 734

    QMetalShaderResourceBindings *srbD = QRHI_RES(QMetalShaderResourceBindings, srb);
Laszlo Agocs's avatar
Laszlo Agocs committed
735
    bool hasSlottedResourceInSrb = false;
736
    bool hasDynamicOffsetInSrb = false;
Laszlo Agocs's avatar
Laszlo Agocs committed
737 738
    bool resNeedsRebind = false;

Laszlo Agocs's avatar
Laszlo Agocs committed
739
    // do buffer writes, figure out if we need to rebind, and mark as in-use
Laszlo Agocs's avatar
Laszlo Agocs committed
740
    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
741
        const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&srbD->sortedBindings[i]);
Laszlo Agocs's avatar
Laszlo Agocs committed
742
        QMetalShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
743
        switch (b->type) {
744
        case QRhiShaderResourceBinding::UniformBuffer:
745
        {
746
            QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, b->u.ubuf.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
747
            Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
Laszlo Agocs's avatar
Laszlo Agocs committed
748 749
            executeBufferHostWritesForCurrentFrame(bufD);
            if (bufD->m_type != QRhiBuffer::Immutable)
Laszlo Agocs's avatar
Laszlo Agocs committed
750
                hasSlottedResourceInSrb = true;
751 752
            if (b->u.ubuf.hasDynamicOffset)
                hasDynamicOffsetInSrb = true;
Laszlo Agocs's avatar
Laszlo Agocs committed
753
            if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
Laszlo Agocs's avatar
Laszlo Agocs committed
754
                resNeedsRebind = true;
Laszlo Agocs's avatar
Laszlo Agocs committed
755
                bd.ubuf.id = bufD->m_id;
Laszlo Agocs's avatar
Laszlo Agocs committed
756 757
                bd.ubuf.generation = bufD->generation;
            }
758 759 760
            bufD->lastActiveFrameSlot = currentFrameSlot;
        }
            break;
761
        case QRhiShaderResourceBinding::SampledTexture:
Laszlo Agocs's avatar
Laszlo Agocs committed
762
        {
763 764
            QMetalTexture *texD = QRHI_RES(QMetalTexture, b->u.stex.tex);
            QMetalSampler *samplerD = QRHI_RES(QMetalSampler, b->u.stex.sampler);
Laszlo Agocs's avatar
Laszlo Agocs committed
765
            if (texD->generation != bd.stex.texGeneration
Laszlo Agocs's avatar
Laszlo Agocs committed
766 767 768
                    || texD->m_id != bd.stex.texId
                    || samplerD->generation != bd.stex.samplerGeneration
                    || samplerD->m_id != bd.stex.samplerId)
Laszlo Agocs's avatar
Laszlo Agocs committed
769 770
            {
                resNeedsRebind = true;
Laszlo Agocs's avatar
Laszlo Agocs committed
771
                bd.stex.texId = texD->m_id;
Laszlo Agocs's avatar
Laszlo Agocs committed
772
                bd.stex.texGeneration = texD->generation;
Laszlo Agocs's avatar
Laszlo Agocs committed
773
                bd.stex.samplerId = samplerD->m_id;
Laszlo Agocs's avatar
Laszlo Agocs committed
774
                bd.stex.samplerGeneration = samplerD->generation;
Laszlo Agocs's avatar
Laszlo Agocs committed
775
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
776 777
            texD->lastActiveFrameSlot = currentFrameSlot;
            samplerD->lastActiveFrameSlot = currentFrameSlot;
Laszlo Agocs's avatar
Laszlo Agocs committed
778
        }
779 780 781 782 783 784 785
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
786
    // make sure the resources for the correct slot get bound
787
    const int resSlot = hasSlottedResourceInSrb ? currentFrameSlot : 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
788 789 790
    if (hasSlottedResourceInSrb && cbD->currentResSlot != resSlot)
        resNeedsRebind = true;

791
    const bool srbChange = cbD->currentSrb != srb || cbD->currentSrbGeneration != srbD->generation;
792

793 794
    // dynamic uniform buffer offsets always trigger a rebind
    if (hasDynamicOffsetInSrb || resNeedsRebind || srbChange) {
Laszlo Agocs's avatar
Laszlo Agocs committed
795 796 797
        cbD->currentSrb = srb;
        cbD->currentSrbGeneration = srbD->generation;
        cbD->currentResSlot = resSlot;
798

799 800
        const bool offsetOnlyChange = hasDynamicOffsetInSrb && !resNeedsRebind && !srbChange;
        enqueueShaderResourceBindings(srbD, cbD, dynamicOffsets, offsetOnlyChange);
Laszlo Agocs's avatar
Laszlo Agocs committed
801
    }
802 803
}

804 805
void QRhiMetal::setVertexInput(QRhiCommandBuffer *cb, int startBinding, const QVector<QRhiCommandBuffer::VertexInput> &bindings,
                               QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
806 807 808
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
Laszlo Agocs's avatar
Laszlo Agocs committed
809

810 811
    QRhiBatchedBindings<id<MTLBuffer> > buffers;
    QRhiBatchedBindings<NSUInteger> offsets;
812 813 814
    for (int i = 0; i < bindings.count(); ++i) {
        QMetalBuffer *bufD = QRHI_RES(QMetalBuffer, bindings[i].first);
        executeBufferHostWritesForCurrentFrame(bufD);
Laszlo Agocs's avatar
Laszlo Agocs committed
815
        bufD->lastActiveFrameSlot = currentFrameSlot;
Laszlo Agocs's avatar
Laszlo Agocs committed
816
        id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->m_type == QRhiBuffer::Immutable ? 0 : currentFrameSlot];
817 818 819 820 821 822 823 824 825
        buffers.feed(startBinding + i, mtlbuf);
        offsets.feed(startBinding + i, bindings[i].second);
    }
    buffers.finish();
    offsets.finish();

    // same binding space for vertex and constant buffers - work it around
    const int firstVertexBinding = QRHI_RES(QMetalShaderResourceBindings, cbD->currentSrb)->maxBinding + 1;

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    if (firstVertexBinding != cbD->d->currentFirstVertexBinding
            || buffers != cbD->d->currentVertexInputsBuffers
            || offsets != cbD->d->currentVertexInputOffsets)
    {
        cbD->d->currentFirstVertexBinding = firstVertexBinding;
        cbD->d->currentVertexInputsBuffers = buffers;
        cbD->d->currentVertexInputOffsets = offsets;

        for (int i = 0, ie = buffers.batches.count(); i != ie; ++i) {
            const auto &bufferBatch(buffers.batches[i]);
            const auto &offsetBatch(offsets.batches[i]);
            [cbD->d->currentPassEncoder setVertexBuffers:
                bufferBatch.resources.constData()
              offsets: offsetBatch.resources.constData()
              withRange: NSMakeRange(firstVertexBinding + bufferBatch.startBinding, bufferBatch.resources.count())];
        }
842
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
843 844 845 846 847

    if (indexBuf) {
        QMetalBuffer *ibufD = QRHI_RES(QMetalBuffer, indexBuf);
        executeBufferHostWritesForCurrentFrame(ibufD);
        ibufD->lastActiveFrameSlot = currentFrameSlot;
848 849 850
        cbD->currentIndexBuffer = indexBuf;
        cbD->currentIndexOffset = indexOffset;
        cbD->currentIndexFormat = indexFormat;
Laszlo Agocs's avatar
Laszlo Agocs committed
851
    } else {
852
        cbD->currentIndexBuffer = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
853
    }
854 855 856 857 858 859
}

static inline MTLViewport toMetalViewport(const QRhiViewport &viewport, const QSize &outputSize)
{
    // x,y is top-left in MTLViewport but bottom-left in QRhiViewport
    MTLViewport vp;
Laszlo Agocs's avatar
Laszlo Agocs committed
860 861 862 863 864 865 866
    const QVector4D r = viewport.viewport();
    vp.originX = r.x();
    vp.originY = outputSize.height() - (r.y() + r.w());
    vp.width = r.z();
    vp.height = r.w();
    vp.znear = viewport.minDepth();
    vp.zfar = viewport.maxDepth();
867 868 869 870 871 872 873
    return vp;
}

static inline MTLScissorRect toMetalScissor(const QRhiScissor &scissor, const QSize &outputSize)
{
    // x,y is top-left in MTLScissorRect but bottom-left in QRhiScissor
    MTLScissorRect s;
Laszlo Agocs's avatar
Laszlo Agocs committed
874 875 876 877 878
    const QVector4D r = scissor.scissor();
    s.x = r.x();
    s.y = outputSize.height() - (r.y() + r.w());
    s.width = r.z();
    s.height = r.w();
879 880 881
    return s;
}

882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
void QRhiMetal::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
    Q_ASSERT(cbD->currentPipeline && cbD->currentTarget);
    const QSize outputSize = cbD->currentTarget->sizeInPixels();
    const MTLViewport vp = toMetalViewport(viewport, outputSize);
    [cbD->d->currentPassEncoder setViewport: vp];

    if (!QRHI_RES(QMetalGraphicsPipeline, cbD->currentPipeline)->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor)) {
        const QVector4D v = viewport.viewport();
        const MTLScissorRect s = toMetalScissor(QRhiScissor(v.x(), v.y(), v.z(), v.w()), outputSize);
        [cbD->d->currentPassEncoder setScissorRect: s];
    }
}

898 899 900 901 902
void QRhiMetal::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
    Q_ASSERT(cbD->currentPipeline && cbD->currentTarget);
903
    Q_ASSERT(QRHI_RES(QMetalGraphicsPipeline, cbD->currentPipeline)->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor));
904 905
    const QSize outputSize = cbD->currentTarget->sizeInPixels();
    const MTLScissorRect s = toMetalScissor(scissor, outputSize);
906
    [cbD->d->currentPassEncoder setScissorRect: s];
907 908 909 910 911 912
}

void QRhiMetal::setBlendConstants(QRhiCommandBuffer *cb, const QVector4D &c)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
913
    [cbD->d->currentPassEncoder setBlendColorRed: c.x() green: c.y() blue: c.z() alpha: c.w()];
914 915 916 917 918 919
}

void QRhiMetal::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
920
    [cbD->d->currentPassEncoder setStencilReferenceValue: refValue];
921 922 923 924 925 926 927
}

void QRhiMetal::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
                     quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
928
    [cbD->d->currentPassEncoder drawPrimitives:
929 930 931 932 933 934 935 936 937
        QRHI_RES(QMetalGraphicsPipeline, cbD->currentPipeline)->d->primitiveType
      vertexStart: firstVertex vertexCount: vertexCount instanceCount: instanceCount baseInstance: firstInstance];
}

void QRhiMetal::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
                            quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
938
    if (!cbD->currentIndexBuffer)
Laszlo Agocs's avatar
Laszlo Agocs committed
939 940
        return;

941
    const quint32 indexOffset = cbD->currentIndexOffset + firstIndex * (cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4);
Laszlo Agocs's avatar
Laszlo Agocs committed
942 943
    Q_ASSERT(indexOffset == aligned(indexOffset, 4));

944
    QMetalBuffer *ibufD = QRHI_RES(QMetalBuffer, cbD->currentIndexBuffer);
Laszlo Agocs's avatar
Laszlo Agocs committed
945 946
    id<MTLBuffer> mtlbuf = ibufD->d->buf[ibufD->m_type == QRhiBuffer::Immutable ? 0 : currentFrameSlot];

947
    [cbD->d->currentPassEncoder drawIndexedPrimitives: QRHI_RES(QMetalGraphicsPipeline, cbD->currentPipeline)->d->primitiveType
Laszlo Agocs's avatar
Laszlo Agocs committed
948
      indexCount: indexCount
949
      indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
Laszlo Agocs's avatar
Laszlo Agocs committed
950 951 952 953 954
      indexBuffer: mtlbuf
      indexBufferOffset: indexOffset
      instanceCount: instanceCount
      baseVertex: vertexOffset
      baseInstance: firstInstance];
955 956
}

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
void QRhiMetal::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
{
    if (!debugMarkers)
        return;

    NSString *str = [NSString stringWithUTF8String: name.constData()];
    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
    if (inPass) {
        [cbD->d->currentPassEncoder pushDebugGroup: str];
    } else {
        if (@available(macOS 10.13, iOS 11.0, *))
            [cbD->d->cb pushDebugGroup: str];
    }
}

void QRhiMetal::debugMarkEnd(QRhiCommandBuffer *cb)
{
    if (!debugMarkers)
        return;

    QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
    if (inPass) {
        [cbD->d->currentPassEncoder popDebugGroup];
    } else {
        if (@available(macOS 10.13, iOS 11.0, *))
            [cbD->d->cb popDebugGroup];
    }
}

void QRhiMetal::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
{
    if (!debugMarkers)
        return;

    if (inPass) {
        QMetalCommandBuffer *cbD = QRHI_RES(QMetalCommandBuffer, cb);
        [cbD->d->currentPassEncoder insertDebugSignpost: [NSString stringWithUTF8String: msg.constData()]];
    }
}

997
QRhi::FrameOpResult QRhiMetal::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
998
{
999
    Q_UNUSED(flags);
1000 1001 1002 1003 1004
    Q_ASSERT(!inFrame);
    inFrame = true;

    QMetalSwapChain *swapChainD = QRHI_RES(QMetalSwapChain, swapChain);

1005
    // This is a bit messed up since for this swapchain we want to wait for the
Laszlo Agocs's avatar
Laszlo Agocs committed
1006
    // commands+present to complete, while for others just for the commands
1007 1008
    // (for this same frame slot) but not sure how to do that in a sane way so
    // wait for full cb completion for now.
Laszlo Agocs's avatar
Laszlo Agocs committed
1009
    for (QMetalSwapChain *sc : qAsConst(swapchains)) {
1010
        dispatch_semaphore_t sem = sc->d->sem[swapChainD->currentFrameSlot];
Laszlo Agocs's avatar
Laszlo Agocs committed
1011 1012 1013 1014
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        if (sc != swapChainD)
            dispatch_semaphore_signal(sem);
    }
1015

1016
    currentSwapChain = swapChainD;
1017
    currentFrameSlot = swapChainD->currentFrameSlot;
Laszlo Agocs's avatar
Laszlo Agocs committed
1018 1019
    if (swapChainD->ds)
        swapChainD->ds->lastActiveFrameSlot = currentFrameSlot;
1020

Laszlo Agocs's avatar
Laszlo Agocs committed
1021 1022 1023
    if (@available(macOS 10.13, iOS 11.0, *))
        [d->captureScope beginScope];

1024 1025 1026
    // Do not let the command buffer mess with the refcount of objects. We do
    // have a proper render loop and will manage lifetimes similarly to other
    // backends (Vulkan).
Laszlo Agocs's avatar
Laszlo Agocs committed
1027
    swapChainD->cbWrapper.d->cb = [d->cmdQueue commandBufferWithUnretainedReferences];
1028

Laszlo Agocs's avatar
Laszlo Agocs committed
1029
    QMetalRenderTargetData::ColorAtt colorAtt;
1030
    if (swapChainD->samples > 1) {
Laszlo Agocs's avatar
Laszlo Agocs committed
1031 1032 1033 1034
        colorAtt.tex = swapChainD->d->msaaTex[currentFrameSlot];
        colorAtt.needsDrawableForResolveTex = true;
    } else {
        colorAtt.needsDrawableForTex = true;
1035 1036
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
1037
    swapChainD->rtWrapper.d->fb.colorAtt[0] = colorAtt;
1038
    swapChainD->rtWrapper.d->fb.dsTex = swapChainD->ds ? swapChainD->ds->d->tex : nil;
Laszlo Agocs's avatar
Laszlo Agocs committed
1039
    swapChainD->rtWrapper.d->fb.hasStencil = swapChainD->ds ? true : false;
1040

1041 1042 1043
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
    QRHI_PROF_F(beginSwapChainFrame(swapChain));

1044
    executeDeferredReleases();
1045 1046
    swapChainD->cbWrapper.resetState();
    finishActiveReadbacks();
1047 1048 1049 1050

    return QRhi::FrameOpSuccess;
}

1051
QRhi::FrameOpResult QRhiMetal::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
1052 1053 1054 1055 1056
{
    Q_ASSERT(inFrame);
    inFrame = false;

    QMetalSwapChain *swapChainD = QRHI_RES(QMetalSwapChain, swapChain);
1057
    Q_ASSERT(currentSwapChain == swapChainD);
1058

1059 1060 1061
    const bool needsPresent = !flags.testFlag(QRhi::SkipPresent);
    if (needsPresent)
        [swapChainD->cbWrapper.d->cb presentDrawable: swapChainD->d->curDrawable];
1062

1063
    __block int thisFrameSlot = currentFrameSlot;
Laszlo Agocs's avatar
Laszlo Agocs committed
1064
    [swapChainD->cbWrapper.d->cb addCompletedHandler: ^(id<MTLCommandBuffer>) {
1065
        dispatch_semaphore_signal(swapChainD->d->sem[thisFrameSlot]);
1066 1067
    }];

Laszlo Agocs's avatar
Laszlo Agocs committed
1068
    [swapChainD->cbWrapper.d->cb commit];
1069

1070 1071 1072
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
    QRHI_PROF_F(endSwapChainFrame(swapChain, swapChainD->frameCount + 1));

Laszlo Agocs's avatar
Laszlo Agocs committed
1073 1074 1075
    if (@available(macOS 10.13, iOS 11.0, *))
        [d->captureScope endScope];

1076 1077
    if (needsPresent)
        swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QMTL_FRAMES_IN_FLIGHT;
1078

1079
    swapChainD->frameCount += 1;
1080
    currentSwapChain = nullptr;
1081 1082 1083
    return QRhi::FrameOpSuccess;
}

1084 1085
QRhi::FrameOpResult QRhiMetal::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
1086 1087 1088 1089
    Q_ASSERT(!inFrame);
    inFrame = true;

    currentFrameSlot = (currentFrameSlot + 1) % QMTL_FRAMES_IN_FLIGHT;
Laszlo Agocs's avatar
Laszlo Agocs committed
1090 1091 1092 1093 1094 1095 1096
    if (swapchains.count() > 1) {
        for (QMetalSwapChain *sc : qAsConst(swapchains)) {
            dispatch_semaphore_t sem = sc->d->sem[currentFrameSlot];
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_signal(sem);
        }
    }
1097 1098 1099 1100 1101 1102 1103