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
qquick3dinstancing.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7#include <QtQuick3DRuntimeRender/private/qssgrenderinstancetable_p.h>
8#include <QtQuick3DUtils/private/qssgutils_p.h>
9#include <QXmlStreamReader>
10#include <QtQml/QQmlFile>
11
12QT_BEGIN_NAMESPACE
13
14/*!
15 \qmltype Instancing
16 \inherits Object3D
17 \inqmlmodule QtQuick3D
18 \nativetype QQuick3DInstancing
19 \since 6.2
20 \brief Base type for instance tables.
21
22 \l {Instanced Rendering}{Instanced rendering} allows duplicating a model with variations.
23
24 The Instancing type defines a table that specifies how each instance is modified relative to the
25 base model. The table has an entry for each index, containing a transform matrix, a color, and
26 generic data for use by custom materials. To use instancing, set a model's
27 \l{Model::instancing}{instancing} property to reference an Instancing object.
28
29 An application can define an Instancing object in C++ by subclassing QQuick3DInstancing,
30 or it can use one of the pre-defined QML types: InstanceList FileInstancing, or RandomInstancing.
31 In addition, it is possible to use a \l {ParticleSystem3D}{particle system} to define an
32 instancing table by using the \l{ModelParticle3D::instanceTable}{ModelParticle3D.instanceTable}
33 property.
34
35 It is also possible to generate instancing data on the GPU by using \l ShaderInstancing together
36 with \l CustomMaterial.
37*/
38
39/*!
40 \qmlproperty int Instancing::instanceCountOverride
41
42 Set this property to limit the number of instances without regenerating or re-uploading the instance table.
43 This allows very inexpensive animation of the number of instances rendered.
44*/
45
46/*!
47 \property QQuick3DInstancing::instanceCountOverride
48
49 Set this property to limit the number of instances without regenerating or re-uploading the instance table.
50 This allows very inexpensive animation of the number of instances rendered.
51*/
52
53/*!
54 \qmlproperty bool Instancing::hasTransparency
55
56 Set this property to true if the instancing table contains alpha values that should be used when
57 rendering the model. This property only makes a difference if the model is opaque: If the model has a
58 transparent \l{Model::materials}{material}, or an \l{Node::opacity}{opacity} less than one, the
59 alpha value from the table will be used regardless.
60
61 \note Enabling alpha blending may cause rendering issues when instances overlap. See the
62 \l{Alpha-blending and instancing}{alpha blending and instancing} documentation for details.
63*/
64
65/*!
66 \property QQuick3DInstancing::hasTransparency
67
68 Set this property to true if the instancing table contains alpha values that should be used when
69 rendering the model. This property only makes a difference if the model is opaque: If the model has a
70 transparent \l{Model::materials}{material}, or an \l{Node::opacity}{opacity} less than one, the
71 alpha value from the table will be used regardless.
72
73 \note Enabling alpha blending may cause rendering issues when instances overlap. See the
74 \l{Alpha-blending and instancing}{alpha blending and instancing} documentation for details.
75*/
76
77/*!
78 \qmlproperty bool Instancing::depthSortingEnabled
79 \default false
80
81 Holds the depth sorting enabled value for the instance table. When enabled, instances are sorted
82 and rendered from the furthest instance from the camera to the nearest i.e. back-to-front.
83 If disabled, instances are rendered in the order they are specified in the instance table.
84 When the \l {instanced-lod}{level of detail} of each instance is selected automatically, they
85 are rendered one level at a time instead, the nearest level first, or the farthest for
86 semi-transparent models, keeping the table order within each level.
87
88 \note The instances are only sorted against each other. Instances are not sorted against other
89 objects in the scene.
90 \note The sorting increases the frame preparation time especially with large instance counts.
91 \note A depth sorted table is drawn in one draw call, so a Model whose geometry has levels
92 of detail does not get the level of each instance selected automatically. All the instances
93 use the level given by \l {Model::instancingLodFactor}{instancingLodFactor}, which is the
94 original geometry when it is not set. To blend semi-transparent instances correctly and
95 keep the level of each instance, leave the table unsorted and use
96 \l {SceneEnvironment::oitMethod}{order independent transparency} instead, which does not
97 depend on the order the instances are drawn in. See \l {instanced-lod}{Instanced models}.
98*/
99
100/*!
101 \property QQuick3DInstancing::depthSortingEnabled
102
103 Holds the depth sorting enabled value for the instance table. When enabled, instances are sorted
104 and rendered from the furthest instance from the camera to the nearest i.e. back-to-front.
105 If disabled, which is the default, instances are rendered in the order they are specified in
106 the instance table. When the \l {instanced-lod}{level of detail} of each instance is selected
107 automatically, they are rendered one level at a time instead, the nearest level first, or the
108 farthest for semi-transparent models, keeping the table order within each level.
109
110 \note The instances are only sorted against each other. Instances are not sorted against other
111 objects in the scene.
112 \note The sorting increases the frame preparation time especially with large instance counts.
113 \note A depth sorted table is drawn in one draw call, so a Model whose geometry has levels
114 of detail does not get the level of each instance selected automatically. All the instances
115 use the level given by \l {Model::instancingLodFactor}{Model.instancingLodFactor}, which is the
116 original geometry when it is not set. To blend semi-transparent instances correctly and
117 keep the level of each instance, leave the table unsorted and use
118 \l {SceneEnvironment::oitMethod}{order independent transparency} instead, which does not
119 depend on the order the instances are drawn in. See \l {instanced-lod}{Instanced models}.
120*/
121
122/*!
123 \property QQuick3DInstancing::shadowBoundsMinimum
124 \since 6.9
125
126 Sets the minimum bounds used when calculating the shadow map bounds of the
127 models in the instance table.
128
129 Default value: \c{(1, 1, 1)}
130
131 \note This property is only enabled when the respective components of
132 shadowBoundsMinimum are smaller than those in shadowBoundsMaximum.
133 Otherwise the bounds are calculated automatically.
134
135 \sa shadowBoundsMaximum
136*/
137/*!
138 \qmlproperty vector3d Instancing::shadowBoundsMinimum
139
140 Sets the minimum bounds used when calculating the shadow map bounds of the models in the
141 instance table.
142
143 Default value: \c{(1, 1, 1)}
144
145 \note This property is only enabled when the respective components of
146 Instancing::shadowBoundsMinimum are smaller than those in
147 Instancing::shadowBoundsMaximum. Otherwise the bounds are calculated automatically.
148 \sa shadowBoundsMaximum
149*/
150
151/*!
152 \property QQuick3DInstancing::shadowBoundsMaximum
153 \since 6.9
154
155 Sets the maximum bounds used when calculating the shadow map bounds of the
156 models in the instance table.
157
158 Default value: \c{(-1, -1, -1)}
159
160 \note This property is only enabled when the respective components of
161 shadowBoundsMinimum are smaller than those in shadowBoundsMaximum.
162 Otherwise the bounds are calculated automatically.
163
164 \sa shadowBoundsMinimum
165*/
166/*!
167 \qmlproperty vector3d Instancing::shadowBoundsMaximum
168
169 Sets the maximum bounds used when calculating the shadow map bounds of the models in the
170 instance table.
171
172 Default value: \c{(-1, -1, -1)}
173
174 \note This property is only enabled when the respective components of
175 Instancing::shadowBoundsMinimum are smaller than those in
176 Instancing::shadowBoundsMaximum. Otherwise the bounds are calculated automatically.
177 \sa shadowBoundsMinimum
178*/
179
180/*!
181 \class QQuick3DInstancing
182 \inmodule QtQuick3D
183 \inherits QQuick3DObject
184 \since 6.2
185 \brief Base class for defining instance tables.
186
187 The QQuick3DInstancing class can be inherited to specify a custom instance table
188 for a Model in the Qt Quick 3D scene.
189
190 This class is abstract: To use it, create a subclass and implement \l getInstanceBuffer().
191*/
192
193/*!
194 \fn QByteArray QQuick3DInstancing::getInstanceBuffer(int *instanceCount)
195
196 Implement this function to return the contents of the instance table. The number of instances should be
197 returned in \a instanceCount. The subclass is responsible for caching the result if necessary. If the
198 instance table changes, the subclass should call markDirty().
199 */
200
201QQuick3DInstancingPrivate::QQuick3DInstancingPrivate()
202 : QQuick3DObjectPrivate(QQuick3DObjectPrivate::Type::ModelInstance)
203{
204}
205
206QQuick3DInstancing::QQuick3DInstancing(QQuick3DObject *parent)
207 : QQuick3DObject(*new QQuick3DInstancingPrivate, parent)
208{
209}
210
211QQuick3DInstancing::~QQuick3DInstancing()
212{
213}
214
215/*!
216 \internal
217 Returns the content of the instancing table for testing purposes.
218*/
219QByteArray QQuick3DInstancing::instanceBuffer(int *instanceCount)
220{
221 Q_D(QQuick3DInstancing);
222 QByteArray retval = getInstanceBuffer(instanceCount);
223 if (instanceCount && d->m_instanceCountOverride >= 0)
224 *instanceCount = qMin(d->m_instanceCountOverride, *instanceCount);
225 return retval;
226}
227
228int QQuick3DInstancing::instanceCountOverride() const
229{
230 Q_D(const QQuick3DInstancing);
231 return d->m_instanceCountOverride;
232}
233
234bool QQuick3DInstancing::hasTransparency() const
235{
236 Q_D(const QQuick3DInstancing);
237 return d->m_hasTransparency;
238}
239
240bool QQuick3DInstancing::depthSortingEnabled() const
241{
242 Q_D(const QQuick3DInstancing);
243 return d->m_depthSortingEnabled;
244}
245
246QVector3D QQuick3DInstancing::shadowBoundsMinimum() const
247{
248 Q_D(const QQuick3DInstancing);
249 return d->m_shadowBoundsMinimum;
250}
251
252QVector3D QQuick3DInstancing::shadowBoundsMaximum() const
253{
254 Q_D(const QQuick3DInstancing);
255 return d->m_shadowBoundsMaximum;
256}
257
258const QQuick3DInstancing::InstanceTableEntry *QQuick3DInstancing::getInstanceEntry(int index)
259{
260 const QByteArray data = getInstanceBuffer(nullptr);
261 if (index >= int(data.size() / sizeof(InstanceTableEntry)))
262 return nullptr;
263 return reinterpret_cast<const QQuick3DInstancing::InstanceTableEntry*>(data.constData()) + index;
264}
265
266QVector3D QQuick3DInstancing::InstanceTableEntry::getPosition() const
267{
268 return QVector3D{ row0[3], row1[3], row2[3] };
269}
270
271QVector3D QQuick3DInstancing::InstanceTableEntry::getScale() const
272{
273 const QVector3D col0{row0[0], row1[0], row2[0]};
274 const QVector3D col1{row0[1], row1[1], row2[1]};
275 const QVector3D col2{row0[2], row1[2], row2[2]};
276 const float scaleX = col0.length();
277 const float scaleY = col1.length();
278 const float scaleZ = col2.length();
279 return QVector3D(scaleX, scaleY, scaleZ);
280}
281
282QQuaternion QQuick3DInstancing::InstanceTableEntry::getRotation() const
283{
284 const QVector3D col0 = QVector3D(row0[0], row1[0], row2[0]).normalized();
285 const QVector3D col1 = QVector3D(row0[1], row1[1], row2[1]).normalized();
286 const QVector3D col2 = QVector3D(row0[2], row1[2], row2[2]).normalized();
287
288 const float data3x3[3*3] { // row-major order
289 col0[0], col1[0], col2[0],
290 col0[1], col1[1], col2[1],
291 col0[2], col1[2], col2[2],
292 };
293 QMatrix3x3 rot(data3x3);
294 return QQuaternion::fromRotationMatrix(rot).normalized();
295}
296
297QColor QQuick3DInstancing::InstanceTableEntry::getColor() const
298{
299 return QColor::fromRgbF(color[0], color[1], color[2], color[3]);
300}
301
302/*!
303 \qmlmethod vector3d QtQuick3D::Instancing::instancePosition(int index)
304 \since 6.3
305
306 Returns the position of the instance at \a index
307
308 \sa instanceScale, instanceRotation, instanceColor, instanceCustomData
309*/
310
311QVector3D QQuick3DInstancing::instancePosition(int index)
312{
313 auto *entry = getInstanceEntry(index);
314 if (!entry)
315 return {};
316
317 return QVector3D{ entry->row0[3], entry->row1[3], entry->row2[3] };
318}
319
320/*!
321 \qmlmethod vector3d QtQuick3D::Instancing::instanceScale(int index)
322 \since 6.3
323
324 Returns the scale of the instance at \a index
325
326 \sa instancePosition, instanceScale, instanceRotation, instanceColor, instanceCustomData
327*/
328
329QVector3D QQuick3DInstancing::instanceScale(int index)
330{
331 auto *entry = getInstanceEntry(index);
332 if (!entry)
333 return {};
334 return entry->getScale();
335}
336
337/*!
338 \qmlmethod quaternion QtQuick3D::Instancing::instanceRotation(int index)
339 \since 6.3
340
341 Returns a quaternion representing the rotation of the instance at \a index
342
343 \sa instancePosition, instanceScale, instanceRotation, instanceColor, instanceCustomData
344*/
345
346QQuaternion QQuick3DInstancing::instanceRotation(int index)
347{
348 const auto *entry = getInstanceEntry(index);
349 if (!entry)
350 return {};
351 return entry->getRotation();
352}
353
354/*!
355 \qmlmethod color QtQuick3D::Instancing::instanceColor(int index)
356 \since 6.3
357
358 Returns the color of the instance at \a index
359
360 \sa instancePosition, instanceScale, instanceRotation, instanceColor, instanceCustomData
361*/
362
363QColor QQuick3DInstancing::instanceColor(int index)
364{
365 const auto *entry = getInstanceEntry(index);
366 if (!entry)
367 return {};
368 return entry->getColor();
369}
370
371/*!
372 \qmlmethod vector3d QtQuick3D::Instancing::instanceCustomData(int index)
373 \since 6.3
374
375 Returns the custom data for the instance at \a index
376
377 \sa instancePosition, instanceScale, instanceRotation, instanceColor, instanceCustomData
378*/
379
380QVector4D QQuick3DInstancing::instanceCustomData(int index)
381{
382 const auto *entry = getInstanceEntry(index);
383 if (!entry)
384 return {};
385 return entry->instanceData;
386}
387
388void QQuick3DInstancing::setInstanceCountOverride(int instanceCountOverride)
389{
390 Q_D(QQuick3DInstancing);
391 if (d->m_instanceCountOverride == instanceCountOverride)
392 return;
393
394 d->m_instanceCountOverride = instanceCountOverride;
395 d->m_instanceCountOverrideChanged = true;
396 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
397 emit instanceCountOverrideChanged();
398}
399
400void QQuick3DInstancing::setHasTransparency(bool hasTransparency)
401{
402 Q_D(QQuick3DInstancing);
403 if (d->m_hasTransparency == hasTransparency)
404 return;
405
406 d->m_hasTransparency = hasTransparency;
407 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
408 emit hasTransparencyChanged();
409}
410
411void QQuick3DInstancing::setDepthSortingEnabled(bool enabled)
412{
413 Q_D(QQuick3DInstancing);
414 if (d->m_depthSortingEnabled == enabled)
415 return;
416
417 d->m_depthSortingEnabled = enabled;
418 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
419 emit depthSortingEnabledChanged();
420}
421
422void QQuick3DInstancing::setShadowBoundsMinimum(const QVector3D &newShadowBoundsMinimum)
423{
424 Q_D(QQuick3DInstancing);
425 if (d->m_shadowBoundsMinimum == newShadowBoundsMinimum)
426 return;
427
428 d->m_shadowBoundsMinimum = newShadowBoundsMinimum;
429 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
430 emit shadowBoundsMinimumChanged();
431}
432
433void QQuick3DInstancing::setShadowBoundsMaximum(const QVector3D &newShadowBoundsMaximum)
434{
435 Q_D(QQuick3DInstancing);
436 if (d->m_shadowBoundsMinimum == newShadowBoundsMaximum)
437 return;
438
439 d->m_shadowBoundsMaximum = newShadowBoundsMaximum;
440 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
441 emit shadowBoundsMaximumChanged();
442}
443
444/*!
445 Mark that the instance data has changed and must be uploaded again.
446
447 \sa getInstanceBuffer, instanceCountOverride
448 */
449
450void QQuick3DInstancing::markDirty()
451{
452 Q_D(QQuick3DInstancing);
453 d->dirty(QQuick3DObjectPrivate::DirtyType::Content);
454 d->m_instanceDataChanged = true;
455 emit instanceTableChanged();
456}
457
458QSSGRenderGraphObject *QQuick3DInstancing::updateSpatialNode(QSSGRenderGraphObject *node)
459{
460 Q_D(QQuick3DInstancing);
461 if (!node) {
462 markAllDirty();
463 node = new QSSGRenderInstanceTable();
464 emit instanceNodeDirty();
465 d->m_instanceDataChanged = true;
466 }
467 QQuick3DObject::updateSpatialNode(node);
468 auto effectiveInstanceCount = [d]() {
469 if (d->m_instanceCountOverride >= 0)
470 return qMin(d->m_instanceCount, d->m_instanceCountOverride);
471 return d->m_instanceCount;
472 };
473 auto *instanceTable = static_cast<QSSGRenderInstanceTable *>(node);
474 if (d->m_instanceDataChanged) {
475 QByteArray buffer = getInstanceBuffer(&d->m_instanceCount);
476 instanceTable->setData(buffer, effectiveInstanceCount(), sizeof(InstanceTableEntry));
477 d->m_instanceDataChanged = false;
478 } else if (d->m_instanceCountOverrideChanged) {
479 instanceTable->setInstanceCountOverride(effectiveInstanceCount());
480 }
481 d->m_instanceCountOverrideChanged = false;
482 instanceTable->setHasTransparency(d->m_hasTransparency);
483 instanceTable->setDepthSorting(d->m_depthSortingEnabled);
484 instanceTable->setShadowBoundsMinimum(d->m_shadowBoundsMinimum);
485 instanceTable->setShadowBoundsMaximum(d->m_shadowBoundsMaximum);
486 return node;
487}
488
489static inline QQuick3DInstancing::InstanceTableEntry calculate(const QVector3D &position, const QVector3D &scale,
490 const QVector3D &eulerRotation, const QColor &color,
491 const QVector4D &customData)
492{
493 QMatrix4x4 xform;
494
495 xform(0, 0) = scale[0];
496 xform(1, 1) = scale[1];
497 xform(2, 2) = scale[2];
498
499 QQuaternion quaternion = QQuaternion::fromEulerAngles(eulerRotation);
500 xform = QMatrix4x4(quaternion.toRotationMatrix()) * xform;
501
502 xform(0, 3) += position[0];
503 xform(1, 3) += position[1];
504 xform(2, 3) += position[2];
505
506 auto linearColor = QSSGUtils::color::sRGBToLinear(color);
507
508 return {
509 xform.row(0),
510 xform.row(1),
511 xform.row(2),
512 linearColor,
513 customData
514 };
515}
516
517/*!
518 Converts the
519 \a position
520 \a scale
521 \a eulerRotation
522 \a color
523 and
524 \a customData
525 to the instance table format expected by the standard vertex shaders. Typical pattern:
526
527 \code
528 QByteArray MyInstanceTable::getInstanceBuffer(int *instanceCount)
529 {
530 QByteArray instanceData;
531
532 ...
533
534 auto entry = calculateTableEntry({xPos, yPos, zPos}, {xScale, yScale, zScale}, {xRot, yRot, zRot}, color, {});
535 instanceData.append(reinterpret_cast<const char *>(&entry), sizeof(entry));
536 \endcode
537
538 \sa calculateTableEntryFromQuaternion
539 */
540QQuick3DInstancing::InstanceTableEntry QQuick3DInstancing::calculateTableEntry(const QVector3D &position, const QVector3D &scale,
541 const QVector3D &eulerRotation, const QColor &color, const QVector4D &customData)
542{
543 return calculate(position, scale, eulerRotation, color, customData);
544}
545
546/*!
547 Converts the
548 \a position
549 \a scale
550 \a rotation
551 \a color
552 and
553 \a customData
554 to the instance table format expected by the standard vertex shaders.
555
556 This is the same as calculateTableEntry(), except for using a quaternion to specify the rotation.
557 */
558QQuick3DInstancing::InstanceTableEntry QQuick3DInstancing::calculateTableEntryFromQuaternion(const QVector3D &position, const QVector3D &scale, const QQuaternion &rotation, const QColor &color, const QVector4D &customData)
559{
560 QMatrix4x4 xform;
561
562 xform(0, 0) = scale[0];
563 xform(1, 1) = scale[1];
564 xform(2, 2) = scale[2];
565
566 xform = QMatrix4x4(rotation.toRotationMatrix()) * xform;
567
568 xform(0, 3) += position[0];
569 xform(1, 3) += position[1];
570 xform(2, 3) += position[2];
571
572 auto linearColor = QSSGUtils::color::sRGBToLinear(color);
573
574 return {
575 xform.row(0),
576 xform.row(1),
577 xform.row(2),
578 linearColor,
579 customData
580 };
581}
582
583/*!
584 \qmltype InstanceList
585 \inherits Instancing
586 \inqmlmodule QtQuick3D
587 \brief Allows manually specifying instancing in QML.
588
589 The InstanceList type makes it possible to define an instance table manually in QML.
590
591 The following example creates an instance table with two items:
592 \qml
593 InstanceList {
594 id: manualInstancing
595 instances: [
596 InstanceListEntry {
597 position: Qt.vector3d(0, 0, -60)
598 eulerRotation: Qt.vector3d(-10, 0, 30)
599 color: "red"
600 },
601 InstanceListEntry {
602 position: Qt.vector3d(50, 10, 100)
603 eulerRotation: Qt.vector3d(0, 180, 0)
604 color: "green"
605 }
606 ]
607 }
608 \endqml
609
610 It is also possible to populate the instances property by just adding children to the
611 InstanceList. The following example is equivalent to the previous one:
612 \qml
613 InstanceList {
614 id: manualInstancing
615 InstanceListEntry {
616 position: Qt.vector3d(0, 0, -60)
617 eulerRotation: Qt.vector3d(-10, 0, 30)
618 color: "red"
619 }
620 InstanceListEntry {
621 position: Qt.vector3d(50, 10, 100)
622 eulerRotation: Qt.vector3d(0, 180, 0)
623 color: "green"
624 }
625 }
626 \endqml
627
628 Each InstanceListEntry is an object that can have property bindings and animations. This gives
629 great flexibility, but also causes memory overhead. Therefore, it is not recommended to use
630 InstanceList for procedurally generated tables containing thousands (or millions) of
631 instances. Also, any property change to an entry will cause the entire instance table to be
632 recalculated and uploaded to the GPU.
633
634 \sa RandomInstancing, QQuick3DInstancing
635*/
636
637/*!
638 \qmlproperty List<QtQuick3D::InstanceListEntry> InstanceList::instances
639 \qmldefault
640
641 This property contains the list of instance definitions. Modifying this list, or any of its elements, will cause the instance table to be updated.
642*/
643
644QQuick3DInstanceList::QQuick3DInstanceList(QQuick3DObject *parent) : QQuick3DInstancing(parent) {}
645
646QQuick3DInstanceList::~QQuick3DInstanceList() {}
647
648QByteArray QQuick3DInstanceList::getInstanceBuffer(int *instanceCount)
649{
650 if (m_dirty)
651 generateInstanceData();
652 if (instanceCount)
653 *instanceCount = m_instances.size();
654 return m_instanceData;
655}
656
657QQmlListProperty<QQuick3DInstanceListEntry> QQuick3DInstanceList::instances()
658{
659
660 return QQmlListProperty<QQuick3DInstanceListEntry>(this,
661 nullptr,
662 qmlAppendInstanceListEntry,
663 qmlInstanceListEntriesCount,
664 qmlInstanceListEntryAt,
665 qmlClearInstanceListEntries);
666}
667
668/*!
669 \qmlproperty int QtQuick3D::InstanceList::instanceCount
670 \since 6.3
671
672 This read-only property contains the number of instances in the list.
673*/
674
675int QQuick3DInstanceList::instanceCount() const
676{
677 return m_instances.size();
678}
679
680void QQuick3DInstanceList::onInstanceDestroyed(QObject *object)
681{
682 if (m_instances.removeAll(object))
683 handleInstanceChange();
684}
685
686void QQuick3DInstanceList::qmlAppendInstanceListEntry(QQmlListProperty<QQuick3DInstanceListEntry> *list, QQuick3DInstanceListEntry *instance)
687{
688 if (instance == nullptr)
689 return;
690 auto *self = static_cast<QQuick3DInstanceList *>(list->object);
691 self->m_instances.push_back(instance);
692
693 if (instance->parentItem() == nullptr)
694 instance->setParentItem(self);
695 connect(instance, &QQuick3DInstanceListEntry::changed, self, &QQuick3DInstanceList::handleInstanceChange);
696 connect(instance, &QObject::destroyed, self, &QQuick3DInstanceList::onInstanceDestroyed);
697 self->handleInstanceChange();
698}
699
700QQuick3DInstanceListEntry *QQuick3DInstanceList::qmlInstanceListEntryAt(QQmlListProperty<QQuick3DInstanceListEntry> *list, qsizetype index)
701{
702 auto *self = static_cast<QQuick3DInstanceList *>(list->object);
703 return self->m_instances.at(index);
704}
705
706qsizetype QQuick3DInstanceList::qmlInstanceListEntriesCount(QQmlListProperty<QQuick3DInstanceListEntry> *list)
707{
708 auto *self = static_cast<QQuick3DInstanceList *>(list->object);
709 return self->m_instances.size();
710}
711
712void QQuick3DInstanceList::qmlClearInstanceListEntries(QQmlListProperty<QQuick3DInstanceListEntry> *list)
713{
714 auto *self = static_cast<QQuick3DInstanceList *>(list->object);
715 for (auto *instance : std::as_const(self->m_instances)) {
716 disconnect(instance, &QObject::destroyed, self, &QQuick3DInstanceList::onInstanceDestroyed);
717 disconnect(instance, &QQuick3DInstanceListEntry::changed, self, &QQuick3DInstanceList::handleInstanceChange);
718 }
719 self->m_instances.clear();
720 self->handleInstanceChange();
721}
722
723void QQuick3DInstanceList::handleInstanceChange()
724{
725 m_dirty = true;
726 markDirty();
727 emit instanceCountChanged();
728}
729
730void QQuick3DInstanceList::generateInstanceData()
731{
732 m_dirty = false;
733 const int count = m_instances.size();
734
735 qsizetype tableSize = count * sizeof(InstanceTableEntry);
736 m_instanceData.resize(tableSize);
737 auto *array = reinterpret_cast<InstanceTableEntry*>(m_instanceData.data());
738 for (int i = 0; i < count; ++i) {
739 const auto *inst = m_instances.at(i);
740 if (inst->m_useEulerRotation)
741 array[i] = calculateTableEntry(inst->position(), inst->scale(), inst->eulerRotation(), inst->color(), inst->customData());
742 else
743 array[i] = calculateTableEntryFromQuaternion(inst->position(), inst->scale(), inst->rotation(), inst->color(), inst->customData());
744 }
745}
746
747/*!
748 \qmltype InstanceListEntry
749 \inherits Object3D
750 \inqmlmodule QtQuick3D
751 \since 6.2
752 \brief Specifies an instance in an InstanceList.
753
754 The InstanceListEntry QML type is used to specify one instance in an instance list.
755
756 All the properties can have bindings and animation. Changing a property will cause the entire
757 instance table to be recalculated and uploaded to the GPU, so this can be expensive for instance
758 lists with many members.
759*/
760
761QQuick3DInstanceListEntry::QQuick3DInstanceListEntry(QQuick3DObject *parent)
762 : QQuick3DObject(parent)
763{
764}
765
766/*!
767 \qmlproperty vector3d QtQuick3D::InstanceListEntry::position
768
769 This property specifies the position for the instance.
770*/
771void QQuick3DInstanceListEntry::setPosition(QVector3D position)
772{
773 if (m_position == position)
774 return;
775
776 m_position = position;
777 emit positionChanged();
778 emit changed();
779}
780
781/*!
782 \qmlproperty vector3d QtQuick3D::InstanceListEntry::scale
783
784 This property specifies the scale for the instance as a vector containing the scale factor along the x, y and z axes.
785*/
786void QQuick3DInstanceListEntry::setScale(QVector3D scale)
787{
788 if (m_scale == scale)
789 return;
790
791 m_scale = scale;
792 emit scaleChanged();
793 emit changed();
794}
795
796/*!
797 \qmlproperty vector3d QtQuick3D::InstanceListEntry::eulerRotation
798
799 This property specifies the rotation for the instance as an Euler vector, that
800 is a vector containing the rotation in degrees around the x, y and z axes.
801*/
802void QQuick3DInstanceListEntry::setEulerRotation(QVector3D eulerRotation)
803{
804 if (m_useEulerRotation && m_eulerRotation == eulerRotation)
805 return;
806 m_eulerRotation = eulerRotation;
807 m_useEulerRotation = true;
808 emit eulerRotationChanged();
809 emit changed();
810}
811
812/*!
813 \qmlproperty quaternion QtQuick3D::InstanceListEntry::rotation
814
815 This property specifies the rotation for the instance as a quaternion.
816*/
817void QQuick3DInstanceListEntry::setRotation(QQuaternion rotation)
818{
819 if (!m_useEulerRotation && m_rotation == rotation)
820 return;
821
822 m_rotation = rotation;
823 m_useEulerRotation = false;
824 emit rotationChanged();
825 emit changed();
826}
827
828/*!
829 \qmlproperty color QtQuick3D::InstanceListEntry::color
830
831 This property specifies the color for the instance.
832*/
833void QQuick3DInstanceListEntry::setColor(QColor color)
834{
835 if (m_color == color)
836 return;
837
838 m_color = color;
839 emit colorChanged();
840 emit changed();
841}
842
843/*!
844 \qmlproperty vector4d QtQuick3D::InstanceListEntry::customData
845
846 This property specifies the custom data for the instance. This is not used by default,
847 but is made available to the vertex shader of custom materials as \c INSTANCE_DATA.
848*/
849void QQuick3DInstanceListEntry::setCustomData(QVector4D customData)
850{
851 if (m_customData == customData)
852 return;
853
854 m_customData = customData;
855 emit customDataChanged();
856 emit changed();
857}
858
859/*!
860 \qmltype FileInstancing
861 \inherits Instancing
862 \inqmlmodule QtQuick3D
863 \since 6.2
864 \brief Allows reading instance tables from file.
865
866 The FileInstancing type makes it possible to read instance tables from files.
867
868 There are two supported file formats: XML, and a Qt-specific binary format. The
869 binary file format uses the same layout as the table that is uploaded to the GPU,
870 so it can be directly mapped to memory. The \l{Instancer Tool}{instancer} tool converts
871 from XML to the binary format.
872
873 This is an example of the XML file format:
874 \badcode
875 <?xml version="1.0" encoding="UTF-8" ?>
876 <InstanceTable>
877 <Instance position="0 200 0" scale="0.75 0.75 0.75" custom="20 20" color="#ffcf7f"/>
878 <Instance position="0 -100 0" scale="0.5 0.5 0.5" color="red"/>
879 <Instance position="0 -200 0" eulerRotation="0 0 60" color="darkred" custom="10 40 0 0"/>
880 </InstanceTable>
881 \endcode
882
883 In order to be valid, the XML file must have a top-level \c{InstanceTable} element. Each
884 instance is represented by an \c{Instance} element inside the \c{InstanceTable}. Unknown
885 elements are silently ignored.
886
887 An \c{Instance} element can have a number of attributes. \c{color} attributes are specified by the normal Qt
888 SVG color names, or by hexadecimal notation. \c{vector3d} and {vector4d} attributes are specified by
889 a string of space-separated numbers, where missing trailing numbers indicate zeroes. The following
890 attributes are supported:
891 \table
892 \header
893 \li name
894 \li type
895 \row
896 \li \c position
897 \li \c vector3d
898 \row
899 \li \c scale
900 \li \c vector3d
901 \row
902 \li \c eulerRotation
903 \li \c vector3d
904 \row
905 \li \c quaternion
906 \li \c vector4d
907 \row
908 \li \c custom
909 \li \c vector4d
910 \row
911 \li \c color
912 \li \c color
913 \endtable
914 Unknown attributes are silently ignored.
915*/
916
917/*!
918 \qmlproperty url QtQuick3D::FileInstancing::source
919
920 This property holds the location of an XML or binary file containing the instance data.
921
922 If the file name has a ".bin" extension, it is assumed to refer to a binary file.
923 Otherwise it is assumed to refer to an XML file. If an XML file \e{foo.xml} is specified, and
924 the file \e{foo.xml.bin} exists, the binary file \e{foo.xml.bin} will be loaded instead.
925*/
926
927/*!
928 \qmlproperty int QtQuick3D::FileInstancing::instanceCount
929 \since 6.3
930
931 This read-only property contains the number of instances in the instance table.
932*/
933
934static constexpr quint16 currentMajorVersion = 1;
935
945
946/*!
947 \internal
948 Writes \a instanceData, an array of \a instanceCount InstanceTableEntry
949 elements, to \a out in the binary instance table format that
950 FileInstancing reads.
951*/
952bool QQuick3DFileInstancing::writeInstanceTable(QIODevice *out, const QByteArray &instanceData, int instanceCount)
953{
954 QQuick3DInstancingBinaryFileHeader header;
955
956 header.offset = sizeof(header);
957 header.count = instanceCount;
958
959 if (instanceData.size() != qsizetype(header.stride) * instanceCount) {
960 qWarning() << "inconsistent data";
961 return false;
962 }
963
964 // Ignoring endianness: Assume we always create on little-endian, and then special-case reading if we need to.
965
966 out->write(reinterpret_cast<const char *>(&header), sizeof(header));
967 out->write(instanceData.constData(), instanceData.size());
968 return true;
969}
970
971
972bool QQuick3DFileInstancing::loadFromBinaryFile(const QString &filename)
973{
974 auto binaryFile = std::make_unique<QFile>(filename);
975 if (!binaryFile->open(QFile::ReadOnly))
976 return false;
977
978 constexpr auto headerSize = sizeof(QQuick3DInstancingBinaryFileHeader);
979 const quint64 fileSize = binaryFile->size();
980 if (fileSize < headerSize) {
981 qWarning() << "data file too small";
982 return false;
983 }
984 const char *data = reinterpret_cast<const char *>(binaryFile->map(0, fileSize));
985 const auto *header = reinterpret_cast<const QQuick3DInstancingBinaryFileHeader *>(data);
986
987 if (header->majorVersion > currentMajorVersion) {
988 qWarning() << "Version" << header->majorVersion << "is too new";
989 return false;
990 }
991
992 if (fileSize != headerSize + header->count * header->stride) {
993 qWarning() << "wrong data size";
994 return false;
995 }
996
997 delete m_dataFile;
998
999 // In order to use fromRawData safely, the file has to stay open so that the mmap stays valid
1000 m_dataFile = binaryFile.release();
1001
1002 m_instanceData = QByteArray::fromRawData(data + header->offset, header->count * header->stride);
1003 m_instanceCount = header->count;
1004
1005 return true;
1006}
1007
1008bool QQuick3DFileInstancing::loadFromXmlFile(const QString &filename)
1009{
1010 QFile f(filename);
1011 if (!f.open(QFile::ReadOnly))
1012 return false;
1013
1014 bool valid = false;
1015 QXmlStreamReader reader(&f);
1016 int instances = 0;
1017
1018 //### Why is there not a QTextStream constructor that takes a QStringView
1019 const auto toVector3D = [](const QStringView &str) {
1020 float x, y, z;
1021 QTextStream(str.toLocal8Bit()) >> x >> y >> z;
1022 return QVector3D { x, y, z };
1023 };
1024 const auto toVector4D = [](const QStringView &str) {
1025 float x, y, z, w;
1026 QTextStream(str.toLocal8Bit()) >> x >> y >> z >> w;
1027 return QVector4D { x, y, z, w };
1028 };
1029
1030 QByteArray instanceData;
1031
1032 while (reader.readNextStartElement()) {
1033
1034 if (reader.name() == QLatin1String("InstanceTable")) {
1035 valid = true;
1036 while (reader.readNextStartElement()) {
1037 if (reader.name() == QLatin1String("Instance")) {
1038 QColor color = Qt::white;
1039 QVector3D position;
1040 QVector3D eulerRotation;
1041 QQuaternion quaternion;
1042 bool useQuaternion = false;
1043 QVector4D custom;
1044 QVector3D scale { 1, 1, 1 };
1045 for (auto &attr : reader.attributes()) {
1046 if (attr.name() == QLatin1String("color")) {
1047 color = QColor::fromString(attr.value());
1048 } else if (attr.name() == QLatin1String("position")) {
1049 position = toVector3D(attr.value());
1050 } else if (attr.name() == QLatin1String("eulerRotation")) {
1051 eulerRotation = toVector3D(attr.value());
1052 } else if (attr.name() == QLatin1String("scale")) {
1053 scale = toVector3D(attr.value());
1054 } else if (attr.name() == QLatin1String("quaternion")) {
1055 quaternion = QQuaternion(toVector4D(attr.value()));
1056 useQuaternion = true;
1057 } else if (attr.name() == QLatin1String("custom")) {
1058 custom = toVector4D(attr.value());
1059 }
1060 }
1061 auto entry = useQuaternion ? calculateTableEntryFromQuaternion(position, scale, quaternion, color, custom)
1062 : calculateTableEntry(position, scale, eulerRotation, color, custom);
1063 instanceData.append(reinterpret_cast<const char *>(&entry), sizeof(entry));
1064 instances++;
1065 }
1066 reader.skipCurrentElement();
1067 }
1068 } else {
1069 reader.skipCurrentElement();
1070 }
1071 }
1072
1073 if (valid) {
1074 m_instanceCount = instances;
1075 m_instanceData = instanceData;
1076 }
1077
1078 f.close();
1079 return valid;
1080}
1081
1082int QQuick3DFileInstancing::writeToBinaryFile(QIODevice *out)
1083{
1084 bool success = writeInstanceTable(out, m_instanceData, m_instanceCount);
1085 return success ? m_instanceCount : -1;
1086}
1087
1088int QQuick3DFileInstancing::instanceCount() const
1089{
1090 return m_instanceCount;
1091}
1092
1093/*!
1094 \qmltype ShaderInstancing
1095 \inherits Instancing
1096 \inqmlmodule QtQuick3D
1097 \since 6.13
1098 \brief GPU-generated instancing without an instance table.
1099
1100 Renders a number of instances of a model without any per-instance data.
1101
1102 This is for the case where the per-instance data can be produced by the
1103 vertex shader, e.g. by reading a storage buffer written by a compute shader.
1104 This type only specifies the number of instances to render, using the
1105 \l instanceCount property:
1106
1107 \badcode
1108 Model {
1109 source: "#Rectangle"
1110 instancing: ShaderInstancing { instanceCount: 100000 }
1111 materials: CustomMaterial {
1112 vertexShader: "myplacement.vert"
1113 }
1114 }
1115 \endcode
1116
1117 where \c myplacement.vert sets the transform for each instance itself:
1118
1119 \badcode
1120 void MAIN()
1121 {
1122 INSTANCE_TRANSFORM[3].xyz = myPositions[INSTANCE_INDEX];
1123 }
1124 \endcode
1125
1126 \c INSTANCE_TRANSFORM is a \c mat4, starting out as the identity. It plays
1127 the part of an instance table's per-instance transform: it is applied
1128 after \c MAIN, together with the model's own transform, which is split
1129 around it in the same way as with an instance table (see
1130 \l{Model::instanceRoot}{instanceRoot}). It is applied after morphing and
1131 skinning too, so animated models work as with an instance table.
1132 \c VERTEX is in the model's own coordinates, as without instancing.
1133
1134 \c INSTANCE_TRANSFORM only has an effect in the vertex shader of a shaded
1135 material. An unshaded material writes \c POSITION itself. There,
1136 \c MODEL_MATRIX is the part of the model transform that goes before the
1137 instance transform, and \c MODELVIEWPROJECTION_MATRIX includes the part
1138 that goes after it:
1139
1140 \badcode
1141 POSITION = MODELVIEWPROJECTION_MATRIX * myInstanceTransform * MODEL_MATRIX * vec4(VERTEX, 1.0);
1142 \endcode
1143
1144 ShaderInstancing can also be used on a model whose geometry is an
1145 \l IndirectShaderGeometry. The instance count then comes from the draw
1146 command in the IndirectShaderGeometry's buffer, and \l instanceCount is
1147 ignored:
1148
1149 \badcode
1150 Model {
1151 geometry: IndirectShaderGeometry { buffer: drawArgs }
1152 instancing: ShaderInstancing { }
1153 materials: CustomMaterial {
1154 vertexShader: "myplacement.vert"
1155 }
1156 }
1157 \endcode
1158
1159 Without ShaderInstancing, an IndirectShaderGeometry still draws the number
1160 of instances given by its draw command, and \c INSTANCE_INDEX is
1161 available, but there is no \c INSTANCE_TRANSFORM.
1162
1163 \note \c INSTANCE_INDEX is the only instancing keyword available here.
1164 \c INSTANCE_COLOR, \c INSTANCE_DATA, \c INSTANCE_MODEL_MATRIX,
1165 \c INSTANCE_MODELVIEWPROJECTION_MATRIX and \c INSTANCE_NORMAL_MATRIX only
1166 exist when there is an instance table, so a shader using them will fail
1167 to compile.
1168
1169 \note Instances are not frustum culled, since the renderer cannot know
1170 where the vertex shader puts them. The model is always drawn, unless
1171 \l{Instancing::shadowBoundsMinimum}{shadowBoundsMinimum} and
1172 \l{Instancing::shadowBoundsMaximum}{shadowBoundsMaximum} are set, in
1173 which case those bounds are used for culling. For the same reason an
1174 auto-fitted shadow camera only sees the model's own bounds, so the shadow
1175 bounds have to be set by hand.
1176
1177 \note \l{Instancing::depthSortingEnabled}{depthSortingEnabled} and instance
1178 level of detail both read per-instance data on the CPU, so they have
1179 nothing to work from and do nothing. For the same reason, the model cannot
1180 be \l{Model::pickable}{picked}. An application needing any of these must
1181 implement it in its own shader.
1182 \l{Instancing::hasTransparency}{hasTransparency} is ignored: as without
1183 instancing, the CustomMaterial's
1184 \l{CustomMaterial::sourceBlend}{sourceBlend} and
1185 \l{CustomMaterial::destinationBlend}{destinationBlend} determine whether
1186 the model is transparent.
1187
1188 \note Motion vectors do not take \c INSTANCE_TRANSFORM into account, so
1189 effects relying on them, such as temporal anti-aliasing, will not work
1190 properly. Consider setting \l{Model::motionVectorEnabled}{motionVectorEnabled}
1191 to \c false on the model.
1192
1193 \sa Instancing, InstanceList, IndirectShaderGeometry, CustomMaterial
1194*/
1195
1196/*!
1197 \qmlproperty int ShaderInstancing::instanceCount
1198
1199 The number of instances to draw.
1200
1201 This property is ignored when the model's geometry is an
1202 \l IndirectShaderGeometry, whose buffer provides the instance count.
1203*/
1204
1205QQuick3DShaderInstancing::QQuick3DShaderInstancing(QQuick3DObject *parent)
1206 : QQuick3DInstancing(parent)
1207{
1208}
1209
1210QQuick3DShaderInstancing::~QQuick3DShaderInstancing() { }
1211
1212int QQuick3DShaderInstancing::instanceCount() const
1213{
1214 return m_instanceCount;
1215}
1216
1217void QQuick3DShaderInstancing::setInstanceCount(int instanceCount)
1218{
1219 if (m_instanceCount == instanceCount)
1220 return;
1221 if (instanceCount < 0) {
1222 qWarning("ShaderInstancing.instanceCount cannot be negative");
1223 return;
1224 }
1225 m_instanceCount = instanceCount;
1226 markDirty();
1227 emit instanceCountChanged();
1228}
1229
1230QByteArray QQuick3DShaderInstancing::getInstanceBuffer(int *instanceCount)
1231{
1232 if (instanceCount)
1233 *instanceCount = m_instanceCount;
1234 return QByteArray();
1235}
1236
1237QSSGRenderGraphObject *QQuick3DShaderInstancing::updateSpatialNode(QSSGRenderGraphObject *node)
1238{
1239 node = QQuick3DInstancing::updateSpatialNode(node);
1240 static_cast<QSSGRenderInstanceTable *>(node)->setBufferless(true);
1241 return node;
1242}
1243
1244bool QQuick3DFileInstancing::loadFromFile(const QUrl &source)
1245{
1246 const QQmlContext *context = qmlContext(this);
1247
1248 const QString filePath = QQmlFile::urlToLocalFileOrQrc(context ? context->resolvedUrl(source) : source);
1249
1250 if (filePath.endsWith(QStringLiteral(".bin")))
1251 return loadFromBinaryFile(filePath);
1252
1253 const QString binaryFilePath = filePath + QStringLiteral(".bin");
1254
1255 int oldCount = m_instanceCount;
1256 bool success = loadFromBinaryFile(binaryFilePath) || loadFromXmlFile(filePath);
1257 if (m_instanceCount != oldCount)
1258 emit instanceCountChanged();
1259
1260 return success;
1261}
1262
1263QQuick3DFileInstancing::QQuick3DFileInstancing(QQuick3DObject *parent) : QQuick3DInstancing(parent) { }
1264
1265QQuick3DFileInstancing::~QQuick3DFileInstancing()
1266{
1267 delete m_dataFile;
1268}
1269
1270const QUrl &QQuick3DFileInstancing::source() const
1271{
1272 return m_source;
1273}
1274
1275void QQuick3DFileInstancing::setSource(const QUrl &newSource)
1276{
1277 if (m_source == newSource)
1278 return;
1279 m_source = newSource;
1280 m_dirty = true;
1281 markDirty();
1282
1283 emit sourceChanged();
1284}
1285
1286QByteArray QQuick3DFileInstancing::getInstanceBuffer(int *instanceCount)
1287{
1288 if (m_dirty) {
1289 if (!loadFromFile(m_source)) {
1290 qWarning() << Q_FUNC_INFO << "could not load" << m_source;
1291 m_instanceData = {};
1292 m_instanceCount = 0;
1293 }
1294 m_dirty = false;
1295 }
1296
1297 if (instanceCount)
1298 *instanceCount = m_instanceCount;
1299 return m_instanceData;
1300}
1301
1302static_assert(sizeof(QQuick3DInstancing::InstanceTableEntry) == sizeof(QSSGRenderInstanceTableEntry)
1303 && alignof(QQuick3DInstancing::InstanceTableEntry) == alignof(QSSGRenderInstanceTableEntry),
1304 "QSSGRenderInstanceTableEntry and QQuick3DInstancing::InstanceTableEntry do not match");
1305
1306QT_END_NAMESPACE
static constexpr quint16 currentMajorVersion
\qmltype FileInstancing \inherits Instancing \inqmlmodule QtQuick3D
static QQuick3DInstancing::InstanceTableEntry calculate(const QVector3D &position, const QVector3D &scale, const QVector3D &eulerRotation, const QColor &color, const QVector4D &customData)