qrhigles2.cpp 80.3 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 38 39 40
/****************************************************************************
**
** 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 "qrhigles2_p.h"
#include <QWindow>
#include <QOffscreenSurface>
#include <QOpenGLContext>
Laszlo Agocs's avatar
Laszlo Agocs committed
41
#include <QtGui/private/qopenglextensions_p.h>
42 43 44 45 46
#include <qmath.h>

QT_BEGIN_NAMESPACE

/*
Laszlo Agocs's avatar
Laszlo Agocs committed
47 48 49 50 51 52 53 54 55 56 57 58
  OpenGL ES 2.0 (3.0) + GLSL 100/120 backend. Binding vertex attribute
  locations and decomposing uniform buffers into uniforms (as expected by the
  GLSL 1xx shader generated by SPIRV-Cross) are handled transparently to the
  application via the reflection data (QShaderDescription). Textures and
  buffers feature no special logic, it's all just glTexSubImage2D and
  glBufferSubData (with "dynamic" buffers set to GL_DYNAMIC_DRAW). The
  swapchain and the associated renderbuffer for depth-stencil will be dummies
  since we have no control over the underlying buffers here. It is up to the
  application to create the context and window with the appropriate
  QSurfaceFormat when it comes to depth/stencil and MSAA. While we try to keep
  this backend clean GLES 2.0, some GL(ES) 3.0 features like multisample
  renderbuffers and blits are used when available.
59 60 61
*/

QRhiGles2::QRhiGles2(QRhiInitParams *params)
62
    : ofr(this)
63 64 65 66 67 68 69
{
    QRhiGles2InitParams *glparams = static_cast<QRhiGles2InitParams *>(params);
    ctx = glparams->context;
    maybeWindow = glparams->window; // may be null
    fallbackSurface = glparams->fallbackSurface;
}

70
bool QRhiGles2::ensureContext(QSurface *surface) const
71 72 73 74 75 76 77 78 79 80 81 82 83
{
    bool nativeWindowGone = false;
    if (surface && surface->surfaceClass() == QSurface::Window && !surface->surfaceHandle()) {
        surface = fallbackSurface;
        nativeWindowGone = true;
    }

    if (!surface)
        surface = fallbackSurface;

    if (buffersSwapped)
        buffersSwapped = false;
    else if (!nativeWindowGone && QOpenGLContext::currentContext() == ctx && (surface == fallbackSurface || ctx->surface() == surface))
84
        return true;
85

86
    if (!ctx->makeCurrent(surface)) {
87
        qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen.");
88 89 90 91
        return false;
    }

    return true;
92 93
}

94
bool QRhiGles2::create(QRhi::Flags flags)
95
{
96
    Q_UNUSED(flags);
97 98 99
    Q_ASSERT(ctx);
    Q_ASSERT(fallbackSurface);

100
    if (!ensureContext(maybeWindow ? maybeWindow : fallbackSurface)) // see 'window' discussion in QRhiGles2InitParams comments
101
        return false;
102

Laszlo Agocs's avatar
Laszlo Agocs committed
103
    f = static_cast<QOpenGLExtensions *>(ctx->extraFunctions());
104 105 106 107 108 109

    const char *vendor = reinterpret_cast<const char *>(f->glGetString(GL_VENDOR));
    const char *renderer = reinterpret_cast<const char *>(f->glGetString(GL_RENDERER));
    const char *version = reinterpret_cast<const char *>(f->glGetString(GL_VERSION));
    if (vendor && renderer && version)
        qDebug("OpenGL VENDOR: %s RENDERER: %s VERSION: %s", vendor, renderer, version);
110 111 112 113 114 115

    GLint n = 0;
    f->glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &n);
    supportedCompressedFormats.resize(n);
    if (n > 0)
        f->glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, supportedCompressedFormats.data());
Laszlo Agocs's avatar
Laszlo Agocs committed
116 117 118

    caps.msaaRenderBuffer = f->hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample)
            && f->hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit);
119

120 121
    f->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &caps.maxTextureSize);

122 123
    nativeHandlesStruct.context = ctx;

124
    return true;
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
}

void QRhiGles2::destroy()
{
    if (!f)
        return;

    ensureContext();
    executeDeferredReleases();

    f = nullptr;
}

// Strictly speaking this is not necessary since we could do the deletes in
// release(). However, it is kind of nice that no release() ever requires a
// current context and so GL calls are isolated to specific places (build,
// beginFrame, endFrame) as much as possible.
void QRhiGles2::executeDeferredReleases()
{
    for (int i = releaseQueue.count() - 1; i >= 0; --i) {
        const QRhiGles2::DeferredReleaseEntry &e(releaseQueue[i]);
        switch (e.type) {
        case QRhiGles2::DeferredReleaseEntry::Buffer:
            f->glDeleteBuffers(1, &e.buffer.buffer);
            break;
        case QRhiGles2::DeferredReleaseEntry::Pipeline:
            f->glDeleteProgram(e.pipeline.program);
            break;
        case QRhiGles2::DeferredReleaseEntry::Texture:
            f->glDeleteTextures(1, &e.texture.texture);
            break;
        case QRhiGles2::DeferredReleaseEntry::RenderBuffer:
            f->glDeleteRenderbuffers(1, &e.renderbuffer.renderbuffer);
            break;
        case QRhiGles2::DeferredReleaseEntry::TextureRenderTarget:
            f->glDeleteFramebuffers(1, &e.textureRenderTarget.framebuffer);
            break;
        default:
            break;
        }
        releaseQueue.removeAt(i);
    }
}

QVector<int> QRhiGles2::supportedSampleCounts() const
{
    return { 1 };
}

QRhiSwapChain *QRhiGles2::createSwapChain()
{
    return new QGles2SwapChain(this);
}

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

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

bool QRhiGles2::isYUpInFramebuffer() const
{
    return true;
}

QMatrix4x4 QRhiGles2::clipSpaceCorrMatrix() const
{
    return QMatrix4x4(); // identity
}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
static inline GLenum toGlCompressedTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
{
    const bool srgb = flags.testFlag(QRhiTexture::sRGB);
    switch (format) {
    case QRhiTexture::BC1:
        return srgb ? 0x8C4C : 0x83F0;
    case QRhiTexture::BC3:
        return srgb ? 0x8C4E : 0x83F2;
    case QRhiTexture::BC5:
        return srgb ? 0x8C4F : 0x83F3;

    case QRhiTexture::ETC2_RGB8:
        return srgb ? 0x9275 : 0x9274;
    case QRhiTexture::ETC2_RGB8A1:
        return srgb ? 0x9277 : 0x9276;
    case QRhiTexture::ETC2_RGBA8:
        return srgb ? 0x9279 : 0x9278;

    case QRhiTexture::ASTC_4x4:
        return srgb ? 0x93D0 : 0x93B0;
    case QRhiTexture::ASTC_5x4:
        return srgb ? 0x93D1 : 0x93B1;
    case QRhiTexture::ASTC_5x5:
        return srgb ? 0x93D2 : 0x93B2;
    case QRhiTexture::ASTC_6x5:
        return srgb ? 0x93D3 : 0x93B3;
    case QRhiTexture::ASTC_6x6:
        return srgb ? 0x93D4 : 0x93B4;
    case QRhiTexture::ASTC_8x5:
        return srgb ? 0x93D5 : 0x93B5;
    case QRhiTexture::ASTC_8x6:
        return srgb ? 0x93D6 : 0x93B6;
    case QRhiTexture::ASTC_8x8:
        return srgb ? 0x93D7 : 0x93B7;
    case QRhiTexture::ASTC_10x5:
        return srgb ? 0x93D8 : 0x93B8;
    case QRhiTexture::ASTC_10x6:
        return srgb ? 0x93D9 : 0x93B9;
    case QRhiTexture::ASTC_10x8:
        return srgb ? 0x93DA : 0x93BA;
    case QRhiTexture::ASTC_10x10:
        return srgb ? 0x93DB : 0x93BB;
    case QRhiTexture::ASTC_12x10:
        return srgb ? 0x93DC : 0x93BC;
    case QRhiTexture::ASTC_12x12:
        return srgb ? 0x93DD : 0x93BD;

    default:
        return 0; // this is reachable, just return an invalid format
    }
}

251
bool QRhiGles2::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
252
{
253 254
    if (isCompressedFormat(format))
        return supportedCompressedFormats.contains(toGlCompressedTextureFormat(format, flags));
255 256 257 258

    return true;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
259 260 261 262 263 264 265
bool QRhiGles2::isFeatureSupported(QRhi::Feature feature) const
{
    switch (feature) {
    case QRhi::MultisampleTexture:
        return false;
    case QRhi::MultisampleRenderBuffer:
        return caps.msaaRenderBuffer;
266 267
    case QRhi::DebugMarkers:
        return false;
Laszlo Agocs's avatar
Laszlo Agocs committed
268 269 270 271 272 273
    default:
        Q_UNREACHABLE();
        return false;
    }
}

274 275 276 277 278 279 280 281 282 283 284 285 286
int QRhiGles2::resourceSizeLimit(QRhi::ResourceSizeLimit limit) const
{
    switch (limit) {
    case QRhi::TextureSizeMin:
        return 1;
    case QRhi::TextureSizeMax:
        return caps.maxTextureSize;
    default:
        Q_UNREACHABLE();
        return 0;
    }
}

287
const QRhiNativeHandles *QRhiGles2::nativeHandles()
288 289 290 291
{
    return &nativeHandlesStruct;
}

292
QRhiRenderBuffer *QRhiGles2::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
293
                                                int sampleCount, QRhiRenderBuffer::Flags flags)
294
{
Laszlo Agocs's avatar
Laszlo Agocs committed
295
    return new QGles2RenderBuffer(this, type, pixelSize, sampleCount, flags);
296 297
}

Laszlo Agocs's avatar
Laszlo Agocs committed
298 299
QRhiTexture *QRhiGles2::createTexture(QRhiTexture::Format format, const QSize &pixelSize,
                                      int sampleCount, QRhiTexture::Flags flags)
300
{
Laszlo Agocs's avatar
Laszlo Agocs committed
301
    return new QGles2Texture(this, format, pixelSize, sampleCount, flags);
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
}

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

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

QRhiGraphicsPipeline *QRhiGles2::createGraphicsPipeline()
{
    return new QGles2GraphicsPipeline(this);
}

QRhiShaderResourceBindings *QRhiGles2::createShaderResourceBindings()
{
    return new QGles2ShaderResourceBindings(this);
}

void QRhiGles2::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps, QRhiShaderResourceBindings *srb)
{
    Q_ASSERT(inPass);

Laszlo Agocs's avatar
Laszlo Agocs committed
331
    QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, ps);
332
    if (!srb)
Laszlo Agocs's avatar
Laszlo Agocs committed
333
        srb = psD->m_shaderResourceBindings;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

    QGles2ShaderResourceBindings *srbD = QRHI_RES(QGles2ShaderResourceBindings, srb);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    const bool pipelineChanged = cbD->currentPipeline != ps || cbD->currentPipelineGeneration != psD->generation;
    const bool srbChanged = cbD->currentSrb != srb || cbD->currentSrbGeneration != srbD->generation;

    if (pipelineChanged || srbChanged) {
        cbD->currentPipeline = ps;
        cbD->currentPipelineGeneration = psD->generation;
        cbD->currentSrb = srb;
        cbD->currentSrbGeneration = srbD->generation;

        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindGraphicsPipeline;
        cmd.args.bindGraphicsPipeline.ps = ps;
        cmd.args.bindGraphicsPipeline.srb = srb;
        cmd.args.bindGraphicsPipeline.resOnlyChange = !pipelineChanged && srbChanged;
        cbD->commands.append(cmd);
    }
}

356 357
void QRhiGles2::setVertexInput(QRhiCommandBuffer *cb, int startBinding, const QVector<QRhiCommandBuffer::VertexInput> &bindings,
                               QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
358 359 360 361 362 363 364 365
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    for (int i = 0, ie = bindings.count(); i != ie; ++i) {
        QRhiBuffer *buf = bindings[i].first;
        quint32 ofs = bindings[i].second;
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
366
        Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
367 368 369 370 371 372 373 374 375 376 377
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindVertexBuffer;
        cmd.args.bindVertexBuffer.ps = cbD->currentPipeline;
        cmd.args.bindVertexBuffer.buffer = bufD->buffer;
        cmd.args.bindVertexBuffer.offset = ofs;
        cmd.args.bindVertexBuffer.binding = startBinding + i;
        cbD->commands.append(cmd);
    }

    if (indexBuf) {
        QGles2Buffer *ibufD = QRHI_RES(QGles2Buffer, indexBuf);
Laszlo Agocs's avatar
Laszlo Agocs committed
378
        Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
379 380 381 382
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindIndexBuffer;
        cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
        cmd.args.bindIndexBuffer.offset = indexOffset;
383
        cmd.args.bindIndexBuffer.type = indexFormat == QRhiCommandBuffer::IndexUInt16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        cbD->commands.append(cmd);
    }
}

void QRhiGles2::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Viewport;
    cmd.args.viewport.x = viewport.r.x();
    cmd.args.viewport.y = viewport.r.y();
    cmd.args.viewport.w = viewport.r.z();
    cmd.args.viewport.h = viewport.r.w();
    cmd.args.viewport.d0 = viewport.minDepth;
    cmd.args.viewport.d1 = viewport.maxDepth;
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Scissor;
    cmd.args.scissor.x = scissor.r.x();
    cmd.args.scissor.y = scissor.r.y();
    cmd.args.scissor.w = scissor.r.z();
    cmd.args.scissor.h = scissor.r.w();
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setBlendConstants(QRhiCommandBuffer *cb, const QVector4D &c)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::BlendConstants;
    cmd.args.blendConstants.r = c.x();
    cmd.args.blendConstants.g = c.y();
    cmd.args.blendConstants.b = c.z();
    cmd.args.blendConstants.a = c.w();
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::StencilRef;
    cmd.args.stencilRef.ref = refValue;
    cmd.args.stencilRef.ps = cbD->currentPipeline;
    cbD->commands.append(cmd);
}

void QRhiGles2::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
                     quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    Q_UNUSED(instanceCount); // no instancing
    Q_UNUSED(firstInstance);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Draw;
    cmd.args.draw.ps = cbD->currentPipeline;
    cmd.args.draw.vertexCount = vertexCount;
    cmd.args.draw.firstVertex = firstVertex;
    cbD->commands.append(cmd);
}

void QRhiGles2::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
                            quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    Q_UNUSED(instanceCount); // no instancing
    Q_UNUSED(firstInstance);
    Q_UNUSED(vertexOffset); // no glDrawElementsBaseVertex
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::DrawIndexed;
    cmd.args.drawIndexed.ps = cbD->currentPipeline;
    cmd.args.drawIndexed.indexCount = indexCount;
    cmd.args.drawIndexed.firstIndex = firstIndex;
    cbD->commands.append(cmd);
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
void QRhiGles2::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
{
    if (!debugMarkers)
        return;

    Q_UNUSED(cb);
    Q_UNUSED(name);
}

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

    Q_UNUSED(cb);
}

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

    Q_UNUSED(cb);
    Q_UNUSED(msg);
}

497 498 499 500 501
QRhi::FrameOpResult QRhiGles2::beginFrame(QRhiSwapChain *swapChain)
{
    Q_ASSERT(!inFrame);

    QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
502 503 504
    if (!ensureContext(swapChainD->surface))
        return QRhi::FrameOpError;

505
    inFrame = true;
506
    currentSwapChain = swapChainD;
507 508 509 510 511 512 513 514 515 516

    executeDeferredReleases();
    QRHI_RES(QGles2CommandBuffer, &swapChainD->cb)->resetState();

    return QRhi::FrameOpSuccess;
}

QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain)
{
    Q_ASSERT(inFrame);
517
    inFrame = false;
518 519

    QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
520 521
    Q_ASSERT(currentSwapChain == swapChainD);

522 523 524
    if (!ensureContext(swapChainD->surface))
        return QRhi::FrameOpError;

525 526
    executeCommandBuffer(&swapChainD->cb);

527
    swapChainD->frameCount += 1;
528
    currentSwapChain = nullptr;
529 530 531 532 533 534 535 536 537

    if (swapChainD->surface) {
        ctx->swapBuffers(swapChainD->surface);
        buffersSwapped = true;
    }

    return QRhi::FrameOpSuccess;
}

538 539
QRhi::FrameOpResult QRhiGles2::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
540 541 542 543 544 545 546 547 548 549 550 551 552
    Q_ASSERT(!inFrame);

    if (!ensureContext())
        return QRhi::FrameOpError;

    inFrame = true;
    ofr.active = true;

    executeDeferredReleases();
    ofr.cbWrapper.resetState();
    *cb = &ofr.cbWrapper;

    return QRhi::FrameOpSuccess;
553 554
}

555
QRhi::FrameOpResult QRhiGles2::endOffscreenFrame()
556
{
557 558 559 560 561 562 563 564 565 566
    Q_ASSERT(inFrame && ofr.active);
    inFrame = false;
    ofr.active = false;

    if (!ensureContext())
        return QRhi::FrameOpError;

    executeCommandBuffer(&ofr.cbWrapper);

    return QRhi::FrameOpSuccess;;
567 568
}

569 570 571
QRhi::FrameOpResult QRhiGles2::finish()
{
    Q_ASSERT(!inPass);
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    if (inFrame) {
        if (ofr.active) {
            Q_ASSERT(!currentSwapChain);
            if (!ensureContext())
                return QRhi::FrameOpError;
            executeCommandBuffer(&ofr.cbWrapper);
            ofr.cbWrapper.resetCommands();
        } else {
            Q_ASSERT(currentSwapChain);
            if (!ensureContext(currentSwapChain->surface))
                return QRhi::FrameOpError;
            executeCommandBuffer(&currentSwapChain->cb);
            currentSwapChain->cb.resetCommands();
        }
    }
587 588 589
    return QRhi::FrameOpSuccess;
}

590
void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
591
{
592
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
593 594 595 596
    QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);

    for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : ud->dynamicBufferUpdates) {
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
597 598
        Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
        if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
599 600 601 602 603 604 605
            memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size());
            QGles2Buffer::ChangeRange &r(bufD->ubufChangeRange);
            if (r.changeBegin == -1 || u.offset < r.changeBegin)
                r.changeBegin = u.offset;
            if (r.changeEnd == -1 || u.offset + u.data.size() > r.changeEnd)
                r.changeEnd = u.offset + u.data.size();
        } else {
606 607 608 609 610 611 612 613
            QGles2CommandBuffer::Command cmd;
            cmd.cmd = QGles2CommandBuffer::Command::BufferSubData;
            cmd.args.bufferSubData.target = bufD->target;
            cmd.args.bufferSubData.buffer = bufD->buffer;
            cmd.args.bufferSubData.offset = u.offset;
            cmd.args.bufferSubData.size = u.data.size();
            cmd.args.bufferSubData.data = cbD->retainData(u.data);
            cbD->commands.append(cmd);
614 615 616 617 618
        }
    }

    for (const QRhiResourceUpdateBatchPrivate::StaticBufferUpload &u : ud->staticBufferUploads) {
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
619
        Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
620
        Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
Laszlo Agocs's avatar
Laszlo Agocs committed
621
        if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
Laszlo Agocs's avatar
Laszlo Agocs committed
622
            memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size());
623 624
            bufD->ubufChangeRange = { 0, u.data.size() };
        } else {
625
            QGles2CommandBuffer::Command cmd;
626 627 628 629 630 631
            cmd.cmd = QGles2CommandBuffer::Command::BufferSubData;
            cmd.args.bufferSubData.target = bufD->target;
            cmd.args.bufferSubData.buffer = bufD->buffer;
            cmd.args.bufferSubData.offset = u.offset;
            cmd.args.bufferSubData.size = u.data.size();
            cmd.args.bufferSubData.data = cbD->retainData(u.data);
632
            cbD->commands.append(cmd);
633 634 635 636 637
        }
    }

    for (const QRhiResourceUpdateBatchPrivate::TextureUpload &u : ud->textureUploads) {
        QGles2Texture *texD = QRHI_RES(QGles2Texture, u.tex);
638
        const bool isCompressed = isCompressedFormat(texD->m_format);
Laszlo Agocs's avatar
Laszlo Agocs committed
639
        const bool isCubeMap = texD->m_flags.testFlag(QRhiTexture::CubeMap);
640
        const GLenum faceTargetBase = isCubeMap ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
641
        for (int layer = 0, layerCount = u.desc.layers.count(); layer != layerCount; ++layer) {
Laszlo Agocs's avatar
Laszlo Agocs committed
642
            const QRhiTextureUploadDescription::Layer &layerDesc(u.desc.layers[layer]);
643
            for (int level = 0, levelCount = layerDesc.mipImages.count(); level != levelCount; ++level) {
Laszlo Agocs's avatar
Laszlo Agocs committed
644
                const QRhiTextureUploadDescription::Layer::MipLevel mipDesc(layerDesc.mipImages[level]);
645 646
                const int dx = mipDesc.destinationTopLeft.x();
                const int dy = mipDesc.destinationTopLeft.y();
647
                if (isCompressed && !mipDesc.compressedData.isEmpty()) {
648
                    int w, h;
649
                    if (mipDesc.sourceSize.isEmpty()) {
650 651 652
                        w = qFloor(float(qMax(1, texD->m_pixelSize.width() >> level)));
                        h = qFloor(float(qMax(1, texD->m_pixelSize.height() >> level)));
                    } else {
653 654
                        w = mipDesc.sourceSize.width();
                        h = mipDesc.sourceSize.height();
655
                    }
656
                    if (texD->specified) {
657 658
                        QGles2CommandBuffer::Command cmd;
                        cmd.cmd = QGles2CommandBuffer::Command::CompressedSubImage;
659 660
                        cmd.args.compressedSubImage.dst = texD;
                        cmd.args.compressedSubImage.faceTarget = faceTargetBase + layer;
661 662 663 664 665 666 667 668 669
                        cmd.args.compressedSubImage.level = level;
                        cmd.args.compressedSubImage.dx = dx;
                        cmd.args.compressedSubImage.dy = dy;
                        cmd.args.compressedSubImage.w = w;
                        cmd.args.compressedSubImage.h = h;
                        cmd.args.compressedSubImage.glintformat = texD->glintformat;
                        cmd.args.compressedSubImage.size = mipDesc.compressedData.size();
                        cmd.args.compressedSubImage.data = cbD->retainData(mipDesc.compressedData);
                        cbD->commands.append(cmd);
670
                    } else {
671 672
                        QGles2CommandBuffer::Command cmd;
                        cmd.cmd = QGles2CommandBuffer::Command::CompressedImage;
673 674
                        cmd.args.compressedImage.dst = texD;
                        cmd.args.compressedImage.faceTarget = faceTargetBase + layer;
675 676 677 678 679 680 681
                        cmd.args.compressedImage.level = level;
                        cmd.args.compressedImage.glintformat = texD->glintformat;
                        cmd.args.compressedImage.w = w;
                        cmd.args.compressedImage.h = h;
                        cmd.args.compressedImage.size = mipDesc.compressedData.size();
                        cmd.args.compressedImage.data = cbD->retainData(mipDesc.compressedData);
                        cbD->commands.append(cmd);
682 683
                    }
                } else {
684 685 686
                    QImage img = mipDesc.image;
                    int w = img.width();
                    int h = img.height();
687 688
                    QGles2CommandBuffer::Command cmd;
                    cmd.cmd = QGles2CommandBuffer::Command::SubImage;
689 690 691 692 693 694 695 696 697
                    if (!mipDesc.sourceSize.isEmpty() || !mipDesc.sourceTopLeft.isNull()) {
                        const int sx = mipDesc.sourceTopLeft.x();
                        const int sy = mipDesc.sourceTopLeft.y();
                        if (!mipDesc.sourceSize.isEmpty()) {
                            w = mipDesc.sourceSize.width();
                            h = mipDesc.sourceSize.height();
                        }
                        img = img.copy(sx, sy, w, h);
                    }
698 699
                    cmd.args.subImage.dst = texD;
                    cmd.args.subImage.faceTarget = faceTargetBase + layer;
700 701 702 703 704 705 706 707 708
                    cmd.args.subImage.level = level;
                    cmd.args.subImage.dx = dx;
                    cmd.args.subImage.dy = dy;
                    cmd.args.subImage.w = w;
                    cmd.args.subImage.h = h;
                    cmd.args.subImage.glformat = texD->glformat;
                    cmd.args.subImage.gltype = texD->gltype;
                    cmd.args.subImage.data = cbD->retainImage(img);
                    cbD->commands.append(cmd);
709
                }
710 711
            }
        }
712
        texD->specified = true;
713 714
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
715 716 717 718 719 720 721 722 723 724 725 726 727
    for (const QRhiResourceUpdateBatchPrivate::TextureCopy &u : ud->textureCopies) {
        Q_ASSERT(u.src && u.dst);
        QGles2Texture *srcD = QRHI_RES(QGles2Texture, u.src);
        QGles2Texture *dstD = QRHI_RES(QGles2Texture, u.dst);

        const QSize size = u.desc.pixelSize.isEmpty() ? srcD->m_pixelSize : u.desc.pixelSize;
        // source offset is bottom-left
        const float sx = u.desc.sourceTopLeft.x();
        const float sy = srcD->m_pixelSize.height() - (u.desc.sourceTopLeft.y() + size.height() - 1);
        // destination offset is top-left
        const float dx = u.desc.destinationTopLeft.x();
        const float dy = u.desc.destinationTopLeft.y();

728 729
        const GLenum srcFaceTargetBase = srcD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : srcD->target;
        const GLenum dstFaceTargetBase = dstD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : dstD->target;
Laszlo Agocs's avatar
Laszlo Agocs committed
730

731 732
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::CopyTex;
Laszlo Agocs's avatar
Laszlo Agocs committed
733

734
        cmd.args.copyTex.srcFaceTarget = srcFaceTargetBase + u.desc.sourceLayer;
735 736 737 738 739
        cmd.args.copyTex.srcTexture = srcD->texture;
        cmd.args.copyTex.srcLevel = u.desc.sourceLevel;
        cmd.args.copyTex.srcX = sx;
        cmd.args.copyTex.srcY = sy;

740 741
        cmd.args.copyTex.dst = dstD;
        cmd.args.copyTex.dstFaceTarget = dstFaceTargetBase + u.desc.destinationLayer;
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        cmd.args.copyTex.dstLevel = u.desc.destinationLevel;
        cmd.args.copyTex.dstX = dx;
        cmd.args.copyTex.dstY = dy;

        cmd.args.copyTex.w = size.width();
        cmd.args.copyTex.h = size.height();

        cbD->commands.append(cmd);
    }

    for (const QRhiResourceUpdateBatchPrivate::TextureRead &u : ud->textureReadbacks) {
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::ReadPixels;
        cmd.args.readPixels.result = u.result;
        cmd.args.readPixels.texture = QRHI_RES(QGles2Texture, u.rb.texture);
        cmd.args.readPixels.layer = u.rb.layer;
        cmd.args.readPixels.level = u.rb.level;
        cbD->commands.append(cmd);
Laszlo Agocs's avatar
Laszlo Agocs committed
760 761
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
762 763 764 765 766 767 768
    for (const QRhiResourceUpdateBatchPrivate::TextureMipGen &u : ud->textureMipGens) {
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::GenMip;
        cmd.args.genMip.tex = QRHI_RES(QGles2Texture, u.tex);
        cbD->commands.append(cmd);
    }

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    ud->free();
}

static inline GLenum toGlTopology(QRhiGraphicsPipeline::Topology t)
{
    switch (t) {
    case QRhiGraphicsPipeline::Triangles:
        return GL_TRIANGLES;
    case QRhiGraphicsPipeline::TriangleStrip:
        return GL_TRIANGLE_STRIP;
    case QRhiGraphicsPipeline::Lines:
        return GL_LINES;
    case QRhiGraphicsPipeline::LineStrip:
        return GL_LINE_STRIP;
    case QRhiGraphicsPipeline::Points:
        return GL_POINTS;
    default:
        Q_UNREACHABLE();
        return GL_TRIANGLES;
    }
}

static inline GLenum toGlCullMode(QRhiGraphicsPipeline::CullMode c)
{
    switch (c) {
    case QRhiGraphicsPipeline::Front:
        return GL_FRONT;
    case QRhiGraphicsPipeline::Back:
        return GL_BACK;
    default:
        Q_UNREACHABLE();
        return GL_BACK;
    }
}

static inline GLenum toGlFrontFace(QRhiGraphicsPipeline::FrontFace f)
{
    switch (f) {
    case QRhiGraphicsPipeline::CCW:
        return GL_CCW;
    case QRhiGraphicsPipeline::CW:
        return GL_CW;
    default:
        Q_UNREACHABLE();
        return GL_CCW;
    }
}

static inline GLenum toGlBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
{
    switch (f) {
    case QRhiGraphicsPipeline::Zero:
        return GL_ZERO;
    case QRhiGraphicsPipeline::One:
        return GL_ONE;
    case QRhiGraphicsPipeline::SrcColor:
        return GL_SRC_COLOR;
    case QRhiGraphicsPipeline::OneMinusSrcColor:
        return GL_ONE_MINUS_SRC_COLOR;
    case QRhiGraphicsPipeline::DstColor:
        return GL_DST_COLOR;
    case QRhiGraphicsPipeline::OneMinusDstColor:
        return GL_ONE_MINUS_DST_COLOR;
    case QRhiGraphicsPipeline::SrcAlpha:
        return GL_SRC_ALPHA;
    case QRhiGraphicsPipeline::OneMinusSrcAlpha:
        return GL_ONE_MINUS_SRC_ALPHA;
    case QRhiGraphicsPipeline::DstAlpha:
        return GL_DST_ALPHA;
    case QRhiGraphicsPipeline::OneMinusDstAlpha:
        return GL_ONE_MINUS_DST_ALPHA;
    case QRhiGraphicsPipeline::ConstantColor:
        return GL_CONSTANT_COLOR;
    case QRhiGraphicsPipeline::OneMinusConstantColor:
        return GL_ONE_MINUS_CONSTANT_COLOR;
    case QRhiGraphicsPipeline::ConstantAlpha:
        return GL_CONSTANT_ALPHA;
    case QRhiGraphicsPipeline::OneMinusConstantAlpha:
        return GL_ONE_MINUS_CONSTANT_ALPHA;
    case QRhiGraphicsPipeline::SrcAlphaSaturate:
        return GL_SRC_ALPHA_SATURATE;
    case QRhiGraphicsPipeline::Src1Color:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::OneMinusSrc1Color:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::Src1Alpha:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
        qWarning("Unsupported blend factor %d", f);
        return GL_ZERO;
    default:
        Q_UNREACHABLE();
        return GL_ZERO;
    }
}

static inline GLenum toGlBlendOp(QRhiGraphicsPipeline::BlendOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::Add:
        return GL_FUNC_ADD;
    case QRhiGraphicsPipeline::Subtract:
        return GL_FUNC_SUBTRACT;
    case QRhiGraphicsPipeline::ReverseSubtract:
        return GL_FUNC_REVERSE_SUBTRACT;
    case QRhiGraphicsPipeline::Min:
        return GL_MIN;
    case QRhiGraphicsPipeline::Max:
        return GL_MAX;
    default:
        Q_UNREACHABLE();
        return GL_FUNC_ADD;
    }
}

static inline GLenum toGlCompareOp(QRhiGraphicsPipeline::CompareOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::Never:
        return GL_NEVER;
    case QRhiGraphicsPipeline::Less:
        return GL_LESS;
    case QRhiGraphicsPipeline::Equal:
        return GL_EQUAL;
    case QRhiGraphicsPipeline::LessOrEqual:
        return GL_LEQUAL;
    case QRhiGraphicsPipeline::Greater:
        return GL_GREATER;
    case QRhiGraphicsPipeline::NotEqual:
        return GL_NOTEQUAL;
    case QRhiGraphicsPipeline::GreaterOrEqual:
        return GL_GEQUAL;
    case QRhiGraphicsPipeline::Always:
        return GL_ALWAYS;
    default:
        Q_UNREACHABLE();
        return GL_ALWAYS;
    }
}

static inline GLenum toGlStencilOp(QRhiGraphicsPipeline::StencilOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::StencilZero:
        return GL_ZERO;
    case QRhiGraphicsPipeline::Keep:
        return GL_KEEP;
    case QRhiGraphicsPipeline::Replace:
        return GL_REPLACE;
    case QRhiGraphicsPipeline::IncrementAndClamp:
        return GL_INCR;
    case QRhiGraphicsPipeline::DecrementAndClamp:
        return GL_DECR;
    case QRhiGraphicsPipeline::Invert:
        return GL_INVERT;
    case QRhiGraphicsPipeline::IncrementAndWrap:
        return GL_INCR_WRAP;
    case QRhiGraphicsPipeline::DecrementAndWrap:
        return GL_DECR_WRAP;
    default:
        Q_UNREACHABLE();
        return GL_KEEP;
    }
}

static inline GLenum toGlMinFilter(QRhiSampler::Filter f, QRhiSampler::Filter m)
{
    switch (f) {
    case QRhiSampler::Nearest:
        if (m == QRhiSampler::None)
            return GL_NEAREST;
        else
            return m == QRhiSampler::Nearest ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR;
    case QRhiSampler::Linear:
        if (m == QRhiSampler::None)
            return GL_LINEAR;
        else
            return m == QRhiSampler::Nearest ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR;
    default:
        Q_UNREACHABLE();
        return GL_LINEAR;
    }
}

static inline GLenum toGlMagFilter(QRhiSampler::Filter f)
{
    switch (f) {
    case QRhiSampler::Nearest:
        return GL_NEAREST;
    case QRhiSampler::Linear:
        return GL_LINEAR;
    default:
        Q_UNREACHABLE();
        return GL_LINEAR;
    }
}

static inline GLenum toGlWrapMode(QRhiSampler::AddressMode m)
{
    switch (m) {
    case QRhiSampler::Repeat:
        return GL_REPEAT;
    case QRhiSampler::ClampToEdge:
        return GL_CLAMP_TO_EDGE;
    case QRhiSampler::Mirror:
        return GL_MIRRORED_REPEAT;
    case QRhiSampler::MirrorOnce:
        Q_FALLTHROUGH();
    case QRhiSampler::Border:
        qWarning("Unsupported wrap mode %d", m);
        return GL_CLAMP_TO_EDGE;
    default:
        Q_UNREACHABLE();
        return GL_CLAMP_TO_EDGE;
    }
}

void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb)
{
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
    GLenum indexType = GL_UNSIGNED_SHORT;
    quint32 indexStride = sizeof(quint16);
    quint32 indexOffset = 0;

    for (const QGles2CommandBuffer::Command &cmd : qAsConst(cbD->commands)) {
        switch (cmd.cmd) {
        case QGles2CommandBuffer::Command::Viewport:
            f->glViewport(cmd.args.viewport.x, cmd.args.viewport.y, cmd.args.viewport.w, cmd.args.viewport.h);
            f->glDepthRangef(cmd.args.viewport.d0, cmd.args.viewport.d1);
            break;
        case QGles2CommandBuffer::Command::Scissor:
            f->glScissor(cmd.args.scissor.x, cmd.args.scissor.y, cmd.args.scissor.w, cmd.args.scissor.h);
            break;
        case QGles2CommandBuffer::Command::BlendConstants:
            f->glBlendColor(cmd.args.blendConstants.r, cmd.args.blendConstants.g, cmd.args.blendConstants.b, cmd.args.blendConstants.a);
            break;
        case QGles2CommandBuffer::Command::StencilRef:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1007 1008 1009 1010
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.stencilRef.ps);
            if (psD) {
                f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask);
                f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask);
1011 1012 1013 1014 1015 1016 1017
            } else {
                qWarning("No graphics pipeline active for setStencilRef; ignored");
            }
        }
            break;
        case QGles2CommandBuffer::Command::BindVertexBuffer:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1018 1019 1020
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.bindVertexBuffer.ps);
            if (psD) {
                for (const QRhiVertexInputLayout::Attribute &a : psD->m_vertexInputLayout.attributes) {
1021 1022 1023 1024 1025 1026
                    if (a.binding != cmd.args.bindVertexBuffer.binding)
                        continue;

                    // we do not support more than one vertex buffer
                    f->glBindBuffer(GL_ARRAY_BUFFER, cmd.args.bindVertexBuffer.buffer);

Laszlo Agocs's avatar
Laszlo Agocs committed
1027
                    const int stride = psD->m_vertexInputLayout.bindings[a.binding].stride;
1028 1029
                    int size = 1;
                    GLenum type = GL_FLOAT;
1030
                    bool normalize = false;
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
                    switch (a.format) {
                    case QRhiVertexInputLayout::Attribute::Float4:
                        type = GL_FLOAT;
                        size = 4;
                        break;
                    case QRhiVertexInputLayout::Attribute::Float3:
                        type = GL_FLOAT;
                        size = 3;
                        break;
                    case QRhiVertexInputLayout::Attribute::Float2:
                        type = GL_FLOAT;
                        size = 2;
                        break;
                    case QRhiVertexInputLayout::Attribute::Float:
                        type = GL_FLOAT;
                        size = 1;
                        break;
                    case QRhiVertexInputLayout::Attribute::UNormByte4:
                        type = GL_UNSIGNED_BYTE;
1050
                        normalize = true;
1051 1052 1053 1054
                        size = 4;
                        break;
                    case QRhiVertexInputLayout::Attribute::UNormByte2:
                        type = GL_UNSIGNED_BYTE;
1055
                        normalize = true;
1056 1057 1058 1059
                        size = 2;
                        break;
                    case QRhiVertexInputLayout::Attribute::UNormByte:
                        type = GL_UNSIGNED_BYTE;
1060
                        normalize = true;
1061 1062 1063 1064 1065 1066
                        size = 1;
                        break;
                    default:
                        break;
                    }
                    quint32 ofs = a.offset + cmd.args.bindVertexBuffer.offset;
1067
                    f->glVertexAttribPointer(a.location, size, type, normalize, stride,
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
                                             reinterpret_cast<const GLvoid *>(quintptr(ofs)));
                    f->glEnableVertexAttribArray(a.location);
                }
            } else {
                qWarning("No graphics pipeline active for setVertexInput; ignored");
            }
        }
            break;
        case QGles2CommandBuffer::Command::BindIndexBuffer:
            indexType = cmd.args.bindIndexBuffer.type;
            indexStride = indexType == GL_UNSIGNED_SHORT ? sizeof(quint16) : sizeof(quint32);
            indexOffset = cmd.args.bindIndexBuffer.offset;
            f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cmd.args.bindIndexBuffer.buffer);
            break;
        case QGles2CommandBuffer::Command::Draw:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1084 1085 1086
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.draw.ps);
            if (psD)
                f->glDrawArrays(psD->drawMode, cmd.args.draw.firstVertex, cmd.args.draw.vertexCount);
1087 1088 1089 1090 1091 1092
            else
                qWarning("No graphics pipeline active for draw; ignored");
        }
            break;
        case QGles2CommandBuffer::Command::DrawIndexed:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1093 1094
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndexed.ps);
            if (psD) {
1095
                quint32 ofs = cmd.args.drawIndexed.firstIndex * indexStride + indexOffset;
Laszlo Agocs's avatar
Laszlo Agocs committed
1096
                f->glDrawElements(psD->drawMode,
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
                                  cmd.args.drawIndexed.indexCount,
                                  indexType,
                                  reinterpret_cast<const GLvoid *>(quintptr(ofs)));
            } else {
                qWarning("No graphics pipeline active for drawIndexed; ignored");
            }
        }
            break;
        case QGles2CommandBuffer::Command::BindGraphicsPipeline:
            if (cmd.args.bindGraphicsPipeline.resOnlyChange) {
                setChangedUniforms(QRHI_RES(QGles2GraphicsPipeline, cmd.args.bindGraphicsPipeline.ps),
                                   cmd.args.bindGraphicsPipeline.srb,
                                   false);
            } else {
                executeBindGraphicsPipeline(cmd.args.bindGraphicsPipeline.ps, cmd.args.bindGraphicsPipeline.srb);
            }
            break;
        case QGles2CommandBuffer::Command::BindFramebuffer:
            if (cmd.args.bindFramebuffer.rt)
                f->glBindFramebuffer(GL_FRAMEBUFFER,
                                     QRHI_RES(QGles2TextureRenderTarget, cmd.args.bindFramebuffer.rt)->framebuffer);
            else
                f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
            break;
        case QGles2CommandBuffer::Command::Clear:
            f->glDisable(GL_SCISSOR_TEST);
            if (cmd.args.clear.mask & GL_COLOR_BUFFER_BIT) {
                f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
                f->glClearColor(cmd.args.clear.c[0], cmd.args.clear.c[1], cmd.args.clear.c[2], cmd.args.clear.c[3]);
            }
            if (cmd.args.clear.mask & GL_DEPTH_BUFFER_BIT) {
                f->glDepthMask(GL_TRUE);
                f->glClearDepthf(cmd.args.clear.d);
            }
            if (cmd.args.clear.mask & GL_STENCIL_BUFFER_BIT) {
                f->glStencilMask(GL_TRUE);
                f->glClearStencil(cmd.args.clear.s);
            }
            f->glClear(cmd.args.clear.mask);
            break;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        case QGles2CommandBuffer::Command::BufferSubData:
            f->glBindBuffer(cmd.args.bufferSubData.target, cmd.args.bufferSubData.buffer);
            f->glBufferSubData(cmd.args.bufferSubData.target, cmd.args.bufferSubData.offset, cmd.args.bufferSubData.size,
                               cmd.args.bufferSubData.data);
            break;
        case QGles2CommandBuffer::Command::CopyTex:
        {
            GLuint fbo;
            f->glGenFramebuffers(1, &fbo);
            f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
            f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
1148 1149 1150
                                      cmd.args.copyTex.srcFaceTarget, cmd.args.copyTex.srcTexture, cmd.args.copyTex.srcLevel);
            f->glBindTexture(cmd.args.copyTex.dst->target, cmd.args.copyTex.dst->texture);
            f->glCopyTexSubImage2D(cmd.args.copyTex.dstFaceTarget, cmd.args.copyTex.dstLevel,
1151 1152 1153 1154 1155 1156 1157
                                   cmd.args.copyTex.dstX, cmd.args.copyTex.dstY,
                                   cmd.args.copyTex.srcX, cmd.args.copyTex.srcY,
                                   cmd.args.copyTex.w, cmd.args.copyTex.h);
            f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
            f->glDeleteFramebuffers(1, &fbo);
        }
            break;
1158 1159
        case QGles2CommandBuffer::Command::ReadPixels:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1160
            // ### more formats
1161
            QRhiReadbackResult *result = cmd.args.readPixels.result;
1162
            QGles2Texture *texD = cmd.args.readPixels.texture;
1163
            GLuint fbo = 0;
1164
            if (texD) {
1165 1166 1167 1168
                result->pixelSize = texD->m_pixelSize;
                result->format = texD->m_format;
                f->glGenFramebuffers(1, &fbo);
                f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1169 1170
                const GLenum faceTargetBase = texD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
                f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, faceTargetBase + cmd.args.readPixels.layer, texD->texture, cmd.args.readPixels.level);
1171 1172 1173
            } else {
                result->pixelSize = currentSwapChain->pixelSize;
                result->format = QRhiTexture::RGBA8;
1174
                // readPixels handles multisample resolving implicitly
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            }
            result->data.resize(result->pixelSize.width() * result->pixelSize.height() * 4);
            f->glReadPixels(0, 0, result->pixelSize.width(), result->pixelSize.height(),
                            GL_RGBA, GL_UNSIGNED_BYTE,
                            result->data.data());
            if (fbo) {
                f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
                f->glDeleteFramebuffers(1, &fbo);
            }
            if (result->completed)
                result->completed();
        }
            break;
1188
        case QGles2CommandBuffer::Command::SubImage:
1189 1190
            f->glBindTexture(cmd.args.subImage.dst->target, cmd.args.subImage.dst->texture);
            f->glTexSubImage2D(cmd.args.subImage.faceTarget, cmd.args.subImage.level,
1191 1192 1193 1194 1195 1196
                               cmd.args.subImage.dx, cmd.args.subImage.dy,
                               cmd.args.subImage.w, cmd.args.subImage.h,
                               cmd.args.subImage.glformat, cmd.args.subImage.gltype,
                               cmd.args.subImage.data);
            break;
        case QGles2CommandBuffer::Command::CompressedImage:
1197 1198
            f->glBindTexture(cmd.args.compressedImage.dst->target, cmd.args.compressedImage.dst->texture);
            f->glCompressedTexImage2D(cmd.args.compressedImage.faceTarget, cmd.args.compressedImage.level,
1199 1200 1201 1202 1203
                                      cmd.args.compressedImage.glintformat,
                                      cmd.args.compressedImage.w, cmd.args.compressedImage.h, 0,
                                      cmd.args.compressedImage.size, cmd.args.compressedImage.data);
            break;
        case QGles2CommandBuffer::Command::CompressedSubImage:
1204 1205
            f->glBindTexture(cmd.args.compressedSubImage.dst->target, cmd.args.compressedSubImage.dst->texture);
            f->glCompressedTexSubImage2D(cmd.args.compressedSubImage.faceTarget, cmd.args.compressedSubImage.level,
1206 1207 1208 1209 1210
                                         cmd.args.compressedSubImage.dx, cmd.args.compressedSubImage.dy,
                                         cmd.args.compressedSubImage.w, cmd.args.compressedSubImage.h,
                                         cmd.args.compressedSubImage.glintformat,
                                         cmd.args.compressedSubImage.size, cmd.args.compressedSubImage.data);
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1211 1212 1213 1214 1215 1216 1217 1218 1219
        case QGles2CommandBuffer::Command::BlitFromRenderbuffer:
        {
            GLuint fbo[2];
            f->glGenFramebuffers(2, fbo);
            f->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
            f->glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                         GL_RENDERBUFFER, cmd.args.blitFromRb.renderbuffer);
            f->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
            QGles2Texture *texD = cmd.args.blitFromRb.dst;
1220 1221
            const GLenum faceTargetBase = texD->m_flags.testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
            f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, faceTargetBase + cmd.args.blitFromRb.dstLayer,
Laszlo Agocs's avatar
Laszlo Agocs committed
1222 1223 1224 1225 1226 1227 1228 1229
                                      texD->texture, cmd.args.blitFromRb.dstLevel);
            f->glBlitFramebuffer(0, 0, cmd.args.blitFromRb.w, cmd.args.blitFromRb.h,
                                 0, 0, cmd.args.blitFromRb.w, cmd.args.blitFromRb.h,
                                 GL_COLOR_BUFFER_BIT,
                                 GL_LINEAR);
            f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
        }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1230 1231 1232 1233
        case QGles2CommandBuffer::Command::GenMip:
            f->glBindTexture(cmd.args.genMip.tex->target, cmd.args.genMip.tex->texture);
            f->glGenerateMipmap(cmd.args.genMip.tex->target);
            break;
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        default:
            break;
        }
    }
}

void QRhiGles2::executeBindGraphicsPipeline(QRhiGraphicsPipeline *ps, QRhiShaderResourceBindings *srb)
{
    QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, ps);

Laszlo Agocs's avatar
Laszlo Agocs committed
1244
    if (psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
1245 1246 1247
        f->glEnable(GL_SCISSOR_TEST);
    else
        f->glDisable(GL_SCISSOR_TEST);
Laszlo Agocs's avatar
Laszlo Agocs committed
1248
    if (psD->m_cullMode == QRhiGraphicsPipeline::None) {
1249 1250 1251
        f->glDisable(GL_CULL_FACE);
    } else {
        f->glEnable(GL_CULL_FACE);
Laszlo Agocs's avatar
Laszlo Agocs committed
1252
        f->glCullFace(toGlCullMode(psD->m_cullMode));
1253
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
1254 1255 1256
    f->glFrontFace(toGlFrontFace(psD->m_frontFace));
    if (!psD->m_targetBlends.isEmpty()) {
        const QRhiGraphicsPipeline::TargetBlend &blend(psD->m_targetBlends.first()); // no MRT
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
        GLboolean wr = blend.colorWrite.testFlag(QRhiGraphicsPipeline::R);
        GLboolean wg = blend.colorWrite.testFlag(QRhiGraphicsPipeline::G);
        GLboolean wb = blend.colorWrite.testFlag(QRhiGraphicsPipeline::B);
        GLboolean wa = blend.colorWrite.testFlag(QRhiGraphicsPipeline::A);
        f->glColorMask(wr, wg, wb, wa);
        if (blend.enable) {
            f->glEnable(GL_BLEND);
            f->glBlendFuncSeparate(toGlBlendFactor(blend.srcColor),
                                   toGlBlendFactor(blend.dstColor),
                                   toGlBlendFactor(blend.srcAlpha),
                                   toGlBlendFactor(blend.dstAlpha));
            f->glBlendEquationSeparate(toGlBlendOp(blend.opColor), toGlBlendOp(blend.opAlpha));
        } else {
            f->glDisable(GL_BLEND);
        }
    } else {
        f->glDisable(GL_BLEND);
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
1275
    if (psD->m_depthTest)
1276 1277 1278
        f->glEnable(GL_DEPTH_TEST);
    else
        f->glDisable(GL_DEPTH_TEST);
Laszlo Agocs's avatar
Laszlo Agocs committed
1279
    if (psD->m_depthWrite)
1280 1281 1282
        f->glDepthMask(GL_TRUE);
    else
        f->glDepthMask(GL_FALSE);
Laszlo Agocs's avatar
Laszlo Agocs committed
1283 1284
    f->glDepthFunc(toGlCompareOp(psD->m_depthOp));
    if (psD->m_stencilTest) {
1285
        f->glEnable(GL_STENCIL_TEST);
Laszlo Agocs's avatar
Laszlo Agocs committed
1286
        f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), 0, psD->m_stencilReadMask);
1287
        f->glStencilOpSeparate(GL_FRONT,
Laszlo Agocs's avatar
Laszlo Agocs committed
1288 1289 1290 1291 1292
                               toGlStencilOp(psD->m_stencilFront.failOp),
                               toGlStencilOp(psD->m_stencilFront.depthFailOp),
                               toGlStencilOp(psD->m_stencilFront.passOp));
        f->glStencilMaskSeparate(GL_FRONT, psD->m_stencilWriteMask);
        f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), 0, psD->m_stencilReadMask);
1293
        f->glStencilOpSeparate(GL_BACK,
Laszlo Agocs's avatar
Laszlo Agocs committed
1294 1295 1296 1297
                               toGlStencilOp(psD->m_stencilBack.failOp),
                               toGlStencilOp(psD->m_stencilBack.depthFailOp),
                               toGlStencilOp(psD->m_stencilBack.passOp));
        f->glStencilMaskSeparate(GL_BACK, psD->m_stencilWriteMask);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    } else {
        f->glDisable(GL_STENCIL_TEST);
    }

    f->glUseProgram(psD->program);
    // buffer data cannot change within the pass so this time is as good to update uniforms as any
    setChangedUniforms(psD, srb, false);
}

void QRhiGles2::setChangedUniforms(QGles2GraphicsPipeline *psD, QRhiShaderResourceBindings *srb, bool changedOnly)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1309
    QGles2ShaderResourceBindings *srbD = QRHI_RES(QGles2ShaderResourceBindings, srb);
Laszlo Agocs's avatar
Laszlo Agocs committed
1310

Laszlo Agocs's avatar
Laszlo Agocs committed
1311 1312
    for (int i = 0, ie = srbD->m_bindings.count(); i != ie; ++i) {
        const QRhiShaderResourceBinding &b(srbD->m_bindings[i]);
Laszlo Agocs's avatar
Laszlo Agocs committed
1313 1314
        QGles2ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);

1315
        switch (b.type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
1316
        case QRhiShaderResourceBinding::UniformBuffer:
1317 1318 1319 1320 1321
        {
            QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, b.ubuf.buf);
            if (changedOnly && bufD->ubufChangeRange.isNull()) // do not set again when nothing changed
                break;
            const QByteArray bufView = QByteArray::fromRawData(bufD->ubuf.constData() + b.ubuf.offset,
Laszlo Agocs's avatar
Laszlo Agocs committed
1322
                                                               b.ubuf.maybeSize ? b.ubuf.maybeSize : bufD->m_size);
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
            for (QGles2GraphicsPipeline::Uniform &uniform : psD->uniforms) {
                if (uniform.binding == b.binding
                        && (!changedOnly ||
                            (uniform.offset >= uint(bufD->ubufChangeRange.changeBegin)
                             && uniform.offset < uint(bufD->ubufChangeRange.changeEnd))))
                {
                    memcpy(uniform.data.data(), bufView.constData() + uniform.offset, uniform.data.size());

                    switch (uniform.type) {
                    case QShaderDescription::Float:
                        f->glUniform1f(uniform.glslLocation, *reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Vec2:
                        f->glUniform2fv(uniform.glslLocation, 1, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Vec3:
                        f->glUniform3fv(uniform.glslLocation, 1, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Vec4:
                        f->glUniform4fv(uniform.glslLocation, 1, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Mat2:
                        f->glUniformMatrix2fv(uniform.glslLocation, 1, GL_FALSE, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Mat3:
                        f->glUniformMatrix3fv(uniform.glslLocation, 1, GL_FALSE, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Mat4:
                        f->glUniformMatrix4fv(uniform.glslLocation, 1, GL_FALSE, reinterpret_cast<const float *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Int:
                        f->glUniform1i(uniform.glslLocation, *reinterpret_cast<const qint32 *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Int2:
                        f->glUniform2iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Int3:
                        f->glUniform3iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(uniform.data.constData()));
                        break;
                    case QShaderDescription::Int4:
                        f->glUniform4iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(uniform.data.constData()));
                        break;
                    // ### more types
                    default:
                        break;
                    }
                }
            }

            bufD->ubufChangeRange = QGles2Buffer::ChangeRange();
        }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1375
        case QRhiShaderResourceBinding::SampledTexture:
1376 1377 1378 1379
        {
            QGles2Texture *texD = QRHI_RES(QGles2Texture, b.stex.tex);
            QGles2Sampler *samplerD = QRHI_RES(QGles2Sampler, b.stex.sampler);

Laszlo Agocs's avatar
Laszlo Agocs committed
1380 1381 1382 1383 1384 1385 1386
            const bool textureChanged = QRHI_RES(QGles2Texture, b.stex.tex)->generation != bd.stex.texGeneration;
            if (textureChanged)
                bd.stex.texGeneration = QRHI_RES(QGles2Texture, b.stex.tex)->generation;
            const bool samplerChanged = QRHI_RES(QGles2Sampler, b.stex.sampler)->generation != bd.stex.samplerGeneration;
            if (samplerChanged)
                bd.stex.samplerGeneration = QRHI_RES(QGles2Sampler, b.stex.sampler)->generation;

1387 1388 1389 1390 1391 1392
            int texUnit = 0;
            for (QGles2GraphicsPipeline::Sampler &sampler : psD->samplers) {
                if (sampler.binding == b.binding) {
                    f->glActiveTexture(GL_TEXTURE0 + texUnit);
                    f->glBindTexture(texD->target, texD->texture);

Laszlo Agocs's avatar
Laszlo Agocs committed
1393 1394 1395 1396 1397 1398 1399
                    if (textureChanged || samplerChanged) {
                        f->glTexParameteri(texD->target, GL_TEXTURE_MIN_FILTER, samplerD->glminfilter);
                        f->glTexParameteri(texD->target, GL_TEXTURE_MAG_FILTER, samplerD->glmagfilter);
                        f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_S, samplerD->glwraps);
                        f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_T, samplerD->glwrapt);
                        f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_R, samplerD->glwrapr);
                    }
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415

                    f->glUniform1i(sampler.glslLocation, texUnit);
                    ++texUnit;
                }
            }
            if (texUnit)
                f->glActiveTexture(GL_TEXTURE0);
        }
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }
}

1416 1417 1418 1419 1420 1421 1422 1423 1424
void QRhiGles2::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
{
    Q_ASSERT(inFrame && !inPass);

    enqueueResourceUpdates(cb, resourceUpdates);
}

void QRhiGles2::beginPass(QRhiCommandBuffer *cb,
                          QRhiRenderTarget *rt,
1425 1426 1427 1428 1429 1430 1431
                          const QRhiColorClearValue &colorClearValue,
                          const QRhiDepthStencilClearValue &depthStencilClearValue,
                          QRhiResourceUpdateBatch *resourceUpdates)
{
    Q_ASSERT(!inPass);

    if (resourceUpdates)
1432
        enqueueResourceUpdates(cb, resourceUpdates);
1433 1434 1435

    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
    bool needsColorClear = true;
1436
    bool needsDsClear = true;
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    QGles2BasicRenderTargetData *rtD = nullptr;
    QGles2CommandBuffer::Command fbCmd;
    fbCmd.cmd = QGles2CommandBuffer::Command::BindFramebuffer;
    switch (rt->type()) {
    case QRhiRenderTarget::RtRef:
        rtD = &QRHI_RES(QGles2ReferenceRenderTarget, rt)->d;
        fbCmd.args.bindFramebuffer.rt = nullptr;
        break;
    case QRhiRenderTarget::RtTexture:
    {
        QGles2TextureRenderTarget *rtTex = QRHI_RES(QGles2TextureRenderTarget, rt);
        rtD = &rtTex->d;
Laszlo Agocs's avatar
Laszlo Agocs committed
1449
        needsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
1450
        needsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
        fbCmd.args.bindFramebuffer.rt = rtTex;
    }
        break;
    default:
        Q_UNREACHABLE();
        break;
    }
    cbD->commands.append(fbCmd);

    cbD->currentTarget = rt;

    Q_ASSERT(rtD->attCount == 1 || rtD->attCount == 2);
    QGles2CommandBuffer::Command clearCmd;
    clearCmd.cmd = QGles2CommandBuffer::Command::Clear;
    clearCmd.args.clear.mask = 0;