| 1 | // Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only |
| 3 | |
| 4 | #include <Qt3DQuickExtras/qt3dquickwindow.h> |
| 5 | #include <Qt3DRender/QSceneLoader> |
| 6 | #include <Qt3DCore/QEntity> |
| 7 | |
| 8 | #include <QGuiApplication> |
| 9 | #include <qqml.h> |
| 10 | |
| 11 | class SceneHelper : public QObject |
| 12 | { |
| 13 | Q_OBJECT |
| 14 | |
| 15 | public: |
| 16 | Q_INVOKABLE QObject *findEntity(Qt3DRender::QSceneLoader *loader, const QString &name); |
| 17 | Q_INVOKABLE QObject *findComponent(Qt3DCore::QEntity *entity, const QString &componentMetatype); |
| 18 | Q_INVOKABLE void addListEntry(const QVariant &list, QObject *entry); |
| 19 | }; |
| 20 | |
| 21 | QObject *SceneHelper::findEntity(Qt3DRender::QSceneLoader *loader, const QString &name) |
| 22 | { |
| 23 | // The QSceneLoader instance is a component of an entity. The loaded scene |
| 24 | // tree is added under this entity. |
| 25 | QList<Qt3DCore::QEntity *> entities = loader->entities(); |
| 26 | |
| 27 | if (entities.isEmpty()) |
| 28 | return 0; |
| 29 | |
| 30 | // Technically there could be multiple entities referencing the scene loader |
| 31 | // but sharing is discouraged, and in our case there will be one anyhow. |
| 32 | Qt3DCore::QEntity *root = entities[0]; |
| 33 | |
| 34 | // The scene structure and names always depend on the asset. |
| 35 | return root->findChild<Qt3DCore::QEntity *>(name); |
| 36 | } |
| 37 | |
| 38 | QObject *SceneHelper::findComponent(Qt3DCore::QEntity *entity, const QString &componentMetatype) |
| 39 | { |
| 40 | Q_ASSERT(entity); |
| 41 | const Qt3DCore::QComponentVector components = entity->components(); |
| 42 | for (Qt3DCore::QComponent *component : components) { |
| 43 | qDebug() << component->metaObject()->className(); |
| 44 | if (component->metaObject()->className() == componentMetatype) { |
| 45 | return component; |
| 46 | } |
| 47 | } |
| 48 | return nullptr; |
| 49 | } |
| 50 | |
| 51 | void SceneHelper::addListEntry(const QVariant &list, QObject *entry) |
| 52 | { |
| 53 | QQmlListReference ref = list.value<QQmlListReference>(); |
| 54 | ref.append(entry); |
| 55 | } |
| 56 | |
| 57 | int main(int argc, char* argv[]) |
| 58 | { |
| 59 | QGuiApplication app(argc, argv); |
| 60 | |
| 61 | Qt3DExtras::Quick::Qt3DQuickWindow view; |
| 62 | |
| 63 | qmlRegisterType<SceneHelper>("Qt3D.Examples", 2, 0, "SceneHelper"); |
| 64 | view.setSource(QUrl("qrc:/main.qml")); |
| 65 | view.show(); |
| 66 | |
| 67 | return app.exec(); |
| 68 | } |
| 69 | |
| 70 | #include "main.moc" |