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
qquick3dmodel.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
11
12#include <QtQuick3DRuntimeRender/private/qssgrendergraphobject_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrendercustommaterial_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrenderdefaultmaterial_p.h>
15#include <QtQuick3DRuntimeRender/private/qssgrendermodel_p.h>
16
17#include <QtQuick3DUtils/private/qssgutils_p.h>
18
19#include <QtQml/QQmlFile>
20
22
23/*!
24 \qmltype Model
25 \inherits Node
26 \inqmlmodule QtQuick3D
27 \brief Lets you load a 3D model data.
28
29 The Model item makes it possible to load a mesh and modify how its shaded, by adding materials
30 to it. For a model to be renderable, it needs at least a mesh and a material.
31
32 \section1 Mesh format and built-in primitives
33
34 The model can load static meshes from storage or one of the built-in primitive types.
35 The mesh format used is a run-time format that's native to the engine, but additional formats are
36 supported through the asset import tool \l {Balsam Asset Import Tool}{Balsam}.
37
38 The built-in primitives can be loaded by setting the \c source property to one of these values:
39 \c {#Rectangle, #Sphere, #Cube, #Cylinder or #Cone}.
40
41 \qml
42 Model {
43 source: "#Sphere"
44 }
45 \endqml
46
47 The table below describes the built-in meshes in more detail.
48
49 \table
50 \header
51 \li Name
52 \li Description
53 \li No. faces
54 \row
55 \li #Cone
56 \li A cone with a height and diameter of \c{100}. The base is at the
57 origin and the cone is pointing upwards in the y direction.
58 \li \c{78}
59 \row
60 \li #Cube
61 \li A cube centered at the origin with \c{100} long sides along x, y and z.
62 \li \c{12}
63 \row
64 \li #Cylinder
65 \li A cylinder with \c{100} height and diameter centered at the origin
66 expanding along the y direction.
67 \li \c{316}
68 \row
69 \li #Rectangle
70 \li A rectangle with \c{100} width and height centered at the origin
71 lying in the xy plane.
72 \li \c{2}
73 \row
74 \li #Sphere
75 \li A sphere with \c{100} diameter centered at the origin.
76 \li \c{4900}
77 \endtable
78
79 \section2 Custom geometry
80
81 In addition to using static meshes, you can implement a
82 \l {QQuick3DGeometry}{custom geometry} provider that provides the model with
83 custom vertex data at run-time. See the
84 \l {Qt Quick 3D - Custom Geometry Example}{Custom Geometry Example} for an
85 example on how to create and use a custom material with your model.
86
87 \section1 Materials
88
89 A model can consist of several sub-meshes, each of which can have its own
90 material. The sub-mesh uses a material from the \l{materials} list,
91 corresponding to its index. If the number of materials is less than the
92 sub-meshes, the last material in the list is used for subsequent sub-meshes.
93 This is demonstrated in the
94 \l {Qt Quick 3D - Sub-mesh Example}{Sub-mesh example}.
95
96 You can use the following materials with the model item:
97 \l {PrincipledMaterial}, \l {DefaultMaterial}, and \l {CustomMaterial}.
98
99 \section1 Picking
100
101 \e Picking is the process of sending a ray through the scene from some
102 starting position to find which models intersect with the ray. In
103 Qt Quick 3D, the ray is normally sent from the view using 2D coordinates
104 resulting from a touch or mouse event. If a model was hit by the ray,
105 \l {pickResult} will be returned with a handle to the model and information
106 about where the ray hit the model. For models that use
107 \l {QQuick3DGeometry}{custom geometry}, the picking is less accurate than
108 for static mesh data, as picking is only done against the model's
109 \l {bounds}{bounding volume}. If the ray goes through more than one model,
110 the closest \l {Model::pickable}{pickable} model is selected.
111
112 Note that for models to be \l {Model::pickable}{pickable}, their
113 \l {Model::pickable}{pickable} property must be set to \c true. For more
114 information, see \l {Qt Quick 3D - Picking example}.
115
116*/
117
118/*!
119 \qmlvaluetype bounds
120 \inqmlmodule QtQuick3D
121 \since 5.15
122 \brief Specifies the bounds of a model.
123
124 bounds specify a bounding box with minimum and maximum points.
125 bounds is a readonly property of the model.
126*/
127
128/*!
129 \qmlproperty vector3d bounds::minimum
130
131 Specifies the minimum point of the model bounds.
132 \sa maximum
133*/
134
135/*!
136 \qmlproperty vector3d bounds::maximum
137
138 Specifies the maximum point of the model bounds.
139 \sa minimum
140*/
141
142QQuick3DModel::QQuick3DModel(QQuick3DNode *parent)
143 : QQuick3DNode(*(new QQuick3DNodePrivate(QQuick3DNodePrivate::Type::Model)), parent) {}
144
145QQuick3DModel::~QQuick3DModel()
146{
147 disconnect(m_geometryConnection);
148
149 auto matList = materials();
150 qmlClearMaterials(&matList);
151 auto morphList = morphTargets();
152 qmlClearMorphTargets(&morphList);
153}
154
155/*!
156 \qmlproperty url Model::source
157
158 This property defines the location of the mesh file containing the geometry
159 of this Model or one of the built-in primitive meshes listed below
160 as described in \l {Mesh format and built-in primitives}.
161
162 \list
163 \li "#Rectangle"
164 \li "#Sphere"
165 \li "#Cube"
166 \li "#Cone"
167 \li "#Cylinder"
168 \endlist
169*/
170
171QUrl QQuick3DModel::source() const
172{
173 return m_source;
174}
175
176/*!
177 \qmlproperty List<QtQuick3D::Material> Model::materials
178
179 This property contains a list of materials used to render the provided
180 geometry. To render anything, there must be at least one material. Normally
181 there should be one material for each sub-mesh included in the source
182 geometry.
183
184 \sa {Qt Quick 3D - Sub-mesh Example}
185*/
186
187
188QQmlListProperty<QQuick3DMaterial> QQuick3DModel::materials()
189{
190 return QQmlListProperty<QQuick3DMaterial>(this,
191 nullptr,
192 QQuick3DModel::qmlAppendMaterial,
193 QQuick3DModel::qmlMaterialsCount,
194 QQuick3DModel::qmlMaterialAt,
195 QQuick3DModel::qmlClearMaterials);
196}
197
198/*!
199 \qmlproperty List<QtQuick3D::MorphTarget> Model::morphTargets
200
201 This property contains a list of \l [QtQuick3D QML] {MorphTarget}{MorphTarget}s used to
202 render the provided geometry. Meshes should have at least one attribute
203 among positions, normals, tangents, binormals, texture coordinates,
204 and vertex colors for the morph targets.
205
206 \sa {MorphTarget}
207*/
208
209QQmlListProperty<QQuick3DMorphTarget> QQuick3DModel::morphTargets()
210{
211 return QQmlListProperty<QQuick3DMorphTarget>(this,
212 nullptr,
213 QQuick3DModel::qmlAppendMorphTarget,
214 QQuick3DModel::qmlMorphTargetsCount,
215 QQuick3DModel::qmlMorphTargetAt,
216 QQuick3DModel::qmlClearMorphTargets);
217}
218
219/*!
220 \qmlproperty QtQuick3D::Instancing Model::instancing
221
222 If this property is set, the model will not be rendered normally. Instead, a number of
223 instances of the model will be rendered, as defined by the instance table.
224
225 \sa Instancing
226*/
227
228QQuick3DInstancing *QQuick3DModel::instancing() const
229{
230 return m_instancing;
231}
232
233/*!
234 \qmlproperty QtQuick3D::Node Model::instanceRoot
235
236 This property defines the origin of the instance’s coordinate system.
237
238 See the \l{Transforms and instancing}{overview documentation} for a detailed explanation.
239
240 \sa instancing, Instancing
241*/
242QQuick3DNode *QQuick3DModel::instanceRoot() const
243{
244 return m_instanceRoot;
245}
246
247// Source URL's need a bit of translation for the engine because of the
248// use of fragment syntax for specifiying primitives and sub-meshes
249// So we need to check for the fragment before translating to a qmlfile
250
251QString QQuick3DModel::translateMeshSource(const QUrl &source, QObject *contextObject)
252{
253 QString fragment;
254 if (source.hasFragment()) {
255 // Check if this is an index, or primitive
256 bool isNumber = false;
257 source.fragment().toInt(&isNumber);
258 fragment = QStringLiteral("#") + source.fragment();
259 // If it wasn't an index, then it was a primitive
260 if (!isNumber)
261 return fragment;
262 }
263
264 const QQmlContext *context = qmlContext(contextObject);
265 const auto resolvedUrl = context ? context->resolvedUrl(source) : source;
266 const auto qmlSource = QQmlFile::urlToLocalFileOrQrc(resolvedUrl);
267 return (qmlSource.isEmpty() ? source.path() : qmlSource) + fragment;
268}
269
270void QQuick3DModel::markAllDirty()
271{
272 m_dirtyAttributes = 0xffffffff;
273 QQuick3DNode::markAllDirty();
274}
275
276/*!
277 \qmlproperty bool Model::castsShadows
278
279 When this property is \c true, the geometry of this model is used when
280 rendering to the shadow maps, and is also generating shadows in baked
281 lighting.
282
283 The default value is \c true.
284*/
285
286bool QQuick3DModel::castsShadows() const
287{
288 return m_castsShadows;
289}
290
291/*!
292 \qmlproperty bool Model::receivesShadows
293
294 When this property is set to \c true, the model's materials take shadow
295 contribution from shadow casting lights into account.
296
297 \note When lightmapping is enabled for this model, fully baked lights with
298 Light::bakeMode set to Light.BakeModeAll will always generate (baked)
299 shadows on the model, regardless of the value of this property.
300
301 The default value is \c true.
302*/
303
304bool QQuick3DModel::receivesShadows() const
305{
306 return m_receivesShadows;
307}
308
309/*!
310 \qmlproperty bool Model::pickable
311
312 This property controls whether the model is pickable or not. Set this property
313 to \c true to make the model pickable. Models are not pickable by default.
314
315 \sa {View3D::pick}
316*/
317bool QQuick3DModel::pickable() const
318{
319 return m_pickable;
320}
321
322/*!
323 \qmlproperty Geometry Model::geometry
324
325 Specify a custom geometry for the model. The Model::source must be empty when custom geometry
326 is used.
327
328*/
329QQuick3DGeometry *QQuick3DModel::geometry() const
330{
331 return m_geometry;
332}
333
334/*!
335 \qmlproperty Skeleton Model::skeleton
336
337 Contains the skeleton for the model. The Skeleton is used together with \l {inverseBindPoses}
338 for \l {Vertex Skinning}{skinning}.
339
340 \note Meshes of the model must have both joints and weights attributes.
341 \note If this property is set, skinning animation is enabled. It means
342 that \l {Model} is transformed based on \l {Skeleton} ignoring Model's global
343 transformation.
344
345 \sa {Model::inverseBindPoses}, {Qt Quick 3D - Simple Skinning Example}
346*/
347QQuick3DSkeleton *QQuick3DModel::skeleton() const
348{
349 return m_skeleton;
350}
351
352/*!
353 \qmlproperty Skin Model::skin
354
355 Contains the skeleton for the model. The Skeleton is used for
356 \l {Vertex Skinning}{skinning}.
357
358 \note Meshes of the model must have both joints and weights attributes.
359 \note If this property is set, skinning animation is enabled. This means
360 the \l {Model} will be transformed based on \l {Skin::joints} and the
361 Model's global transformation will be ignored.
362 \note If a model has both a skeleton and a skin, then the skin will be used.
363
364 \sa {Model::skeleton} {Qt Quick 3D - Simple Skinning Example}
365*/
366QQuick3DSkin *QQuick3DModel::skin() const
367{
368 return m_skin;
369}
370
371
372/*!
373 \qmlproperty List<matrix4x4> Model::inverseBindPoses
374
375 This property contains a list of Inverse Bind Pose matrixes used for the
376 skeletal animation. Each inverseBindPose matrix means the inverse of the
377 global transform of the repective \l {Joint::index} in \l {skeleton}, which
378 will be used initially.
379
380 \note This property is only used if the Model::skeleton is valid.
381 \note If some of the matrices are not set, identity values will be used.
382
383 \sa {skeleton} {Joint::index}
384*/
385QList<QMatrix4x4> QQuick3DModel::inverseBindPoses() const
386{
387 return m_inverseBindPoses;
388}
389
390/*!
391 \qmlproperty Bounds Model::bounds
392
393 The bounds of the model descibes the extents of the bounding volume around the model.
394
395 \note The bounds might not be immediately available if the model needs to be loaded first.
396
397 \readonly
398*/
399QQuick3DBounds3 QQuick3DModel::bounds() const
400{
401 return m_bounds;
402}
403
404/*!
405 \qmlproperty real Model::depthBias
406
407 Holds the depth bias of the model. Depth bias is added to the object distance from camera when sorting
408 objects. This can be used to force rendering order between objects close to each other, that
409 might otherwise be rendered in different order in different frames. Negative values cause the
410 sorting value to move closer to the camera while positive values move it further from the camera.
411*/
412float QQuick3DModel::depthBias() const
413{
414 return m_depthBias;
415}
416
417/*!
418 \qmlproperty bool Model::receivesReflections
419
420 When this property is set to \c true, the model's materials take reflections contribution from
421 a reflection probe. If the model is inside more than one reflection probe at the same time,
422 the nearest reflection probe is taken into account.
423*/
424
425bool QQuick3DModel::receivesReflections() const
426{
427 return m_receivesReflections;
428}
429
430/*!
431 \qmlproperty bool Model::castsReflections
432 \since 6.4
433
434 When this property is set to \c true, the model is rendered by reflection probes and can be
435 seen in the reflections.
436*/
437bool QQuick3DModel::castsReflections() const
438{
439 return m_castsReflections;
440}
441
442/*!
443 \qmlproperty bool Model::usedInBakedLighting
444
445 When this property is set to \c true, the model contributes to baked
446 lighting, such as lightmaps, for example in form of casting shadows or
447 indirect light. This setting is independent of controlling lightmap
448 generation for the model, use \l bakedLightmap for that.
449
450 The default value is \c false.
451
452 \note The default value is false, because designers and developers must
453 always evaluate on a per-model basis if the object is suitable to take part
454 in baked lighting.
455
456 \warning Models with dynamically changing properties, for example, animated
457 position, rotation, or other properties, are not suitable for participating
458 in baked lighting.
459
460 For more information on how to bake lightmaps, see the \l Lightmapper
461 documentation.
462
463 This property is relevant only when baking lightmaps. It has no effect
464 afterwards, when using the generated lightmaps during rendering.
465
466 \sa Light::bakeMode, bakedLightmap, Lightmapper, {Lightmaps and Global Illumination}
467 */
468
469bool QQuick3DModel::isUsedInBakedLighting() const
470{
471 return m_usedInBakedLighting;
472}
473
474/*!
475 \qmlproperty int Model::lightmapBaseResolution
476
477 \deprecated [6.10] This has no effect. Use Model::texelsPerUnit instead.
478 */
479int QQuick3DModel::lightmapBaseResolution() const
480{
481 return m_lightmapBaseResolution;
482}
483
484/*!
485 \qmlproperty BakedLightmap Model::bakedLightmap
486
487 When this property is set to a valid, enabled BakedLightmap object, the
488 model will get a lightmap generated when baking lighting, the lightmap is
489 then stored persistently. When rendering, the model will load and use the
490 associated lightmap. The default value is null.
491
492 \note When the intention is to generate a persistently stored lightmap for
493 a Model, both bakedLightmap and \l usedInBakedLighting must be set on it,
494 in order to indicate that the Model not only participates in the
495 lightmapped scene, but also wants a full lightmap to be baked and stored.
496
497 For more information on how to bake lightmaps, see the \l Lightmapper
498 documentation.
499
500 This property is relevant both when baking and when using lightmaps. A
501 consistent state between the baking run and the subsequent runs that use
502 the generated data is essential. For example, changing the lightmap key
503 will make it impossible to load the previously generated data. An exception
504 is \l {BakedLightmap::}{enabled}, which can be used to dynamically toggle
505 the usage of lightmaps (outside of the baking run), but be aware that the
506 rendered results will depend on the Lights' \l{Light::bakeMode}{bakeMode}
507 settings in the scene.
508
509 \sa usedInBakedLighting, Lightmapper
510 */
511
512QQuick3DBakedLightmap *QQuick3DModel::bakedLightmap() const
513{
514 return m_bakedLightmap;
515}
516
517/*!
518 \qmlproperty real Model::instancingLodMin
519 \since 6.5
520 \default -1.0
521
522 Defines the minimum distance from the camera at which an instance of this
523 model is shown, in world space. Instances closer than this are not drawn,
524 in any pass. A negative value, the default, sets no minimum.
525
526 When the geometry has levels of detail, the level of each instance in the
527 range is still selected automatically, except in the cases listed in
528 \l {instanced-lod}{Instanced models}, such as when \l instancingLodFactor is
529 set or the instance table is \l {Instancing::depthSortingEnabled}{depth sorted}.
530
531 \sa instancingLodMax, instancingLodFactor, {instanced-lod}{Instanced models}
532*/
533float QQuick3DModel::instancingLodMin() const
534{
535 return m_instancingLodMin;
536}
537
538/*!
539 \qmlproperty real Model::instancingLodMax
540 \since 6.5
541 \default -1.0
542
543 Defines the maximum distance from the camera at which an instance of this
544 model is shown, in world space. Instances at this distance or farther are
545 not drawn, in any pass. A negative value, the default, sets no maximum.
546
547 When the geometry has levels of detail, the level of each instance in the
548 range is still selected automatically, except in the cases listed in
549 \l {instanced-lod}{Instanced models}, such as when \l instancingLodFactor is
550 set or the instance table is \l {Instancing::depthSortingEnabled}{depth sorted}.
551
552 \sa instancingLodMin, instancingLodFactor, {instanced-lod}{Instanced models}
553*/
554float QQuick3DModel::instancingLodMax() const
555{
556 return m_instancingLodMax;
557}
558
559void QQuick3DModel::setSource(const QUrl &source)
560{
561 if (m_source == source)
562 return;
563
564 m_source = source;
565 emit sourceChanged();
566 markDirty(SourceDirty);
567 if (QQuick3DObjectPrivate::get(this)->sceneManager)
568 QQuick3DObjectPrivate::get(this)->sceneManager->dirtyBoundingBoxList.append(this);
569}
570
571void QQuick3DModel::setCastsShadows(bool castsShadows)
572{
573 if (m_castsShadows == castsShadows)
574 return;
575
576 m_castsShadows = castsShadows;
577 emit castsShadowsChanged();
578 markDirty(ShadowsDirty);
579}
580
581void QQuick3DModel::setReceivesShadows(bool receivesShadows)
582{
583 if (m_receivesShadows == receivesShadows)
584 return;
585
586 m_receivesShadows = receivesShadows;
587 emit receivesShadowsChanged();
588 markDirty(ShadowsDirty);
589}
590
591void QQuick3DModel::setPickable(bool isPickable)
592{
593 if (m_pickable == isPickable)
594 return;
595
596 m_pickable = isPickable;
597 emit pickableChanged();
598 markDirty(PickingDirty);
599}
600
601void QQuick3DModel::setGeometry(QQuick3DGeometry *geometry)
602{
603 if (geometry == m_geometry)
604 return;
605
606 // Make sure to disconnect if the geometry gets deleted out from under us
607 QQuick3DObjectPrivate::attachWatcher(this, &QQuick3DModel::setGeometry, geometry, m_geometry);
608
609 if (m_geometry)
610 QObject::disconnect(m_geometryConnection);
611 m_geometry = geometry;
612
613 if (m_geometry) {
614 m_geometryConnection
615 = QObject::connect(m_geometry, &QQuick3DGeometry::geometryNodeDirty, this, [this]() {
616 markDirty(GeometryDirty);
617 });
618 }
619 emit geometryChanged();
620 markDirty(GeometryDirty);
621}
622
623void QQuick3DModel::setSkeleton(QQuick3DSkeleton *skeleton)
624{
625 if (skeleton == m_skeleton)
626 return;
627
628 // Make sure to disconnect if the skeleton gets deleted out from under us
629 QQuick3DObjectPrivate::attachWatcher(this, &QQuick3DModel::setSkeleton, skeleton, m_skeleton);
630
631 m_skeleton = skeleton;
632
633 emit skeletonChanged();
634 markDirty(SkeletonDirty);
635}
636
637void QQuick3DModel::setSkin(QQuick3DSkin *skin)
638{
639 if (skin == m_skin)
640 return;
641
642 // Make sure to disconnect if the skin gets deleted out from under us
643 QQuick3DObjectPrivate::attachWatcher(this, &QQuick3DModel::setSkin, skin, m_skin);
644
645 m_skin = skin;
646 emit skinChanged();
647 markDirty(SkinDirty);
648}
649
650void QQuick3DModel::setInverseBindPoses(const QList<QMatrix4x4> &poses)
651{
652 if (m_inverseBindPoses == poses)
653 return;
654
655 m_inverseBindPoses = poses;
656 emit inverseBindPosesChanged();
657 markDirty(PoseDirty);
658}
659
660
661void QQuick3DModel::setBounds(const QVector3D &min, const QVector3D &max)
662{
663 if (!qFuzzyCompare(m_bounds.maximum(), max)
664 || !qFuzzyCompare(m_bounds.minimum(), min)) {
665 m_bounds.bounds = QSSGBounds3 { min, max };
666 emit boundsChanged();
667 }
668}
669
670void QQuick3DModel::setInstancing(QQuick3DInstancing *instancing)
671{
672 if (m_instancing == instancing)
673 return;
674
675 // Make sure to disconnect if the instance table gets deleted out from under us
676 QQuick3DObjectPrivate::attachWatcher(this, &QQuick3DModel::setInstancing, instancing, m_instancing);
677 if (m_instancing)
678 QObject::disconnect(m_instancingConnection);
679 m_instancing = instancing;
680 if (m_instancing) {
681 m_instancingConnection = QObject::connect
682 (m_instancing, &QQuick3DInstancing::instanceNodeDirty,
683 this, [this]{ markDirty(InstancesDirty);});
684 }
685 markDirty(InstancesDirty);
686 emit instancingChanged();
687}
688
689void QQuick3DModel::setInstanceRoot(QQuick3DNode *instanceRoot)
690{
691 if (m_instanceRoot == instanceRoot)
692 return;
693
694 QQuick3DObjectPrivate::attachWatcher(this, &QQuick3DModel::setInstanceRoot, instanceRoot, m_instanceRoot);
695
696 m_instanceRoot = instanceRoot;
697 markDirty(InstanceRootDirty);
698 emit instanceRootChanged();
699}
700
701void QQuick3DModel::setDepthBias(float bias)
702{
703 if (qFuzzyCompare(bias, m_depthBias))
704 return;
705
706 m_depthBias = bias;
707 markDirty(PropertyDirty);
708 emit depthBiasChanged();
709}
710
711void QQuick3DModel::setReceivesReflections(bool receivesReflections)
712{
713 if (m_receivesReflections == receivesReflections)
714 return;
715
716 m_receivesReflections = receivesReflections;
717 emit receivesReflectionsChanged();
718 markDirty(ReflectionDirty);
719}
720
721void QQuick3DModel::setCastsReflections(bool castsReflections)
722{
723 if (m_castsReflections == castsReflections)
724 return;
725 m_castsReflections = castsReflections;
726 emit castsReflectionsChanged();
727 markDirty(ReflectionDirty);
728}
729
730void QQuick3DModel::setUsedInBakedLighting(bool enable)
731{
732 if (m_usedInBakedLighting == enable)
733 return;
734
735 m_usedInBakedLighting = enable;
736 emit usedInBakedLightingChanged();
737 markDirty(PropertyDirty);
738}
739
740void QQuick3DModel::setLightmapBaseResolution(int resolution)
741{
742 resolution = qMax(128, resolution);
743 if (m_lightmapBaseResolution == resolution)
744 return;
745
746 qWarning() << "Model::lightmapBaseResolution is deprecated and will have no effect.";
747
748 m_lightmapBaseResolution = resolution;
749 emit lightmapBaseResolutionChanged();
750 markDirty(PropertyDirty);
751}
752
753void QQuick3DModel::setBakedLightmap(QQuick3DBakedLightmap *bakedLightmap)
754{
755 if (m_bakedLightmap == bakedLightmap)
756 return;
757
758 if (m_bakedLightmap)
759 m_bakedLightmap->disconnect(m_bakedLightmapSignalConnection);
760
761 m_bakedLightmap = bakedLightmap;
762
763 m_bakedLightmapSignalConnection = QObject::connect(m_bakedLightmap, &QQuick3DBakedLightmap::changed, this,
764 [this] { markDirty(PropertyDirty); });
765
766 QObject::connect(m_bakedLightmap, &QObject::destroyed, this,
767 [this]
768 {
769 m_bakedLightmap = nullptr;
770 markDirty(PropertyDirty);
771 });
772
773 emit bakedLightmapChanged();
774 markDirty(PropertyDirty);
775}
776
777void QQuick3DModel::itemChange(ItemChange change, const ItemChangeData &value)
778{
779 if (change == QQuick3DObject::ItemSceneChange)
780 updateSceneManager(value.sceneManager);
781}
782
783QSSGRenderGraphObject *QQuick3DModel::updateSpatialNode(QSSGRenderGraphObject *node)
784{
785 if (!node) {
786 markAllDirty();
787 node = new QSSGRenderModel();
788 }
789
790 QQuick3DNode::updateSpatialNode(node);
791 int dirtyAttribute = 0;
792
793 auto modelNode = static_cast<QSSGRenderModel *>(node);
794 if (m_dirtyAttributes & SourceDirty) {
795 const QString path = translateMeshSource(m_source, this);
796 const QString lightmapKey = m_bakedLightmap ? m_bakedLightmap->key() : QString();
797 modelNode->meshPath = QSSGRenderPath(path, lightmapKey);
798 }
799 if (m_dirtyAttributes & PickingDirty)
800 modelNode->setState(QSSGRenderModel::LocalState::Pickable, m_pickable);
801
802 if (m_dirtyAttributes & ShadowsDirty) {
803 modelNode->castsShadows = m_castsShadows;
804 modelNode->receivesShadows = m_receivesShadows;
805 }
806
807 if (m_dirtyAttributes & MaterialsDirty) {
808 if (!m_materials.isEmpty()) {
809 if (modelNode->materials.isEmpty()) {
810 // Easy mode, just add each material
811 for (const Material &material : std::as_const(m_materials)) {
812 QSSGRenderGraphObject *graphObject = QQuick3DObjectPrivate::get(material.material)->spatialNode;
813 if (graphObject)
814 modelNode->materials.append(graphObject);
815 else
816 dirtyAttribute |= MaterialsDirty; // We still got dirty materials
817 }
818 } else {
819 // Hard mode, go through each material and see if they match
820 if (modelNode->materials.size() != m_materials.size())
821 modelNode->materials.resize(m_materials.size());
822 for (int i = 0; i < m_materials.size(); ++i) {
823 QSSGRenderGraphObject *graphObject = QQuick3DObjectPrivate::get(m_materials[i].material)->spatialNode;
824 if (modelNode->materials[i] != graphObject)
825 modelNode->materials[i] = graphObject;
826 }
827 }
828 } else {
829 // No materials
830 modelNode->materials.clear();
831 }
832 }
833
834 if (m_dirtyAttributes & MorphTargetsDirty) {
835 if (!m_morphTargets.isEmpty()) {
836 const int numMorphTarget = m_morphTargets.size();
837 if (modelNode->morphTargets.isEmpty()) {
838 // Easy mode, just add each morphTarget
839 for (const auto morphTarget : std::as_const(m_morphTargets)) {
840 QSSGRenderGraphObject *graphObject = QQuick3DObjectPrivate::get(morphTarget)->spatialNode;
841 if (graphObject)
842 modelNode->morphTargets.append(graphObject);
843 else
844 dirtyAttribute |= MorphTargetsDirty; // We still got dirty morphTargets
845 }
846 modelNode->morphWeights.resize(numMorphTarget);
847 modelNode->morphAttributes.resize(numMorphTarget);
848 } else {
849 // Hard mode, go through each morphTarget and see if they match
850 if (modelNode->morphTargets.size() != numMorphTarget) {
851 modelNode->morphTargets.resize(numMorphTarget);
852 modelNode->morphWeights.resize(numMorphTarget);
853 modelNode->morphAttributes.resize(numMorphTarget);
854 }
855 for (int i = 0; i < numMorphTarget; ++i)
856 modelNode->morphTargets[i] = QQuick3DObjectPrivate::get(m_morphTargets.at(i))->spatialNode;
857 }
858 } else {
859 // No morphTargets
860 modelNode->morphTargets.clear();
861 }
862 }
863
864 if (m_dirtyAttributes & quint32(InstancesDirty | InstanceRootDirty)) {
865 // If we have an instance root set we have lower priority and the instance root node should already
866 // have been created.
867 QSSGRenderNode *instanceRootNode = nullptr;
868 if (m_instanceRoot) {
869 if (m_instanceRoot == this)
870 instanceRootNode = modelNode;
871 else
872 instanceRootNode = static_cast<QSSGRenderNode *>(QQuick3DObjectPrivate::get(m_instanceRoot)->spatialNode);
873 }
874 if (instanceRootNode != modelNode->instanceRoot) {
875 modelNode->instanceRoot = instanceRootNode;
876 modelNode->markDirty(QSSGRenderNode::DirtyFlag::TransformDirty);
877 }
878
879 if (m_instancing) {
880 modelNode->instanceTable = static_cast<QSSGRenderInstanceTable *>(QQuick3DObjectPrivate::get(m_instancing)->spatialNode);
881 } else {
882 modelNode->instanceTable = nullptr;
883 }
884 }
885
886 if (m_dirtyAttributes & GeometryDirty) {
887 if (m_geometry) {
888 modelNode->geometry = static_cast<QSSGRenderGeometry *>(QQuick3DObjectPrivate::get(m_geometry)->spatialNode);
889 setBounds(m_geometry->boundsMin(), m_geometry->boundsMax());
890 } else {
891 modelNode->geometry = nullptr;
892 setBounds(QVector3D(), QVector3D());
893 }
894 }
895
896 if (m_dirtyAttributes & SkeletonDirty) {
897 if (m_skeleton) {
898 modelNode->skeleton = static_cast<QSSGRenderSkeleton *>(QQuick3DObjectPrivate::get(m_skeleton)->spatialNode);
899 if (modelNode->skeleton)
900 modelNode->skeleton->skinningDirty = true;
901 } else {
902 modelNode->skeleton = nullptr;
903 }
904 }
905
906 if (m_dirtyAttributes & SkinDirty) {
907 if (m_skin)
908 modelNode->skin = static_cast<QSSGRenderSkin *>(QQuick3DObjectPrivate::get(m_skin)->spatialNode);
909 else
910 modelNode->skin = nullptr;
911 }
912
913 if (m_dirtyAttributes & LodDirty) {
914 modelNode->instancingLodMin = m_instancingLodMin;
915 modelNode->instancingLodMax = m_instancingLodMax;
916 }
917
918 if (m_dirtyAttributes & PoseDirty) {
919 modelNode->inverseBindPoses = m_inverseBindPoses.toVector();
920 if (modelNode->skeleton)
921 modelNode->skeleton->skinningDirty = true;
922 }
923
924 if (m_dirtyAttributes & PropertyDirty) {
925 modelNode->m_depthBiasSq = QSSGRenderModel::signedSquared(m_depthBias);
926 modelNode->usedInBakedLighting = m_usedInBakedLighting;
927 modelNode->texelsPerUnit = m_texelsPerUnit;
928 if (m_bakedLightmap && m_bakedLightmap->isEnabled()) {
929 modelNode->lightmapKey = m_bakedLightmap->key();
930 } else {
931 modelNode->lightmapKey.clear();
932 }
933 // Need new hash if lightmapKey has changed
934 const QString path = translateMeshSource(m_source, this);
935 modelNode->meshPath = QSSGRenderPath(path, modelNode->lightmapKey);
936 modelNode->levelOfDetailBias = m_levelOfDetailBias;
937 modelNode->instancingLodFactor = m_instancingLodFactor;
938 modelNode->motionVectorEnabled = m_motionVectorEnabled;
939 modelNode->motionVectorScale = m_motionVectorScale;
940 }
941
942 if (m_dirtyAttributes & ReflectionDirty) {
943 modelNode->receivesReflections = m_receivesReflections;
944 modelNode->castsReflections = m_castsReflections;
945 }
946
947 m_dirtyAttributes = dirtyAttribute;
948
949 return modelNode;
950}
951
952void QQuick3DModel::markDirty(QQuick3DModel::QSSGModelDirtyType type)
953{
954 if (InstanceRootDirty & quint32(type))
955 QQuick3DObjectPrivate::get(this)->dirty(QQuick3DObjectPrivate::InstanceRootChanged);
956
957 if (!(m_dirtyAttributes & quint32(type))) {
958 m_dirtyAttributes |= quint32(type);
959 update();
960 }
961}
962
963void QQuick3DModel::updateSceneManager(QQuick3DSceneManager *sceneManager)
964{
965 if (sceneManager) {
966 sceneManager->dirtyBoundingBoxList.append(this);
967 QQuick3DObjectPrivate::refSceneManager(m_skeleton, *sceneManager);
968 QQuick3DObjectPrivate::refSceneManager(m_skin, *sceneManager);
969 QQuick3DObjectPrivate::refSceneManager(m_geometry, *sceneManager);
970 QQuick3DObjectPrivate::refSceneManager(m_instancing, *sceneManager);
971 for (Material &mat : m_materials) {
972 if (!mat.material->parentItem() && !QQuick3DObjectPrivate::get(mat.material)->sceneManager) {
973 if (!mat.refed) {
974 QQuick3DObjectPrivate::refSceneManager(mat.material, *sceneManager);
975 mat.refed = true;
976 }
977 }
978 }
979 } else {
980 QQuick3DObjectPrivate::derefSceneManager(m_skeleton);
981 QQuick3DObjectPrivate::derefSceneManager(m_skin);
982 QQuick3DObjectPrivate::derefSceneManager(m_geometry);
983 QQuick3DObjectPrivate::derefSceneManager(m_instancing);
984 for (Material &mat : m_materials) {
985 if (mat.refed) {
986 QQuick3DObjectPrivate::derefSceneManager(mat.material);
987 mat.refed = false;
988 }
989 }
990 }
991}
992
993void QQuick3DModel::onMaterialDestroyed(QObject *object)
994{
995 bool found = false;
996 for (int i = 0; i < m_materials.size(); ++i) {
997 if (m_materials[i].material == object) {
998 m_materials.removeAt(i--);
999 found = true;
1000 }
1001 }
1002 if (found)
1003 markDirty(QQuick3DModel::MaterialsDirty);
1004}
1005
1006void QQuick3DModel::qmlAppendMaterial(QQmlListProperty<QQuick3DMaterial> *list, QQuick3DMaterial *material)
1007{
1008 if (material == nullptr)
1009 return;
1010 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1011 self->m_materials.push_back({ material, false });
1012 self->markDirty(QQuick3DModel::MaterialsDirty);
1013
1014 if (material->parentItem() == nullptr) {
1015 // If the material has no parent, check if it has a hierarchical parent that's a QQuick3DObject
1016 // and re-parent it to that, e.g., inline materials
1017 QQuick3DObject *parentItem = qobject_cast<QQuick3DObject *>(material->parent());
1018 if (parentItem) {
1019 material->setParentItem(parentItem);
1020 } else { // If no valid parent was found, make sure the material refs our scene manager
1021 const auto &sceneManager = QQuick3DObjectPrivate::get(self)->sceneManager;
1022 if (sceneManager) {
1023 QQuick3DObjectPrivate::get(material)->refSceneManager(*sceneManager);
1024 // Have to keep track if we called refSceneManager because we
1025 // can end up in double deref attempts when a model is going
1026 // away, due to updateSceneManager() being called on
1027 // ItemSceneChanged (and also doing deref). We must ensure that
1028 // is one deref for each ref.
1029 self->m_materials.last().refed = true;
1030 }
1031 // else: If there's no scene manager, defer until one is set, see itemChange()
1032 }
1033 }
1034
1035 // Make sure materials are removed when destroyed
1036 connect(material, &QQuick3DMaterial::destroyed, self, &QQuick3DModel::onMaterialDestroyed);
1037}
1038
1039QQuick3DMaterial *QQuick3DModel::qmlMaterialAt(QQmlListProperty<QQuick3DMaterial> *list, qsizetype index)
1040{
1041 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1042 return self->m_materials.at(index).material;
1043}
1044
1045qsizetype QQuick3DModel::qmlMaterialsCount(QQmlListProperty<QQuick3DMaterial> *list)
1046{
1047 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1048 return self->m_materials.size();
1049}
1050
1051void QQuick3DModel::qmlClearMaterials(QQmlListProperty<QQuick3DMaterial> *list)
1052{
1053 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1054 for (Material &mat : self->m_materials) {
1055 if (mat.material->parentItem() == nullptr) {
1056 if (mat.refed) {
1057 QQuick3DObjectPrivate::get(mat.material)->derefSceneManager();
1058 mat.refed = false;
1059 }
1060 }
1061 disconnect(mat.material, &QQuick3DMaterial::destroyed, self, &QQuick3DModel::onMaterialDestroyed);
1062 }
1063 self->m_materials.clear();
1064 self->markDirty(QQuick3DModel::MaterialsDirty);
1065}
1066
1067void QQuick3DModel::onMorphTargetDestroyed(QObject *object)
1068{
1069 bool found = false;
1070 for (int i = 0; i < m_morphTargets.size(); ++i) {
1071 if (m_morphTargets.at(i) == object) {
1072 m_morphTargets.removeAt(i--);
1073 found = true;
1074 }
1075 }
1076 if (found) {
1077 markDirty(QQuick3DModel::MorphTargetsDirty);
1078 }
1079}
1080
1081void QQuick3DModel::qmlAppendMorphTarget(QQmlListProperty<QQuick3DMorphTarget> *list, QQuick3DMorphTarget *morphTarget)
1082{
1083 if (morphTarget == nullptr)
1084 return;
1085 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1086 self->m_morphTargets.push_back(morphTarget);
1087
1088 self->markDirty(QQuick3DModel::MorphTargetsDirty);
1089
1090 if (morphTarget->parentItem() == nullptr) {
1091 // If the morphTarget has no parent, check if it has a hierarchical parent that's a QQuick3DObject
1092 // and re-parent it to that, e.g., inline morphTargets
1093 QQuick3DObject *parentItem = qobject_cast<QQuick3DObject *>(morphTarget->parent());
1094 if (parentItem) {
1095 morphTarget->setParentItem(parentItem);
1096 } else { // If no valid parent was found, make sure the morphTarget refs our scene manager
1097 const auto &scenManager = QQuick3DObjectPrivate::get(self)->sceneManager;
1098 if (scenManager)
1099 QQuick3DObjectPrivate::get(morphTarget)->refSceneManager(*scenManager);
1100 // else: If there's no scene manager, defer until one is set, see itemChange()
1101 }
1102 }
1103
1104 // Make sure morphTargets are removed when destroyed
1105 connect(morphTarget, &QQuick3DMorphTarget::destroyed, self, &QQuick3DModel::onMorphTargetDestroyed);
1106}
1107
1108QQuick3DMorphTarget *QQuick3DModel::qmlMorphTargetAt(QQmlListProperty<QQuick3DMorphTarget> *list, qsizetype index)
1109{
1110 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1111 if (index >= self->m_morphTargets.size()) {
1112 qWarning("The index exceeds the range of valid morph targets.");
1113 return nullptr;
1114 }
1115 return self->m_morphTargets.at(index);
1116}
1117
1118qsizetype QQuick3DModel::qmlMorphTargetsCount(QQmlListProperty<QQuick3DMorphTarget> *list)
1119{
1120 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1121 return self->m_morphTargets.size();
1122}
1123
1124void QQuick3DModel::qmlClearMorphTargets(QQmlListProperty<QQuick3DMorphTarget> *list)
1125{
1126 QQuick3DModel *self = static_cast<QQuick3DModel *>(list->object);
1127 for (const auto &morph : std::as_const(self->m_morphTargets)) {
1128 if (morph->parentItem() == nullptr)
1129 QQuick3DObjectPrivate::get(morph)->derefSceneManager();
1130 disconnect(morph, &QQuick3DMorphTarget::destroyed, self, &QQuick3DModel::onMorphTargetDestroyed);
1131 }
1132 self->m_morphTargets.clear();
1133 self->markDirty(QQuick3DModel::MorphTargetsDirty);
1134}
1135
1136void QQuick3DModel::setInstancingLodMin(float minDistance)
1137{
1138 if (qFuzzyCompare(m_instancingLodMin, minDistance))
1139 return;
1140 m_instancingLodMin = minDistance;
1141 emit instancingLodMinChanged();
1142 markDirty(LodDirty);
1143}
1144
1145void QQuick3DModel::setInstancingLodMax(float maxDistance)
1146{
1147 if (qFuzzyCompare(m_instancingLodMax, maxDistance))
1148 return;
1149 m_instancingLodMax = maxDistance;
1150 emit instancingLodMaxChanged();
1151 markDirty(LodDirty);
1152}
1153
1154/*!
1155 \qmlproperty real Model::instancingLodFactor
1156 \since 6.12
1157 \default -1.0
1158
1159 This property allows manual determination of the level of detail (LOD) for
1160 all instances of an instanced model.
1161
1162 When the geometry has levels of detail, an instanced model gets the level
1163 of each instance selected automatically, unless its instance table is
1164 \l {Instancing::depthSortingEnabled}{depth sorted}. Setting a value of \c 0.0
1165 or more turns that off and uses the same level for all instances instead.
1166 The closer the value is to \c 1.0, the less geometry will be rendered for
1167 the model: \c 0.0 is the original geometry and \c 1.0, or more, the coarsest
1168 level of detail. A negative value, the default, is automatic, and gives the
1169 original geometry where the level cannot be selected for each instance, as
1170 for a depth sorted table.
1171
1172 Several models that share an instance table can use \l instancingLodMin and
1173 \l instancingLodMax to draw different parts of it, each with its own
1174 instancingLodFactor or with the automatic level. instancingLodMin and
1175 instancingLodMax do not turn the automatic selection off on their own.
1176
1177 Like the automatic selection, this has no effect when \l levelOfDetailBias, or
1178 \l {Camera::levelOfDetailBias}{Camera.levelOfDetailBias}, is \c 0.0: the instances then
1179 use the original geometry.
1180
1181 \sa levelOfDetailBias, instancingLodMin, instancingLodMax, {instanced-lod}{Instanced models}
1182*/
1183
1184float QQuick3DModel::instancingLodFactor() const
1185{
1186 return m_instancingLodFactor;
1187}
1188
1189void QQuick3DModel::setInstancingLodFactor(float newInstancingLodFactor)
1190{
1191 if (qFuzzyCompare(m_instancingLodFactor, newInstancingLodFactor))
1192 return;
1193
1194 m_instancingLodFactor = newInstancingLodFactor;
1195 emit instancingLodFactorChanged();
1196 markDirty(QQuick3DModel::PropertyDirty);
1197}
1198
1199/*!
1200 \qmlproperty real Model::levelOfDetailBias
1201 \since 6.5
1202
1203 This property changes the size the model needs to be when rendered before the
1204 automatic level of detail meshes are used. Each generated level of detail
1205 mesh contains an ideal size value that each level should be shown, which is
1206 a ratio of how much of the rendered scene will be that mesh. A model that
1207 represents only a few pixels on screen will not require the full geometry
1208 to look correct, so a lower level of detail mesh will be used instead in
1209 this case. This value is a bias to the ideal value such that a value smaller
1210 than \c 1.0 will require an even smaller rendered size before switching to
1211 a lesser level of detail. Values above \c 1.0 will lead to lower levels of detail
1212 being used sooner. A value of \c 0.0 will disable the usage of levels of detail
1213 completely.
1214
1215 The default value is \c 1.0
1216
1217 \note This property will only have an effect when the Model's geometry contains
1218 levels of detail.
1219
1220 For an instanced Model, the level of detail is selected for each instance
1221 by its own distance from the camera, except in the cases listed in
1222 \l {instanced-lod}{Instanced models}, such as when \l instancingLodFactor is
1223 set or the instance table is \l {Instancing::depthSortingEnabled}{depth sorted}.
1224 All the instances then use the level given by \l instancingLodFactor.
1225
1226 \sa Camera::levelOfDetailBias, instancingLodFactor, {instanced-lod}{Instanced models}
1227*/
1228
1229float QQuick3DModel::levelOfDetailBias() const
1230{
1231 return m_levelOfDetailBias;
1232}
1233
1234void QQuick3DModel::setLevelOfDetailBias(float newLevelOfDetailBias)
1235{
1236 if (qFuzzyCompare(m_levelOfDetailBias, newLevelOfDetailBias))
1237 return;
1238 m_levelOfDetailBias = newLevelOfDetailBias;
1239 emit levelOfDetailBiasChanged();
1240 markDirty(QQuick3DModel::PropertyDirty);
1241}
1242
1243/*!
1244 \qmlproperty real Model::texelsPerUnit
1245 \since 6.10
1246 \default 0.0
1247
1248 A value greater than zero means this value will override the
1249 \l {Lightmapper::texelsPerUnit} value for this specific model during
1250 lightmap baking.
1251
1252 \sa Lightmapper::texelsPerUnit
1253*/
1254
1255float QQuick3DModel::texelsPerUnit() const
1256{
1257 return m_texelsPerUnit;
1258}
1259
1260void QQuick3DModel::setTexelsPerUnit(float newTexelsPerUnit)
1261{
1262 if (qFuzzyCompare(m_texelsPerUnit, newTexelsPerUnit))
1263 return;
1264 m_texelsPerUnit = newTexelsPerUnit;
1265 emit texelsPerUnitChanged();
1266 markDirty(PropertyDirty);
1267}
1268
1269/*!
1270 \qmlproperty bool Model::motionVectorEnabled
1271 \since 6.11
1272 \default true
1273
1274 Specifies whether the model participates in the motion vector pass.
1275
1276 When this property is set to \c true, the model contributes its
1277 motion information to the motion vector buffer. This is used by
1278 temporal anti-aliasing (TAA) and other effects that rely on
1279 per-pixel motion data.
1280
1281 When set to \c false, the model is excluded from motion vector
1282 generation.
1283
1284 \sa Model::motionVectorScale
1285*/
1286
1287bool QQuick3DModel::motionVectorEnabled() const
1288{
1289 return m_motionVectorEnabled;
1290}
1291
1292void QQuick3DModel::setMotionVectorEnabled(bool newMotionVectorEnabled)
1293{
1294 if (m_motionVectorEnabled == newMotionVectorEnabled)
1295 return;
1296 m_motionVectorEnabled = newMotionVectorEnabled;
1297 emit motionVectorEnabledChanged();
1298 markDirty(QQuick3DModel::PropertyDirty);
1299}
1300
1301/*!
1302 \qmlproperty real Model::motionVectorScale
1303 \since 6.11
1304 \default 1.0
1305
1306 Specifies a scaling factor applied to the model's generated motion
1307 vectors.
1308
1309 A value of \c 1.0 preserves the model's actual motion, while values
1310 greater than \c 1.0 exaggerate the motion vectors and values lower
1311 than \c 1.0 reduce them. This can be useful for stylized effects or
1312 fine-tuning visual behavior in effects that rely on the motion
1313 vector buffer.
1314
1315 \sa Model::motionVectorEnabled
1316*/
1317
1318float QQuick3DModel::motionVectorScale() const
1319{
1320 return m_motionVectorScale;
1321}
1322
1323void QQuick3DModel::setMotionVectorScale(float newMotionVectorScale)
1324{
1325 if (qFuzzyCompare(m_motionVectorScale, newMotionVectorScale))
1326 return;
1327 m_motionVectorScale = newMotionVectorScale;
1328 emit motionVectorScaleChanged();
1329 markDirty(QQuick3DModel::PropertyDirty);
1330}
1331
1332QT_END_NAMESPACE
Combined button and popup list for selecting options.