Debian Codegraph @

tests/manual/rhi/vrs/vrs.cpp

raw
1 // Copyright (C) 2024 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 #define EXAMPLEFW_IMGUI
5 #define EXAMPLEFW_BEFORE_FRAME
6 #include "../shared/examplefw.h"
7
8 #include "../shared/cube.h"
9
10 #include <QPainter>
11 #include <QRandomGenerator>
12
13 #if QT_CONFIG(metal)
14 void *makeRateMap(QRhi *rhi, const QSize &outputSizeInPixels);
15 void releaseRateMap(void *map);
16 #endif
17
18 const int CUBE_COUNT = 10;
19
20 struct {
21 QMatrix4x4 winProj;
22 QList<QRhiResource *> releasePool;
23 QRhiResourceUpdateBatch *initialUpdates = nullptr;
24 QRhiBuffer *vbuf = nullptr;
25 QRhiBuffer *ubuf = nullptr;
26 QRhiTexture *tex = nullptr;
27 QRhiSampler *sampler = nullptr;
28 QRhiShaderResourceBindings *srb = nullptr;
29 QRhiGraphicsPipeline *ps = nullptr;
30 bool showDemoWindow = true;
31 float rotation = 35.0f;
32 bool vrsSupported = false;
33 bool vrsMapSupported = false;
34 bool vrsMapImageSupported = false;
35 QMap<int, QList<QSize>> supportedShadingRates;
36 int cps[2] = {};
37 bool applyRateMapWithImage = false;
38 bool applyRateMapNative = false;
39 bool applyRateMapPending = false;
40 QRhiShadingRateMap *rateMap = nullptr;
41 QRhiRenderPassDescriptor *scRpWithRateMap = nullptr;
42 QRhiTexture *rateMapTexture = nullptr;
43 QRhiTexture *rateMapTextureForVisualization = nullptr;
44 void *nativeRateMap = nullptr;
45 QSize nativeRateMapSize;
46 QVector<float> tx;
47 QVector<float> ty;
48 QVector<float> scale;
49 quint32 ubufAlignedSize;
50
51 bool textureBased = false;
52 QRhiTexture *outTexture = nullptr;
53 QRhiTextureRenderTarget *texRt = nullptr;
54 QRhiRenderPassDescriptor *texRtRp = nullptr;
55 QRhiRenderPassDescriptor *texRtRpWithRateMap = nullptr;
56 } d;
57
58 void Window::customInit()
59 {
60 d.vrsSupported = m_r->isFeatureSupported(QRhi::VariableRateShading);
61 d.vrsMapSupported = m_r->isFeatureSupported(QRhi::VariableRateShadingMap);
62 d.vrsMapImageSupported = m_r->isFeatureSupported(QRhi::VariableRateShadingMapWithTexture);
63 for (int sampleCount : { 1, 2, 4, 8, 16 })
64 d.supportedShadingRates.insert(sampleCount, m_r->supportedShadingRates(sampleCount));
65
66 d.initialUpdates = m_r->nextResourceUpdateBatch();
67
68 d.vbuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(cube));
69 d.vbuf->create();
70 d.releasePool << d.vbuf;
71
72 d.initialUpdates->uploadStaticBuffer(d.vbuf, cube);
73
74 d.ubufAlignedSize = m_r->ubufAligned(68);
75 const quint32 ubufSize = d.ubufAlignedSize * CUBE_COUNT;
76 d.ubuf = m_r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, ubufSize);
77 d.ubuf->create();
78 d.releasePool << d.ubuf;
79
80 QImage image = QImage(QLatin1String(":/qt256.png")).convertToFormat(QImage::Format_RGBA8888).flipped();
81 d.tex = m_r->newTexture(QRhiTexture::RGBA8, QSize(image.width(), image.height()), 1, {});
82 d.releasePool << d.tex;
83 d.tex->create();
84 d.initialUpdates->uploadTexture(d.tex, image);
85
86 d.sampler = m_r->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
87 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
88 d.releasePool << d.sampler;
89 d.sampler->create();
90
91 d.srb = m_r->newShaderResourceBindings();
92 d.releasePool << d.srb;
93 d.srb->setBindings({
94 QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf, 68),
95 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, d.tex, d.sampler)
96 });
97 d.srb->create();
98
99 d.ps = m_r->newGraphicsPipeline();
100 d.releasePool << d.ps;
101
102 d.ps->setFlags(QRhiGraphicsPipeline::UsesShadingRate);
103
104 d.ps->setCullMode(QRhiGraphicsPipeline::Back);
105 const QRhiShaderStage stages[] = {
106 { QRhiShaderStage::Vertex, getShader(QLatin1String(":/texture.vert.qsb")) },
107 { QRhiShaderStage::Fragment, getShader(QLatin1String(":/texture.frag.qsb")) }
108 };
109 d.ps->setShaderStages(stages, stages + 2);
110 QRhiVertexInputLayout inputLayout;
111 inputLayout.setBindings({
112 { 3 * sizeof(float) },
113 { 2 * sizeof(float) }
114 });
115 inputLayout.setAttributes({
116 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
117 { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
118 });
119 d.ps->setVertexInputLayout(inputLayout);
120 d.ps->setShaderResourceBindings(d.srb);
121 d.ps->setRenderPassDescriptor(m_rp);
122 d.ps->create();
123
124 // resources for trying out rendering into a texture
125 d.outTexture = m_r->newTexture(QRhiTexture::RGBA8, QSize(1024, 1024), 1, QRhiTexture::RenderTarget);
126 d.releasePool << d.outTexture;
127 d.outTexture->create();
128
129 d.texRt = m_r->newTextureRenderTarget({ d.outTexture });
130 d.releasePool << d.texRt;
131 d.texRtRp = d.texRt->newCompatibleRenderPassDescriptor();
132 d.releasePool << d.texRtRp;
133 d.texRt->setRenderPassDescriptor(d.texRtRp);
134 d.texRt->create();
135
136 QRandomGenerator *rg = QRandomGenerator::global();
137 for (int i = 0; i < CUBE_COUNT; i++) {
138 d.tx.append(rg->bounded(-20, 20) / 10.0f);
139 d.ty.append(rg->bounded(-20, 20) / 10.0f);
140 d.scale.append(rg->bounded(0, 10) / 10.0f);
141 }
142 }
143
144 void Window::customRelease()
145 {
146 qDeleteAll(d.releasePool);
147 d.releasePool.clear();
148
149 #if QT_CONFIG(metal)
150 if (d.nativeRateMap)
151 releaseRateMap(d.nativeRateMap);
152 #endif
153 }
154
155 void Window::customBeforeFrame()
156 {
157 // This function is invoked before calling rhi->beginFrame().
158 // Thus it is suitable to do things that involve rebuilding render target related things.
159
160 if (d.applyRateMapPending) {
161 d.applyRateMapPending = false;
162 if (d.applyRateMapWithImage || d.applyRateMapNative) {
163 if (d.textureBased) {
164 QRhiTextureRenderTargetDescription desc = d.texRt->description();
165 desc.setShadingRateMap(d.rateMap);
166 d.texRt->setDescription(desc);
167 if (!d.texRtRpWithRateMap) {
168 d.texRtRpWithRateMap = d.texRt->newCompatibleRenderPassDescriptor();
169 d.releasePool << d.texRtRpWithRateMap;
170 }
171 d.texRt->setRenderPassDescriptor(d.texRtRpWithRateMap);
172 d.texRt->create();
173 d.ps->setRenderPassDescriptor(d.texRtRpWithRateMap);
174 d.ps->create();
175 } else {
176 m_sc->setShadingRateMap(d.rateMap);
177 if (!d.scRpWithRateMap) {
178 d.scRpWithRateMap = m_sc->newCompatibleRenderPassDescriptor();
179 d.releasePool << d.scRpWithRateMap;
180 }
181 m_sc->setRenderPassDescriptor(d.scRpWithRateMap);
182 m_sc->createOrResize();
183 d.ps->setRenderPassDescriptor(d.scRpWithRateMap);
184 d.ps->create();
185 }
186 } else {
187 if (d.textureBased) {
188 QRhiTextureRenderTargetDescription desc = d.texRt->description();
189 desc.setShadingRateMap(nullptr);
190 d.texRt->setDescription(desc);
191 d.texRt->setRenderPassDescriptor(d.texRtRp);
192 d.texRt->create();
193 d.ps->setRenderPassDescriptor(d.texRtRp);
194 d.ps->create();
195 } else {
196 m_sc->setShadingRateMap(nullptr);
197 m_sc->setRenderPassDescriptor(m_rp);
198 m_sc->createOrResize();
199 d.ps->setRenderPassDescriptor(m_rp);
200 d.ps->create();
201 }
202 }
203 }
204 }
205
206 static void renderCube(QRhiCommandBuffer *cb, const QSize &outputSizeInPixels, quint32 ubufAlignedSize)
207 {
208 cb->setGraphicsPipeline(d.ps);
209 cb->setViewport(QRhiViewport(0, 0, outputSizeInPixels.width(), outputSizeInPixels.height()));
210 if (d.vrsSupported) {
211 int coarsePixelWidth = 1;
212 if (d.cps[0] == 1)
213 coarsePixelWidth = 2;
214 if (d.cps[0] == 2)
215 coarsePixelWidth = 4;
216 int coarsePixelHeight = 1;
217 if (d.cps[1] == 1)
218 coarsePixelHeight = 2;
219 if (d.cps[1] == 2)
220 coarsePixelHeight = 4;
221 const QSize shadingRate(coarsePixelWidth, coarsePixelHeight);
222 cb->setShadingRate(shadingRate);
223 }
224 const QRhiCommandBuffer::VertexInput vbufBindings[] = {
225 { d.vbuf, 0 },
226 { d.vbuf, quint32(36 * 3 * sizeof(float)) }
227 };
228 cb->setVertexInput(0, 2, vbufBindings);
229 for (int i = 0; i < CUBE_COUNT; ++i) {
230 QRhiCommandBuffer::DynamicOffset dynOfs(0, i * ubufAlignedSize);
231 cb->setShaderResources(d.srb, 1, &dynOfs);
232 cb->draw(36);
233 }
234 }
235
236 void Window::customRender()
237 {
238 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
239 QRhiResourceUpdateBatch *u = m_r->nextResourceUpdateBatch();
240 if (d.initialUpdates) {
241 u->merge(d.initialUpdates);
242 d.initialUpdates->release();
243 d.initialUpdates = nullptr;
244 }
245
246 float opacity = 1.0f;
247 quint32 uoffset = 0;
248 for (int i = 0; i < CUBE_COUNT; ++i) {
249 QMatrix4x4 mvp = m_proj;
250 mvp.translate(d.tx[i], d.ty[i], 0.0f);
251 mvp.rotate(d.rotation, 0, 1, 0);
252 mvp.scale(d.scale[i], d.scale[i], d.scale[i]);
253 u->updateDynamicBuffer(d.ubuf, uoffset, 64, mvp.constData());
254 u->updateDynamicBuffer(d.ubuf, uoffset + 64, 4, &opacity);
255 uoffset += d.ubufAlignedSize;
256 }
257 cb->resourceUpdate(u);
258
259 if (d.textureBased) {
260 cb->beginPass(d.texRt, Qt::black, { 1.0f, 0 }, nullptr);
261 renderCube(cb, d.texRt->pixelSize(), d.ubufAlignedSize);
262 cb->endPass();
263 }
264
265 cb->beginPass(m_sc->currentFrameRenderTarget(), m_clearColor, { 1.0f, 0 });
266 if (!d.textureBased)
267 renderCube(cb, m_sc->currentPixelSize(), d.ubufAlignedSize);
268
269 m_imguiRenderer->render();
270
271 cb->endPass();
272
273 d.rotation += 0.1f;
274 }
275
276 void Window::customGui()
277 {
278 ImGui::ShowDemoWindow(&d.showDemoWindow);
279
280 ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver);
281 ImGui::SetNextWindowSize(ImVec2(620, 500), ImGuiCond_FirstUseEver);
282 ImGui::Begin("Variable Rate Shading Test");
283 ImGui::Text("Per-draw VRS supported = %s", d.vrsSupported ? "true" : "false");
284 ImGui::Text("Map-based VRS supported = %s", d.vrsMapSupported ? "true" : "false");
285 ImGui::Text("Map/Image-based VRS supported = %s", d.vrsMapImageSupported ? "true" : "false");
286 const int tileSize = m_r->resourceLimit(QRhi::ShadingRateImageTileSize);
287 ImGui::Text("VRS image tile size: %dx%d", tileSize, tileSize);
288
289 if (ImGui::TreeNodeEx("Supported rates", ImGuiTreeNodeFlags_DefaultOpen)) {
290 ImGui::Columns(2, "ratecols");
291 ImGui::Separator();
292 ImGui::Text("Sample count"); ImGui::NextColumn();
293 ImGui::Text("Rates"); ImGui::NextColumn();
294 ImGui::Separator();
295 for (int sampleCount : { 1, 2, 4, 8, 16 }) {
296 ImGui::Text("%d", sampleCount);
297 ImGui::NextColumn();
298 QString rateStr;
299 for (QSize coarsePixelSize : d.supportedShadingRates[sampleCount])
300 rateStr += QString::asprintf(" %dx%d", coarsePixelSize.width(), coarsePixelSize.height());
301 ImGui::Text("%s", qPrintable(rateStr));
302 ImGui::NextColumn();
303 }
304 ImGui::Columns(1);
305 ImGui::Separator();
306 ImGui::TreePop();
307 }
308
309 ImGui::Text("Sample count: %d", sampleCount);
310
311 const bool wasThisFrameTextureBased = d.textureBased;
312 if (ImGui::Checkbox("Render cubes to texture and apply VRS to that", &d.textureBased)) {
313 d.applyRateMapPending = true;
314 // this imgui callback is made before customRender(), ensure the pipeline
315 // and renderpasses are valid; customBeforeFrame() comes only before the next frame.
316 if (d.textureBased) {
317 d.ps->setRenderPassDescriptor(d.texRtRp);
318 d.ps->create();
319 } else {
320 d.ps->setRenderPassDescriptor(m_rp);
321 d.ps->create();
322 }
323 m_imguiRenderer->registerCustomTexture(d.outTexture, d.outTexture, QRhiSampler::Nearest, QRhiImguiRenderer::NoCustomTextureOwnership);
324 }
325
326 if (d.vrsSupported) {
327 ImGui::Text("Coarse pixel size");
328 ImGui::PushID("cps_width");
329 ImGui::Text("Width"); ImGui::SameLine(); ImGui::RadioButton("1", &d.cps[0], 0); ImGui::SameLine(); ImGui::RadioButton("2", &d.cps[0], 1); ImGui::SameLine(); ImGui::RadioButton("4", &d.cps[0], 2);
330 ImGui::PopID();
331 ImGui::PushID("cps_height");
332 ImGui::Text("Height"); ImGui::SameLine(); ImGui::RadioButton("1", &d.cps[1], 0); ImGui::SameLine(); ImGui::RadioButton("2", &d.cps[1], 1); ImGui::SameLine(); ImGui::RadioButton("4", &d.cps[1], 2);
333 ImGui::PopID();
334 }
335
336 if (d.vrsMapImageSupported) {
337 if (ImGui::Checkbox("Apply R8_UINT texture as shading rate image", &d.applyRateMapWithImage)) {
338 // We are recording a frame already (between beginFrame..endFrame), it is too
339 // late to attempt to change settings that involve recreating the render
340 // targets, because the swapchain is involved here. It can only apply from the
341 // next frame (the one after this one).
342 d.applyRateMapPending = true;
343 if (d.applyRateMapWithImage && tileSize > 0) {
344 const QSize outputSizeInPixels = d.textureBased ? d.texRt->pixelSize() : m_sc->currentPixelSize();
345 if (d.rateMap && d.rateMapTexture->pixelSize() != outputSizeInPixels)
346 d.rateMap = nullptr;
347 if (!d.rateMap) {
348 const QSize rateImageSize(qCeil(outputSizeInPixels.width() / (float)tileSize),
349 qCeil(outputSizeInPixels.height() / (float)tileSize));
350 qDebug() << "Tile size" << tileSize << "Shading rate texture size" << rateImageSize;
351 d.rateMapTexture = m_r->newTexture(QRhiTexture::R8UI, rateImageSize, 1, QRhiTexture::UsedAsShadingRateMap);
352 d.releasePool << d.rateMapTexture;
353 d.rateMapTexture->create();
354
355 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
356 QRhiResourceUpdateBatch *u = m_r->nextResourceUpdateBatch();
357 // 1x1 in a certain area, but use 4x4 outside
358 QImage img(rateImageSize, QImage::Format_Grayscale8);
359 img.fill(0xA); // 4x4
360 QPainter pnt(&img);
361 // pnt.setPen(QColor::fromRgb(0, 0, 0)); // 1x1
362 // pnt.setBrush(QColor::fromRgb(0, 0, 0));
363 // pnt.drawEllipse(20, 20, rateImageSize.width() - 40, rateImageSize.height() - 40);
364 pnt.fillRect(20, 20, rateImageSize.width() - 40, rateImageSize.height() - 40, QColor::fromRgb(0, 0, 0));
365 pnt.end();
366 u->uploadTexture(d.rateMapTexture, img);
367 cb->resourceUpdate(u);
368
369 d.rateMap = m_r->newShadingRateMap();
370 d.releasePool << d.rateMap;
371 d.rateMap->createFrom(d.rateMapTexture);
372
373 d.rateMapTextureForVisualization = m_r->newTexture(QRhiTexture::RGBA8, rateImageSize, 1);
374 d.releasePool << d.rateMapTextureForVisualization;
375 d.rateMapTextureForVisualization->create();
376 QImage rgbaImg = img.convertToFormat(QImage::Format_RGBA8888);
377 u = m_r->nextResourceUpdateBatch();
378 u->uploadTexture(d.rateMapTextureForVisualization, rgbaImg);
379 cb->resourceUpdate(u);
380 m_imguiRenderer->registerCustomTexture(d.rateMapTextureForVisualization, d.rateMapTextureForVisualization, QRhiSampler::Nearest, QRhiImguiRenderer::NoCustomTextureOwnership);
381 }
382 }
383 }
384 } else if (d.vrsMapSupported) {
385 #if QT_CONFIG(metal)
386 if (ImGui::Checkbox("Apply a MTLRasterizationRateMap (no scaling, incomplete!)", &d.applyRateMapNative)) {
387 d.applyRateMapPending = true;
388 const QSize outputSizeInPixels = d.textureBased ? d.texRt->pixelSize() : m_sc->currentPixelSize();
389 if (d.applyRateMapNative && d.nativeRateMap && d.nativeRateMapSize != outputSizeInPixels) {
390 releaseRateMap(d.nativeRateMap);
391 d.nativeRateMap = nullptr;
392 }
393 if (d.applyRateMapNative && !d.nativeRateMap) {
394 d.nativeRateMap = makeRateMap(m_r, outputSizeInPixels);
395 d.nativeRateMapSize = outputSizeInPixels;
396 d.rateMap = m_r->newShadingRateMap();
397 d.releasePool << d.rateMap;
398 // rateMap will not own nativeRateMap as per cross-platform docs,
399 // but it does actually do a retain/release in the Metal backend.
400 // Regardless, we make sure nativeRateMap lives until the end.
401 d.rateMap->createFrom({ quint64(d.nativeRateMap) });
402 }
403 }
404 #endif
405 }
406
407 ImGui::End();
408
409 if (wasThisFrameTextureBased) {
410 QSize s = d.outTexture->pixelSize();
411 ImGui::SetNextWindowPos(ImVec2(500, 50), ImGuiCond_FirstUseEver);
412 ImGui::SetNextWindowSize(ImVec2(s.width() / 2, s.height() / 2), ImGuiCond_FirstUseEver);
413 ImGui::Begin("Texture", nullptr, ImGuiWindowFlags_HorizontalScrollbar);
414 ImGui::Image(d.outTexture, ImVec2(s.width(), s.height()));
415 ImGui::End();
416
417 if (d.applyRateMapWithImage && !d.applyRateMapPending) {
418 ImGui::SetNextWindowPos(ImVec2(500, 250), ImGuiCond_FirstUseEver);
419 ImGui::SetNextWindowSize(ImVec2(s.width() / 2, s.height() / 2), ImGuiCond_FirstUseEver);
420 ImGui::Begin("Shading rate image", nullptr, ImGuiWindowFlags_HorizontalScrollbar);
421 s = d.rateMapTextureForVisualization->pixelSize();
422 const int tileSize = m_r->resourceLimit(QRhi::ShadingRateImageTileSize);
423 const float alpha = 0.4f;
424 ImGui::Image(d.rateMapTextureForVisualization, ImVec2(s.width() * tileSize, s.height() * tileSize), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, alpha));
425 ImGui::End();
426 }
427 }
428 }