Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qssgiblbaker.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
7#include <QFile>
8#include <QFileInfo>
9#include <QScopeGuard>
10
11#include <QtQuick3DRuntimeRender/private/qssgrhicontext_p.h>
12#include <QtQuick3DRuntimeRender/private/qssgrenderloadedtexture_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrenderbuffermanager_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrenderimagetexture_p.h>
15#include <QtQuick3DRuntimeRender/private/qssgrendershadercache_p.h>
16
17#if QT_CONFIG(opengl)
18#include <QOffscreenSurface>
19#include <QOpenGLContext>
20#endif
21
23
24#define GL_FLOAT 0x1406
25#define GL_HALF_FLOAT 0x140B
26#define GL_UNSIGNED_BYTE 0x1401
27#define GL_RGBA 0x1908
28#define GL_RGBA8 0x8058
29#define GL_RGBA16F 0x881A
30#define GL_RGBA32F 0x8814
31
33
34const QStringList QSSGIblBaker::inputExtensions() const
35{
36 return { QStringLiteral("hdr"), QStringLiteral("exr")};
37}
38
39const QString QSSGIblBaker::outputExtension() const
40{
41 return QStringLiteral(".ktx");
42}
43
44namespace {
45void writeUInt32(QIODevice &device, quint32 value)
46{
47 device.write(reinterpret_cast<char *>(&value), sizeof(qint32));
48}
49
50void appendBinaryVector(QVector<char> &dest, const quint32 src)
51{
52 qsizetype oldsize = dest.size();
53 dest.resize(dest.size() + sizeof(src));
54 memcpy(dest.data() + oldsize, &src, sizeof(src));
55}
56
57void appendBinaryVector(QVector<char> &dest, const std::string &src)
58{
59 qsizetype oldsize = dest.size();
60 dest.resize(dest.size() + src.size() + 1);
61 memcpy(dest.data() + oldsize, src.c_str(), src.size() + 1);
62}
63}
64
65QString renderToKTXFileInternal(const char *name, const QString &inPath, const QString &outPath, QRhi::Implementation impl, QRhiInitParams *initParams)
66{
67 qDebug() << "Using RHI backend" << name;
68
69 // Open output file
70 QFile ktxOutputFile(outPath);
71 if (!ktxOutputFile.open(QIODevice::WriteOnly)) {
72 return QStringLiteral("Could not open file: %1").arg(outPath);
73 }
74
75 QScopedPointer<QRhi> rhi(QRhi::create(impl, initParams, QRhi::Flags(), nullptr));
76 if (!rhi)
77 return QStringLiteral("Failed to initialize QRhi");
78
79 qDebug() << rhi->driverInfo();
80
81 QRhiCommandBuffer *cb;
82 rhi->beginOffscreenFrame(&cb);
83
84 const auto rhiContext = std::make_unique<QSSGRhiContext>(rhi.get());
85 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiContext.get());
86 rhiCtxD->setCommandBuffer(cb);
87
88 QScopedPointer<QSSGLoadedTexture> inImage(QSSGLoadedTexture::loadHdrImage(QSSGInputUtil::getStreamForFile(inPath), FORMAT));
89 if (!inImage)
90 return QStringLiteral("Failed to load hdr file");
91
92 auto shaderCache = std::make_unique<QSSGShaderCache>(*rhiContext);
93
94 QSSGRenderImageTexture envMap;
95 if (!QSSGBufferManager::createEnvironmentMap(rhiContext.get(), shaderCache.get(), inImage.get(), &envMap, inPath))
96 return QStringLiteral("Failed to generate the environment map");
97 QRhiTexture *preFilteredEnvCubeMap = envMap.m_texture;
98 if (preFilteredEnvCubeMap->format() != QRhiTexture::RGBA16F)
99 return QStringLiteral("Unexpected environment map format");
100 const QSize environmentMapSize = preFilteredEnvCubeMap->pixelSize();
101
102 // Write ktx
103
104 const quint32 numberOfMipmapLevels = envMap.m_mipmapCount;
105 const quint32 numberOfFaces = 6;
106
107 constexpr size_t KTX_IDENTIFIER_LENGTH = 12;
108 constexpr char ktxIdentifier[KTX_IDENTIFIER_LENGTH] = { '\xAB', 'K', 'T', 'X', ' ', '1',
109 '1', '\xBB', '\r', '\n', '\x1A', '\n' };
110 constexpr quint32 platformEndianIdentifier = 0x04030201;
111 QVector<char> keyValueData;
112
113 // Prepare Key/Value array
114 {
115 // Add a key to the metadata to know it was created by our IBL baker
116 static const char key[] = "QT_IBL_BAKER_VERSION";
117 static const char value[] = "1";
118
119 constexpr size_t keyAndValueByteSize = sizeof(key) + sizeof(value); // NB: 2x null terminator
120 appendBinaryVector(keyValueData, keyAndValueByteSize);
121 appendBinaryVector(keyValueData, key);
122 appendBinaryVector(keyValueData, value);
123
124 // Pad until next multiple of 4
125 const size_t padding = 3 - ((keyAndValueByteSize + 3) % 4); // Pad until next multiple of 4
126 keyValueData.resize(keyValueData.size() + padding);
127 }
128
129 // Header
130
131 // identifier
132 ktxOutputFile.write(ktxIdentifier, KTX_IDENTIFIER_LENGTH);
133
134 // endianness
135 writeUInt32(ktxOutputFile, quint32(platformEndianIdentifier));
136
137 // glType
138 writeUInt32(ktxOutputFile, quint32(GL_HALF_FLOAT));
139
140 // glTypeSize (in bytes per component)
141 writeUInt32(ktxOutputFile, quint32(FORMAT.getSizeofFormat()) / quint32(FORMAT.getNumberOfComponent()));
142
143 // glFormat
144 writeUInt32(ktxOutputFile, quint32(GL_RGBA));
145
146 // glInternalFormat
147 writeUInt32(ktxOutputFile, quint32(GL_RGBA16F));
148
149 // glBaseInternalFormat
150 writeUInt32(ktxOutputFile, quint32(GL_RGBA));
151
152 // pixelWidth
153 writeUInt32(ktxOutputFile, quint32(environmentMapSize.width()));
154
155 // pixelHeight
156 writeUInt32(ktxOutputFile, quint32(environmentMapSize.height()));
157
158 // pixelDepth
159 writeUInt32(ktxOutputFile, quint32(0));
160
161 // numberOfArrayElements
162 writeUInt32(ktxOutputFile, quint32(0));
163
164 // numberOfFaces
165 writeUInt32(ktxOutputFile, quint32(numberOfFaces));
166
167 // numberOfMipLevels
168 writeUInt32(ktxOutputFile, quint32(numberOfMipmapLevels));
169
170 // bytesOfKeyValueData
171 writeUInt32(ktxOutputFile, quint32(keyValueData.size()));
172
173 // Key/Value
174 ktxOutputFile.write(keyValueData.data(), keyValueData.size());
175
176 // Images
177 for (quint32 mipmap_level = 0; mipmap_level < numberOfMipmapLevels; mipmap_level++) {
178 quint32 imageSize = 0;
179 for (size_t face = 0; face < numberOfFaces; face++) {
180 // Read back texture
181 Q_ASSERT(rhi->isRecordingFrame());
182
183 QRhiReadbackResult result;
184 QRhiReadbackDescription readbackDesc(preFilteredEnvCubeMap);
185 readbackDesc.setLayer(int(face));
186 readbackDesc.setLevel(mipmap_level);
187
188 QRhiResourceUpdateBatch *resourceUpdates = rhi->nextResourceUpdateBatch();
189 resourceUpdates->readBackTexture(readbackDesc, &result);
190
191 cb->resourceUpdate(resourceUpdates);
192 rhi->finish(); // make sure the readback has finished, stall the pipeline if needed
193
194 // Write imageSize once size is known
195 if (imageSize == 0) {
196 imageSize = result.data.size();
197 writeUInt32(ktxOutputFile, quint32(imageSize));
198 }
199
200 ktxOutputFile.write(result.data);
201 }
202 }
203
204 ktxOutputFile.close();
205
206 preFilteredEnvCubeMap->deleteLater();
207
208 rhi->endOffscreenFrame();
209 rhi->finish();
210
211 return {};
212}
213
214void adjustToPlatformQuirks(QRhi::Implementation &impl)
215{
216#if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
217 // A macOS VM may not have Metal support at all. We have to decide at this
218 // point, it will be too late afterwards, and the only way is to see if
219 // MTLCreateSystemDefaultDevice succeeds.
220 if (impl == QRhi::Metal) {
221 QRhiMetalInitParams rhiParams;
222 QRhi *tempRhi = QRhi::create(impl, &rhiParams, {});
223 if (!tempRhi) {
224 impl = QRhi::OpenGLES2;
225 qDebug("Metal does not seem to be supported. Falling back to OpenGL.");
226 } else {
227 delete tempRhi;
228 }
229 }
230#else
231 Q_UNUSED(impl);
232#endif
233}
234
236{
237 QRhi::Implementation implementation = QRhi::Implementation::Null;
238
239 // check env.vars., fall back to platform-specific defaults when backend is not set
240 const QByteArray rhiBackend = qgetenv("QSG_RHI_BACKEND");
241 if (rhiBackend == QByteArrayLiteral("gl") || rhiBackend == QByteArrayLiteral("gles2")
242 || rhiBackend == QByteArrayLiteral("opengl")) {
243 implementation = QRhi::OpenGLES2;
244 } else if (rhiBackend == QByteArrayLiteral("d3d11") || rhiBackend == QByteArrayLiteral("d3d")) {
245 implementation = QRhi::D3D11;
246 } else if (rhiBackend == QByteArrayLiteral("d3d12")) {
247 implementation = QRhi::D3D12;
248 } else if (rhiBackend == QByteArrayLiteral("vulkan")) {
249 implementation = QRhi::Vulkan;
250 } else if (rhiBackend == QByteArrayLiteral("metal")) {
251 implementation = QRhi::Metal;
252 } else if (rhiBackend == QByteArrayLiteral("null")) {
253 implementation = QRhi::Null;
254 } else {
255 if (!rhiBackend.isEmpty()) {
256 qWarning("Unknown key \"%s\" for QSG_RHI_BACKEND, falling back to default backend.", rhiBackend.constData());
257 }
258#if defined(Q_OS_WIN)
259 implementation = QRhi::D3D11;
260#elif defined(Q_OS_MACOS) || defined(Q_OS_IOS)
261 implementation = QRhi::Metal;
262#elif QT_CONFIG(opengl)
263 implementation = QRhi::OpenGLES2;
264#else
265 implementation = QRhi::Vulkan;
266#endif
267 }
268
269 adjustToPlatformQuirks(implementation);
270
271 return implementation;
272}
273
274QString renderToKTXFile(const QString &inPath, const QString &outPath)
275{
276 const auto rhiImplementation = getRhiImplementation();
277
278#if QT_CONFIG(opengl)
279 if (rhiImplementation == QRhi::OpenGLES2) {
280 QRhiGles2InitParams params;
281 if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) {
282 // OpenGL 3.2 or higher
283 params.format.setProfile(QSurfaceFormat::CoreProfile);
284 params.format.setVersion(3, 2);
285 } else {
286 // OpenGL ES 3.0 or higher
287 params.format.setVersion(3, 0);
288 }
289 params.fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
290 const QString result = renderToKTXFileInternal("OpenGL", inPath, outPath, QRhi::OpenGLES2, &params);
291 delete params.fallbackSurface;
292 return result;
293 }
294#endif
295
296#if QT_CONFIG(vulkan)
297 if (rhiImplementation == QRhi::Vulkan) {
298 QVulkanInstance vulkanInstance;
299 vulkanInstance.create();
300 QRhiVulkanInitParams params;
301 params.inst = &vulkanInstance;
302 return renderToKTXFileInternal("Vulkan", inPath, outPath, QRhi::Vulkan, &params);
303 }
304#endif
305
306#ifdef Q_OS_WIN
307 if (rhiImplementation == QRhi::D3D11) {
308 QRhiD3D11InitParams params;
309 return renderToKTXFileInternal("Direct3D 11", inPath, outPath, QRhi::D3D11, &params);
310 } else if (rhiImplementation == QRhi::D3D12) {
311 QRhiD3D12InitParams params;
312 return renderToKTXFileInternal("Direct3D 12", inPath, outPath, QRhi::D3D12, &params);
313 }
314#endif
315
316#if QT_CONFIG(metal)
317 if (rhiImplementation == QRhi::Metal) {
318 QRhiMetalInitParams params;
319 return renderToKTXFileInternal("Metal", inPath, outPath, QRhi::Metal, &params);
320 }
321#endif
322
323 return QStringLiteral("No RHI backend");
324}
325
326const QString QSSGIblBaker::import(const QString &sourceFile, const QDir &savePath, QStringList *generatedFiles)
327{
328 qDebug() << "IBL lightprobe baker" << sourceFile;
329
330 QString outFileName = savePath.absoluteFilePath(QFileInfo(sourceFile).baseName() + QStringLiteral(".ktx"));
331
332 QString error = renderToKTXFile(sourceFile, outFileName);
333 if (!error.isEmpty())
334 return error;
335
336 m_generatedFiles.append(outFileName);
337
338 if (generatedFiles)
339 *generatedFiles = m_generatedFiles;
340
341 return QString();
342}
343
344QT_END_NAMESPACE
Combined button and popup list for selecting options.
#define GL_RGBA16F
Definition qopenglext.h:913
#define GL_HALF_FLOAT
void adjustToPlatformQuirks(QRhi::Implementation &impl)
QRhi::Implementation getRhiImplementation()
QString renderToKTXFile(const QString &inPath, const QString &outPath)
QString renderToKTXFileInternal(const char *name, const QString &inPath, const QString &outPath, QRhi::Implementation impl, QRhiInitParams *initParams)
static constexpr QSSGRenderTextureFormat FORMAT(QSSGRenderTextureFormat::RGBA16F)
#define GL_RGBA