Commit d98468e2 authored by Laszlo Agocs's avatar Laszlo Agocs

gl: implement begin/endOffscreenFrame

parent 72a476b3
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** 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 https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QGuiApplication>
#include <QImage>
#include <QFileInfo>
#include <QFile>
#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QBakedShader>
#include <QRhiGles2InitParams>
static float vertexData[] = { // Y up (note m_proj), CCW
0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.0f, 0.0f, 1.0f,
};
static QBakedShader getShader(const QString &name)
{
QFile f(name);
if (f.open(QIODevice::ReadOnly))
return QBakedShader::fromSerialized(f.readAll());
return QBakedShader();
}
int main(int argc, char **argv)
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QOpenGLContext context;
if (!context.create())
qFatal("Failed to get OpenGL context");
QOffscreenSurface offscreenSurface;
offscreenSurface.setFormat(context.format());
offscreenSurface.create();
QRhiGles2InitParams params;
params.context = &context;
params.fallbackSurface = &offscreenSurface;
QRhi *r = QRhi::create(QRhi::OpenGLES2, &params);
if (!r) {
qWarning("Failed to initialize RHI");
return 1;
}
QRhiTexture *tex = r->newTexture(QRhiTexture::RGBA8, QSize(1280, 720), QRhiTexture::RenderTarget | QRhiTexture::ReadBack);
tex->build();
QRhiTextureRenderTarget *rt = r->newTextureRenderTarget({ tex });
QRhiRenderPassDescriptor *rp = rt->newCompatibleRenderPassDescriptor();
rt->setRenderPassDescriptor(rp);
rt->build();
QMatrix4x4 proj = r->clipSpaceCorrMatrix();
proj.perspective(45.0f, 1280 / 720.f, 0.01f, 1000.0f);
proj.translate(0, 0, -4);
QRhiBuffer *vbuf = r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
vbuf->build();
QRhiBuffer *ubuf = r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 68);
ubuf->build();
QRhiShaderResourceBindings *srb = r->newShaderResourceBindings();
srb->setBindings({
QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
});
srb->build();
QRhiGraphicsPipeline *ps = r->newGraphicsPipeline();
QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
premulAlphaBlend.enable = true;
ps->setTargetBlends({ premulAlphaBlend });
const QBakedShader vs = getShader(QLatin1String(":/color.vert.qsb"));
if (!vs.isValid())
qFatal("Failed to load shader pack (vertex)");
const QBakedShader fs = getShader(QLatin1String(":/color.frag.qsb"));
if (!fs.isValid())
qFatal("Failed to load shader pack (fragment)");
ps->setShaderStages({
{ QRhiGraphicsShaderStage::Vertex, vs },
{ QRhiGraphicsShaderStage::Fragment, fs }
});
QRhiVertexInputLayout inputLayout;
inputLayout.bindings = {
{ 5 * sizeof(float) }
};
inputLayout.attributes = {
{ 0, 0, QRhiVertexInputLayout::Attribute::Float2, 0 },
{ 0, 1, QRhiVertexInputLayout::Attribute::Float3, 2 * sizeof(float) }
};
ps->setVertexInputLayout(inputLayout);
ps->setShaderResourceBindings(srb);
ps->setRenderPassDescriptor(rp);
ps->build();
for (int frame = 0; frame < 20; ++frame) {
QRhiCommandBuffer *cb;
if (r->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
break;
qDebug("Generating offscreen frame %d", frame);
QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
if (frame == 0)
u->uploadStaticBuffer(vbuf, vertexData);
static float rotation = 0.0f;
QMatrix4x4 mvp = proj;
mvp.rotate(rotation, 0, 1, 0);
u->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
rotation += 5.0f;
static float opacity = 1.0f;
static int opacityDir= 1;
u->updateDynamicBuffer(ubuf, 64, 4, &opacity);
opacity += opacityDir * 0.005f;
if (opacity < 0.0f || opacity > 1.0f) {
opacityDir *= -1;
opacity = qBound(0.0f, opacity, 1.0f);
}
r->beginPass(rt, cb, { 0, 1, 0, 1 }, { 1, 0 }, u);
r->setGraphicsPipeline(cb, ps);
r->setViewport(cb, { 0, 0, 1280, 720 });
r->setVertexInput(cb, 0, { { vbuf, 0 } });
r->draw(cb, 3);
r->endPass(cb);
QRhiReadbackDescription rb(tex);
QRhiReadbackResult rbResult;
rbResult.completed = [frame] { qDebug(" - readback %d completed", frame); };
r->readback(cb, rb, &rbResult);
qDebug("Submit and wait");
r->endOffscreenFrame();
// No finish() or waiting for the completed callback is needed here
// since the endOffscreenFrame() implies a wait for completion.
if (!rbResult.data.isEmpty()) {
const uchar *p = reinterpret_cast<const uchar *>(rbResult.data.constData());
QImage image(p, rbResult.pixelSize.width(), rbResult.pixelSize.height(), QImage::Format_RGBA8888);
QString fn = QString::asprintf("frame%d.png", frame);
fn = QFileInfo(fn).absoluteFilePath();
qDebug("Saving into %s", qPrintable(fn));
image.save(fn);
} else {
qWarning("Readback failed!");
}
}
ps->releaseAndDestroy();
srb->releaseAndDestroy();
ubuf->releaseAndDestroy();
vbuf->releaseAndDestroy();
rt->releaseAndDestroy();
rp->releaseAndDestroy();
tex->releaseAndDestroy();
delete r;
return 0;
}
TEMPLATE = app
CONFIG += console
QT += shadertools rhi
SOURCES = \
main.cpp
RESOURCES = offscreen_gles2.qrc
target.path = $$[QT_INSTALL_EXAMPLES]/rhi/offscreen_gles2
INSTALLS += target
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="color.vert.qsb">../shared/color.vert.qsb</file>
<file alias="color.frag.qsb">../shared/color.frag.qsb</file>
</qresource>
</RCC>
......@@ -3,7 +3,8 @@ TEMPLATE = subdirs
SUBDIRS += \
hellominimalcrossgfxtriangle \
compressedtexture_bc1 \
plainqwindow_gles2
plainqwindow_gles2 \
offscreen_gles2
qtConfig(vulkan) {
SUBDIRS += \
......
......@@ -56,6 +56,7 @@ QT_BEGIN_NAMESPACE
*/
QRhiGles2::QRhiGles2(QRhiInitParams *params)
: ofr(this)
{
QRhiGles2InitParams *glparams = static_cast<QRhiGles2InitParams *>(params);
ctx = glparams->context;
......@@ -70,7 +71,7 @@ QRhiGles2::~QRhiGles2()
destroy();
}
void QRhiGles2::ensureContext(QSurface *surface)
bool QRhiGles2::ensureContext(QSurface *surface)
{
bool nativeWindowGone = false;
if (surface && surface->surfaceClass() == QSurface::Window && !surface->surfaceHandle()) {
......@@ -84,10 +85,14 @@ void QRhiGles2::ensureContext(QSurface *surface)
if (buffersSwapped)
buffersSwapped = false;
else if (!nativeWindowGone && QOpenGLContext::currentContext() == ctx && (surface == fallbackSurface || ctx->surface() == surface))
return;
return true;
if (!ctx->makeCurrent(surface))
if (!ctx->makeCurrent(surface)) {
qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen.");
return false;
}
return true;
}
void QRhiGles2::create()
......@@ -371,8 +376,11 @@ QRhi::FrameOpResult QRhiGles2::beginFrame(QRhiSwapChain *swapChain)
Q_ASSERT(!inFrame);
QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
ensureContext(swapChainD->surface);
if (!ensureContext(swapChainD->surface))
return QRhi::FrameOpError;
inFrame = true;
currentSwapChain = swapChainD;
executeDeferredReleases();
QRHI_RES(QGles2CommandBuffer, &swapChainD->cb)->resetState();
......@@ -383,12 +391,15 @@ QRhi::FrameOpResult QRhiGles2::beginFrame(QRhiSwapChain *swapChain)
QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain)
{
Q_ASSERT(inFrame);
inFrame = false;
QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
ensureContext(swapChainD->surface);
if (!ensureContext(swapChainD->surface))
return QRhi::FrameOpError;
executeCommandBuffer(&swapChainD->cb);
inFrame = false;
currentSwapChain = nullptr;
++finishedFrameCount;
if (swapChainD->surface) {
......@@ -401,13 +412,34 @@ QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain)
QRhi::FrameOpResult QRhiGles2::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
Q_UNUSED(cb);
return QRhi::FrameOpError;
Q_ASSERT(!inFrame);
if (!ensureContext())
return QRhi::FrameOpError;
inFrame = true;
ofr.active = true;
executeDeferredReleases();
ofr.cbWrapper.resetState();
*cb = &ofr.cbWrapper;
return QRhi::FrameOpSuccess;
}
QRhi::FrameOpResult QRhiGles2::endOffscreenFrame()
{
return QRhi::FrameOpError;
Q_ASSERT(inFrame && ofr.active);
inFrame = false;
ofr.active = false;
if (!ensureContext())
return QRhi::FrameOpError;
executeCommandBuffer(&ofr.cbWrapper);
++finishedFrameCount;
return QRhi::FrameOpSuccess;;
}
bool QRhiGles2::readback(QRhiCommandBuffer *cb, const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
......@@ -424,7 +456,21 @@ bool QRhiGles2::readback(QRhiCommandBuffer *cb, const QRhiReadbackDescription &r
QRhi::FrameOpResult QRhiGles2::finish()
{
Q_ASSERT(!inPass);
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();
}
}
return QRhi::FrameOpSuccess;
}
......@@ -1112,7 +1158,8 @@ bool QGles2Buffer::build()
return true;
}
rhiD->ensureContext();
if (!rhiD->ensureContext())
return false;
if (m_usage.testFlag(QRhiBuffer::VertexBuffer))
target = GL_ARRAY_BUFFER;
......@@ -1158,7 +1205,8 @@ bool QGles2RenderBuffer::build()
if (m_hints.testFlag(ToBeUsedWithSwapChainOnly))
return true;
rhiD->ensureContext();
if (!rhiD->ensureContext())
return false;
rhiD->f->glGenRenderbuffers(1, &renderbuffer);
rhiD->f->glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
......@@ -1208,7 +1256,8 @@ bool QGles2Texture::build()
if (texture)
release();
rhiD->ensureContext();
if (!rhiD->ensureContext())
return false;
const QSize size = safeSize(m_pixelSize);
// ### adjust size for npot when repeat with npot is not supported?
......@@ -1340,7 +1389,8 @@ bool QGles2TextureRenderTarget::build()
if (m_desc.depthTexture)
qWarning("QGles2TextureRenderTarget: Depth texture is not supported and will be ignored");
rhiD->ensureContext();
if (!rhiD->ensureContext())
return false;
rhiD->f->glGenFramebuffers(1, &framebuffer);
rhiD->f->glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
......@@ -1428,7 +1478,8 @@ bool QGles2GraphicsPipeline::build()
if (program)
release();
rhiD->ensureContext();
if (!rhiD->ensureContext())
return false;
drawMode = toGlTopology(m_topology);
......
......@@ -273,8 +273,12 @@ struct QGles2CommandBuffer : public QRhiCommandBuffer
QRhiShaderResourceBindings *currentSrb;
uint currentSrbGeneration;
void resetState() {
void resetCommands() {
commands.clear();
}
void resetState() {
resetCommands();
currentTarget = nullptr;
currentPipeline = nullptr;
currentPipelineGeneration = 0;
......@@ -371,7 +375,7 @@ public:
QMatrix4x4 clipSpaceCorrMatrix() const override;
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override;
void ensureContext(QSurface *surface = nullptr);
bool ensureContext(QSurface *surface = nullptr);
void create();
void destroy();
void executeDeferredReleases();
......@@ -388,6 +392,7 @@ public:
bool inFrame = false;
int finishedFrameCount = 0;
bool inPass = false;
QGles2SwapChain *currentSwapChain = nullptr;
struct DeferredReleaseEntry {
enum Type {
......@@ -417,6 +422,12 @@ public:
};
};
QVector<DeferredReleaseEntry> releaseQueue;
struct OffscreenFrame {
OffscreenFrame(QRhiImplementation *rhi) : cbWrapper(rhi) { }
bool active = false;
QGles2CommandBuffer cbWrapper;
} ofr;
};
Q_DECLARE_TYPEINFO(QRhiGles2::DeferredReleaseEntry, Q_MOVABLE_TYPE);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment