Debian Codegraph @

tests/manual/rhi/offscreen/offscreen.cpp

raw
1 // Copyright (C) 2018 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 #include <QGuiApplication>
5 #include <QImage>
6 #include <QFileInfo>
7 #include <QFile>
8 #include <QLoggingCategory>
9 #include <QCommandLineParser>
10 #include <QLoggingCategory>
11 #include <QOffscreenSurface>
12
13 #include <rhi/qrhi.h>
14
15 //#define TEST_FINISH
16
17 static float vertexData[] = { // Y up (note m_proj), CCW
18 0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
19 -0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
20 0.5f, -0.5f, 0.0f, 0.0f, 1.0f,
21 };
22
23 static QShader getShader(const QString &name)
24 {
25 QFile f(name);
26 if (f.open(QIODevice::ReadOnly))
27 return QShader::fromSerialized(f.readAll());
28
29 return QShader();
30 }
31
32 enum GraphicsApi
33 {
34 OpenGL,
35 Vulkan,
36 D3D11,
37 D3D12,
38 Metal,
39 Null
40 };
41
42 GraphicsApi graphicsApi;
43
44 QString graphicsApiName()
45 {
46 switch (graphicsApi) {
47 case OpenGL:
48 return QLatin1String("OpenGL 2.x");
49 case Vulkan:
50 return QLatin1String("Vulkan");
51 case D3D11:
52 return QLatin1String("Direct3D 11");
53 case D3D12:
54 return QLatin1String("Direct3D 12");
55 case Metal:
56 return QLatin1String("Metal");
57 case Null:
58 return QLatin1String("Null");
59 default:
60 break;
61 }
62 return QString();
63 }
64
65 int main(int argc, char **argv)
66 {
67 QGuiApplication app(argc, argv);
68
69 #if defined(Q_OS_WIN)
70 graphicsApi = D3D11;
71 #elif QT_CONFIG(metal)
72 graphicsApi = Metal;
73 #elif QT_CONFIG(vulkan)
74 graphicsApi = Vulkan;
75 #else
76 graphicsApi = OpenGL;
77 #endif
78
79 QCommandLineParser cmdLineParser;
80 cmdLineParser.addHelpOption();
81 QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL (2.x)"));
82 cmdLineParser.addOption(glOption);
83 QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
84 cmdLineParser.addOption(vkOption);
85 QCommandLineOption d3d11Option({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
86 cmdLineParser.addOption(d3d11Option);
87 QCommandLineOption d3d12Option({ "D", "d3d12" }, QLatin1String("Direct3D 12"));
88 cmdLineParser.addOption(d3d12Option);
89 QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
90 cmdLineParser.addOption(mtlOption);
91 QCommandLineOption nullOption({ "n", "null" }, QLatin1String("Null"));
92 cmdLineParser.addOption(nullOption);
93 cmdLineParser.process(app);
94 if (cmdLineParser.isSet(glOption))
95 graphicsApi = OpenGL;
96 if (cmdLineParser.isSet(vkOption))
97 graphicsApi = Vulkan;
98 if (cmdLineParser.isSet(d3d11Option))
99 graphicsApi = D3D11;
100 if (cmdLineParser.isSet(d3d12Option))
101 graphicsApi = D3D12;
102 if (cmdLineParser.isSet(mtlOption))
103 graphicsApi = Metal;
104 if (cmdLineParser.isSet(nullOption))
105 graphicsApi = Null;
106
107 qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
108 qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));
109
110 QRhi *r = nullptr;
111 QRhi::Flags rhiFlags = QRhi::EnableTimestamps;
112
113 if (graphicsApi == Null) {
114 QRhiNullInitParams params;
115 r = QRhi::create(QRhi::Null, &params, rhiFlags);
116 }
117
118 #if QT_CONFIG(vulkan)
119 QVulkanInstance inst;
120 if (graphicsApi == Vulkan) {
121 QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true"));
122 inst.setLayers({ "VK_LAYER_KHRONOS_validation" });
123 inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
124 if (inst.create()) {
125 QRhiVulkanInitParams params;
126 params.inst = &inst;
127 r = QRhi::create(QRhi::Vulkan, &params, rhiFlags);
128 } else {
129 qWarning("Failed to create Vulkan instance, switching to OpenGL");
130 graphicsApi = OpenGL;
131 }
132 }
133 #endif
134
135 #ifndef QT_NO_OPENGL
136 QScopedPointer<QOffscreenSurface> offscreenSurface;
137 if (graphicsApi == OpenGL) {
138 offscreenSurface.reset(QRhiGles2InitParams::newFallbackSurface());
139 QRhiGles2InitParams params;
140 params.fallbackSurface = offscreenSurface.data();
141 r = QRhi::create(QRhi::OpenGLES2, &params, rhiFlags);
142 }
143 #endif
144
145 #ifdef Q_OS_WIN
146 if (graphicsApi == D3D11) {
147 QRhiD3D11InitParams params;
148 params.enableDebugLayer = true;
149 r = QRhi::create(QRhi::D3D11, &params, rhiFlags);
150 } else if (graphicsApi == D3D12) {
151 QRhiD3D12InitParams params;
152 params.enableDebugLayer = true;
153 r = QRhi::create(QRhi::D3D12, &params, rhiFlags);
154 }
155 #endif
156
157 #if QT_CONFIG(metal)
158 if (graphicsApi == Metal) {
159 QRhiMetalInitParams params;
160 r = QRhi::create(QRhi::Metal, &params, rhiFlags);
161 }
162 #endif
163
164 if (!r)
165 qFatal("Failed to initialize RHI");
166
167 QRhiTexture *tex = r->newTexture(QRhiTexture::RGBA8, QSize(1280, 720), 1, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
168 tex->create();
169 QRhiTextureRenderTarget *rt = r->newTextureRenderTarget({ tex });
170 QRhiRenderPassDescriptor *rp = rt->newCompatibleRenderPassDescriptor();
171 rt->setRenderPassDescriptor(rp);
172 rt->create();
173
174 QMatrix4x4 proj = r->clipSpaceCorrMatrix();
175 proj.perspective(45.0f, 1280 / 720.f, 0.01f, 1000.0f);
176 proj.translate(0, 0, -4);
177
178 QRhiBuffer *vbuf = r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
179 vbuf->create();
180
181 QRhiBuffer *ubuf = r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 68);
182 ubuf->create();
183
184 QRhiShaderResourceBindings *srb = r->newShaderResourceBindings();
185 srb->setBindings({
186 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
187 });
188 srb->create();
189
190 QRhiGraphicsPipeline *ps = r->newGraphicsPipeline();
191
192 QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
193 premulAlphaBlend.enable = true;
194 ps->setTargetBlends({ premulAlphaBlend });
195
196 const QShader vs = getShader(QLatin1String(":/color.vert.qsb"));
197 if (!vs.isValid())
198 qFatal("Failed to load shader pack (vertex)");
199 const QShader fs = getShader(QLatin1String(":/color.frag.qsb"));
200 if (!fs.isValid())
201 qFatal("Failed to load shader pack (fragment)");
202
203 ps->setShaderStages({
204 { QRhiShaderStage::Vertex, vs },
205 { QRhiShaderStage::Fragment, fs }
206 });
207
208 QRhiVertexInputLayout inputLayout;
209 inputLayout.setBindings({
210 { 5 * sizeof(float) }
211 });
212 inputLayout.setAttributes({
213 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
214 { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
215 });
216
217 ps->setVertexInputLayout(inputLayout);
218 ps->setShaderResourceBindings(srb);
219 ps->setRenderPassDescriptor(rp);
220 ps->create();
221
222 int frame = 0;
223 for (; frame < 20; ++frame) {
224 QRhiCommandBuffer *cb;
225 if (r->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
226 break;
227
228 qDebug("Generating offscreen frame %d", frame);
229 QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
230 if (frame == 0)
231 u->uploadStaticBuffer(vbuf, vertexData);
232
233 static float rotation = 0.0f;
234 QMatrix4x4 mvp = proj;
235 mvp.rotate(rotation, 0, 1, 0);
236 u->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
237 rotation += 5.0f;
238 static float opacity = 1.0f;
239 static int opacityDir= 1;
240 u->updateDynamicBuffer(ubuf, 64, 4, &opacity);
241 opacity += opacityDir * 0.005f;
242 if (opacity < 0.0f || opacity > 1.0f) {
243 opacityDir *= -1;
244 opacity = qBound(0.0f, opacity, 1.0f);
245 }
246
247 cb->beginPass(rt, QColor::fromRgbF(0.0f, 1.0f, 0.0f, 1.0f), { 1, 0 }, u);
248 cb->setGraphicsPipeline(ps);
249 cb->setViewport({ 0, 0, 1280, 720 });
250 cb->setShaderResources();
251 const QRhiCommandBuffer::VertexInput vbufBinding(vbuf, 0);
252 cb->setVertexInput(0, 1, &vbufBinding);
253 cb->draw(3);
254
255 u = r->nextResourceUpdateBatch();
256 QRhiReadbackDescription rb(tex);
257 QRhiReadbackResult rbResult;
258 rbResult.completed = [frame] { qDebug(" - readback %d completed", frame); };
259 u->readBackTexture(rb, &rbResult);
260
261 cb->endPass(u);
262
263 qDebug("Submit and wait");
264 #ifdef TEST_FINISH
265 r->finish();
266 #else
267 r->endOffscreenFrame();
268 #endif
269 // The data should be ready either because endOffscreenFrame() waits
270 // for completion or because finish() did.
271 if (!rbResult.data.isEmpty()) {
272 const uchar *p = reinterpret_cast<const uchar *>(rbResult.data.constData());
273 QImage image(p, rbResult.pixelSize.width(), rbResult.pixelSize.height(), QImage::Format_RGBA8888);
274 QString fn = QString::asprintf("frame%d.png", frame);
275 fn = QFileInfo(fn).absoluteFilePath();
276 qDebug("Saving into %s", qPrintable(fn));
277 if (r->isYUpInFramebuffer())
278 image.flipped().save(fn);
279 else
280 image.save(fn);
281 } else {
282 qWarning("Readback failed!");
283 }
284 #ifdef TEST_FINISH
285 r->endOffscreenFrame();
286 #endif
287 if (r->isFeatureSupported(QRhi::Timestamps))
288 qDebug() << "GPU time:" << cb->lastCompletedGpuTime() << "seconds (may refer to a previous frame)";
289 }
290
291 delete ps;
292 delete srb;
293 delete ubuf;
294 delete vbuf;
295
296 delete rt;
297 delete rp;
298 delete tex;
299
300 delete r;
301
302 qDebug("\nRendered and read back %d frames using %s", frame, qPrintable(graphicsApiName()));
303
304 return 0;
305 }