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
qssgrenderer.cpp
Go to the documentation of this file.
1// Copyright (C) 2008-2012 NVIDIA Corporation.
2// Copyright (C) 2019 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
9
10#include <QtQuick3DRuntimeRender/private/qssgrenderitem2d_p.h>
11#include "../qssgrendercontextcore.h"
12#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrenderlight_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrenderimage_p.h>
15#include <QtQuick3DRuntimeRender/private/qssgrenderbuffermanager_p.h>
16#include "../qssgrendercontextcore.h"
17#include <QtQuick3DRuntimeRender/private/qssgrendereffect_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgrhicustommaterialsystem_p.h>
19#include <QtQuick3DRuntimeRender/private/qssgrendershadercodegenerator_p.h>
20#include <QtQuick3DRuntimeRender/private/qssgrenderdefaultmaterialshadergenerator_p.h>
21#include <QtQuick3DRuntimeRender/private/qssgperframeallocator_p.h>
22#include <QtQuick3DRuntimeRender/private/qssgrhiquadrenderer_p.h>
23#include <QtQuick3DRuntimeRender/private/qssgrendertexturedata_p.h>
24#include <QtQuick3DRuntimeRender/private/qssgrenderskymaterial_p.h>
25#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
26#include <QtQuick3DRuntimeRender/private/qssgrhiparticles_p.h>
27#include <QtQuick3DRuntimeRender/private/qssgvertexpipelineimpl_p.h>
28#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
29#include "../qssgshadermapkey_p.h"
30#include "../qssgrenderpickresult_p.h"
31#include "../graphobjects/qssgrenderroot_p.h"
32#include "../graphobjects/qssgrendermodel_p.h"
33#include "../graphobjects/qssgrenderdefaultmaterial_p.h"
34#include "../graphobjects/qssgrendercustommaterial_p.h"
35
36#include <QtQuick3DUtils/private/qquick3dprofiler_p.h>
37#include <QtQuick3DUtils/private/qssgdataref_p.h>
38#include <QtQuick3DUtils/private/qssgutils_p.h>
39#include <QtQuick3DUtils/private/qssgassert_p.h>
40#include <QtQuick3DUtils/private/qssgfrustum_p.h>
41#include <qtquick3d_tracepoints_p.h>
42
43#include <QtQuick/private/qsgcontext_p.h>
44#include <QtQuick/private/qsgrenderer_p.h>
45
46#include <QtCore/QMutexLocker>
47#include <QtCore/QBitArray>
48
49#include <cstdlib>
50#include <algorithm>
51#include <limits>
52
53/*
54 Rendering is done is several steps, these are:
55
56 1. \l{QSSGRenderer::beginFrame(){beginFrame()} - set's up the renderer to start a new frame.
57
58 2. Now that the renderer is reset, values for the \l{QSSGRenderer::setViewport}{viewport}, \l{QSSGRenderer::setDpr}{dpr},
59 \l{QSSGRenderer::setScissorRect}{scissorRect} etc. should be updated.
60
61 3. \l{QSSGRenderer::prepareLayerForRender()} - At this stage the scene tree will be traversed
62 and state for the renderer needed to render gets collected. This includes, but is not limited to,
63 calculating global transforms, loading of meshes, preparing materials and setting up the rendering
64 steps needed for the frame (opaque and transparent pass etc.)
65 If the there are custom \l{QQuick3DRenderExtension}{render extensions} added to to \l{View3D::extensions}{View3D}
66 then they will get their first chance to modify or react to the collected data here.
67 If the users have implemented the virtual function \l{QSSGRenderExtension::prepareData()}{prepareData} it will be
68 called after all active nodes have been collected and had their global data updated, but before any mesh or material
69 has been loaded.
70
71 4. \l{QSSGRenderer::rhiPrepare()} - Starts rendering necessary sub-scenes and prepare resources.
72 Sub-scenes, or sub-passes that are to be done in full, will be done at this stage.
73
74 5. \l{QSSGRenderer::rhiRender()} - Renders the scene to the main target.
75
76 6. \l{QSSGRenderer::endFrame()} - Marks the frame as done and cleans-up dirty states and
77 uneeded resources.
78*/
79
80QT_BEGIN_NAMESPACE
81
82struct QSSGRenderableImage;
83class QSSGSubsetRenderable;
84
85void QSSGRenderer::releaseCachedResources()
86{
87 m_rhiQuadRenderer.reset();
88 m_rhiCubeRenderer.reset();
89}
90
91void QSSGRenderer::registerItem2DData(QSSGRenderItem2DData &data)
92{
93 // Check if data is already in the m_item2DDatas list, if not insert it.
94 for (const auto *item2DData : m_item2DDatas) {
95 if (item2DData == &data)
96 return;
97 }
98
99 m_item2DDatas.push_back(&data);
100}
101
102void QSSGRenderer::unregisterItem2DData(QSSGRenderItem2DData &data)
103{
104 const auto foundIt = std::find(m_item2DDatas.begin(), m_item2DDatas.end(), &data);
105 if (foundIt != m_item2DDatas.end())
106 m_item2DDatas.erase(foundIt);
107}
108
109void QSSGRenderer::releaseItem2DData(const QSSGRenderItem2D &item2D)
110{
111 for (auto *item2DData : m_item2DDatas)
112 item2DData->releaseRenderData(item2D);
113}
114
115QSSGRenderer::QSSGRenderer() = default;
116
117QSSGRenderer::~QSSGRenderer()
118{
119 m_contextInterface = nullptr;
120 releaseCachedResources();
121}
122
123void QSSGRenderer::cleanupUnreferencedBuffers(QSSGRenderLayer *inLayer)
124{
125 // Now check for unreferenced buffers and release them if necessary
126 m_contextInterface->bufferManager()->cleanupUnreferencedBuffers(m_frameCount, inLayer);
127}
128
129void QSSGRenderer::resetResourceCounters(QSSGRenderLayer *inLayer)
130{
131 m_contextInterface->bufferManager()->resetUsageCounters(m_frameCount, inLayer);
132}
133
134bool QSSGRenderer::prepareLayerForRender(QSSGRenderLayer &inLayer)
135{
136 QSSGLayerRenderData *theRenderData = getOrCreateLayerRenderData(inLayer);
137 Q_ASSERT(theRenderData);
138
139 // Need to check if the world root node is dirty and if we need to trigger
140 // a reindex of the world root node.
141 Q_ASSERT(inLayer.rootNode);
142 if (inLayer.rootNode->isDirty(QSSGRenderRoot::DirtyFlag::TreeDirty))
143 inLayer.rootNode->reindex(); // Clears TreeDirty flag
144
145 beginLayerRender(*theRenderData);
146 theRenderData->resetForFrame();
147 theRenderData->prepareForRender();
148 endLayerRender();
149 return theRenderData->layerPrepResult.getFlags().wasDirty();
150}
151
152// Phase 1: prepare. Called when the renderpass is not yet started on the command buffer.
153void QSSGRenderer::rhiPrepare(QSSGRenderLayer &inLayer)
154{
155 QSSGLayerRenderData *theRenderData = getOrCreateLayerRenderData(inLayer);
156 QSSG_ASSERT(theRenderData && !theRenderData->renderedCameras.isEmpty(), return);
157
158 const auto layerPrepResult = theRenderData->layerPrepResult;
159 if (layerPrepResult.isLayerVisible()) {
160 ///
161 QSSGRhiContext *rhiCtx = contextInterface()->rhiContext().get();
162 QSSG_ASSERT(rhiCtx->isValid() && rhiCtx->rhi()->isRecordingFrame(), return);
163 beginLayerRender(*theRenderData);
164 theRenderData->maybeProcessLightmapBaking();
165 // Process active passes. "PreMain" passes are individual passes
166 // that does can and should be done in the rhi prepare phase.
167 // It is assumed that passes are sorted in the list with regards to
168 // execution order.
169 const auto &activePasses = theRenderData->activePasses;
170 for (const auto &pass : activePasses) {
171 pass->renderPrep(*this, *theRenderData);
172 if (pass->passType() == QSSGRenderPass::Type::Standalone)
173 pass->renderPass(*this);
174 }
175
176 endLayerRender();
177 }
178}
179
180// Phase 2: render. Called within an active renderpass on the command buffer.
181void QSSGRenderer::rhiRender(QSSGRenderLayer &inLayer)
182{
183 QSSGLayerRenderData *theRenderData = getOrCreateLayerRenderData(inLayer);
184 QSSG_ASSERT(theRenderData && !theRenderData->renderedCameras.isEmpty(), return);
185 if (theRenderData->layerPrepResult.isLayerVisible()) {
186 beginLayerRender(*theRenderData);
187 const auto &activePasses = theRenderData->activePasses;
188 for (const auto &pass : activePasses) {
189 if (pass->passType() == QSSGRenderPass::Type::Main || pass->passType() == QSSGRenderPass::Type::Extension)
190 pass->renderPass(*this);
191 }
192 endLayerRender();
193 }
194}
195
196template<typename Container>
197static void cleanupResourcesImpl(const QSSGRenderContextInterface &rci, const Container &resources)
198{
199 const auto &rhiCtx = rci.rhiContext();
200 if (!rhiCtx->isValid())
201 return;
202
203 const auto &bufferManager = rci.bufferManager();
204
205 for (const auto &resource : resources) {
206 if (resource->type == QSSGRenderGraphObject::Type::Geometry) {
207 auto geometry = static_cast<QSSGRenderGeometry*>(resource);
208 bufferManager->releaseGeometry(geometry);
209 } else if (resource->type == QSSGRenderGraphObject::Type::Model) {
210 auto model = static_cast<QSSGRenderModel*>(resource);
211 QSSGRhiContextPrivate::get(rhiCtx.get())->cleanupDrawCallData(model);
212 QSSGRhiContextPrivate::get(rhiCtx.get())->releaseModelInstanceData(model);
213 delete model->particleBuffer;
214 } else if (QSSGRenderGraphObject::isMaterial(resource->type)) {
215 QSSGRhiContextPrivate::get(rhiCtx.get())->cleanupDrawCallDataForResource(resource);
216 } else if (resource->type == QSSGRenderGraphObject::Type::SkyMaterial) {
217 auto *skyMaterial = static_cast<QSSGRenderSkyMaterial *>(resource);
218 auto *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
219 rhiCtxD->cleanupDrawCallDataForSkyMaterial(skyMaterial);
220 } else if (resource->type == QSSGRenderGraphObject::Type::TextureData || resource->type == QSSGRenderGraphObject::Type::Skin) {
221 static_assert(std::is_base_of_v<QSSGRenderTextureData, QSSGRenderSkin>, "QSSGRenderSkin is expected to be a QSSGRenderTextureData type!");
222 auto textureData = static_cast<QSSGRenderTextureData *>(resource);
223 bufferManager->releaseTextureData(textureData);
224 } else if (QSSGRenderGraphObject::isExtension(resource->type)) {
225 auto *rext = static_cast<QSSGRenderExtension *>(resource);
226 bufferManager->releaseExtensionResult(*rext);
227 // Extensions can create draw call data keyed on themselves.
228 QSSGRhiContextPrivate::get(rhiCtx.get())->cleanupDrawCallDataForCid(resource);
229 } else if (resource->type == QSSGRenderGraphObject::Type::ModelInstance) {
230 auto *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
231 auto *table = static_cast<QSSGRenderInstanceTable *>(resource);
232 rhiCtxD->releaseInstanceBuffer(table);
233 } else if (resource->type == QSSGRenderGraphObject::Type::Item2D) {
234 auto *item2D = static_cast<QSSGRenderItem2D *>(resource);
235 rci.renderer()->releaseItem2DData(*item2D);
236 } else if (QSSGRenderGraphObjectUtils::isUserRenderPass(resource->type)) {
237 auto *userPassBase = static_cast<QSSGRenderUserPassBase *>(resource);
238 bufferManager->releaseUserRenderPass(*userPassBase);
239 } else if (resource->type == QSSGRenderGraphObject::Type::ShaderStorageBuffer) {
240 auto *buffer = static_cast<QSSGRenderBuffer *>(resource);
241 bufferManager->releaseBuffer(*buffer);
242 } else if (resource->type == QSSGRenderGraphObject::Type::Image2D
243 || resource->type == QSSGRenderGraphObject::Type::ImageCube) {
244 auto *image = static_cast<QSSGRenderImage *>(resource);
245 if (image->m_shaderImage)
246 bufferManager->releaseRenderImage(*image);
247 }
248
249 // ### There might be more types that need to be supported
250
251 delete resource;
252 }
253}
254
255void QSSGRenderer::cleanupResources(QList<QSSGRenderGraphObject *> &resources)
256{
257 cleanupResourcesImpl(*m_contextInterface, resources);
258 resources.clear();
259}
260
261void QSSGRenderer::cleanupResources(QSet<QSSGRenderGraphObject *> &resources)
262{
263 cleanupResourcesImpl(*m_contextInterface, resources);
264 resources.clear();
265}
266
267QSSGLayerRenderData *QSSGRenderer::getOrCreateLayerRenderData(QSSGRenderLayer &layer)
268{
269 if (layer.renderData == nullptr)
270 layer.renderData = new QSSGLayerRenderData(layer, *this);
271
272 return layer.renderData;
273}
274
275void QSSGRenderer::addMaterialDirtyClear(QSSGRenderGraphObject *material)
276{
277 m_materialClearDirty.insert(material);
278}
279
280static QByteArray rendererLogPrefix() { return QByteArrayLiteral("mesh default material pipeline-- "); }
281
282
283QSSGRhiShaderPipelinePtr QSSGRendererPrivate::generateRhiShaderPipelineImpl(QSSGSubsetRenderable &renderable,
284 QSSGShaderLibraryManager &shaderLibraryManager,
285 QSSGShaderCache &shaderCache,
286 QSSGProgramGenerator &shaderProgramGenerator,
287 const QSSGShaderDefaultMaterialKeyProperties &shaderKeyProperties,
288 const QSSGShaderFeatures &featureSet,
289 const QSSGUserShaderAugmentation &shaderAugmentation,
290 QByteArray &shaderString)
291{
292 shaderString = rendererLogPrefix();
293 QSSGShaderDefaultMaterialKey theKey(renderable.shaderDescription);
294
295 // This is not a cheap operation. This function assumes that it will not be
296 // hit for every material for every model in every frame (except of course
297 // for materials that got changed). In practice this is ensured by the
298 // cheaper-to-lookup cache in getShaderPipelineForDefaultMaterial().
299 theKey.toString(shaderString, shaderKeyProperties);
300
301 // Include augment defines, preamble and body in the cache key, and the hash,
302 // which also covers the declarations generated from the pass' properties.
303 for (const auto &def : shaderAugmentation.defines)
304 shaderString.append(def.name).append(';').append(def.value).append(';');
305 shaderString.append(shaderAugmentation.preamble).append(';');
306 shaderString.append(shaderAugmentation.body).append(';');
307 shaderString.append(shaderAugmentation.hash).append(';');
308
309 // Check the in-memory, per-QSSGShaderCache (and so per-QQuickWindow)
310 // runtime cache. That may get cleared upon an explicit call to
311 // QQuickWindow::releaseResources(), but will otherwise store all
312 // encountered shader pipelines in any View3D in the window.
313 if (const auto &maybePipeline = shaderCache.tryGetRhiShaderPipeline(shaderString, featureSet))
314 return maybePipeline;
315
316 // Check if there's a pre-built (offline generated) shader for available.
317 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(featureSet));
318 const QQsbCollection::EntryMap &pregenEntries = shaderLibraryManager.m_preGeneratedShaderEntries;
319 if (!pregenEntries.isEmpty()) {
320 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
321 if (foundIt != pregenEntries.cend())
322 return shaderCache.newPipelineFromPregenerated(shaderString, featureSet, *foundIt, renderable.material);
323 }
324
325 // Try the persistent (disk-based) cache then.
326 if (const auto &maybePipeline = shaderCache.tryNewPipelineFromPersistentCache(qsbcKey, shaderString, featureSet))
327 return maybePipeline;
328
329 // Otherwise, build new shader code and run the resulting shaders through
330 // the shader conditioning pipeline.
331 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(renderable.getMaterial());
332 QSSGMaterialVertexPipeline vertexPipeline(shaderProgramGenerator,
333 shaderKeyProperties,
334 material.adapter);
335
336 return QSSGMaterialShaderGenerator::generateMaterialRhiShader(rendererLogPrefix(),
337 shaderString,
338 vertexPipeline,
339 renderable.shaderDescription,
340 shaderKeyProperties,
341 featureSet,
342 renderable.material,
343 shaderLibraryManager,
344 shaderCache,
345 shaderAugmentation);
346}
347
348QSSGRhiShaderPipelinePtr QSSGRendererPrivate::generateRhiShaderPipeline(QSSGRenderer &renderer,
349 QSSGSubsetRenderable &inRenderable,
350 const QSSGShaderFeatures &inFeatureSet,
351 const QSSGUserShaderAugmentation &shaderAugmentation = {})
352{
353 auto *currentLayer = renderer.m_currentLayer;
354 auto &generatedShaderString = currentLayer->generatedShaderString;
355 const auto &m_contextInterface = renderer.m_contextInterface;
356 const auto &theCache = m_contextInterface->shaderCache();
357 const auto &shaderProgramGenerator = m_contextInterface->shaderProgramGenerator();
358 const auto &shaderLibraryManager = m_contextInterface->shaderLibraryManager();
359 return QSSGRendererPrivate::generateRhiShaderPipelineImpl(inRenderable, *shaderLibraryManager, *theCache, *shaderProgramGenerator, currentLayer->defaultMaterialShaderKeyProperties, inFeatureSet, shaderAugmentation, generatedShaderString);
360}
361
362void QSSGRenderer::beginFrame(QSSGRenderLayer &layer, bool allowRecursion)
363{
364 const bool executeBeginFrame = !(allowRecursion && (m_activeFrameRef++ != 0));
365 if (executeBeginFrame) {
366 m_contextInterface->perFrameAllocator()->reset();
367 QSSGRHICTX_STAT(m_contextInterface->rhiContext().get(), start(&layer));
368 resetResourceCounters(&layer);
369 }
370}
371
372bool QSSGRenderer::endFrame(QSSGRenderLayer &layer, bool allowRecursion)
373{
374 const bool executeEndFrame = !(allowRecursion && (--m_activeFrameRef != 0));
375 // The data of the automatic per-instance LOD is kept per layer, so it can be released for
376 // each layer that ends its frame, also when the frames of several layers overlap, as with
377 // several View3Ds rendered inline in one window. m_frameCount only changes after the last
378 // of them.
379 QSSGRhiContextPrivate::get(m_contextInterface->rhiContext().get())->releaseUnusedAutoLodData(&layer, m_frameCount);
380 if (executeEndFrame) {
381 cleanupUnreferencedBuffers(&layer);
382
383 // We need to do this endFrame(), as the material nodes might not exist after this!
384 for (auto *matObj : std::as_const(m_materialClearDirty)) {
385 if (matObj->type == QSSGRenderGraphObject::Type::CustomMaterial) {
386 static_cast<QSSGRenderCustomMaterial *>(matObj)->clearDirty();
387 } else if (matObj->type == QSSGRenderGraphObject::Type::DefaultMaterial ||
388 matObj->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
389 matObj->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
390 static_cast<QSSGRenderDefaultMaterial *>(matObj)->clearDirty();
391 }
392 }
393 m_materialClearDirty.clear();
394
395 QSSGRHICTX_STAT(m_contextInterface->rhiContext().get(), stop(&layer));
396
397 ++m_frameCount;
398 }
399
400 return executeEndFrame;
401}
402
403QSSGRendererPrivate::PickResultList QSSGRendererPrivate::syncPickAll(const QSSGRenderContextInterface &ctx,
404 const QSSGRenderLayer &layer,
405 const QSSGRenderRay &ray)
406{
407 const auto &bufferManager = ctx.bufferManager();
408 const bool isGlobalPickingEnabled = QSSGRendererPrivate::isGlobalPickingEnabled(*ctx.renderer());
409 PickResultList pickResults;
410 Q_ASSERT(layer.getGlobalState(QSSGRenderNode::GlobalState::Active));
411 getLayerHitObjectList(layer, *bufferManager, ray, isGlobalPickingEnabled, pickResults);
412 // Things are rendered in a particular order and we need to respect that ordering.
413 std::stable_sort(pickResults.begin(), pickResults.end(), [](const QSSGRenderPickResult &lhs, const QSSGRenderPickResult &rhs) {
414 return lhs.m_distanceSq < rhs.m_distanceSq;
415 });
416 return pickResults;
417}
418
419QSSGRendererPrivate::PickResultList QSSGRendererPrivate::syncPick(const QSSGRenderContextInterface &ctx,
420 const QSSGRenderLayer &layer,
421 const QSSGRenderRay &ray,
422 QSSGRenderNode *target)
423{
424 const auto &bufferManager = ctx.bufferManager();
425 const bool isGlobalPickingEnabled = QSSGRendererPrivate::isGlobalPickingEnabled(*ctx.renderer());
426
427 Q_ASSERT(layer.getGlobalState(QSSGRenderNode::GlobalState::Active));
428 PickResultList pickResults;
429 if (target)
430 intersectRayWithSubsetRenderable(layer, *bufferManager, ray, *target, pickResults);
431 else
432 getLayerHitObjectList(layer, *bufferManager, ray, isGlobalPickingEnabled, pickResults);
433
434 std::stable_sort(pickResults.begin(), pickResults.end(), [](const QSSGRenderPickResult &lhs, const QSSGRenderPickResult &rhs) {
435 return lhs.m_distanceSq < rhs.m_distanceSq;
436 });
437 return pickResults;
438}
439
440using RenderableList = QVarLengthArray<const QSSGRenderNode *>;
441static void getPickableRecursive(const QSSGRenderNode &node, RenderableList &renderables, bool pickEverything = false)
442{
443 if (QSSGRenderGraphObject::isRenderable(node.type) && (pickEverything || node.getLocalState(QSSGRenderNode::LocalState::Pickable))) {
444 renderables.push_back(&node);
445 }
446
447 for (const auto &child : node.children)
448 getPickableRecursive(child, renderables, pickEverything);
449}
450
451std::optional<QSSGRenderPickResult> QSSGRendererPrivate::syncPickClosestPoint(const QSSGRenderContextInterface &ctx,
452 const QSSGRenderLayer &layer,
453 const QVector3D &center, const float radiusSquared,
454 QSSGRenderNode *target)
455{
456 const auto &bufferManager = ctx.bufferManager();
457
458 Q_ASSERT(layer.getGlobalState(QSSGRenderNode::GlobalState::Active));
459 std::optional<QSSGRenderPickResult> result = std::nullopt;
460 if (target) {
461 result = closestPointOnSubsetRenderable(layer, *bufferManager, center, radiusSquared, *target);
462 } else {
463 const bool pickEverything = QSSGRendererPrivate::isGlobalPickingEnabled(*ctx.renderer());
464 RenderableList renderables;
465 for (const auto &childNode : layer.children)
466 getPickableRecursive(childNode, renderables, pickEverything);
467 float bestDistSquared = radiusSquared;
468 for (const auto &childNode : renderables) {
469 const auto res = closestPointOnSubsetRenderable(layer, *bufferManager, center, bestDistSquared, *childNode);
470 if (res.has_value()) {
471 bestDistSquared = res.value().m_distanceSq;
472 result = res;
473 }
474 }
475 }
476
477 return result;
478}
479
480QSSGRendererPrivate::PickResultList QSSGRendererPrivate::syncPickSubset(const QSSGRenderLayer &layer,
481 QSSGBufferManager &bufferManager,
482 const QSSGRenderRay &ray,
483 QVarLengthArray<QSSGRenderNode*> subset)
484{
485 QSSGRendererPrivate::PickResultList pickResults;
486 Q_ASSERT(layer.getGlobalState(QSSGRenderNode::GlobalState::Active));
487
488 for (auto target : subset)
489 intersectRayWithSubsetRenderable(layer, bufferManager, ray, *target, pickResults);
490
491 std::stable_sort(pickResults.begin(), pickResults.end(), [](const QSSGRenderPickResult &lhs, const QSSGRenderPickResult &rhs) {
492 return lhs.m_distanceSq < rhs.m_distanceSq;
493 });
494 return pickResults;
495}
496
497void QSSGRendererPrivate::setGlobalPickingEnabled(QSSGRenderer &renderer, bool isEnabled)
498{
499 renderer.m_globalPickingEnabled = isEnabled;
500}
501
502void QSSGRendererPrivate::setRenderContextInterface(QSSGRenderer &renderer, QSSGRenderContextInterface *ctx)
503{
504 renderer.m_contextInterface = ctx;
505}
506
507void QSSGRendererPrivate::setSgRenderContext(QSSGRenderer &renderer, QSGRenderContext *sgRenderCtx)
508{
509 renderer.m_qsgRenderContext = sgRenderCtx;
510}
511
512QSGRenderContext *QSSGRendererPrivate::getSgRenderContext(const QSSGRenderer &renderer)
513{
514 return renderer.m_qsgRenderContext.data();
515}
516
517const std::unique_ptr<QSSGRhiQuadRenderer> &QSSGRenderer::rhiQuadRenderer() const
518{
519 if (!m_rhiQuadRenderer)
520 m_rhiQuadRenderer = std::make_unique<QSSGRhiQuadRenderer>();
521
522 return m_rhiQuadRenderer;
523}
524
525const std::unique_ptr<QSSGRhiCubeRenderer> &QSSGRenderer::rhiCubeRenderer() const
526{
527 if (!m_rhiCubeRenderer)
528 m_rhiCubeRenderer = std::make_unique<QSSGRhiCubeRenderer>();
529
530 return m_rhiCubeRenderer;
531
532}
533
534void QSSGRenderer::beginSubLayerRender(QSSGLayerRenderData &inLayer)
535{
536 inLayer.saveRenderState(*this);
537 m_currentLayer = nullptr;
538}
539
540void QSSGRenderer::endSubLayerRender(QSSGLayerRenderData &inLayer)
541{
542 inLayer.restoreRenderState(*this);
543 m_currentLayer = &inLayer;
544}
545
546void QSSGRenderer::beginLayerRender(QSSGLayerRenderData &inLayer)
547{
548 m_currentLayer = &inLayer;
549}
550void QSSGRenderer::endLayerRender()
551{
552 m_currentLayer = nullptr;
553}
554
555static void dfs(const QSSGRenderNode &node, RenderableList &renderables)
556{
557 if (QSSGRenderGraphObject::isRenderable(node.type))
558 renderables.push_back(&node);
559
560 for (const auto &child : node.children)
561 dfs(child, renderables);
562}
563
564void QSSGRendererPrivate::getLayerHitObjectList(const QSSGRenderLayer &layer,
565 QSSGBufferManager &bufferManager,
566 const QSSGRenderRay &ray,
567 bool inPickEverything,
568 PickResultList &outIntersectionResult)
569{
570 RenderableList renderables;
571 for (const auto &childNode : layer.children)
572 dfs(childNode, renderables);
573
574 for (int idx = renderables.size() - 1; idx >= 0; --idx) {
575 const auto &pickableObject = renderables.at(idx);
576 if (inPickEverything || pickableObject->getLocalState(QSSGRenderNode::LocalState::Pickable))
577 intersectRayWithSubsetRenderable(layer, bufferManager, ray, *pickableObject, outIntersectionResult);
578 }
579}
580
581namespace {
582
583static inline QVector3D multiply(const QMatrix3x3& M, const QVector3D& v)
584{
585 return QVector3D(
586 M(0,0) * v.x() + M(0,1) * v.y() + M(0,2) * v.z(),
587 M(1,0) * v.x() + M(1,1) * v.y() + M(1,2) * v.z(),
588 M(2,0) * v.x() + M(2,1) * v.y() + M(2,2) * v.z()
589 );
590}
591
592// Return true if G ≈ s^2 I; outputs s2 (>=0). tolerance is relative-ish.
593static inline bool isUniformScaleMetric(const QMatrix3x3& G, float& s2, float tolerance = 1e-5f) {
594 const float gxx = G(0,0), gyy = G(1,1), gzz = G(2,2);
595 const float gxy = G(0,1), gxz = G(0,2), gyz = G(1,2);
596
597 // Average of diagonals as robust estimate of s^2
598 s2 = (gxx + gyy + gzz) / 3.0f;
599
600 // Scale for relative tolerance (avoid divide by zero)
601 const float scale = std::max({ std::fabs(gxx), std::fabs(gyy), std::fabs(gzz), 1.0f });
602
603 // Off-diagonals should be ~0; diagonals should be ~equal to s2
604 const bool offDiagOK = (std::fabs(gxy) <= tolerance * scale) &&
605 (std::fabs(gxz) <= tolerance * scale) &&
606 (std::fabs(gyz) <= tolerance * scale) &&
607 (std::fabs(G(1,0)) <= tolerance * scale) && // in case it's not exactly symmetric
608 (std::fabs(G(2,0)) <= tolerance * scale) &&
609 (std::fabs(G(2,1)) <= tolerance * scale);
610
611 const bool diagOK = (std::fabs(gxx - s2) <= tolerance * scale) &&
612 (std::fabs(gyy - s2) <= tolerance * scale) &&
613 (std::fabs(gzz - s2) <= tolerance * scale);
614
615 return offDiagOK && diagOK && (s2 >= 0.0f);
616}
617
618struct EuclideanDot
619{
620 inline float operator()(const QVector3D& u, const QVector3D& v) const {
621 return QVector3D::dotProduct(u, v);
622 }
623};
624
625struct MetricDot
626{
627 QMatrix3x3 G;
628 inline float operator()(const QVector3D& u, const QVector3D& v) const {
629 // u^T (G v)
630 return QVector3D::dotProduct(u, multiply(G, v));
631 }
632};
633
634
635struct SphereData
636{
637 QMatrix4x4 globalTransform; // model -> world
638 QMatrix3x3 pullbackMetric;
639 QVector3D centerLocal; // sphere center in model local space
640};
641
642// Create local-space query data from world-space sphere and model transform.
643// The local radius uses max column length of the inverse linear part as a cheap,
644// conservative bound under non-uniform scaling/shear.
645static inline SphereData createSphereData(const QMatrix4x4 &globalTransform,
646 const QVector3D &centerWorld)
647{
648 QMatrix4x4 inv = globalTransform.inverted();
649
650 // center in local space
651 const QVector3D centerLocal = QSSGUtils::mat44::transform(inv, centerWorld);
652
653 const QMatrix3x3 A = QSSGUtils::mat44::getUpper3x3(globalTransform);
654 const QMatrix3x3 G = A.transposed() * A;
655
656 return SphereData{ globalTransform, G, centerLocal };
657}
658
659// Squared distance from point to axis-aligned bounding box.
660static inline float distanceSqPointTransformedAABB(const QVector3D &localPoint,
661 const QSSGBounds3 &localAABB,
662 const QMatrix3x3 &G)
663{
664 // Find the closest point on the AABB in local space
665 QVector3D closestLocal(
666 qBound(localAABB.minimum.x(), localPoint.x(), localAABB.maximum.x()),
667 qBound(localAABB.minimum.y(), localPoint.y(), localAABB.maximum.y()),
668 qBound(localAABB.minimum.z(), localPoint.z(), localAABB.maximum.z())
669 );
670
671 // Compute the difference vector in local space
672 QVector3D localDiff = localPoint - closestLocal;
673
674 // Use the pullback metric to get the squared world-space distance
675 // ||v||_world^2 = v^T * G * v where G = A^T * A
676 MetricDot dot{G};
677 return dot(localDiff, localDiff);
678}
679
680struct ClosestPointResult
681{
682 bool found = false;
683 float distSq = std::numeric_limits<float>::max();
684 QVector3D localPoint;
685 QVector3D scenePoint;
686 QVector3D faceNormal;
687 QVector3D sceneNormal;
688 QVector2D uv;
689 int subset = -1;
690 int instanceIndex = -1;
691};
692
693static void closestPointBVHLeafNode(const SphereData &data,
694 const QSSGMeshBVHNode *node,
695 const QSSGRenderMesh *mesh,
696 int subset,
697 int instanceIndex,
698 ClosestPointResult &best)
699{
700 const int begin = node->offset;
701 const int end = begin + node->count;
702 const auto &triangles = mesh->bvh->triangles();
703
704 // Determine if we can use faster Euclidean distance computation
705 float uniformScaleFactor = 1.0f;
706 const bool isUniformScale = isUniformScaleMetric(data.pullbackMetric, uniformScaleFactor);
707 const MetricDot metricDot { data.pullbackMetric };
708
709 for (int i = begin; i < end; ++i) {
710 const auto &triangle = triangles[i];
711
712 // Micro-pruning: skip triangles whose bounds are already farther than current best
713 const float triangleDistSq = distanceSqPointTransformedAABB(data.centerLocal, triangle.bounds, data.pullbackMetric);
714 if (triangleDistSq >= best.distSq)
715 continue;
716
717 // Find closest point on triangle
718 float u, v, w;
719 QVector3D closestPoint;
720
721 if (isUniformScale) {
722 closestPoint = closestPointOnTriangle(data.centerLocal,
723 triangle.vertex1, triangle.vertex2, triangle.vertex3,
724 EuclideanDot{},
725 u, v, w);
726 } else {
727 closestPoint = closestPointOnTriangle(data.centerLocal,
728 triangle.vertex1, triangle.vertex2, triangle.vertex3,
729 metricDot,
730 u, v, w);
731 }
732
733 // Compute squared distance in metric space
734 const QVector3D delta = data.centerLocal - closestPoint;
735 const float distSq = metricDot(delta, delta);
736
737 // Update best result if this is closer
738 if (distSq < best.distSq) {
739 best.distSq = distSq;
740 best.localPoint = closestPoint;
741 best.scenePoint = QSSGUtils::mat44::transform(data.globalTransform, closestPoint);
742 best.subset = subset;
743 best.instanceIndex = instanceIndex;
744 best.found = true;
745
746 // Interpolate UV coordinates using barycentric coordinates.
747 // Note that we're using a different definition of u, v, w than intersectWithBVHTriangles
748 best.uv = u * triangle.uvCoord1 + v * triangle.uvCoord2 + w * triangle.uvCoord3;
749
750 // Compute face normal in local space
751 const QVector3D edge1 = triangle.vertex2 - triangle.vertex1;
752 const QVector3D edge2 = triangle.vertex3 - triangle.vertex1;
753 best.faceNormal = QVector3D::normal(edge1, edge2).normalized();
754 const QMatrix3x3 normalMatrix = data.globalTransform.normalMatrix();
755 best.sceneNormal = QSSGUtils::mat33::transform(normalMatrix, best.faceNormal);
756 }
757 }
758}
759
760static void closestPointBVH(const SphereData &data,
761 const QSSGMeshBVHNode *node,
762 const QSSGRenderMesh *mesh,
763 int subset,
764 int instanceIndex,
765 ClosestPointResult &best)
766{
767 if (!node || !mesh || !mesh->bvh)
768 return;
769
770 // Prune by AABB distance vs. current best
771 const float aabbDistSq = distanceSqPointTransformedAABB(data.centerLocal, node->boundingData, data.pullbackMetric);
772 if (aabbDistSq >= best.distSq)
773 return;
774
775 // Leaf node: compute closest point on each triangle
776 if (node->count != 0) {
777 closestPointBVHLeafNode(data, node, mesh, subset, instanceIndex, best);
778 return;
779 }
780
781 // Internal node: visit children in order of increasing AABB distance
782 const auto *leftChild = static_cast<const QSSGMeshBVHNode *>(node->left);
783 const auto *rightChild = static_cast<const QSSGMeshBVHNode *>(node->right);
784
785 // Compute AABB distances for both children
786 const float leftDistSq = leftChild
787 ? distanceSqPointTransformedAABB(data.centerLocal, leftChild->boundingData, data.pullbackMetric)
788 : std::numeric_limits<float>::max();
789 const float rightDistSq = rightChild
790 ? distanceSqPointTransformedAABB(data.centerLocal, rightChild->boundingData, data.pullbackMetric)
791 : std::numeric_limits<float>::max();
792
793 // Visit children in order of increasing distance (closer child first for better pruning)
794 if (leftDistSq < rightDistSq) {
795 if (leftDistSq < best.distSq)
796 closestPointBVH(data, leftChild, mesh, subset, instanceIndex, best);
797 if (rightDistSq < best.distSq)
798 closestPointBVH(data, rightChild, mesh, subset, instanceIndex, best);
799 } else {
800 if (rightDistSq < best.distSq)
801 closestPointBVH(data, rightChild, mesh, subset, instanceIndex, best);
802 if (leftDistSq < best.distSq)
803 closestPointBVH(data, leftChild, mesh, subset, instanceIndex, best);
804 }
805}
806} // namespace (anonymous)
807
808std::optional<QSSGRenderPickResult>
809QSSGRendererPrivate::closestPointOnSubsetRenderable(const QSSGRenderLayer& layer,
810 QSSGBufferManager& bufferManager,
811 const QVector3D& center,
812 const float radiusSquared,
813 const QSSGRenderNode& node)
814{
815 if (!layer.renderData)
816 return std::nullopt;
817
818 const auto *renderData = layer.renderData;
819
820 // Note: If we want to extend this to also handling Item2D, this is where we would do it.
821 // if (node.type == QSSGRenderGraphObject::Type::Item2D) {
822 // ...
823 // }
824
825 if (node.type != QSSGRenderGraphObject::Type::Model)
826 return std::nullopt;
827
828 const auto &model = static_cast<const QSSGRenderModel &>(node);
829
830 // We have to have a guard here, as the meshes are usually loaded on the render thread,
831 // and we assume all meshes are loaded before picking and none are removed, which
832 // is usually true, except for custom geometry which can be updated at any time. So this
833 // guard should really only be locked whenever a custom geometry buffer is being updated
834 // on the render thread. Still naughty though because this can block the render thread.
835
836 QMutexLocker mutexLocker(bufferManager.meshUpdateMutex());
837
838 auto mesh = bufferManager.getMeshForPicking(model, model.hasLightmap() ? layer.lightmapSource : QString());
839 if (!mesh)
840 return std::nullopt;
841
842 // Early culling: check if sphere can reach model bounds
843 QSSGBounds3 modelBounds;
844 for (const auto &subset : std::as_const(mesh->subsets))
845 modelBounds.include(subset.bounds);
846
847 if (modelBounds.isEmpty())
848 return std::nullopt;
849
850 // No transforms to test against
851 if (model.usesBufferlessInstancing())
852 return std::nullopt;
853
854 const bool instancing = model.instancing();
855 int instanceCount = instancing ? model.instanceTable->count() : 1;
856 const auto instanceTransforms = instancing ? renderData->getInstanceTransforms(model) : QSSGLayerRenderData::InstanceTransforms{};
857
858 ClosestPointResult best;
859 best.distSq = radiusSquared; // Start with sphere radius as max distance
860
861 for (int i = 0; i < instanceCount; ++i) {
862 int instanceIndex = 0;
863 QMatrix4x4 modelTransform;
864 if (instancing) {
865 instanceIndex = i;
866 modelTransform = instanceTransforms.global * model.instanceTable->getTransform(instanceIndex) * instanceTransforms.local;
867 } else {
868 modelTransform = renderData->getGlobalTransform(model);
869 }
870 const SphereData data = createSphereData(modelTransform, center);
871
872 if (distanceSqPointTransformedAABB(data.centerLocal, modelBounds, data.pullbackMetric) > best.distSq)
873 continue;
874
875 for (int subsetIndex = 0; subsetIndex < mesh->subsets.size(); ++subsetIndex) {
876 const auto &subset = mesh->subsets[subsetIndex];
877
878 // Cull subset if its bounds are beyond our current best distance
879 if (distanceSqPointTransformedAABB(data.centerLocal, subset.bounds, data.pullbackMetric) >= best.distSq)
880 continue;
881
882 if (!subset.bvhRoot.isNull()) {
883 const auto *bvhRoot = static_cast<const QSSGMeshBVHNode *>(subset.bvhRoot);
884 closestPointBVH(data, bvhRoot, mesh, subsetIndex, instanceIndex, best);
885 }
886 }
887 }
888 if (best.found) {
889 return QSSGRenderPickResult{
890 &model,
891 best.distSq,
892 best.uv,
893 best.scenePoint,
894 best.localPoint,
895 best.faceNormal,
896 best.sceneNormal,
897 best.subset,
898 best.instanceIndex
899 };
900 }
901
902 return std::nullopt;
903}
904
905// Subsets past the end of the material list use the last material, as in the renderer.
906// Uses the model's own materials, so extension API overrides are not taken into account.
907static QSSGCullFaceMode cullModeForSubset(const QSSGRenderModel &model, int subset)
908{
909 if (model.materials.isEmpty())
910 return QSSGCullFaceMode::Back;
911 const int idx = qMin(subset, int(model.materials.size()) - 1);
912 const QSSGRenderGraphObject *material = model.materials.at(idx);
913 if (!material)
914 return QSSGCullFaceMode::Back;
915 switch (material->type) {
916 case QSSGRenderGraphObject::Type::DefaultMaterial:
917 case QSSGRenderGraphObject::Type::PrincipledMaterial:
918 case QSSGRenderGraphObject::Type::SpecularGlossyMaterial:
919 return static_cast<const QSSGRenderDefaultMaterial *>(material)->cullMode;
920 case QSSGRenderGraphObject::Type::CustomMaterial:
921 return static_cast<const QSSGRenderCustomMaterial *>(material)->m_cullMode;
922 default:
923 return QSSGCullFaceMode::Back;
924 }
925}
926
927// A mirroring transform flips the winding the renderer sees, but not the local-space
928// winding the ray is tested against.
929static QSSGCullFaceMode mirroredCullMode(QSSGCullFaceMode cullMode)
930{
931 switch (cullMode) {
932 case QSSGCullFaceMode::Unknown:
933 case QSSGCullFaceMode::Back:
934 return QSSGCullFaceMode::Front;
935 case QSSGCullFaceMode::Front:
936 return QSSGCullFaceMode::Back;
937 case QSSGCullFaceMode::Disabled:
938 case QSSGCullFaceMode::FrontAndBack:
939 break;
940 }
941 return cullMode;
942}
943
944void QSSGRendererPrivate::intersectRayWithSubsetRenderable(const QSSGRenderLayer &layer,
945 QSSGBufferManager &bufferManager,
946 const QSSGRenderRay &inRay,
947 const QSSGRenderNode &node,
948 PickResultList &outIntersectionResultList)
949{
950 if (!layer.renderData)
951 return;
952
953 const auto *renderData = layer.renderData;
954
955 // Item2D's requires special handling
956 if (node.type == QSSGRenderGraphObject::Type::Item2D) {
957 const QSSGRenderItem2D &item2D = static_cast<const QSSGRenderItem2D &>(node);
958 intersectRayWithItem2D(layer, inRay, item2D, outIntersectionResultList);
959 return;
960 }
961
962 if (node.type != QSSGRenderGraphObject::Type::Model)
963 return;
964
965 const QSSGRenderModel &model = static_cast<const QSSGRenderModel &>(node);
966
967 // We have to have a guard here, as the meshes are usually loaded on the render thread,
968 // and we assume all meshes are loaded before picking and none are removed, which
969 // is usually true, except for custom geometry which can be updated at any time. So this
970 // guard should really only be locked whenever a custom geometry buffer is being updated
971 // on the render thread. Still naughty though because this can block the render thread.
972 QMutexLocker mutexLocker(bufferManager.meshUpdateMutex());
973 auto mesh = bufferManager.getMeshForPicking(model, model.hasLightmap() ? layer.lightmapSource : QString());
974 if (!mesh)
975 return;
976
977 const auto &subMeshes = mesh->subsets;
978 QSSGBounds3 modelBounds;
979 for (const auto &subMesh : subMeshes)
980 modelBounds.include(subMesh.bounds);
981
982 if (modelBounds.isEmpty())
983 return;
984
985 // No transforms to test against
986 if (model.usesBufferlessInstancing())
987 return;
988
989 const bool instancing = model.instancing(); // && instancePickingEnabled
990 int instanceCount = instancing ? model.instanceTable->count() : 1;
991
992 const auto instanceTransforms = instancing ? renderData->getInstanceTransforms(model) : QSSGLayerRenderData::InstanceTransforms{};
993
994 for (int instanceIndex = 0; instanceIndex < instanceCount; ++instanceIndex) {
995
996 QMatrix4x4 modelTransform;
997 if (instancing) {
998 modelTransform = instanceTransforms.global * model.instanceTable->getTransform(instanceIndex) * instanceTransforms.local;
999 } else {
1000 modelTransform = renderData->getGlobalTransform(model);
1001 }
1002 auto rayData = QSSGRenderRay::createRayData(modelTransform, inRay);
1003
1004 auto hit = QSSGRenderRay::intersectWithAABBv2(rayData, modelBounds);
1005
1006 // If we don't intersect with the model at all, then there's no need to go furher down!
1007 if (!hit.intersects())
1008 continue;
1009
1010 const bool mirrored = modelTransform.determinant() < 0.0f;
1011
1012 // Check each submesh to find the closest intersection point
1013 float minRayLength = std::numeric_limits<float>::max();
1014 QSSGRenderRay::IntersectionResult intersectionResult;
1015 QVector<QSSGRenderRay::IntersectionResult> results;
1016
1017 int subset = 0;
1018 int resultSubset = 0;
1019 for (const auto &subMesh : subMeshes) {
1020 QSSGRenderRay::IntersectionResult result;
1021 if (!subMesh.bvhRoot.isNull()) {
1022 hit = QSSGRenderRay::intersectWithAABBv2(rayData, subMesh.bvhRoot->boundingData);
1023 if (hit.intersects()) {
1024 results.clear();
1025 QSSGCullFaceMode cullMode = cullModeForSubset(model, subset);
1026 if (mirrored)
1027 cullMode = mirroredCullMode(cullMode);
1028 inRay.intersectWithBVH(rayData, static_cast<const QSSGMeshBVHNode *>(subMesh.bvhRoot), mesh, results, cullMode);
1029 float subMeshMinRayLength = std::numeric_limits<float>::max();
1030 for (const auto &subMeshResult : std::as_const(results)) {
1031 if (subMeshResult.rayLengthSquared < subMeshMinRayLength) {
1032 result = subMeshResult;
1033 subMeshMinRayLength = result.rayLengthSquared;
1034 }
1035 }
1036 }
1037 } else {
1038 hit = QSSGRenderRay::intersectWithAABBv2(rayData, subMesh.bounds);
1039 if (hit.intersects())
1040 result = QSSGRenderRay::createIntersectionResult(rayData, hit);
1041 }
1042 if (result.intersects && result.rayLengthSquared < minRayLength) {
1043 intersectionResult = result;
1044 minRayLength = intersectionResult.rayLengthSquared;
1045 resultSubset = subset;
1046 }
1047 subset++;
1048 }
1049
1050 if (intersectionResult.intersects)
1051 outIntersectionResultList.push_back(QSSGRenderPickResult { &model,
1052 intersectionResult.rayLengthSquared,
1053 intersectionResult.relXY,
1054 intersectionResult.scenePosition,
1055 intersectionResult.localPosition,
1056 intersectionResult.faceNormal,
1057 intersectionResult.sceneFaceNormal,
1058 resultSubset,
1059 instanceIndex
1060 });
1061 }
1062}
1063
1064void QSSGRendererPrivate::intersectRayWithItem2D(const QSSGRenderLayer &layer,
1065 const QSSGRenderRay &inRay,
1066 const QSSGRenderItem2D &item2D,
1067 PickResultList &outIntersectionResultList)
1068{
1069 const auto &globalTransform = layer.renderData->getGlobalTransform(item2D);
1070
1071 // Get the plane (and normal) that the item 2D is on
1072 const QVector3D p0 = QSSGRenderNode::getGlobalPos(globalTransform);
1073 const QVector3D normal = -QSSGRenderNode::getDirection(globalTransform);
1074
1075 const float d = QVector3D::dotProduct(inRay.direction, normal);
1076 float intersectionTime = 0;
1077 if (d > 1e-6f) {
1078 const QVector3D p0l0 = p0 - inRay.origin;
1079 intersectionTime = QVector3D::dotProduct(p0l0, normal) / d;
1080 if (intersectionTime >= 0) {
1081 // Intersection
1082 const QVector3D intersectionPoint = inRay.origin + inRay.direction * intersectionTime;
1083 const QMatrix4x4 inverseGlobalTransform = globalTransform.inverted();
1084 const QVector3D localIntersectionPoint = QSSGUtils::mat44::transform(inverseGlobalTransform, intersectionPoint);
1085 const QVector2D qmlCoordinate(localIntersectionPoint.x(), -localIntersectionPoint.y());
1086 outIntersectionResultList.push_back(QSSGRenderPickResult { &item2D,
1087 intersectionTime * intersectionTime,
1088 qmlCoordinate,
1089 intersectionPoint,
1090 localIntersectionPoint,
1091 -normal, -normal });
1092 }
1093 }
1094}
1095
1096QSSGRhiShaderPipelinePtr QSSGRendererPrivate::getShaderPipelineForDefaultMaterial(QSSGRenderer &renderer,
1097 QSSGSubsetRenderable &inRenderable,
1098 const QSSGShaderFeatures &inFeatureSet,
1099 const QSSGUserShaderAugmentation &shaderAugmentation)
1100{
1101 auto *m_currentLayer = renderer.m_currentLayer;
1102 QSSG_ASSERT(m_currentLayer != nullptr, return {});
1103
1104 // This function is the main entry point for retrieving the shaders for a
1105 // default material, and is called for every material for every model in
1106 // every frame. Therefore, like with custom materials, employ a first level
1107 // cache (a simple hash table), with a key that's quick to
1108 // generate/hash/compare. Even though there are other levels of caching in
1109 // the components that get invoked from here, those may not be suitable
1110 // performance wise. So bail out right here as soon as possible.
1111 auto &shaderMap = m_currentLayer->shaderMap;
1112
1113 QElapsedTimer timer;
1114 timer.start();
1115
1116 QSSGRhiShaderPipelinePtr shaderPipeline;
1117
1118 // This just references inFeatureSet and inRenderable.shaderDescription -
1119 // cheap to construct and is good enough for the find()
1120 QByteArray name = shaderAugmentation.hash;
1121 for (const auto &def : shaderAugmentation.defines)
1122 name.append(def.name).append(def.value);
1123 QSSGShaderMapKey skey = QSSGShaderMapKey(name,
1124 inFeatureSet,
1125 inRenderable.shaderDescription);
1126 auto it = shaderMap.find(skey);
1127 if (it == shaderMap.end()) {
1128 Q_TRACE_SCOPE(QSSG_generateShader);
1129 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
1130 shaderPipeline = QSSGRendererPrivate::generateRhiShaderPipeline(renderer, inRenderable, inFeatureSet, shaderAugmentation);
1131 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, inRenderable.material.profilingId);
1132 // make skey useable as a key for the QHash (makes a copy of the materialKey, instead of just referencing)
1133 skey.detach();
1134 // insert it no matter what, no point in trying over and over again
1135 shaderMap.insert(skey, shaderPipeline);
1136 } else {
1137 shaderPipeline = it.value();
1138 }
1139
1140 if (shaderPipeline != nullptr) {
1141 if (m_currentLayer && !m_currentLayer->renderedCameras.isEmpty())
1142 m_currentLayer->ensureCachedCameraDatas();
1143 }
1144
1145 const auto &rhiContext = renderer.m_contextInterface->rhiContext();
1146 QSSGRhiContextStats::get(*rhiContext).registerMaterialShaderGenerationTime(timer.elapsed());
1147
1148 return shaderPipeline;
1149}
1150
1151QList<const QSSGRenderNode *> QSSGRendererPrivate::syncPickInFrustum(const QSSGRenderContextInterface &ctx,
1152 const QSSGRenderLayer &layer,
1153 const QSSGFrustum &frustum)
1154{
1155 if (!layer.renderData)
1156 return {};
1157
1158 auto &bufferManager = ctx.bufferManager();
1159 const bool pickEverything = QSSGRendererPrivate::isGlobalPickingEnabled(*ctx.renderer());
1160
1161 RenderableList nodes;
1162 for (const auto &child : layer.children)
1163 getPickableRecursive(child, nodes, pickEverything);
1164
1165 QList<const QSSGRenderNode *> ret;
1166 for (const auto node : nodes) {
1167 auto aabb = node->getBounds(*bufferManager);
1168 if (!aabb.isEmpty()) {
1169 const auto &transform = layer.renderData->getGlobalTransform(*node);
1170 aabb.transform(transform);
1171 if (frustum.contains(aabb))
1172 ret.append(node);
1173 }
1174 }
1175
1176 return ret;
1177}
1178
1179QT_END_NAMESPACE
friend class QSSGRenderContextInterface
static void cleanupResourcesImpl(const QSSGRenderContextInterface &rci, const Container &resources)
static void getPickableRecursive(const QSSGRenderNode &node, RenderableList &renderables, bool pickEverything=false)
static void dfs(const QSSGRenderNode &node, RenderableList &renderables)
static QByteArray rendererLogPrefix()
static QSSGCullFaceMode mirroredCullMode(QSSGCullFaceMode cullMode)
static QSSGCullFaceMode cullModeForSubset(const QSSGRenderModel &model, int subset)