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
qssgrhicontext.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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
8#include "graphobjects/qssgrenderskymaterial_p.h"
9
10#include <QtCore/qthread.h>
11#include <QtCore/qvariant.h>
12#include <QtGui/private/qrhi_p.h>
13
14#include <QtQuick3DUtils/private/qquick3dprofiler_p.h>
15#include <QtQuick3DUtils/private/qssgmesh_p.h>
16#include <QtQuick3DUtils/private/qssgassert_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgrenderableimage_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgrendermesh_p.h>
19#include <QtQuick3DRuntimeRender/private/qssgrenderimage_p.h>
20#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
21#include <QtQuick3DUtils/private/qssgutils_p.h>
22#include <QtQuick3DUtils/private/qssgassert_p.h>
23#include <qtquick3d_tracepoints_p.h>
24
25#include <QtGui/qquaternion.h>
26
27#include <memory>
28
30
31Q_TRACE_POINT(qtquick3d, QSSG_renderPass_entry, const QString &renderPass);
33Q_TRACE_POINT(qtquick3d, QSSG_drawIndexed, int indexCount, int instanceCount);
34Q_TRACE_POINT(qtquick3d, QSSG_draw, int vertexCount, int instanceCount);
35
36/*!
37 \class QSSGRhiContext
38 \inmodule QtQuick3D
39 \since 6.7
40
41 \brief QSSGRhiContext.
42 */
43
44/*!
45 \class QSSGRhiGraphicsPipelineState
46 \inmodule QtQuick3D
47 \since 6.7
48
49 \brief Graphics pipeline state for the spatial scene graph.
50
51 This class is a convenience class used by QtQuick3D to wrap relevant pipeline state from the QRhi classes,
52 like \l QRhiGraphicsPipeline. Most of the types and value used in QSSGRhiGraphicsPipelineState will
53 therefore map directly to an equivalent QRhi type or class.
54 */
55
56/*!
57 \variable QSSGRhiGraphicsPipelineState::samples
58
59 The sample count.
60
61 \note A sample count of 1 means no multisample antialiasing.
62
63 \sa QRhiSwapChain::sampleCount()
64 */
65
66/*!
67 \enum QSSGRhiGraphicsPipelineState::Flag
68 \value DepthTestEnabled
69 \value DepthWriteEnabled
70 \value BlendEnabled
71 \value UsesStencilRef
72 \value UsesScissor
73 */
74
75/*!
76 \variable QSSGRhiGraphicsPipelineState::depthFunc
77
78 The depth comparison function.
79
80 \sa QRhiGraphicsPipeline::CompareOp
81 */
82
83/*!
84 \variable QSSGRhiGraphicsPipelineState::cullMode
85
86 Specifies the culling mode.
87
88 \sa QRhiGraphicsPipeline::CullMode
89 */
90
91/*!
92 \variable QSSGRhiGraphicsPipelineState::stencilOpFrontState
93
94 Describes the stencil operation state.
95
96 \sa QRhiGraphicsPipeline::StencilOpState
97 */
98
99/*!
100 \variable QSSGRhiGraphicsPipelineState::stencilWriteMask
101
102 The stencil write mask value. The default value is \c 0xFF.
103
104 \sa QRhiGraphicsPipeline::stencilWriteMask()
105 */
106
107/*!
108 \variable QSSGRhiGraphicsPipelineState::stencilRef
109
110 The active stencil reference value.
111
112 \note Only used when \l{QSSGRhiGraphicsPipelineState::Flag::}{UsesStencilRef} is set.
113
114 \sa QRhiCommandBuffer::setStencilRef()
115 */
116
117/*!
118 \variable QSSGRhiGraphicsPipelineState::depthBias
119
120 The depth bias. The default value is 0.
121
122 \sa QRhiGraphicsPipeline::depthBias()
123 */
124
125/*!
126 \variable QSSGRhiGraphicsPipelineState::slopeScaledDepthBias
127
128 The slope scaled depth bias. The default value is 0.
129
130 \sa QRhiGraphicsPipeline::slopeScaledDepthBias()
131 */
132
133/*!
134 \variable QSSGRhiGraphicsPipelineState::targetBlend
135
136 The blend state for one color attachment.
137
138 \sa QRhiGraphicsPipeline::TargetBlend
139 */
140
141/*!
142 \variable QSSGRhiGraphicsPipelineState::colorAttachmentCount
143
144 The number of color attachments. The default is 1.
145
146 \sa QRhiTextureRenderTargetDescription::setColorAttachments(),
147 QRhiTextureRenderTargetDescription::colorAttachmentCount()
148 */
149
150/*!
151 \variable QSSGRhiGraphicsPipelineState::viewport
152
153 The viewport dimensions used for rendering.
154 */
155
156/*!
157 \variable QSSGRhiGraphicsPipelineState::scissor
158
159 The scissor rect.
160
161 \note Only used if \l{QSSGRhiGraphicsPipelineState::Flag::}{UsesScissor} is set.
162
163 \sa QRhiCommandBuffer::setScissor()
164 */
165
166/*!
167 \variable QSSGRhiGraphicsPipelineState::lineWidth
168
169 The line width used. The default is 1.0
170
171 \note For values other than 1.0 it's required that feature \l QRhi::WideLines is reported
172 as supported at runtime.
173 */
174
175/*!
176 \variable QSSGRhiGraphicsPipelineState::polygonMode
177
178 The polygon mode value. The default is \l{QRhiGraphicsPipeline::Fill}{Fill}.
179
180 \sa QRhiGraphicsPipeline::polygonMode()
181 */
182
183/*!
184 \struct QSSGRhiSamplerDescription
185 \inmodule QtQuick3D
186 \since 6.7
187
188 \brief QSSGRhiSamplerDescription.
189
190 Convenience class used to request a \l QRhiSampler from QtQuick3D internal cache.
191
192 \note Samplers are owned by QtQuick3D.
193
194 \sa QSSGRhiContext::sampler()
195*/
196
197/*!
198 \variable QSSGRhiSamplerDescription::minFilter
199
200 The minification filter mode.
201
202 \sa QRhiSampler::Filter, QRhiSampler::minFilter()
203 */
204
205/*!
206 \variable QSSGRhiSamplerDescription::magFilter
207
208 The magnification filter mode.
209
210 \sa QRhiSampler::Filter, QRhiSampler::magFilter()
211 */
212
213/*!
214 \variable QSSGRhiSamplerDescription::mipmap
215
216 The mipmap filtering mode.
217
218 \sa QRhiSampler::Filter, QRhiSampler::mipmapMode()
219 */
220
221/*!
222 \variable QSSGRhiSamplerDescription::hTiling
223
224 The horizontal wrap mode.
225
226 \sa QRhiSampler::AddressMode
227 */
228
229/*!
230 \variable QSSGRhiSamplerDescription::vTiling
231
232 The vertical wrap mode.
233
234 \sa QRhiSampler::AddressMode
235 */
236
237/*!
238 \variable QSSGRhiSamplerDescription::zTiling
239
240 The depth wrap mode.
241
242 \sa QRhiSampler::AddressMode
243 */
244
245QSSGRhiBuffer::QSSGRhiBuffer(QSSGRhiContext &context,
246 QRhiBuffer::Type type,
247 QRhiBuffer::UsageFlags usageMask,
248 quint32 stride,
249 qsizetype size,
250 QRhiCommandBuffer::IndexFormat indexFormat)
251 : m_context(context),
252 m_stride(stride),
253 m_indexFormat(indexFormat)
254{
255 QSSG_ASSERT(size >= 0, size = 0);
256 m_buffer = m_context.rhi()->newBuffer(type, usageMask, quint32(size));
257 if (!m_buffer->create())
258 qWarning("Failed to build QRhiBuffer with size %d", m_buffer->size());
259}
260
261QSSGRhiBuffer::~QSSGRhiBuffer()
262{
263 delete m_buffer;
264}
265
266namespace QSSGRhiHelpers {
267QRhiVertexInputAttribute::Format toVertexInputFormat(QSSGRenderComponentType compType, quint32 numComps)
268{
269 if (compType == QSSGRenderComponentType::Float32) {
270 switch (numComps) {
271 case 1:
272 return QRhiVertexInputAttribute::Float;
273 case 2:
274 return QRhiVertexInputAttribute::Float2;
275 case 3:
276 return QRhiVertexInputAttribute::Float3;
277 case 4:
278 return QRhiVertexInputAttribute::Float4;
279 default:
280 break;
281 }
282 } else if (compType == QSSGRenderComponentType::UnsignedInt32) {
283 switch (numComps) {
284 case 1:
285 return QRhiVertexInputAttribute::UInt;
286 case 2:
287 return QRhiVertexInputAttribute::UInt2;
288 case 3:
289 return QRhiVertexInputAttribute::UInt3;
290 case 4:
291 return QRhiVertexInputAttribute::UInt4;
292 default:
293 break;
294 }
295 } else if (compType == QSSGRenderComponentType::Int32) {
296 switch (numComps) {
297 case 1:
298 return QRhiVertexInputAttribute::SInt;
299 case 2:
300 return QRhiVertexInputAttribute::SInt2;
301 case 3:
302 return QRhiVertexInputAttribute::SInt3;
303 case 4:
304 return QRhiVertexInputAttribute::SInt4;
305 default:
306 break;
307 }
308 }
309 Q_ASSERT(false);
310 return QRhiVertexInputAttribute::Float4;
311}
312
313QRhiGraphicsPipeline::Topology toTopology(QSSGRenderDrawMode drawMode)
314{
315 switch (drawMode) {
316 case QSSGRenderDrawMode::Points:
317 return QRhiGraphicsPipeline::Points;
318 case QSSGRenderDrawMode::LineStrip:
319 return QRhiGraphicsPipeline::LineStrip;
320 case QSSGRenderDrawMode::Lines:
321 return QRhiGraphicsPipeline::Lines;
322 case QSSGRenderDrawMode::TriangleStrip:
323 return QRhiGraphicsPipeline::TriangleStrip;
324 case QSSGRenderDrawMode::TriangleFan:
325 return QRhiGraphicsPipeline::TriangleFan;
326 case QSSGRenderDrawMode::Triangles:
327 return QRhiGraphicsPipeline::Triangles;
328 case QSSGRenderDrawMode::LineLoop:
329 QSSG_ASSERT_X(false, "LineLoop draw mode is not supported", return QRhiGraphicsPipeline::Triangles);
330 }
331
332 Q_UNREACHABLE_RETURN(QRhiGraphicsPipeline::Triangles);
333}
334
335void bakeVertexInputLocations(QSSGRhiInputAssemblerState *ia, const QSSGRhiShaderPipeline &shaders, int instanceBufferBinding)
336{
337 if (!shaders.vertexStage())
338 return;
339
340 const auto &vertexInputs = shaders.vertexInputs();
341
342 QVarLengthArray<QRhiVertexInputAttribute, 8> attrs;
343 int inputIndex = 0;
344 for (auto it = ia->inputLayout.cbeginAttributes(), itEnd = ia->inputLayout.cendAttributes(); it != itEnd; ++it) {
345 const QSSGRhiInputAssemblerState::InputSemantic sem = ia->inputs.at(inputIndex); // avoid detaching - submeshes share the same name list
346 auto vertexInputVar = vertexInputs.constFind(sem);
347 if (vertexInputVar != vertexInputs.constEnd()) {
348 attrs.append(*it);
349 attrs.last().setLocation(vertexInputVar->location);
350 } // else the mesh has an input attribute that is not declared and used in the vertex shader - that's fine
351
352 ++inputIndex;
353 }
354
355 // Add instance buffer input if necessary
356 if (instanceBufferBinding >= 0) {
357 auto instanceBufferLocations = shaders.instanceBufferLocations();
358 // transform0
359 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding,
360 instanceBufferLocations.transform0,
361 QRhiVertexInputAttribute::Float4,
362 0));
363 // transform1
364 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding,
365 instanceBufferLocations.transform1,
366 QRhiVertexInputAttribute::Float4,
367 sizeof(float) * 4));
368 // transform2
369 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding,
370 instanceBufferLocations.transform2,
371 QRhiVertexInputAttribute::Float4,
372 sizeof(float) * 4 * 2));
373 // color
374 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding,
375 instanceBufferLocations.color,
376 QRhiVertexInputAttribute::Float4,
377 sizeof(float) * 4 * 3));
378 // data
379 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding,
380 instanceBufferLocations.data,
381 QRhiVertexInputAttribute::Float4,
382 sizeof(float) * 4 * 4));
383 // index
384 if (instanceBufferLocations.index >= 0) {
385 attrs.append(QRhiVertexInputAttribute(instanceBufferBinding + 1,
386 instanceBufferLocations.index,
387 QRhiVertexInputAttribute::SInt,
388 0));
389 }
390 }
391
392 ia->inputLayout.setAttributes(attrs.cbegin(), attrs.cend());
393}
394
395QShaderDescription::VariableType samplerType(const QSSGRhiShaderPipeline &shaders, const QByteArray &name)
396{
397 for (auto stage = shaders.cbeginStages(); stage != shaders.cendStages(); ++stage) {
398 const auto samplers = stage->shader().description().combinedImageSamplers();
399 const auto it = std::find_if(samplers.cbegin(), samplers.cend(),
400 [&name](const QShaderDescription::InOutVariable &var) { return var.name == name; });
401 if (it != samplers.cend())
402 return it->type;
403 }
404 return QShaderDescription::Sampler2D;
405}
406
423
424} // namespace QSSGRhiHelpers
425
426void QSSGRhiShaderPipeline::addStage(const QRhiShaderStage &stage, StageFlags flags)
427{
428 m_stages.append(stage);
429
430 // Copy all member infos for the uniform block with binding 0 into m_ub0
431 // for faster lookup.
432 if (stage.type() == QRhiShaderStage::Vertex || stage.type() == QRhiShaderStage::Compute) {
433 // For graphics pipelines, optimize by doing it only for the vertex
434 // shader. Pipelines with vertex+fragment stages from materials have an
435 // identical uniform block in both shaders, so go through only one of
436 // them. Compute pipelines have a single stage.
437 const QVector<QShaderDescription::UniformBlock> uniformBlocks = stage.shader().description().uniformBlocks();
438 for (const QShaderDescription::UniformBlock &blk : uniformBlocks) {
439 if (blk.binding == 0) {
440 m_ub0Size = blk.size;
441 m_ub0NextUBufOffset = m_context.rhi()->ubufAligned(m_ub0Size);
442 for (const QShaderDescription::BlockVariable &var : blk.members)
443 m_ub0[var.name] = var;
444 break;
445 }
446 }
447 // Now the same for vertex inputs.
448 if (!flags.testFlag(UsedWithoutIa)) {
449 const QVector<QShaderDescription::InOutVariable> inputs = stage.shader().description().inputVariables();
450 for (const QShaderDescription::InOutVariable &var : inputs) {
451 if (var.name == QSSGMesh::MeshInternal::getPositionAttrName()) {
452 m_vertexInputs[QSSGRhiInputAssemblerState::PositionSemantic] = var;
453 } else if (var.name == QSSGMesh::MeshInternal::getNormalAttrName()) {
454 m_vertexInputs[QSSGRhiInputAssemblerState::NormalSemantic] = var;
455 } else if (var.name == QSSGMesh::MeshInternal::getUV0AttrName()) {
456 m_vertexInputs[QSSGRhiInputAssemblerState::TexCoord0Semantic] = var;
457 } else if (var.name == QSSGMesh::MeshInternal::getUV1AttrName()) {
458 m_vertexInputs[QSSGRhiInputAssemblerState::TexCoord1Semantic] = var;
459 } else if (var.name == QSSGMesh::MeshInternal::getLightmapUVAttrName()) {
460 m_vertexInputs[QSSGRhiInputAssemblerState::TexCoordLightmapSemantic] = var;
461 } else if (var.name == QSSGMesh::MeshInternal::getTexTanAttrName()) {
462 m_vertexInputs[QSSGRhiInputAssemblerState::TangentSemantic] = var;
463 } else if (var.name == QSSGMesh::MeshInternal::getTexBinormalAttrName()) {
464 m_vertexInputs[QSSGRhiInputAssemblerState::BinormalSemantic] = var;
465 } else if (var.name == QSSGMesh::MeshInternal::getColorAttrName()) {
466 m_vertexInputs[QSSGRhiInputAssemblerState::ColorSemantic] = var;
467 } else if (var.name == QSSGMesh::MeshInternal::getJointAttrName()) {
468 m_vertexInputs[QSSGRhiInputAssemblerState::JointSemantic] = var;
469 } else if (var.name == QSSGMesh::MeshInternal::getWeightAttrName()) {
470 m_vertexInputs[QSSGRhiInputAssemblerState::WeightSemantic] = var;
471 } else if (var.name == "qt_instanceTransform0") {
472 instanceLocations.transform0 = var.location;
473 } else if (var.name == "qt_instanceTransform1") {
474 instanceLocations.transform1 = var.location;
475 } else if (var.name == "qt_instanceTransform2") {
476 instanceLocations.transform2 = var.location;
477 } else if (var.name == "qt_instanceColor") {
478 instanceLocations.color = var.location;
479 } else if (var.name == "qt_instanceData") {
480 instanceLocations.data = var.location;
481 } else if (var.name == "qt_instanceIndex") {
482 instanceLocations.index = var.location;
483 } else {
484 qWarning("Ignoring vertex input %s in shader", var.name.constData());
485 }
486 }
487 }
488 }
489 const QVector<QShaderDescription::StorageBlock> storageBlocks = stage.shader().description().storageBlocks();
490 for (const QShaderDescription::StorageBlock &blk : storageBlocks) {
491 if (blk.binding > 0)
492 m_storageBuffers[blk.blockName] = blk;
493 }
494
495 const QVector<QShaderDescription::InOutVariable> combinedImageSamplers = stage.shader().description().combinedImageSamplers();
496 for (const QShaderDescription::InOutVariable &var : combinedImageSamplers)
497 m_combinedImageSamplers[var.name] = var;
498
499 const QVector<QShaderDescription::InOutVariable> storageImages = stage.shader().description().storageImages() + stage.shader().description().separateImages();
500 for (const QShaderDescription::InOutVariable &var : storageImages)
501 m_storageImages[var.name] = var;
502
503 std::fill(m_materialImageSamplerBindings,
504 m_materialImageSamplerBindings + size_t(QSSGRhiSamplerBindingHints::BindingMapSize),
505 -1);
506}
507
508int QSSGRhiShaderPipeline::ub0DirectionalLightDataOffset() const
509{
510 return m_ub0NextUBufOffset + m_context.rhi()->ubufAligned(sizeof(QSSGShaderLightsUniformData));
511}
512
513void QSSGRhiShaderPipeline::addStorageBufferBinding(const QByteArray &name, QRhiShaderResourceBinding::Type type, QRhiBuffer *buffer, int binding)
514{
515 QSSG_ASSERT(type >= QRhiShaderResourceBinding::BufferLoad && type <= QRhiShaderResourceBinding::BufferLoadStore, return);
516 QSSG_ASSERT(buffer->usage().testFlag(QRhiBuffer::StorageBuffer), return);
517 m_storageBufferBindings.insert(binding, StorageResourceBinding(binding, name, type, buffer));
518}
519
520void QSSGRhiShaderPipeline::addStorageImageBinding(const QByteArray &name, QRhiShaderResourceBinding::Type type, QRhiTexture *texture, int binding)
521{
522 QSSG_ASSERT(type >= QRhiShaderResourceBinding::ImageLoad && type <= QRhiShaderResourceBinding::ImageLoadStore, return);
523 QSSG_ASSERT(texture->flags().testFlags(QRhiTexture::UsedWithLoadStore), return);
524 m_storageImageBindings.insert(binding, StorageResourceBinding(binding, name, type, texture));
525}
526
527void QSSGRhiShaderPipeline::applyAndClearStorageBindings(QRhiShaderResourceBinding::StageFlags stage, QSSGRhiShaderResourceBindingList &bindings)
528{
529 for (const auto &binding : std::as_const(m_storageBufferBindings)) {
530 if (binding.type == QRhiShaderResourceBinding::BufferLoad)
531 bindings.addStorageBufferLoad(binding.binding, stage, binding.buffer);
532 else if (binding.type == QRhiShaderResourceBinding::BufferStore)
533 bindings.addStorageBufferStore(binding.binding, stage, binding.buffer);
534 else
535 bindings.addStorageBufferLoadStore(binding.binding, stage, binding.buffer);
536 }
537 for (const auto &binding : std::as_const(m_storageImageBindings)) {
538 if (binding.type == QRhiShaderResourceBinding::ImageLoad)
539 bindings.addImageLoad(binding.binding, stage, binding.texture, 0);
540 else if (binding.type == QRhiShaderResourceBinding::ImageStore)
541 bindings.addImageStore(binding.binding, stage, binding.texture, 0);
542 else
543 bindings.addImageLoadStore(binding.binding, stage, binding.texture, 0);
544 }
545 m_storageBufferBindings.clear();
546 m_storageImageBindings.clear();
547}
548
549void QSSGRhiShaderPipeline::setUniformValue(char *ubufData, const char *name, const QVariant &inValue, QSSGRenderShaderValue::Type inType)
550{
551 using namespace QSSGRenderShaderValue;
552 switch (inType) {
553 case QSSGRenderShaderValue::Integer:
554 {
555 const qint32 v = inValue.toInt();
556 setUniform(ubufData, name, &v, sizeof(qint32));
557 }
558 break;
559 case QSSGRenderShaderValue::IntegerVec2:
560 {
561 const ivec2 v = inValue.value<ivec2>();
562 setUniform(ubufData, name, &v, 2 * sizeof(qint32));
563 }
564 break;
565 case QSSGRenderShaderValue::IntegerVec3:
566 {
567 const ivec3 v = inValue.value<ivec3>();
568 setUniform(ubufData, name, &v, 3 * sizeof(qint32));
569 }
570 break;
571 case QSSGRenderShaderValue::IntegerVec4:
572 {
573 const ivec4 v = inValue.value<ivec4>();
574 setUniform(ubufData, name, &v, 4 * sizeof(qint32));
575 }
576 break;
577 case QSSGRenderShaderValue::Boolean:
578 {
579 // whatever bool is does not matter, what matters is that the GLSL bool is 4 bytes
580 const qint32 v = inValue.value<bool>();
581 setUniform(ubufData, name, &v, sizeof(qint32));
582 }
583 break;
584 case QSSGRenderShaderValue::BooleanVec2:
585 {
586 const bvec2 b = inValue.value<bvec2>();
587 const ivec2 v(b.x, b.y);
588 setUniform(ubufData, name, &v, 2 * sizeof(qint32));
589 }
590 break;
591 case QSSGRenderShaderValue::BooleanVec3:
592 {
593 const bvec3 b = inValue.value<bvec3>();
594 const ivec3 v(b.x, b.y, b.z);
595 setUniform(ubufData, name, &v, 3 * sizeof(qint32));
596 }
597 break;
598 case QSSGRenderShaderValue::BooleanVec4:
599 {
600 const bvec4 b = inValue.value<bvec4>();
601 const ivec4 v(b.x, b.y, b.z, b.w);
602 setUniform(ubufData, name, &v, 4 * sizeof(qint32));
603 }
604 break;
605 case QSSGRenderShaderValue::Float:
606 {
607 const float v = inValue.value<float>();
608 setUniform(ubufData, name, &v, sizeof(float));
609 }
610 break;
611 case QSSGRenderShaderValue::Vec2:
612 {
613 const QVector2D v = inValue.value<QVector2D>();
614 setUniform(ubufData, name, &v, 2 * sizeof(float));
615 }
616 break;
617 case QSSGRenderShaderValue::Vec3:
618 {
619 const QVector3D v = inValue.value<QVector3D>();
620 setUniform(ubufData, name, &v, 3 * sizeof(float));
621 }
622 break;
623 case QSSGRenderShaderValue::Vec4:
624 {
625 const QVector4D v = inValue.value<QVector4D>();
626 setUniform(ubufData, name, &v, 4 * sizeof(float));
627 }
628 break;
629 case QSSGRenderShaderValue::Rgba:
630 {
631 const QVector4D v = QSSGUtils::color::sRGBToLinear(inValue.value<QColor>());
632 setUniform(ubufData, name, &v, 4 * sizeof(float));
633 }
634 break;
635 case QSSGRenderShaderValue::UnsignedInteger:
636 {
637 const quint32 v = inValue.value<quint32>();
638 setUniform(ubufData, name, &v, sizeof(quint32));
639 }
640 break;
641 case QSSGRenderShaderValue::UnsignedIntegerVec2:
642 {
643 const uvec2 v = inValue.value<uvec2>();
644 setUniform(ubufData, name, &v, 2 * sizeof(quint32));
645 }
646 break;
647 case QSSGRenderShaderValue::UnsignedIntegerVec3:
648 {
649 const uvec3 v = inValue.value<uvec3>();
650 setUniform(ubufData, name, &v, 3 * sizeof(quint32));
651 }
652 break;
653 case QSSGRenderShaderValue::UnsignedIntegerVec4:
654 {
655 const uvec4 v = inValue.value<uvec4>();
656 setUniform(ubufData, name, &v, 4 * sizeof(quint32));
657 }
658 break;
659 case QSSGRenderShaderValue::Matrix3x3:
660 {
661 const QMatrix3x3 m = inValue.value<QMatrix3x3>();
662 setUniform(ubufData, name, m.constData(), 12 * sizeof(float), nullptr, QSSGRhiShaderPipeline::UniformFlag::Mat3);
663 }
664 break;
665 case QSSGRenderShaderValue::Matrix4x4:
666 {
667 const QMatrix4x4 v = inValue.value<QMatrix4x4>();
668 setUniform(ubufData, name, v.constData(), 16 * sizeof(float));
669 }
670 break;
671 case QSSGRenderShaderValue::Size:
672 {
673 const QSize s = inValue.value<QSize>();
674 float v[2] = { float(s.width()), float(s.height()) };
675 setUniform(ubufData, name, v, 2 * sizeof(float));
676 }
677 break;
678 case QSSGRenderShaderValue::SizeF:
679 {
680 const QSizeF s = inValue.value<QSizeF>();
681 float v[2] = { float(s.width()), float(s.height()) };
682 setUniform(ubufData, name, v, 2 * sizeof(float));
683 }
684 break;
685 case QSSGRenderShaderValue::Point:
686 {
687 const QPoint p = inValue.value<QPoint>();
688 float v[2] = { float(p.x()), float(p.y()) };
689 setUniform(ubufData, name, v, 2 * sizeof(float));
690 }
691 break;
692 case QSSGRenderShaderValue::PointF:
693 {
694 const QPointF p = inValue.value<QPointF>();
695 float v[2] = { float(p.x()), float(p.y()) };
696 setUniform(ubufData, name, v, 2 * sizeof(float));
697 }
698 break;
699 case QSSGRenderShaderValue::Rect:
700 {
701 const QRect r = inValue.value<QRect>();
702 float v[4] = { float(r.x()), float(r.y()), float(r.width()), float(r.height()) };
703 setUniform(ubufData, name, v, 4 * sizeof(float));
704 }
705 break;
706 case QSSGRenderShaderValue::RectF:
707 {
708 const QRectF r = inValue.value<QRectF>();
709 float v[4] = { float(r.x()), float(r.y()), float(r.width()), float(r.height()) };
710 setUniform(ubufData, name, v, 4 * sizeof(float));
711 }
712 break;
713 case QSSGRenderShaderValue::Quaternion:
714 {
715 const QQuaternion q = inValue.value<QQuaternion>();
716 float v[4] = { float(q.x()), float(q.y()), float(q.z()), float(q.scalar()) };
717 setUniform(ubufData, name, v, 4 * sizeof(float));
718 }
719 break;
720 default:
721 qWarning("Attempted to set uniform %s value with unsupported data type %i",
722 name, int(inType));
723 break;
724 }
725}
726
727int QSSGRhiShaderPipeline::offsetOfUniform(const QByteArray &name)
728{
729 auto iter = m_ub0.constFind(name);
730 if (iter != m_ub0.cend())
731 return iter->offset;
732 return -1;
733}
734
735static QString getUBMemberSizeWarning(QLatin1StringView name, qsizetype correctedSize, qsizetype requestedSize)
736{
737 return QStringLiteral("Uniform block member '%1' got %2 bytes whereas the true size is %3").arg(name, QString::number(correctedSize), QString::number(requestedSize));
738}
739
740void QSSGRhiShaderPipeline::setUniform(char *ubufData, const char *name, const void *data, size_t size, int *storeIndex, UniformFlags flags)
741{
742 int index = -1;
743 if (!storeIndex || *storeIndex == -1) {
744 const QByteArray ba = QByteArray::fromRawData(name, strlen(name));
745 auto it = m_uniformIndex.constFind(ba);
746 if (it != m_uniformIndex.cend()) {
747 index = int(*it);
748 } else if (ba.size() < qsizetype(sizeof(QSSGRhiShaderUniform::name))) {
749 QSSGRhiShaderUniform u;
750 memcpy(u.name, name, ba.size() + 1);
751 u.size = size;
752
753 const int new_idx = m_uniforms.size();
754 m_uniformIndex[name] = new_idx; // key is name, not ba, this has to be a deep copy QByteArray
755 m_uniforms.push_back(u);
756 index = new_idx;
757 } else {
758 qWarning("Attempted to set uniform with too long name: %s", name);
759 return;
760 }
761 if (storeIndex)
762 *storeIndex = index;
763 } else {
764 index = *storeIndex;
765 }
766
767 Q_ASSERT(index >= 0);
768 QSSGRhiShaderUniform &u = m_uniforms[index];
769 if (size <= u.size) {
770 if (u.offset == SIZE_MAX && u.maybeExists) {
771 auto it = m_ub0.constFind(QByteArray::fromRawData(u.name, strlen(u.name)));
772 if (it != m_ub0.constEnd()) {
773 u.offset = it->offset;
774 QSSG_ASSERT_X(QSSG_DEBUG_COND(int(u.size) == it->size), qPrintable(getUBMemberSizeWarning(QLatin1StringView(it->name), u.size, it->size)), return);
775 }
776 }
777 if (u.offset == SIZE_MAX) {
778 // must silently ignore uniforms that are not in the actual shader
779 u.maybeExists = false; // but do not try again
780 return;
781 }
782
783 char *dst = ubufData + u.offset;
784 if (flags.testFlag(UniformFlag::Mat3)) {
785 // mat3 is still 4 floats per column in the uniform buffer (but there
786 // is no 4th column), so 48 bytes altogether, not 36 or 64.
787 const float *src = static_cast<const float *>(data);
788 memcpy(dst, src, 3 * sizeof(float));
789 memcpy(dst + 4 * sizeof(float), src + 3, 3 * sizeof(float));
790 memcpy(dst + 8 * sizeof(float), src + 6, 3 * sizeof(float));
791 } else {
792 memcpy(dst, data, size);
793 }
794 } else {
795 qWarning("Attempted to set %u bytes to uniform %s with size %u", uint(size), name, uint(u.size));
796 }
797}
798
799// Quick3D uniform buffer is std140 type and all array data should be stored in this rule.
800// You can check it in glspec45.core.pdf's 7.6.2.2.(4)
801// https://www.khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf
802void QSSGRhiShaderPipeline::setUniformArray(char *ubufData, const char *name, const void *data, size_t itemCount, QSSGRenderShaderValue::Type type, int *storeIndex)
803{
804 using namespace QSSGRenderShaderValue;
805
806 QSSGRhiShaderUniformArray *ua = nullptr;
807 constexpr size_t std140BaseTypeSize = 4 * sizeof(float);
808
809 static const auto checkSize = [std140BaseTypeSize](QSSGRhiShaderUniformArray *ua) -> bool {
810 Q_UNUSED(std140BaseTypeSize); // Silence clang warning about unneeded lambda capture (MSVC requires it be captrued).
811 const size_t uniformSize = std140BaseTypeSize < ua->typeSize ? ua->typeSize * ua->itemCount : std140BaseTypeSize * ua->itemCount;
812 QSSG_ASSERT_X(uniformSize == ua->size, qPrintable(getUBMemberSizeWarning(QLatin1StringView(ua->name), uniformSize, ua->size)), return false);
813 return true;
814 };
815
816 if (!storeIndex || *storeIndex == -1) {
817 int index = -1;
818 const QByteArray ba = QByteArray::fromRawData(name, strlen(name));
819 auto it = m_uniformIndex.constFind(ba);
820 if (it != m_uniformIndex.cend()) {
821 index = int(*it);
822 ua = &m_uniformArrays[index];
823 } else if (ba.size() < qsizetype(sizeof(QSSGRhiShaderUniformArray::name))) {
824 index = m_uniformArrays.size();
825 m_uniformArrays.push_back(QSSGRhiShaderUniformArray());
826 m_uniformIndex[name] = index; // key needs deep copy
827 ua = &m_uniformArrays.last();
828 memcpy(ua->name, name, ba.size() + 1);
829 } else {
830 qWarning("Attempted to set uniform array with too long name: %s", name);
831 return;
832 }
833 if (storeIndex)
834 *storeIndex = index;
835 } else {
836 ua = &m_uniformArrays[*storeIndex];
837 }
838
839 if (!ua)
840 return;
841
842 if (ua->offset == SIZE_MAX && ua->maybeExists) {
843 auto it = m_ub0.constFind(QByteArray::fromRawData(ua->name, strlen(ua->name)));
844 if (it != m_ub0.constEnd()) {
845 ua->offset = it->offset;
846 ua->size = it->size;
847 }
848 }
849 if (ua->offset == SIZE_MAX) {
850 // must silently ignore uniforms that are not in the actual shader
851 ua->maybeExists = false; // but do not try again
852 return;
853 }
854
855 char *p = ubufData + ua->offset;
856
857 switch (type) {
858 case QSSGRenderShaderValue::Integer:
859 {
860 const qint32 *v = static_cast<const qint32 *>(data);
861 if (sizeof(qint32) != ua->typeSize || itemCount != ua->itemCount) {
862 ua->typeSize = sizeof(qint32);
863 ua->itemCount = itemCount;
864 }
865
866 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
867
868 for (size_t i = 0; i < itemCount; ++i)
869 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
870 }
871 break;
872 case QSSGRenderShaderValue::IntegerVec2:
873 {
874 const ivec2 *v = static_cast<const ivec2 *>(data);
875 if (2 * sizeof(qint32) != ua->typeSize || itemCount != ua->itemCount) {
876 ua->typeSize = 2 * sizeof(qint32);
877 ua->itemCount = itemCount;
878 }
879
880 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
881
882 for (size_t i = 0; i < itemCount; ++i)
883 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
884 }
885 break;
886 case QSSGRenderShaderValue::IntegerVec3:
887 {
888 const QSSGRenderShaderValue::ivec3 *v = static_cast<const QSSGRenderShaderValue::ivec3 *>(data);
889 if (3 * sizeof(qint32) != ua->typeSize || itemCount != ua->itemCount) {
890 ua->typeSize = 3 * sizeof(qint32);
891 ua->itemCount = itemCount;
892 }
893
894 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
895
896 for (size_t i = 0; i < itemCount; ++i)
897 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
898 }
899 break;
900 case QSSGRenderShaderValue::IntegerVec4:
901 {
902 const ivec4 *v = static_cast<const ivec4 *>(data);
903 if (4 * sizeof(qint32) != ua->typeSize || itemCount != ua->itemCount) {
904 ua->typeSize = 4 * sizeof(qint32);
905 ua->itemCount = itemCount;
906 }
907
908 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
909
910 memcpy(p, v, ua->typeSize * ua->itemCount);
911 }
912 break;
913 case QSSGRenderShaderValue::Float:
914 {
915 const float *v = static_cast<const float *>(data);
916 if (sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
917 ua->typeSize = sizeof(float);
918 ua->itemCount = itemCount;
919 }
920
921 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
922
923 for (size_t i = 0; i < itemCount; ++i)
924 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
925 }
926 break;
927 case QSSGRenderShaderValue::Vec2:
928 {
929 const QVector2D *v = static_cast<const QVector2D *>(data);
930 if (2 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
931 ua->typeSize = 2 * sizeof(float);
932 ua->itemCount = itemCount;
933 }
934
935 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
936
937 for (size_t i = 0; i < itemCount; ++i)
938 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
939 }
940 break;
941 case QSSGRenderShaderValue::Vec3:
942 {
943 const QVector3D *v = static_cast<const QVector3D *>(data);
944 if (3 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
945 ua->typeSize = 3 * sizeof(float);
946 ua->itemCount = itemCount;
947 }
948
949 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
950
951 for (size_t i = 0; i < itemCount; ++i)
952 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
953 }
954 break;
955 case QSSGRenderShaderValue::Vec4:
956 {
957 const QVector4D *v = static_cast<const QVector4D *>(data);
958 if (4 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
959 ua->typeSize = 4 * sizeof(float);
960 ua->itemCount = itemCount;
961 }
962
963 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
964
965 memcpy(p, v, ua->typeSize * ua->itemCount);
966 }
967 break;
968 case QSSGRenderShaderValue::Rgba:
969 {
970 const QColor *v = static_cast<const QColor *>(data);
971 if (4 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
972 ua->typeSize = 4 * sizeof(float);
973 ua->itemCount = itemCount;
974 }
975
976 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
977
978 for (size_t i = 0; i < itemCount; ++i) {
979 const QVector4D vi = QSSGUtils::color::sRGBToLinear(v[i]);
980 memcpy(p + i * std140BaseTypeSize, &vi, ua->typeSize);
981 }
982 }
983 break;
984 case QSSGRenderShaderValue::UnsignedInteger:
985 {
986 const quint32 *v = static_cast<const quint32 *>(data);
987 if (sizeof(quint32) != ua->typeSize || itemCount != ua->itemCount) {
988 ua->typeSize = sizeof(quint32);
989 ua->itemCount = itemCount;
990 }
991
992 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
993
994 for (size_t i = 0; i < itemCount; ++i)
995 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
996 }
997 break;
998 case QSSGRenderShaderValue::UnsignedIntegerVec2:
999 {
1000 const uvec2 *v = static_cast<const uvec2 *>(data);
1001 if (2 * sizeof(quint32) != ua->typeSize || itemCount != ua->itemCount) {
1002 ua->typeSize = 2 * sizeof(quint32);
1003 ua->itemCount = itemCount;
1004 }
1005
1006 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
1007
1008 for (size_t i = 0; i < itemCount; ++i)
1009 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
1010 }
1011 break;
1012 case QSSGRenderShaderValue::UnsignedIntegerVec3:
1013 {
1014 const uvec3 *v = static_cast<const uvec3 *>(data);
1015 if (3 * sizeof(quint32) != ua->typeSize || itemCount != ua->itemCount) {
1016 ua->typeSize = 3 * sizeof(quint32);
1017 ua->itemCount = itemCount;
1018 }
1019
1020 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
1021
1022 for (size_t i = 0; i < itemCount; ++i)
1023 memcpy(p + i * std140BaseTypeSize, &v[i], ua->typeSize);
1024 }
1025 break;
1026 case QSSGRenderShaderValue::UnsignedIntegerVec4:
1027 {
1028 const uvec4 *v = static_cast<const uvec4 *>(data);
1029 if (4 * sizeof(quint32) != ua->typeSize || itemCount != ua->itemCount) {
1030 ua->typeSize = 4 * sizeof(quint32);
1031 ua->itemCount = itemCount;
1032 }
1033
1034 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
1035
1036 memcpy(p, v, ua->typeSize * ua->itemCount);
1037 }
1038 break;
1039 case QSSGRenderShaderValue::Matrix3x3:
1040 {
1041 const QMatrix3x3 *v = static_cast<const QMatrix3x3 *>(data);
1042 if (12 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
1043 ua->typeSize = 12 * sizeof(float);
1044 ua->itemCount = itemCount;
1045 }
1046
1047 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
1048
1049 for (uint i = 0; i < ua->itemCount; ++i) {
1050 memcpy(p + i * ua->typeSize, v[i].constData(), 3 * sizeof(float));
1051 memcpy(p + i * ua->typeSize + 4 * sizeof(float), v[i].constData() + 3, 3 * sizeof(float));
1052 memcpy(p + i * ua->typeSize + 8 * sizeof(float), v[i].constData() + 6, 3 * sizeof(float));
1053 }
1054 }
1055 break;
1056 case QSSGRenderShaderValue::Matrix4x4:
1057 {
1058 const QMatrix4x4 *v = static_cast<const QMatrix4x4 *>(data);
1059 if (16 * sizeof(float) != ua->typeSize || itemCount != ua->itemCount) {
1060 ua->typeSize = 16 * sizeof(float);
1061 ua->itemCount = itemCount;
1062 }
1063
1064 QSSG_ASSERT(QSSG_DEBUG_COND(checkSize(ua)), return);
1065
1066 for (uint i = 0; i < ua->itemCount; ++i)
1067 memcpy(p + i * ua->typeSize, &v[i] , ua->typeSize);
1068 }
1069 break;
1070 case QSSGRenderShaderValue::Boolean:
1071 case QSSGRenderShaderValue::BooleanVec2:
1072 case QSSGRenderShaderValue::BooleanVec3:
1073 case QSSGRenderShaderValue::BooleanVec4:
1074 case QSSGRenderShaderValue::Size:
1075 case QSSGRenderShaderValue::SizeF:
1076 case QSSGRenderShaderValue::Point:
1077 case QSSGRenderShaderValue::PointF:
1078 case QSSGRenderShaderValue::Rect:
1079 case QSSGRenderShaderValue::RectF:
1080 case QSSGRenderShaderValue::Quaternion:
1081 default:
1082 qWarning("Attempted to set uniform %s value with type %d that is unsupported for uniform arrays",
1083 name, int(type));
1084 break;
1085 }
1086}
1087
1088void QSSGRhiShaderPipeline::ensureCombinedUniformBuffer(QRhiBuffer **ubuf)
1089{
1090 const quint32 alignedLightsSize = m_context.rhi()->ubufAligned(sizeof(QSSGShaderLightsUniformData));
1091 const quint32 alignedDirectionalLightsSize = m_context.rhi()->ubufAligned(sizeof(QSSGShaderDirectionalLightsUniformData));
1092 const quint32 totalBufferSize = m_ub0NextUBufOffset + alignedLightsSize + alignedDirectionalLightsSize;
1093 if (!*ubuf) {
1094 *ubuf = m_context.rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, totalBufferSize);
1095 (*ubuf)->create();
1096 }
1097 if ((*ubuf)->size() < totalBufferSize) {
1098 (*ubuf)->setSize(totalBufferSize);
1099 (*ubuf)->create();
1100 }
1101}
1102
1103void QSSGRhiShaderPipeline::ensureUniformBuffer(QRhiBuffer **ubuf)
1104{
1105 if (!*ubuf) {
1106 *ubuf = m_context.rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, m_ub0Size);
1107 (*ubuf)->create();
1108 }
1109 // The buffer might have been used by other pipeline. Check the size too.
1110 if ((*ubuf)->size() < quint32(m_ub0Size)) {
1111 (*ubuf)->setSize(m_ub0Size);
1112 (*ubuf)->create();
1113 }
1114}
1115
1116int QSSGRhiShaderPipeline::bindingForTexture(const char *name, int hint)
1117{
1118 if (hint >= 0) {
1119 const int binding = m_materialImageSamplerBindings[hint];
1120 if (binding >= 0)
1121 return binding;
1122 }
1123
1124 auto it = m_combinedImageSamplers.constFind(QByteArray::fromRawData(name, strlen(name)));
1125 const int binding = it != m_combinedImageSamplers.cend() ? it->binding : -1;
1126 if (hint >= 0)
1127 m_materialImageSamplerBindings[hint] = binding;
1128
1129 return binding;
1130}
1131
1132static inline QByteArray asLookupKey(QByteArrayView name)
1133{
1134 return QByteArray::fromRawData(name.data(), name.size());
1135}
1136
1137int QSSGRhiShaderPipeline::bindingForStorageImage(QByteArrayView name)
1138{
1139 auto it = m_storageImages.constFind(asLookupKey(name));
1140 return it != m_storageImages.cend() ? it->binding : -1;
1141}
1142
1143int QSSGRhiShaderPipeline::bindingForStorageBuffer(QByteArrayView name)
1144{
1145 auto storageIt = m_storageBuffers.constFind(asLookupKey(name));
1146 return storageIt != m_storageBuffers.cend() ? storageIt->binding : -1;
1147}
1148
1149void QSSGRhiShaderPipeline::setShaderResources(char *ubufData,
1150 QSSGBufferManager &theBufferManager,
1151 const QByteArray &inPropertyName,
1152 const QVariant &propertyValue,
1153 QSSGRenderShaderValue::Type inPropertyType)
1154{
1155 if (inPropertyType == QSSGRenderShaderValue::Texture) {
1156 QSSGRenderImage *image = propertyValue.value<QSSGRenderImage *>();
1157 if (image) {
1158 const QSSGRenderImageTexture texture = theBufferManager.loadRenderImage(image);
1159 if (texture.m_texture) {
1160 const QSSGRhiTexture t = {
1161 inPropertyName,
1162 texture.m_texture,
1163 { QSSGRhiHelpers::toRhi(image->m_minFilterType),
1164 QSSGRhiHelpers::toRhi(image->m_magFilterType),
1165 image->m_mipFilterType != QSSGRenderTextureFilterOp::None ? QSSGRhiHelpers::toRhi(image->m_mipFilterType) : QRhiSampler::None,
1166 QSSGRhiHelpers::toRhi(image->m_horizontalTilingMode),
1167 QSSGRhiHelpers::toRhi(image->m_verticalTilingMode),
1168 QSSGRhiHelpers::toRhi(image->m_depthTilingMode)
1169 }
1170 };
1171 addExtraTexture(t);
1172 }
1173 }
1174 } else if (inPropertyType == QSSGRenderShaderValue::StorageBuffer) {
1175 int binding = bindingForStorageBuffer(inPropertyName);
1176 if (binding >= 0) {
1177 const QSSGShaderBuffer buffer(propertyValue.value<QSSGShaderBuffer>());
1178 QRhiBuffer *rhiBuf = buffer.buffer ? theBufferManager.loadBuffer(*buffer.buffer) : nullptr;
1179 if (rhiBuf) {
1180 if (buffer.qualifiers.testFlag(QSSGMemoryQualifier::Readonly))
1181 addStorageBufferBinding(inPropertyName, QRhiShaderResourceBinding::BufferLoad, rhiBuf, binding);
1182 else if (buffer.qualifiers.testFlag(QSSGMemoryQualifier::Writeonly))
1183 addStorageBufferBinding(inPropertyName, QRhiShaderResourceBinding::BufferStore, rhiBuf, binding);
1184 else
1185 addStorageBufferBinding(inPropertyName, QRhiShaderResourceBinding::BufferLoadStore, rhiBuf, binding);
1186 } else {
1187 qWarning() << "Buffer binding failed: " << inPropertyName;
1188 }
1189 }
1190 } else if (inPropertyType == QSSGRenderShaderValue::Image) {
1191 int binding = bindingForStorageImage(inPropertyName);
1192 if (binding >= 0) {
1193 const QSSGShaderImage image(propertyValue.value<QSSGShaderImage>());
1194 const QSSGRenderImageTexture texture = image.image ? theBufferManager.loadRenderImage(image.image) : QSSGRenderImageTexture();
1195 if (texture.m_texture) {
1196 if (image.imageType.contains("Cube") && !(texture.m_texture->flags() & QRhiTexture::CubeMap)) {
1197 qWarning() << "Image type is not CubeMap: " << inPropertyName;
1198 return;
1199 }
1200 if (image.qualifiers.testFlag(QSSGMemoryQualifier::Readonly))
1201 addStorageImageBinding(inPropertyName, QRhiShaderResourceBinding::ImageLoad, texture.m_texture, binding);
1202 else if (image.qualifiers.testFlag(QSSGMemoryQualifier::Writeonly))
1203 addStorageImageBinding(inPropertyName, QRhiShaderResourceBinding::ImageStore, texture.m_texture, binding);
1204 else
1205 addStorageImageBinding(inPropertyName, QRhiShaderResourceBinding::ImageLoadStore, texture.m_texture, binding);
1206 } else {
1207 qWarning() << "Image binding failed: " << inPropertyName;
1208 }
1209 }
1210 } else {
1211 setUniformValue(ubufData, inPropertyName, propertyValue, inPropertyType);
1212 }
1213}
1214
1215
1216/*!
1217 \internal
1218 */
1219QSSGRhiContext::QSSGRhiContext(QRhi *rhi)
1220 : d_ptr(new QSSGRhiContextPrivate(*this, rhi))
1221{
1222 Q_ASSERT(rhi);
1223 Q_STATIC_ASSERT(int(QSSGRhiSamplerBindingHints::LightProbe) > int(QSSGRenderableImage::Type::Occlusion));
1224}
1225
1226/*!
1227 \internal
1228 */
1229QSSGRhiContext::~QSSGRhiContext()
1230{
1231 Q_D(QSSGRhiContext);
1232 d->releaseCachedResources();
1233 d->invalidateManagedTextures();
1234
1235 qDeleteAll(d->m_textures);
1236 qDeleteAll(d->m_meshes);
1237}
1238
1239/*!
1240 \return The QRhi object used by the Qt Quick 3D renderer.
1241 */
1242QRhi *QSSGRhiContext::rhi() const
1243{
1244 Q_D(const QSSGRhiContext);
1245 return d->m_rhi;
1246}
1247
1248/*!
1249 \return true if the renderer is initialized successfully.
1250 */
1251bool QSSGRhiContext::isValid() const
1252{
1253 Q_D(const QSSGRhiContext);
1254 return d->m_rhi != nullptr;
1255}
1256
1257void QSSGRhiContextPrivate::setMainRenderPassDescriptor(QRhiRenderPassDescriptor *rpDesc)
1258{
1259 m_mainRpDesc = rpDesc;
1260}
1261
1262/*!
1263 \return The QRhiRenderPassDescriptor used by the main render pass of the Qt
1264 Quick 3D renderer.
1265 */
1266QRhiRenderPassDescriptor *QSSGRhiContext::mainRenderPassDescriptor() const
1267{
1268 Q_D(const QSSGRhiContext);
1269 return d->m_mainRpDesc;
1270}
1271
1272void QSSGRhiContextPrivate::setCommandBuffer(QRhiCommandBuffer *cb)
1273{
1274 m_cb = cb;
1275}
1276
1277/*!
1278 \return The current frame's command buffer used by the Qt Quick 3D renderer.
1279 */
1280QRhiCommandBuffer *QSSGRhiContext::commandBuffer() const
1281{
1282 Q_D(const QSSGRhiContext);
1283 return d->m_cb;
1284}
1285
1286void QSSGRhiContextPrivate::setRenderTarget(QRhiRenderTarget *rt)
1287{
1288 m_rt = rt;
1289}
1290
1291/*!
1292 \return The render target the Qt Quick 3D renderer uses for its main render
1293 pass in the current frame.
1294
1295 This can effectively be a render target from a swapchain, if the \l View3D
1296 uses a renderMode other than Offscreen. More commonly, the render target
1297 refers to a texture (i.e., is a QRhiTextureRenderTarget), e.g. because the
1298 renderMode is the default Offscreen, or because post-processing effects are
1299 in use.
1300 */
1301QRhiRenderTarget *QSSGRhiContext::renderTarget() const
1302{
1303 Q_D(const QSSGRhiContext);
1304 return d->m_rt;
1305}
1306
1307void QSSGRhiContextPrivate::setMainPassSampleCount(int samples)
1308{
1309 m_mainSamples = samples;
1310}
1311
1312/*!
1313 Returns the sample count used in the main render pass.
1314 */
1315int QSSGRhiContext::mainPassSampleCount() const
1316{
1317 Q_D(const QSSGRhiContext);
1318 return d->m_mainSamples;
1319}
1320
1321void QSSGRhiContextPrivate::setMainPassViewCount(int viewCount)
1322{
1323 m_mainViewCount = viewCount;
1324}
1325
1326/*!
1327 Returns the multiview count used in the main render pass. This is either 2,
1328 when multiview rendering is in use, or 1 (no multiview).
1329 */
1330int QSSGRhiContext::mainPassViewCount() const
1331{
1332 Q_D(const QSSGRhiContext);
1333 return d->m_mainViewCount;
1334}
1335
1336void QSSGRhiContextPrivate::releaseCachedResources()
1337{
1338 for (QSSGRhiDrawCallData &dcd : m_drawCallData) {
1339 // We don't call releaseDrawCallData() here, since we're anyways
1340 // are going to delete the non-owned resources further down and
1341 // there's no point in removing each of those one-by-one, as is
1342 // the case with releaseDrawCallData().
1343 // This speeds up the release of cached resources greatly when there
1344 // are many entries in the map, also at application shutdown.
1345 dcd.reset();
1346 }
1347
1348 m_drawCallData.clear();
1349
1350 qDeleteAll(m_pipelines);
1351 qDeleteAll(m_computePipelines);
1352 qDeleteAll(m_srbCache);
1353 qDeleteAll(m_dummyTextures);
1354
1355 m_pipelines.clear();
1356 m_computePipelines.clear();
1357 m_srbCache.clear();
1358 m_dummyTextures.clear();
1359
1360 for (const auto &samplerInfo : std::as_const(m_samplers))
1361 delete samplerInfo.second;
1362
1363 m_samplers.clear();
1364
1365 for (const auto &particleData : std::as_const(m_particleData))
1366 delete particleData.texture;
1367
1368 m_particleData.clear();
1369
1370 for (const auto &instanceData : std::as_const(m_instanceBuffers)) {
1371 if (instanceData.owned)
1372 delete instanceData.buffer;
1373 delete instanceData.instanceIndexBuffer;
1374 }
1375
1376 m_instanceBuffers.clear();
1377
1378 for (const auto &instanceData : std::as_const(m_instanceBuffersPerModel)) {
1379 if (instanceData.owned)
1380 delete instanceData.buffer;
1381 delete instanceData.instanceIndexBuffer;
1382 for (const auto &subsetLod : std::as_const(instanceData.subsetLodData)) {
1383 delete subsetLod.buffer;
1384 delete subsetLod.instanceIndexBuffer;
1385 }
1386 }
1387
1388 m_instanceBuffersPerModel.clear();
1389 m_autoLodLevelOfInstance = {};
1390}
1391
1392QRhiShaderResourceBindings *QSSGRhiContextPrivate::srb(const QSSGRhiShaderResourceBindingList &bindings)
1393{
1394 auto it = m_srbCache.constFind(bindings);
1395 if (it != m_srbCache.constEnd())
1396 return *it;
1397
1398 QRhiShaderResourceBindings *srb = m_rhi->newShaderResourceBindings();
1399 srb->setBindings(bindings.v, bindings.v + bindings.p);
1400 if (srb->create()) {
1401 m_srbCache.insert(bindings, srb);
1402 } else {
1403 qWarning("Failed to build srb");
1404 delete srb;
1405 srb = nullptr;
1406 }
1407 return srb;
1408}
1409
1410void QSSGRhiContextPrivate::releaseCachedSrb(QSSGRhiShaderResourceBindingList &bindings)
1411{
1412 auto srb = m_srbCache.take(bindings);
1413 delete srb;
1414}
1415
1416void QSSGRhiContextPrivate::releaseDrawCallData(QSSGRhiDrawCallData &dcd)
1417{
1418 delete dcd.ubuf;
1419 dcd.ubuf = nullptr;
1420 auto srb = m_srbCache.take(dcd.bindings);
1421 QSSG_CHECK(srb == dcd.srb);
1422 delete srb;
1423 dcd.srb = nullptr;
1424 dcd.pipeline = nullptr;
1425}
1426
1427QRhiGraphicsPipeline *QSSGRhiContextPrivate::pipeline(const QSSGRhiGraphicsPipelineState &ps,
1428 QRhiRenderPassDescriptor *rpDesc,
1429 QRhiShaderResourceBindings *srb)
1430{
1431 return pipeline(QSSGGraphicsPipelineStateKey::create(ps, rpDesc, srb), rpDesc, srb);
1432}
1433
1434QRhiComputePipeline *QSSGRhiContextPrivate::computePipeline(const QShader &shader,
1435 QRhiShaderResourceBindings *srb)
1436{
1437 return computePipeline(QSSGComputePipelineStateKey::create(shader, srb), srb);
1438}
1439
1440QSSGRhiDrawCallData &QSSGRhiContextPrivate::drawCallData(const QSSGRhiDrawCallDataKey &key)
1441{
1442 return m_drawCallData[key];
1443}
1444
1445using SamplerInfo = QPair<QSSGRhiSamplerDescription, QRhiSampler*>;
1446
1447/*!
1448 \return a sampler with the filter and tiling modes specified in \a samplerDescription.
1449
1450 The generated QRhiSampler objects are cached and reused. Thus this is a
1451 convenient way to gain access to a QRhiSampler with the given settings,
1452 without having to create a new, dedicated object all the time.
1453
1454 The ownership of the returned QRhiSampler stays with Qt Quick 3D.
1455 */
1456QRhiSampler *QSSGRhiContext::sampler(const QSSGRhiSamplerDescription &samplerDescription)
1457{
1458 Q_D(QSSGRhiContext);
1459 auto compareSampler = [samplerDescription](const SamplerInfo &info){ return info.first == samplerDescription; };
1460 auto &samplers = d->m_samplers;
1461 const auto found = std::find_if(samplers.cbegin(), samplers.cend(), compareSampler);
1462 if (found != samplers.cend())
1463 return found->second;
1464
1465 QRhiSampler *newSampler = d->m_rhi->newSampler(samplerDescription.magFilter,
1466 samplerDescription.minFilter,
1467 samplerDescription.mipmap,
1468 samplerDescription.hTiling,
1469 samplerDescription.vTiling,
1470 samplerDescription.zTiling);
1471 if (!newSampler->create()) {
1472 qWarning("Failed to build image sampler");
1473 delete newSampler;
1474 return nullptr;
1475 }
1476 samplers << SamplerInfo{samplerDescription, newSampler};
1477 return newSampler;
1478}
1479
1480/*!
1481 Adjusts \a samplerDescription's tiling and filtering modes based on the
1482 pixel size of \a texture.
1483
1484 In most cases, \a samplerDescription is not changed. With older, legacy 3D
1485 APIs in use, there is however a chance that tiling modes such as
1486 \l{QRhiSampler::Repeat} are not supported for textures with a
1487 non-power-of-two width or height.
1488
1489 This convenience function helps creating robust applications that can still
1490 function even when features such as \l{QRhi::NPOTTextureRepeat} are not
1491 supported by an OpenGL ES 2.0 or WebGL 1 implementation at run time.
1492 */
1493void QSSGRhiContext::checkAndAdjustForNPoT(QRhiTexture *texture, QSSGRhiSamplerDescription *samplerDescription)
1494{
1495 Q_D(const QSSGRhiContext);
1496 if (samplerDescription->mipmap != QRhiSampler::None
1497 || samplerDescription->hTiling != QRhiSampler::ClampToEdge
1498 || samplerDescription->vTiling != QRhiSampler::ClampToEdge
1499 || samplerDescription->zTiling != QRhiSampler::ClampToEdge)
1500 {
1501 if (d->m_rhi->isFeatureSupported(QRhi::NPOTTextureRepeat))
1502 return;
1503
1504 const QSize pixelSize = texture->pixelSize();
1505 const int w = qNextPowerOfTwo(pixelSize.width() - 1);
1506 const int h = qNextPowerOfTwo(pixelSize.height() - 1);
1507 if (w != pixelSize.width() || h != pixelSize.height()) {
1508 static bool warnShown = false;
1509 if (!warnShown) {
1510 warnShown = true;
1511 qWarning("Attempted to use an unsupported filtering or wrap mode, "
1512 "this is likely due to lacking proper support for non-power-of-two textures on this platform.\n"
1513 "If this is with WebGL, try updating the application to use QQuick3D::idealSurfaceFormat() in main() "
1514 "in order to ensure WebGL 2 is used.");
1515 }
1516 samplerDescription->mipmap = QRhiSampler::None;
1517 samplerDescription->hTiling = QRhiSampler::ClampToEdge;
1518 samplerDescription->vTiling = QRhiSampler::ClampToEdge;
1519 samplerDescription->zTiling = QRhiSampler::ClampToEdge;
1520 }
1521 }
1522}
1523
1524void QSSGRhiContextPrivate::registerTexture(QRhiTexture *texture)
1525{
1526 m_textures.insert(texture);
1527}
1528
1529void QSSGRhiContextPrivate::releaseTexture(QRhiTexture *texture)
1530{
1531 m_textures.remove(texture);
1532 delete texture;
1533}
1534
1535void QSSGRhiContextPrivate::registerMesh(QSSGRenderMesh *mesh)
1536{
1537 m_meshes.insert(mesh);
1538}
1539
1540void QSSGRhiContextPrivate::refManagedTexture(QRhiTexture *texture)
1541{
1542 auto it = m_managedTextureRefs.find(texture);
1543 if (it != m_managedTextureRefs.end())
1544 it.value() += 1;
1545 else
1546 m_managedTextureRefs.insert(texture, 1);
1547}
1548
1549// Returns false if the texture was not tracked.
1550bool QSSGRhiContextPrivate::derefManagedTexture(QRhiTexture *texture)
1551{
1552 auto it = m_managedTextureRefs.find(texture);
1553 if (it == m_managedTextureRefs.end())
1554 return false;
1555
1556 if (it.value() > 1) {
1557 it.value() -= 1;
1558 } else {
1559 m_managedTextureRefs.erase(it);
1560 m_resourceRegistry.retire(texture);
1561 // The frame being recorded may still reference the texture, so
1562 // deleteLater() keeps it alive until that frame is submitted.
1563 texture->deleteLater();
1564 }
1565
1566 return true;
1567}
1568
1569void QSSGRhiContextPrivate::registerManagedTexture(QSSGManagedRhiTexture *wrapper)
1570{
1571 QSSG_ASSERT(wrapper != nullptr, return);
1572 QSSG_CHECK_X(QThread::currentThread() == m_rhi->thread(), "Managed texture referenced off the render thread");
1573
1574 // An invalid wrapper has nothing to track.
1575 if (!wrapper->m_texture)
1576 return;
1577
1578 if (!m_managedTextureWrappers.contains(wrapper)) {
1579 refManagedTexture(wrapper->m_texture);
1580 m_managedTextureWrappers.insert(wrapper);
1581 }
1582}
1583
1584void QSSGRhiContextPrivate::unregisterManagedTexture(QSSGManagedRhiTexture *wrapper)
1585{
1586 QSSG_ASSERT(wrapper != nullptr, return);
1587 QSSG_CHECK_X(QThread::currentThread() == m_rhi->thread(), "Managed texture referenced off the render thread");
1588
1589 if (m_managedTextureWrappers.remove(wrapper)) {
1590 if (!derefManagedTexture(wrapper->m_texture))
1591 qWarning("QSSGRhiContext: Releasing a managed texture that was not tracked, possible resource leak.");
1592 }
1593}
1594
1595// A wrapper was moved; the reference it holds is unchanged, only its address is.
1596void QSSGRhiContextPrivate::relocateManagedTexture(QSSGManagedRhiTexture *from, QSSGManagedRhiTexture *to)
1597{
1598 QSSG_ASSERT(from != nullptr && to != nullptr, return);
1599 QSSG_CHECK_X(QThread::currentThread() == m_rhi->thread(), "Managed texture referenced off the render thread");
1600
1601 if (m_managedTextureWrappers.remove(from))
1602 m_managedTextureWrappers.insert(to);
1603}
1604
1605// Releases every managed texture and detaches the wrappers that still
1606// reference them. Wrappers that outlive the context, e.g. one in a backend
1607// node that was never released, become invalid instead of dangling.
1608void QSSGRhiContextPrivate::invalidateManagedTextures()
1609{
1610 // invalidate() calls back into unregisterManagedTexture(), so iterate over a copy.
1611 const auto wrappers = m_managedTextureWrappers;
1612 for (auto *wrapper : wrappers)
1613 wrapper->invalidate();
1614
1615 Q_ASSERT(m_managedTextureWrappers.isEmpty());
1616
1617 if (!m_managedTextureRefs.isEmpty()) {
1618 qWarning() << "QSSGRhiContext: There are still" << m_managedTextureRefs.size()
1619 << "tracked managed textures without a wrapper. This indicates a resource leak.";
1620 const auto textures = m_managedTextureRefs.keys();
1621 qDeleteAll(textures);
1622 m_managedTextureRefs.clear();
1623 }
1624}
1625
1626void QSSGRhiContextPrivate::releaseMesh(QSSGRenderMesh *mesh)
1627{
1628 if (mesh) {
1629 for (const auto &subset : std::as_const(mesh->subsets)) {
1630 if (subset.rhi.targetsTexture) {
1631 // If there is a morph targets texture, it should be the same for
1632 // all subsets, so just release and break
1633 releaseTexture(subset.rhi.targetsTexture);
1634 break;
1635 }
1636 }
1637 }
1638 m_meshes.remove(mesh);
1639 delete mesh;
1640}
1641
1642QSSGManagedRhiTexture QSSGRhiContextPrivate::create(QRhiTexture *texture)
1643{
1644 return QSSGManagedRhiTexture{ *this, texture, QSSGManagedRhiTexture::Private::Initialize };
1645}
1646
1647void QSSGRhiContextPrivate::cleanupDrawCallData(const QSSGRenderModel *model)
1648{
1649 // Find all QSSGRhiUniformBufferSet that reference model
1650 // and delete them
1651 const void *modelNode = model;
1652 auto it = m_drawCallData.begin();
1653 while (it != m_drawCallData.end()) {
1654 if (it.key().model == modelNode) {
1655 releaseDrawCallData(*it);
1656 it = m_drawCallData.erase(it);
1657 } else {
1658 ++it;
1659 }
1660 }
1661}
1662
1663template<typename Predicate>
1664static void releaseAutoLodDataIf(QHash<const QSSGRenderModel *, QSSGRhiInstanceBufferData> &instanceBuffersPerModel,
1665 Predicate release)
1666{
1667 using SubsetLodIterator = QHash<QSSGRhiInstanceBufferData::SubsetLodKey, QSSGRhiInstanceBufferData::SubsetLodData>::iterator;
1668 for (auto &instanceData : instanceBuffersPerModel) {
1669 instanceData.subsetLodData.removeIf([&release](SubsetLodIterator it) {
1670 if (!release(it.key(), it.value()))
1671 return false;
1672 // Not drawn in this frame, and QRhi keeps the native buffers of the frames in flight.
1673 delete it->buffer;
1674 delete it->instanceIndexBuffer;
1675 return true;
1676 });
1677 }
1678}
1679
1680void QSSGRhiContextPrivate::releaseUnusedAutoLodData(const QSSGRenderLayer *layer, quint32 frame)
1681{
1682 releaseAutoLodDataIf(m_instanceBuffersPerModel, [layer, frame](const QSSGRhiInstanceBufferData::SubsetLodKey &key,
1683 const QSSGRhiInstanceBufferData::SubsetLodData &data) {
1684 return key.second == layer && data.lastUsedFrame != frame;
1685 });
1686}
1687
1688void QSSGRhiContextPrivate::releaseAutoLodData(const QSSGRenderLayer *layer)
1689{
1690 releaseAutoLodDataIf(m_instanceBuffersPerModel, [layer](const QSSGRhiInstanceBufferData::SubsetLodKey &key,
1691 const QSSGRhiInstanceBufferData::SubsetLodData &) {
1692 return key.second == layer;
1693 });
1694}
1695
1696void QSSGRhiContextPrivate::cleanupDrawCallDataForResource(const void *resource)
1697{
1698 // Find all QSSGRhiUniformBufferSet that were keyed on resource (typically
1699 // a material that is being destroyed) and delete them.
1700 auto it = m_drawCallData.begin();
1701 while (it != m_drawCallData.end()) {
1702 if (it.key().resource == resource) {
1703 releaseDrawCallData(*it);
1704 it = m_drawCallData.erase(it);
1705 } else {
1706 ++it;
1707 }
1708 }
1709}
1710
1711void QSSGRhiContextPrivate::cleanupDrawCallDataForCid(const void *cid)
1712{
1713 // Find all QSSGRhiUniformBufferSet that were keyed on cid (a pass, or a
1714 // pass-like owner such as a render extension or an effect system, that is
1715 // being destroyed) and delete them.
1716 auto it = m_drawCallData.begin();
1717 while (it != m_drawCallData.end()) {
1718 if (it.key().cid == cid) {
1719 releaseDrawCallData(*it);
1720 it = m_drawCallData.erase(it);
1721 } else {
1722 ++it;
1723 }
1724 }
1725}
1726
1727void QSSGRhiContextPrivate::cleanupDrawCallDataForSkyMaterial(QSSGRenderSkyMaterial *skyMaterial)
1728{
1729 // Not a material type-wise, but it keys its uniform buffers the
1730 // same way, and the srbs for the environment cube and background
1731 // passes are cached with the material's binding lists as the key.
1732 releaseCachedSrb(skyMaterial->bindings);
1733 releaseCachedSrb(skyMaterial->backgroundBindings);
1734 cleanupDrawCallDataForResource(skyMaterial);
1735}
1736
1737void QSSGRhiContextPrivate::cleanupDrawCallDataForUserPass(const QSSGRenderUserPassBase *userPass)
1738{
1739 // Releases compute passes, which use the model field.
1740 // Render user passes put the model node in it, but they also don't have pass specific
1741 // draw call data so they don't need to be cleared here.
1742 auto it = m_drawCallData.begin();
1743 while (it != m_drawCallData.end()) {
1744 if (it.key().model == userPass) {
1745 releaseDrawCallData(*it);
1746 it = m_drawCallData.erase(it);
1747 } else {
1748 ++it;
1749 }
1750 }
1751}
1752
1753/*!
1754 \return a texture that has the specified \a flags and pixel \a size.
1755
1756 This is intended to efficiently gain access to a "dummy" texture filled
1757 with a given \a fillColor, and reused in various places in the rendering
1758 stack.
1759
1760 \a rub must be a valid QRhiResourceUpdateBatch since this function will
1761 create a new texture and generate content for it, if a suitable cached
1762 object is not found. The necessary upload operations are then enqueued on
1763 this given update batch.
1764
1765 When \a arraySize is 2 or more, a 2D texture array is returned.
1766
1767 Note that the function currently returns plain cube map instead of array
1768 cube map if requested due to missing support in rhi.
1769
1770 The ownership of the returned texture stays with Qt Quick 3D.
1771 */
1772QRhiTexture *QSSGRhiContext::dummyTexture(QRhiTexture::Flags flags, QRhiResourceUpdateBatch *rub,
1773 const QSize &size, const QColor &fillColor, int arraySize)
1774{
1775 Q_D(QSSGRhiContext);
1776 // The rhi doesn't have cubemap array view type so best we can do is plain cubemap
1777 // Once they are supported, remove arraySize = 0 and update the fill loop for all faces
1778 const bool isCube = flags.testFlags(QRhiTexture::CubeMap);
1779 if (isCube)
1780 arraySize = 0;
1781 auto it = d->m_dummyTextures.constFind({flags, size, fillColor, arraySize});
1782 if (it != d->m_dummyTextures.constEnd())
1783 return *it;
1784
1785 QRhiTexture *t = arraySize < 2
1786 ? d->m_rhi->newTexture(QRhiTexture::RGBA8, size, 1, flags)
1787 : d->m_rhi->newTextureArray(QRhiTexture::RGBA8, arraySize, size, 1, flags);
1788 if (t->create()) {
1789 QImage image(t->pixelSize(), QImage::Format_RGBA8888);
1790 image.fill(fillColor);
1791 rub->uploadTexture(t, image);
1792 // Must fill all cubemap faces. Otherwise the result is undefined.
1793 const int layerCount = isCube ? 6 : arraySize;
1794 for (int layer = 1; layer < layerCount; ++layer)
1795 rub->uploadTexture(t, QRhiTextureUploadDescription(QRhiTextureUploadEntry(layer, 0, QRhiTextureSubresourceUploadDescription(image))));
1796 } else {
1797 qWarning("Failed to build dummy texture");
1798 }
1799
1800 d->m_dummyTextures.insert({flags, size, fillColor, arraySize}, t);
1801 return t;
1802}
1803
1804QSSGRhiInstanceBufferData &QSSGRhiContextPrivate::instanceBufferData(QSSGRenderInstanceTable *instanceTable)
1805{
1806 return m_instanceBuffers[instanceTable];
1807}
1808
1809void QSSGRhiContextPrivate::releaseInstanceBuffer(QSSGRenderInstanceTable *instanceTable)
1810{
1811 auto it = m_instanceBuffers.constFind(instanceTable);
1812 if (it != m_instanceBuffers.constEnd()) {
1813 if (it->owned)
1814 delete it->buffer;
1815 delete it->instanceIndexBuffer;
1816 m_instanceBuffers.erase(it);
1817 }
1818
1819 // Forget this table in the per-model copies built from it, so that they are rebuilt even
1820 // if a new table later gets the same address.
1821 for (auto &instanceData : m_instanceBuffersPerModel) {
1822 if (instanceData.table == instanceTable)
1823 instanceData.table = nullptr;
1824 for (auto &subsetLod : instanceData.subsetLodData) {
1825 if (subsetLod.table == instanceTable)
1826 subsetLod.table = nullptr;
1827 }
1828 }
1829}
1830
1831QSSGRhiInstanceBufferData &QSSGRhiContextPrivate::instanceBufferData(const QSSGRenderModel *model)
1832{
1833 return m_instanceBuffersPerModel[model];
1834}
1835
1836void QSSGRhiContextPrivate::releaseModelInstanceCopy(const QSSGRenderModel *model)
1837{
1838 auto it = m_instanceBuffersPerModel.constFind(model);
1839 if (it == m_instanceBuffersPerModel.constEnd() || !it->buffer)
1840 return;
1841 QSSGRhiInstanceBufferData &instanceData = m_instanceBuffersPerModel[model];
1842 if (instanceData.owned)
1843 delete instanceData.buffer;
1844 instanceData.buffer = nullptr;
1845 delete instanceData.instanceIndexBuffer;
1846 instanceData.instanceIndexBuffer = nullptr;
1847 instanceData.sortedData = {};
1848 instanceData.sortData = {};
1849 instanceData.lodData = {};
1850 instanceData.lodInstanceIndices = {};
1851 // Rebuilt from the table if the model needs a copy again.
1852 instanceData.tableGeneration = -1;
1853 instanceData.sorting = false;
1854 ++instanceData.generation;
1855}
1856
1857void QSSGRhiContextPrivate::releaseModelInstanceData(const QSSGRenderModel *model)
1858{
1859 // Also releases the per-subset buffers of the automatic per-instance LOD.
1860 auto it = m_instanceBuffersPerModel.constFind(model);
1861 if (it != m_instanceBuffersPerModel.constEnd()) {
1862 if (it->owned)
1863 delete it->buffer;
1864 delete it->instanceIndexBuffer;
1865 for (const auto &subsetLod : std::as_const(it->subsetLodData)) {
1866 delete subsetLod.buffer;
1867 delete subsetLod.instanceIndexBuffer;
1868 }
1869 m_instanceBuffersPerModel.erase(it);
1870 }
1871}
1872
1873QSSGRhiParticleData &QSSGRhiContextPrivate::particleData(const QSSGRenderGraphObject *particlesOrModel)
1874{
1875 return m_particleData[particlesOrModel];
1876}
1877
1878void QSSGRhiContextStats::start(QSSGRenderLayer *layer)
1879{
1880 layerKey = layer;
1881 PerLayerInfo &info(perLayerInfo[layerKey]);
1882 info.renderPasses.clear();
1883 info.externalRenderPass = {};
1884 info.currentRenderPassIndex = -1;
1885}
1886
1887void QSSGRhiContextStats::stop(QSSGRenderLayer *layer)
1888{
1889 if (rendererDebugEnabled()) {
1890 PerLayerInfo &info(perLayerInfo[layer]);
1891 const int rpCount = info.renderPasses.size();
1892 qDebug("%d render passes in 3D renderer %p", rpCount, layer);
1893 for (int i = 0; i < rpCount; ++i) {
1894 const RenderPassInfo &rp(info.renderPasses[i]);
1895 qDebug("Render pass %d: rt name='%s' target size %dx%d pixels",
1896 i, rp.rtName.constData(), rp.pixelSize.width(), rp.pixelSize.height());
1897 printRenderPass(rp);
1898 }
1899 if (info.externalRenderPass.indexedDraws.callCount || info.externalRenderPass.instancedIndexedDraws.callCount
1900 || info.externalRenderPass.draws.callCount || info.externalRenderPass.instancedDraws.callCount)
1901 {
1902 qDebug("Within external render passes:");
1903 printRenderPass(info.externalRenderPass);
1904 }
1905 }
1906
1907 // a new start() may preceed stop() for the previous View3D, must handle this gracefully
1908 if (layerKey == layer)
1909 layerKey = nullptr;
1910
1911 // The data must stay valid until the next start() with the same key, the
1912 // QQuick3DRenderStats and DebugView may read it.
1913}
1914
1915void QSSGRhiContextStats::cleanupLayerInfo(QSSGRenderLayer *layer)
1916{
1917 perLayerInfo.remove(layer);
1918 dynamicDataSources.remove(layer);
1919}
1920
1921void QSSGRhiContextStats::beginRenderPass(QRhiTextureRenderTarget *rt)
1922{
1923 PerLayerInfo &info(perLayerInfo[layerKey]);
1924 Q_TRACE(QSSG_renderPass_entry, QString::fromUtf8(rt->name()));
1925 info.renderPasses.append({ rt->name(), rt->pixelSize(), {}, {}, {}, {} });
1926 info.currentRenderPassIndex = info.renderPasses.size() - 1;
1927}
1928
1929void QSSGRhiContextStats::endRenderPass()
1930{
1931 Q_TRACE(QSSG_renderPass_exit);
1932 PerLayerInfo &info(perLayerInfo[layerKey]);
1933 info.currentRenderPassIndex = -1;
1934}
1935
1936QSSGRhiContextStats &QSSGRhiContextStats::get(QSSGRhiContext &rhiCtx)
1937{
1938 return QSSGRhiContextPrivate::get(&rhiCtx)->m_stats;
1939}
1940
1941const QSSGRhiContextStats &QSSGRhiContextStats::get(const QSSGRhiContext &rhiCtx)
1942{
1943 return QSSGRhiContextPrivate::get(&rhiCtx)->m_stats;
1944}
1945
1946bool QSSGRhiContextStats::profilingEnabled()
1947{
1948 static bool enabled = Q_QUICK3D_PROFILING_ENABLED;
1949 return enabled;
1950}
1951
1952bool QSSGRhiContextStats::rendererDebugEnabled()
1953{
1954 static bool enabled = qgetenv("QSG_RENDERER_DEBUG").contains(QByteArrayLiteral("render"));
1955 return enabled;
1956}
1957
1958bool QSSGRhiContextStats::isEnabled() const
1959{
1960 return !dynamicDataSources.isEmpty() || profilingEnabled() || rendererDebugEnabled()
1961 || Q_TRACE_ENABLED(QSSG_draw);
1962}
1963
1964void QSSGRhiContextStats::drawIndexed(quint32 indexCount, quint32 instanceCount)
1965{
1966 Q_TRACE(QSSG_drawIndexed, indexCount, instanceCount);
1967 PerLayerInfo &info(perLayerInfo[layerKey]);
1968 RenderPassInfo &rp(info.currentRenderPassIndex >= 0 ? info.renderPasses[info.currentRenderPassIndex] : info.externalRenderPass);
1969 if (instanceCount > 1) {
1970 rp.instancedIndexedDraws.callCount += 1;
1971 rp.instancedIndexedDraws.vertexOrIndexCount += indexCount;
1972 rp.instancedIndexedDraws.instanceCount += instanceCount;
1973 } else {
1974 rp.indexedDraws.callCount += 1;
1975 rp.indexedDraws.vertexOrIndexCount += indexCount;
1976 }
1977}
1978
1979void QSSGRhiContextStats::draw(quint32 vertexCount, quint32 instanceCount)
1980{
1981 Q_TRACE(QSSG_draw, vertexCount, instanceCount);
1982 PerLayerInfo &info(perLayerInfo[layerKey]);
1983 RenderPassInfo &rp(info.currentRenderPassIndex >= 0 ? info.renderPasses[info.currentRenderPassIndex] : info.externalRenderPass);
1984 if (instanceCount > 1) {
1985 rp.instancedDraws.callCount += 1;
1986 rp.instancedDraws.vertexOrIndexCount += vertexCount;
1987 rp.instancedDraws.instanceCount += instanceCount;
1988 } else {
1989 rp.draws.callCount += 1;
1990 rp.draws.vertexOrIndexCount += vertexCount;
1991 }
1992}
1993
1994void QSSGRhiContextStats::printRenderPass(const QSSGRhiContextStats::RenderPassInfo &rp)
1995{
1996 qDebug("%llu indexed draw calls with %llu indices in total, "
1997 "%llu non-indexed draw calls with %llu vertices in total",
1998 rp.indexedDraws.callCount, rp.indexedDraws.vertexOrIndexCount,
1999 rp.draws.callCount, rp.draws.vertexOrIndexCount);
2000 if (rp.instancedIndexedDraws.callCount || rp.instancedDraws.callCount) {
2001 qDebug("%llu instanced indexed draw calls with %llu indices and %llu instances in total, "
2002 "%llu instanced non-indexed draw calls with %llu indices and %llu instances in total",
2003 rp.instancedIndexedDraws.callCount, rp.instancedIndexedDraws.vertexOrIndexCount, rp.instancedIndexedDraws.instanceCount,
2004 rp.instancedDraws.callCount, rp.instancedDraws.vertexOrIndexCount, rp.instancedDraws.instanceCount);
2005 }
2006}
2007
2008QRhiShaderResourceBinding::Data *QSSGRhiShaderResourceBindingList::newBinding()
2009{
2010#ifdef QT_DEBUG
2011 if (p == MAX_SIZE) {
2012 qWarning("Out of shader resource bindings slots (max is %d)", MAX_SIZE);
2013 return nullptr;
2014 }
2015#endif
2016 return QRhiImplementation::shaderResourceBindingData(v[p++]);
2017}
2018
2019template<QRhiShaderResourceBinding::Type T>
2020void QSSGRhiShaderResourceBindingList::fillImage(QRhiShaderResourceBinding::Data *d, int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiTexture *tex, int level)
2021{
2022 d->binding = binding;
2023 d->stage = stage;
2024 d->u.emplace<T>(QRhiShaderResourceBinding::Data::StorageImageData{ tex, level });
2025 h ^= qintptr(tex) ^ qintptr(level);
2026}
2027
2028template<QRhiShaderResourceBinding::Type T>
2029void QSSGRhiShaderResourceBindingList::fillStorageBuffer(QRhiShaderResourceBinding::Data *d, int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiBuffer *buf, int offset, int size)
2030{
2031 d->binding = binding;
2032 d->stage = stage;
2033 d->u.emplace<T>(QRhiShaderResourceBinding::Data::StorageBufferData{ buf, quint32(offset), quint32(size) }); // size 0 = all
2034 h ^= qintptr(buf);
2035}
2036
2037void QSSGRhiShaderResourceBindingList::addUniformBuffer(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiBuffer *buf, int offset, int size, bool hasDynamicOffset)
2038{
2039 auto *d = newBinding();
2040 if (!d)
2041 return;
2042 h ^= qintptr(buf);
2043 d->binding = binding;
2044 d->stage = stage;
2045 d->u.emplace<QRhiShaderResourceBinding::UniformBuffer>(
2046 QRhiShaderResourceBinding::Data::UniformBufferData{ buf, quint32(offset), quint32(size), hasDynamicOffset }); // size 0 = all
2047}
2048
2049void QSSGRhiShaderResourceBindingList::addStorageBufferLoadStore(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiBuffer *buf, int offset, int size)
2050{
2051 auto *d = newBinding();
2052 if (!d)
2053 return;
2054 fillStorageBuffer<QRhiShaderResourceBinding::BufferLoadStore>(d, binding, stage, buf, offset, size);
2055}
2056
2057void QSSGRhiShaderResourceBindingList::addStorageBufferLoad(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiBuffer *buf, int offset, int size)
2058{
2059 auto *d = newBinding();
2060 if (!d)
2061 return;
2062 fillStorageBuffer<QRhiShaderResourceBinding::BufferLoad>(d, binding, stage, buf, offset, size);
2063}
2064
2065void QSSGRhiShaderResourceBindingList::addStorageBufferStore(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiBuffer *buf, int offset, int size)
2066{
2067 auto *d = newBinding();
2068 if (!d)
2069 return;
2070 fillStorageBuffer<QRhiShaderResourceBinding::BufferStore>(d, binding, stage, buf, offset, size);
2071}
2072
2073void QSSGRhiShaderResourceBindingList::addTexture(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiTexture *tex, QRhiSampler *sampler)
2074{
2075 auto *d = newBinding();
2076 if (!d)
2077 return;
2078 h ^= qintptr(tex) ^ qintptr(sampler);
2079 d->binding = binding;
2080 d->stage = stage;
2081 // not using the return value of emplace(), it is void on VxWorks (no LWG 2857)
2082 d->u.emplace<QRhiShaderResourceBinding::SampledTexture>();
2083 std::get_if<QRhiShaderResourceBinding::SampledTexture>(&d->u)->texSamplers = { { tex, sampler } };
2084}
2085
2086void QSSGRhiShaderResourceBindingList::addImageLoad(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiTexture *tex, int level)
2087{
2088 auto *d = newBinding();
2089 if (!d)
2090 return;
2091 fillImage<QRhiShaderResourceBinding::ImageLoad>(d, binding, stage, tex, level);
2092}
2093
2094void QSSGRhiShaderResourceBindingList::addImageStore(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiTexture *tex, int level)
2095{
2096 auto *d = newBinding();
2097 if (!d)
2098 return;
2099 fillImage<QRhiShaderResourceBinding::ImageStore>(d, binding, stage, tex, level);
2100}
2101
2102void QSSGRhiShaderResourceBindingList::addImageLoadStore(int binding, QRhiShaderResourceBinding::StageFlags stage, QRhiTexture *tex, int level)
2103{
2104 auto *d = newBinding();
2105 if (!d)
2106 return;
2107 fillImage<QRhiShaderResourceBinding::ImageLoadStore>(d, binding, stage, tex, level);
2108}
2109
2110bool QSSGRhiContextPrivate::shaderDebuggingEnabled()
2111{
2112 static const bool isSet = (qEnvironmentVariableIntValue("QT_RHI_SHADER_DEBUG") != 0);
2113 return isSet;
2114}
2115
2116bool QSSGRhiContextPrivate::editorMode()
2117{
2118 static const bool isSet = (qEnvironmentVariableIntValue("QT_QUICK3D_EDITORMODE") != 0);
2119 return isSet;
2120}
2121
2122QRhiGraphicsPipeline *QSSGRhiContextPrivate::pipeline(const QSSGGraphicsPipelineStateKey &key,
2123 QRhiRenderPassDescriptor *rpDesc,
2124 QRhiShaderResourceBindings *srb)
2125{
2126 auto it = m_pipelines.constFind(key);
2127 if (it != m_pipelines.constEnd())
2128 return it.value();
2129
2130 // Build a new one. This is potentially expensive.
2131 QRhiGraphicsPipeline *ps = m_rhi->newGraphicsPipeline();
2132 const auto &ia = QSSGRhiInputAssemblerStatePrivate::get(key.state);
2133
2134 const auto *shaderPipeline = QSSGRhiGraphicsPipelineStatePrivate::getShaderPipeline(key.state);
2135 ps->setShaderStages(shaderPipeline->cbeginStages(), shaderPipeline->cendStages());
2136 ps->setVertexInputLayout(ia.inputLayout);
2137 ps->setShaderResourceBindings(srb);
2138 ps->setRenderPassDescriptor(rpDesc);
2139
2140 QRhiGraphicsPipeline::Flags flags;
2141 if (key.state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesScissor))
2142 flags |= QRhiGraphicsPipeline::UsesScissor;
2143
2144 static const bool shaderDebugInfo = qEnvironmentVariableIntValue("QT_QUICK3D_SHADER_DEBUG_INFO");
2145 if (shaderDebugInfo)
2146 flags |= QRhiGraphicsPipeline::CompileShadersWithDebugInfo;
2147 ps->setFlags(flags);
2148
2149 ps->setTopology(ia.topology);
2150 ps->setCullMode(key.state.cullMode);
2151 if (ia.topology == QRhiGraphicsPipeline::Lines || ia.topology == QRhiGraphicsPipeline::LineStrip)
2152 ps->setLineWidth(key.state.lineWidth);
2153
2154 const bool blendEnabled = key.state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled);
2155 QVarLengthArray<QRhiGraphicsPipeline::TargetBlend, 8> targetBlends(key.state.colorAttachmentCount);
2156 for (int i = 0; i < key.state.colorAttachmentCount; ++i) {
2157 targetBlends[i] = key.state.targetBlend[i];
2158 targetBlends[i].enable = blendEnabled;
2159 }
2160 ps->setTargetBlends(targetBlends.cbegin(), targetBlends.cend());
2161
2162 ps->setSampleCount(key.state.samples);
2163 ps->setMultiViewCount(key.state.viewCount);
2164
2165 ps->setDepthTest(key.state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled));
2166 ps->setDepthWrite(key.state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled));
2167 ps->setDepthOp(key.state.depthFunc);
2168
2169 ps->setDepthBias(key.state.depthBias);
2170 ps->setSlopeScaledDepthBias(key.state.slopeScaledDepthBias);
2171 ps->setPolygonMode(key.state.polygonMode);
2172
2173 const bool usesStencilRef = (key.state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesStencilRef));
2174 if (usesStencilRef)
2175 flags |= QRhiGraphicsPipeline::UsesStencilRef;
2176 ps->setFlags(flags);
2177 ps->setStencilFront(key.state.stencilOpFrontState);
2178 ps->setStencilTest(usesStencilRef);
2179 ps->setStencilWriteMask(key.state.stencilWriteMask);
2180
2181 if (!ps->create()) {
2182 qWarning("Failed to build graphics pipeline state");
2183 delete ps;
2184 return nullptr;
2185 }
2186
2187 m_pipelines.insert(key, ps);
2188 return ps;
2189}
2190
2191QRhiComputePipeline *QSSGRhiContextPrivate::computePipeline(const QSSGComputePipelineStateKey &key, QRhiShaderResourceBindings *srb)
2192{
2193 auto it = m_computePipelines.constFind(key);
2194 if (it != m_computePipelines.constEnd())
2195 return it.value();
2196
2197 QRhiComputePipeline *computePipeline = m_rhi->newComputePipeline();
2198 computePipeline->setShaderResourceBindings(srb);
2199 computePipeline->setShaderStage({ QRhiShaderStage::Compute, key.shader });
2200 if (!computePipeline->create()) {
2201 qWarning("Failed to build compute pipeline");
2202 delete computePipeline;
2203 return nullptr;
2204 }
2205 m_computePipelines.insert(key, computePipeline);
2206 return computePipeline;
2207}
2208
2209/*!
2210 \return The recommended flags when calling QRhiCommandBuffer::beginPass().
2211 */
2212QRhiCommandBuffer::BeginPassFlags QSSGRhiContext::commonPassFlags() const
2213{
2214 return {};
2215}
2216
2217/*!
2218 \internal
2219
2220 \fn void QSSGRhiRenderableTextureV2::setDescription(QSSGRhiContext &rhiCtx, QRhiTextureRenderTargetDescription rtDesc, QRhiTextureRenderTarget::Flags flags)
2221
2222 Hands the textures in \a rtDesc over to \a rhiCtx, which owns them from
2223 now on, and creates a render target. References to the individual
2224 textures can be gotten via getColorTexture() and getDepthTexture().
2225 */
2226void QSSGRhiRenderableTextureV2::setDescription(QSSGRhiContext &rhiCtx, QRhiTextureRenderTargetDescription rtDesc, QRhiTextureRenderTarget::Flags flags)
2227{
2228 QRhi *rhi = rhiCtx.rhi();
2229 Q_ASSERT(rhi);
2230 auto *rhiCtxD = QSSGRhiContextPrivate::get(&rhiCtx);
2231
2232 textures.clear();
2233 const size_t colorAttachmentCount = rtDesc.colorAttachmentCount();
2234 for (size_t i = 0; i < colorAttachmentCount; ++i)
2235 textures.push_back(rhiCtxD->create(rtDesc.colorAttachmentAt(i)->texture()));
2236
2237 if (rtDesc.depthTexture()) {
2238 depthTexture = rhiCtxD->create(rtDesc.depthTexture());
2239 releaseDepthStencil(&rhiCtxD->resourceRegistry());
2240 } else if (rtDesc.depthStencilBuffer()) {
2241 if (depthStencil.get() != rtDesc.depthStencilBuffer()) {
2242 releaseDepthStencil(&rhiCtxD->resourceRegistry());
2243 depthStencil.reset(rtDesc.depthStencilBuffer());
2244 }
2245 depthTexture.invalidate();
2246 } else {
2247 depthTexture.invalidate();
2248 releaseDepthStencil(&rhiCtxD->resourceRegistry());
2249 }
2250
2251 dirty = ColorTextureDirty | DepthTextureDirty | DepthStencilDirty;
2252
2253 rt.reset(rhi->newTextureRenderTarget(rtDesc));
2254 rt->setName(rtName);
2255 rt->setFlags(flags);
2256 rpDesc.reset(rt->newCompatibleRenderPassDescriptor());
2257 rt->setRenderPassDescriptor(rpDesc.get());
2258 if (!rt->create()) {
2259 qWarning("Failed to create renderable texture render target");
2260 rt.reset();
2261 return;
2262 }
2263}
2264
2266{
2267 rt.reset();
2268 rpDesc.reset();
2269}
2270
2271void QSSGRhiRenderableTextureV2::reset(QSSGRhiResourceRegistry *registry)
2272{
2273 if (rt)
2274 rt->setDescription({/* empty */});
2275
2277
2278 // Drops the references this render target holds to its textures. The
2279 // context releases a texture once its last reference is gone.
2280 textures.clear();
2281
2282 releaseDepthStencil(registry);
2283 depthTexture.invalidate();
2284}
2285
2286// Called by the user render pass manager when the layer owning the render
2287// target goes away. Drops the references this render target holds to the
2288// textures; the context releases a texture once its last reference is gone.
2289void QSSGRhiRenderableTextureV2::invalidate(QSSGRhiResourceRegistry *registry)
2290{
2291 reset(registry);
2292}
2293
2294// The depth-stencil is owned here rather than by the context, so it is
2295// released here, with deleteLater() so a pointer obtained from a handle earlier
2296// in the frame stays usable until the end of the frame.
2297void QSSGRhiRenderableTextureV2::releaseDepthStencil(QSSGRhiResourceRegistry *registry)
2298{
2299 if (!depthStencil)
2300 return;
2301 if (registry)
2302 registry->retire(depthStencil.get());
2303 depthStencil.release()->deleteLater();
2304}
2305
2306void QSSGRhiRenderableTexture::reset(QSSGRhiResourceRegistry *registry)
2307{
2308 resetRenderTarget();
2309 for (QRhiResource *resource : { static_cast<QRhiResource *>(texture),
2310 static_cast<QRhiResource *>(depthStencil),
2311 static_cast<QRhiResource *>(depthTexture) }) {
2312 if (!resource)
2313 continue;
2314 if (registry)
2315 registry->retire(resource);
2316 resource->deleteLater();
2317 }
2318 *this = QSSGRhiRenderableTexture();
2319}
2320
2321QSSGManagedRhiTexture::QSSGManagedRhiTexture(QSSGRhiContextPrivate &rhiCtxD, QRhiTexture *texture, Private)
2322 : m_rhiCtxD(&rhiCtxD)
2323 , m_texture(texture)
2324{
2325 m_rhiCtxD->registerManagedTexture(this);
2326}
2327
2328QSSGManagedRhiTexture::~QSSGManagedRhiTexture()
2329{
2330 invalidate();
2331}
2332
2333QSSGManagedRhiTexture::QSSGManagedRhiTexture(const QSSGManagedRhiTexture &other)
2334{
2335 if (other.isValid() && other.m_rhiCtxD) {
2336 m_rhiCtxD = other.m_rhiCtxD;
2337 m_texture = other.m_texture;
2338 m_rhiCtxD->registerManagedTexture(this);
2339 }
2340}
2341
2342QSSGManagedRhiTexture &QSSGManagedRhiTexture::operator=(const QSSGManagedRhiTexture &other)
2343{
2344 if (this != &other) {
2345 // The source keeps its reference, so dropping ours first cannot release
2346 // the texture even when both reference the same one.
2347 invalidate();
2348 if (other.isValid() && other.m_rhiCtxD) {
2349 m_rhiCtxD = other.m_rhiCtxD;
2350 m_texture = other.m_texture;
2351 m_rhiCtxD->registerManagedTexture(this);
2352 }
2353 }
2354 return *this;
2355}
2356
2357QSSGManagedRhiTexture::QSSGManagedRhiTexture(QSSGManagedRhiTexture &&other) noexcept
2358 : m_rhiCtxD(std::exchange(other.m_rhiCtxD, nullptr))
2359 , m_texture(std::exchange(other.m_texture, nullptr))
2360{
2361 // The context tracks wrappers by address, so tell it the reference moved.
2362 if (m_rhiCtxD)
2363 m_rhiCtxD->relocateManagedTexture(&other, this);
2364}
2365
2366QSSGManagedRhiTexture &QSSGManagedRhiTexture::operator=(QSSGManagedRhiTexture &&other) noexcept
2367{
2368 if (this != &other) {
2369 invalidate();
2370 m_rhiCtxD = std::exchange(other.m_rhiCtxD, nullptr);
2371 m_texture = std::exchange(other.m_texture, nullptr);
2372 if (m_rhiCtxD)
2373 m_rhiCtxD->relocateManagedTexture(&other, this);
2374 }
2375 return *this;
2376}
2377
2378// Drops this wrapper's reference to the texture and detaches it from the
2379// context. The wrapper never deletes the texture itself; the context does that
2380// once the last reference is gone.
2381void QSSGManagedRhiTexture::invalidate()
2382{
2383 if (m_rhiCtxD) {
2384 m_rhiCtxD->unregisterManagedTexture(this);
2385 m_rhiCtxD = nullptr;
2386 } else if (Q_UNLIKELY(m_texture)) {
2387 qWarning("QSSGManagedRhiTexture: No context for tracked resource!");
2388 delete m_texture;
2389 }
2390
2391 m_texture = nullptr;
2392}
2393
2394QT_END_NAMESPACE
void setDescription(QSSGRhiContext &rhiCtx, QRhiTextureRenderTargetDescription rtDesc, QRhiTextureRenderTarget::Flags={})
void reset(QSSGRhiResourceRegistry *registry)
QShaderDescription::VariableType samplerType(const QSSGRhiShaderPipeline &shaders, const QByteArray &name)
QRhiVertexInputAttribute::Format toVertexInputFormat(QSSGRenderComponentType compType, quint32 numComps)
QRhiTexture * dummyTextureForSampler(QSSGRhiContext *rhiCtx, QShaderDescription::VariableType samplerType, QRhiResourceUpdateBatch *rub, int arraySize, const QSize &size, const QColor &fillColor)
QRhiGraphicsPipeline::Topology toTopology(QSSGRenderDrawMode drawMode)
void bakeVertexInputLocations(QSSGRhiInputAssemblerState *ia, const QSSGRhiShaderPipeline &shaders, int instanceBufferBinding)
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_exit)
Q_TRACE_POINT(qtcore, QFactoryLoader_update, const QString &fileName)
Q_TRACE_POINT(qtquick3d, QSSG_renderFrame_entry, int width, int height)
static void releaseAutoLodDataIf(QHash< const QSSGRenderModel *, QSSGRhiInstanceBufferData > &instanceBuffersPerModel, Predicate release)
static QString getUBMemberSizeWarning(QLatin1StringView name, qsizetype correctedSize, qsizetype requestedSize)
static QByteArray asLookupKey(QByteArrayView name)