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
qssgqmlutilities.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
8
9#include <QVector2D>
10#include <QVector3D>
11#include <QVector4D>
12#include <QQuaternion>
13#include <QDebug>
14#include <QRegularExpression>
15#include <QtCore/qdir.h>
16#include <QtCore/qfile.h>
17#include <QtCore/qbuffer.h>
18
19#include <QtGui/qimage.h>
20#include <QtGui/qimagereader.h>
21
22#include <QtQuick3DUtils/private/qssgmesh_p.h>
23#include <QtQuick3DUtils/private/qssgassert_p.h>
24
25#include <QtQuick3DRuntimeRender/private/qssgrenderbuffermanager_p.h>
26
27#ifdef QT_QUICK3D_ENABLE_RT_ANIMATIONS
28#include <QtCore/QCborStreamWriter>
29#include <QtQuickTimeline/private/qquicktimeline_p.h>
30#endif // QT_QUICK3D_ENABLE_RT_ANIMATIONS
31
33
34using namespace Qt::StringLiterals;
35
37
39{
40public:
42
44
45 PropertiesMap propertiesForType(QSSGSceneDesc::Node::RuntimeType type);
46 QVariant getDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property);
47 bool isDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property, const QVariant &value);
48
49private:
50 PropertyMap();
51
52 QHash<QSSGSceneDesc::Node::RuntimeType, PropertiesMap> m_properties;
53
54};
55
56QString qmlComponentName(const QString &name) {
57 QString nameCopy = name;
58 if (nameCopy.isEmpty())
59 return QStringLiteral("Presentation");
60
61 nameCopy = sanitizeQmlId(nameCopy);
62
63 if (nameCopy[0].isLower())
64 nameCopy[0] = nameCopy[0].toUpper();
65
66 return nameCopy;
67}
68
69QString colorToQml(const QColor &color) {
70 QString colorString;
71 colorString = QLatin1Char('\"') + color.name(QColor::HexArgb) + QLatin1Char('\"');
72 return colorString;
73}
74
75QString variantToQml(const QVariant &variant) {
76 switch (variant.typeId()) {
77 case QMetaType::Float: {
78 auto value = variant.toDouble();
79 return QString::number(value);
80 }
81 case QMetaType::QVector2D: {
82 auto value = variant.value<QVector2D>();
83 return QString(QStringLiteral("Qt.vector2d(") + QString::number(double(value.x())) +
84 QStringLiteral(", ") + QString::number(double(value.y())) +
85 QStringLiteral(")"));
86 }
87 case QMetaType::QVector3D: {
88 auto value = variant.value<QVector3D>();
89 return QString(QStringLiteral("Qt.vector3d(") + QString::number(double(value.x())) +
90 QStringLiteral(", ") + QString::number(double(value.y())) +
91 QStringLiteral(", ") + QString::number(double(value.z())) +
92 QStringLiteral(")"));
93 }
94 case QMetaType::QVector4D: {
95 auto value = variant.value<QVector4D>();
96 return QString(QStringLiteral("Qt.vector4d(") + QString::number(double(value.x())) +
97 QStringLiteral(", ") + QString::number(double(value.y())) +
98 QStringLiteral(", ") + QString::number(double(value.z())) +
99 QStringLiteral(", ") + QString::number(double(value.w())) +
100 QStringLiteral(")"));
101 }
102 case QMetaType::QColor: {
103 auto value = variant.value<QColor>();
104 return colorToQml(value);
105 }
106 case QMetaType::QQuaternion: {
107 auto value = variant.value<QQuaternion>();
108 return QString(QStringLiteral("Qt.quaternion(") + QString::number(double(value.scalar())) +
109 QStringLiteral(", ") + QString::number(double(value.x())) +
110 QStringLiteral(", ") + QString::number(double(value.y())) +
111 QStringLiteral(", ") + QString::number(double(value.z())) +
112 QStringLiteral(")"));
113 }
114 default:
115 return variant.toString();
116 }
117}
118
119QString sanitizeQmlId(const QString &id)
120{
121 QString idCopy = id;
122 // If the id starts with a number...
123 if (!idCopy.isEmpty() && idCopy.at(0).isNumber())
124 idCopy.prepend(QStringLiteral("node"));
125
126 // sometimes first letter is a # (don't replace with underscore)
127 if (idCopy.startsWith(QChar::fromLatin1('#')))
128 idCopy.remove(0, 1);
129
130 // Replace all the characters other than ascii letters, numbers or underscore to underscores.
131 static QRegularExpression regExp(QStringLiteral("\\W"));
132 idCopy.replace(regExp, QStringLiteral("_"));
133
134 // first letter of id can not be upper case
135 // to make it look nicer, lower-case the initial run of all-upper-case characters
136 if (!idCopy.isEmpty() && idCopy[0].isUpper()) {
137
138 int i = 0;
139 int len = idCopy.length();
140 while (i < len && idCopy[i].isUpper()) {
141 idCopy[i] = idCopy[i].toLower();
142 ++i;
143 }
144 }
145
146 // ### qml keywords as names
147 static QSet<QByteArray> keywords {
148 "x",
149 "y",
150 "as",
151 "do",
152 "if",
153 "in",
154 "on",
155 "of",
156 "for",
157 "get",
158 "int",
159 "let",
160 "new",
161 "set",
162 "try",
163 "var",
164 "top",
165 "byte",
166 "case",
167 "char",
168 "else",
169 "num",
170 "from",
171 "goto",
172 "null",
173 "this",
174 "true",
175 "void",
176 "with",
177 "clip",
178 "item",
179 "flow",
180 "font",
181 "text",
182 "left",
183 "data",
184 "alias",
185 "break",
186 "state",
187 "scale",
188 "color",
189 "right",
190 "catch",
191 "class",
192 "const",
193 "false",
194 "float",
195 "layer", // Design Studio doesn't like "layer" as an id
196 "short",
197 "super",
198 "throw",
199 "while",
200 "yield",
201 "border",
202 "source",
203 "delete",
204 "double",
205 "export",
206 "import",
207 "native",
208 "public",
209 "pragma",
210 "return",
211 "signal",
212 "static",
213 "switch",
214 "throws",
215 "bottom",
216 "parent",
217 "typeof",
218 "boolean",
219 "opacity",
220 "enabled",
221 "anchors",
222 "padding",
223 "default",
224 "extends",
225 "finally",
226 "package",
227 "private",
228 "abstract",
229 "continue",
230 "debugger",
231 "function",
232 "property",
233 "readonly",
234 "children",
235 "volatile",
236 "interface",
237 "protected",
238 "transient",
239 "implements",
240 "instanceof",
241 "synchronized"
242 };
243 if (keywords.contains(idCopy.toUtf8())) {
244 idCopy += QStringLiteral("_");
245 }
246
247 // We may have removed all the characters by now
248 if (idCopy.isEmpty())
249 idCopy = QStringLiteral("node");
250
251 return idCopy;
252}
253
254QString sanitizeQmlSourcePath(const QString &source, bool removeParentDirectory)
255{
256 QString sourceCopy = source;
257
258 if (removeParentDirectory)
259 sourceCopy = QSSGQmlUtilities::stripParentDirectory(sourceCopy);
260
261 sourceCopy.replace(QChar::fromLatin1('\\'), QChar::fromLatin1('/'));
262
263 // must be surrounded in quotes
264 return QString(QStringLiteral("\"") + sourceCopy + QStringLiteral("\""));
265}
266
268{
269 static PropertyMap p;
270 return &p;
271}
272
277
278QVariant PropertyMap::getDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property)
279{
281
285 }
286
287 return value;
288}
289
290bool PropertyMap::isDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property, const QVariant &value)
291{
293 return isTheSame;
294}
295
297 PropertyMap::PropertiesMap propertiesMap;
298 auto metaObject = object->metaObject();
299 for (auto i = 0; i < metaObject->propertyCount(); ++i) {
300 auto property = metaObject->property(i);
301 const auto name = property.name();
302 const auto value = property.read(object);
303 propertiesMap.insert(name, value);
304 }
305 return propertiesMap;
306}
307
308PropertyMap::PropertyMap()
309{
310 // Create a table containing the default values for each property for each supported type
311 {
312 QQuick3DNode node;
313 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Node, getObjectPropertiesMap(&node));
314 }
315 {
316 QQuick3DPrincipledMaterial principledMaterial;
317 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::PrincipledMaterial, getObjectPropertiesMap(&principledMaterial));
318 }
319 {
320 QQuick3DSpecularGlossyMaterial specularGlossyMaterial;
321 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::SpecularGlossyMaterial, getObjectPropertiesMap(&specularGlossyMaterial));
322 }
323 {
324 QQuick3DCustomMaterial customMaterial;
325 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::CustomMaterial, getObjectPropertiesMap(&customMaterial));
326 }
327 {
328 QQuick3DTexture texture;
329 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Image2D, getObjectPropertiesMap(&texture));
330 }
331 {
332 QQuick3DCubeMapTexture cubeMapTexture;
333 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::ImageCube, getObjectPropertiesMap(&cubeMapTexture));
334 }
335 {
336 QQuick3DTextureData textureData;
337 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::TextureData, getObjectPropertiesMap(&textureData));
338 }
339 {
340 QQuick3DModel model;
341 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Model, getObjectPropertiesMap(&model));
342 }
343 {
344 QQuick3DOrthographicCamera orthographicCamera;
345 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::OrthographicCamera, getObjectPropertiesMap(&orthographicCamera));
346 }
347 {
348 QQuick3DPerspectiveCamera perspectiveCamera;
349 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::PerspectiveCamera, getObjectPropertiesMap(&perspectiveCamera));
350 }
351 {
352 QQuick3DDirectionalLight directionalLight;
353 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::DirectionalLight, getObjectPropertiesMap(&directionalLight));
354 }
355 {
356 QQuick3DPointLight pointLight;
357 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::PointLight, getObjectPropertiesMap(&pointLight));
358 }
359 {
360 QQuick3DSpotLight spotLight;
361 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::SpotLight, getObjectPropertiesMap(&spotLight));
362 }
363 {
364 QQuick3DSkeleton skeleton;
365 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Skeleton, getObjectPropertiesMap(&skeleton));
366 }
367 {
368 QQuick3DJoint joint;
369 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Joint, getObjectPropertiesMap(&joint));
370 }
371 {
372 QQuick3DSkin skin;
373 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::Skin, getObjectPropertiesMap(&skin));
374 }
375 {
376 QQuick3DMorphTarget morphTarget;
377 m_properties.insert(QSSGSceneDesc::Node::RuntimeType::MorphTarget, getObjectPropertiesMap(&morphTarget));
378 }
379}
380
398
399template<QSSGSceneDesc::Material::RuntimeType T>
400const char *qmlElementName() { static_assert(!std::is_same_v<decltype(T), decltype(T)>, "Unknown type"); return nullptr; }
401template<> const char *qmlElementName<QSSGSceneDesc::Node::RuntimeType::Node>() { return "Node"; }
402
403template<> const char *qmlElementName<QSSGSceneDesc::Material::RuntimeType::SpecularGlossyMaterial>() { return "SpecularGlossyMaterial"; }
404template<> const char *qmlElementName<QSSGSceneDesc::Material::RuntimeType::PrincipledMaterial>() { return "PrincipledMaterial"; }
405template<> const char *qmlElementName<QSSGSceneDesc::Material::RuntimeType::CustomMaterial>() { return "CustomMaterial"; }
406template<> const char *qmlElementName<QSSGSceneDesc::Material::RuntimeType::OrthographicCamera>() { return "OrthographicCamera"; }
407template<> const char *qmlElementName<QSSGSceneDesc::Material::RuntimeType::PerspectiveCamera>() { return "PerspectiveCamera"; }
408
409template<> const char *qmlElementName<QSSGSceneDesc::Node::RuntimeType::Model>() { return "Model"; }
410
411template<> const char *qmlElementName<QSSGSceneDesc::Texture::RuntimeType::Image2D>() { return "Texture"; }
412template<> const char *qmlElementName<QSSGSceneDesc::Texture::RuntimeType::ImageCube>() { return "CubeMapTexture"; }
413template<> const char *qmlElementName<QSSGSceneDesc::Texture::RuntimeType::TextureData>() { return "TextureData"; }
414
415template<> const char *qmlElementName<QSSGSceneDesc::Camera::RuntimeType::DirectionalLight>() { return "DirectionalLight"; }
416template<> const char *qmlElementName<QSSGSceneDesc::Camera::RuntimeType::SpotLight>() { return "SpotLight"; }
417template<> const char *qmlElementName<QSSGSceneDesc::Camera::RuntimeType::PointLight>() { return "PointLight"; }
418
419template<> const char *qmlElementName<QSSGSceneDesc::Joint::RuntimeType::Joint>() { return "Joint"; }
420template<> const char *qmlElementName<QSSGSceneDesc::Skeleton::RuntimeType::Skeleton>() { return "Skeleton"; }
421template<> const char *qmlElementName<QSSGSceneDesc::Node::RuntimeType::Skin>() { return "Skin"; }
422template<> const char *qmlElementName<QSSGSceneDesc::Node::RuntimeType::MorphTarget>() { return "MorphTarget"; }
423template<> const char *qmlElementName<QSSGSceneDesc::Node::RuntimeType::ModelInstance>() { return "FileInstancing"; }
424
425const char *getQmlElementName(const QSSGSceneDesc::Node &node)
426{
427 using RuntimeType = QSSGSceneDesc::Node::RuntimeType;
428 switch (node.runtimeType) {
429 case RuntimeType::Node:
430 return qmlElementName<RuntimeType::Node>();
431 case RuntimeType::PrincipledMaterial:
432 return qmlElementName<RuntimeType::PrincipledMaterial>();
433 case RuntimeType::SpecularGlossyMaterial:
434 return qmlElementName<RuntimeType::SpecularGlossyMaterial>();
435 case RuntimeType::CustomMaterial:
436 return qmlElementName<RuntimeType::CustomMaterial>();
437 case RuntimeType::Image2D:
438 return qmlElementName<RuntimeType::Image2D>();
439 case RuntimeType::ImageCube:
440 return qmlElementName<RuntimeType::ImageCube>();
441 case RuntimeType::TextureData:
442 return qmlElementName<RuntimeType::TextureData>();
443 case RuntimeType::Model:
444 return qmlElementName<RuntimeType::Model>();
445 case RuntimeType::OrthographicCamera:
446 return qmlElementName<RuntimeType::OrthographicCamera>();
447 case RuntimeType::PerspectiveCamera:
448 return qmlElementName<RuntimeType::PerspectiveCamera>();
449 case RuntimeType::DirectionalLight:
450 return qmlElementName<RuntimeType::DirectionalLight>();
451 case RuntimeType::PointLight:
452 return qmlElementName<RuntimeType::PointLight>();
453 case RuntimeType::SpotLight:
454 return qmlElementName<RuntimeType::SpotLight>();
455 case RuntimeType::Skeleton:
456 return qmlElementName<RuntimeType::Skeleton>();
457 case RuntimeType::Joint:
458 return qmlElementName<RuntimeType::Joint>();
459 case RuntimeType::Skin:
460 return qmlElementName<RuntimeType::Skin>();
461 case RuntimeType::MorphTarget:
462 return qmlElementName<RuntimeType::MorphTarget>();
463 case RuntimeType::ModelInstance:
464 return qmlElementName<RuntimeType::ModelInstance>();
465 default:
466 return "UNKNOWN_TYPE";
467 }
468}
469
493
494static constexpr QByteArrayView qml_basic_types[] {
495 "bool",
496 "double",
497 "int",
498 "list",
499 "real",
500 "string",
501 "url",
502 "var",
503 "color",
504 "date",
505 "font",
506 "matrix4x4",
507 "point",
508 "quaternion",
509 "rect",
510 "size",
511 "vector2d",
512 "vector3d",
513 "vector4d"
514};
515
516static_assert(std::size(qml_basic_types) == QMLBasicType::Unknown_Count, "Missing type?");
517
518static QByteArrayView typeName(QMetaType mt)
519{
520 switch (mt.id()) {
521 case QMetaType::Bool:
522 return qml_basic_types[QMLBasicType::Bool];
523 case QMetaType::Char:
524 case QMetaType::SChar:
525 case QMetaType::UChar:
526 case QMetaType::Char16:
527 case QMetaType::Char32:
528 case QMetaType::QChar:
529 case QMetaType::Short:
530 case QMetaType::UShort:
531 case QMetaType::Int:
532 case QMetaType::UInt:
533 case QMetaType::Long:
534 case QMetaType::ULong:
535 case QMetaType::LongLong:
536 case QMetaType::ULongLong:
537 return qml_basic_types[QMLBasicType::Int];
538 case QMetaType::Float:
539 case QMetaType::Double:
540 return qml_basic_types[QMLBasicType::Real];
541 case QMetaType::QByteArray:
542 case QMetaType::QString:
543 return qml_basic_types[QMLBasicType::String];
544 case QMetaType::QDate:
545 case QMetaType::QTime:
546 case QMetaType::QDateTime:
547 return qml_basic_types[QMLBasicType::Date];
548 case QMetaType::QUrl:
549 return qml_basic_types[QMLBasicType::Url];
550 case QMetaType::QRect:
551 case QMetaType::QRectF:
552 return qml_basic_types[QMLBasicType::Rect];
553 case QMetaType::QSize:
554 case QMetaType::QSizeF:
555 return qml_basic_types[QMLBasicType::Size];
556 case QMetaType::QPoint:
557 case QMetaType::QPointF:
558 return qml_basic_types[QMLBasicType::Point];
559 case QMetaType::QVariant:
560 return qml_basic_types[QMLBasicType::Var];
561 case QMetaType::QColor:
562 return qml_basic_types[QMLBasicType::Color];
563 case QMetaType::QMatrix4x4:
564 return qml_basic_types[QMLBasicType::Mat44];
565 case QMetaType::QVector2D:
566 return qml_basic_types[QMLBasicType::Vector2D];
567 case QMetaType::QVector3D:
568 return qml_basic_types[QMLBasicType::Vector3D];
569 case QMetaType::QVector4D:
570 return qml_basic_types[QMLBasicType::Vector4D];
571 case QMetaType::QQuaternion:
572 return qml_basic_types[QMLBasicType::Quaternion];
573 case QMetaType::QFont:
574 return qml_basic_types[QMLBasicType::Font];
575 default:
576 return qml_basic_types[QMLBasicType::Var];
577 }
578}
579
584// Normally g_idMap will contain all the ids but in some cases
585// (like Animation, not Node) the ids will just be stored
586// to avoid conflict.
587// Now, Animations will be processed after all the Nodes,
588// For Nodes, it is not used.
590Q_GLOBAL_STATIC(UniqueIdOthers, g_idOthers)
591
592// The id allocator is process-wide and g_nodeNameMap is keyed by node pointer,
593// so it has to start empty for every component that is written out. A tool can
594// write several in one process - balsam converts every positional argument,
595// the material editor exports repeatedly - and each new scene's nodes are
596// allocated at addresses the previous scene's freed nodes occupied, so a stale
597// entry would otherwise take a false hit and hand a new node the earlier id.
598static void resetIdAllocator()
599{
600 g_nodeNameMap->clear();
601 g_idMap->clear();
602 g_idOthers->clear();
603}
604
605static QString getIdForNode(const QSSGSceneDesc::Node &node)
606{
607 static constexpr const char *typeNames[] = {
608 "", // Transform
609 "_camera",
610 "", // Model
611 "_texture",
612 "_material",
613 "_light",
614 "_mesh",
615 "_skin",
616 "_skeleton",
617 "_joint",
618 "_morphtarget",
619 "_instancing",
620 "_unknown"
621 };
622 constexpr uint nameCount = sizeof(typeNames)/sizeof(const char*);
623 const bool nodeHasName = (node.name.size() > 0);
624 uint nameIdx = qMin(uint(node.nodeType), nameCount);
625 QString name = nodeHasName ? QString::fromUtf8(node.name + typeNames[nameIdx]) : QString::fromLatin1(getQmlElementName(node));
626 QString sanitizedName = QSSGQmlUtilities::sanitizeQmlId(name);
627
628 // Make sure we return a unique id.
629 if (const auto it = g_nodeNameMap->constFind(&node); it != g_nodeNameMap->constEnd())
630 return *it;
631
632 quint64 id = node.id;
633 int attempts = 1000;
634 QString candidate = sanitizedName;
635 do {
636 if (const auto it = g_idMap->constFind(candidate); it == g_idMap->constEnd()) {
637 g_idMap->insert(candidate, &node);
638 g_nodeNameMap->insert(&node, candidate);
639 return candidate;
640 }
641
642 candidate = QStringLiteral("%1%2").arg(sanitizedName).arg(id++);
643 } while (--attempts);
644
645 return candidate;
646}
647
648static QString getIdForAnimation(const QByteArray &inName)
649{
650 QString name = !inName.isEmpty() ? QString::fromUtf8(inName + "_timeline") : "timeline0"_L1;
651 QString sanitizedName = QSSGQmlUtilities::sanitizeQmlId(name);
652
653 int attempts = 1000;
654 quint16 id = 0;
655 QString candidate = sanitizedName;
656 do {
657 if (const auto it = g_idMap->constFind(candidate); it == g_idMap->constEnd()) {
658 if (const auto oIt = g_idOthers->constFind(candidate); oIt == g_idOthers->constEnd()) {
659 g_idOthers->insert(candidate);
660 return candidate;
661 }
662 }
663
664 candidate = QStringLiteral("%1%2").arg(sanitizedName).arg(++id);
665 } while (--attempts);
666
667 return candidate;
668}
669
670QString stripParentDirectory(const QString &filePath) {
671 QString sourceCopy = filePath;
672 while (sourceCopy.startsWith(QChar::fromLatin1('.')) || sourceCopy.startsWith(QChar::fromLatin1('/')) || sourceCopy.startsWith(QChar::fromLatin1('\\')))
673 sourceCopy.remove(0, 1);
674 return sourceCopy;
675}
676
677QUrl urlForFilePath(const QString &path)
678{
679 // Resource paths (":/...") are not valid relative URLs
680 if (path.startsWith(u':')) {
681 QUrl url;
682 url.setScheme(u"qrc"_s);
683 url.setPath(path.mid(1));
684 return url;
685 }
686 return QUrl(path);
687}
688
689static const char *blockBegin() { return " {\n"; }
690static const char *blockEnd() { return "}\n"; }
691static const char *comment() { return "// "; }
692static const char *indent() { return " "; }
693
695{
696 enum : quint8 { QSSG_INDENT = 4 };
697 explicit QSSGQmlScopedIndent(OutputContext &out) : output(out) { out.indent += QSSG_INDENT; };
698 ~QSSGQmlScopedIndent() { output.indent = qMax(output.indent - QSSG_INDENT, 0); }
700};
701
702static QString indentString(OutputContext &output)
703{
704 QString str;
705 for (quint8 i = 0; i < output.indent; i += QSSGQmlScopedIndent::QSSG_INDENT)
706 str += QString::fromLatin1(indent());
707 return str;
708}
709
711{
712 for (quint8 i = 0; i < output.indent; i += QSSGQmlScopedIndent::QSSG_INDENT)
713 output.stream << indent();
714 return output.stream;
715}
716
717static const char *blockBegin(OutputContext &output)
718{
719 ++output.scopeDepth;
720 return blockBegin();
721}
722
723static const char *blockEnd(OutputContext &output)
724{
725 output.scopeDepth = qMax(0, output.scopeDepth - 1);
726 return blockEnd();
727}
728
729static void writeImportHeader(OutputContext &output, bool hasAnimation = false)
730{
731 output.stream << "import QtQuick\n"
732 << "import QtQuick3D\n\n";
733 if (hasAnimation)
734 output.stream << "import QtQuick.Timeline\n\n";
735}
736
737static QString toQuotedString(const QString &text) { return QStringLiteral("\"%1\"").arg(text); }
738
739static inline QString getMeshFolder() { return QStringLiteral("meshes/"); }
740static inline QString getMeshExtension() { return QStringLiteral(".mesh"); }
741
742QString getMeshSourceName(const QString &name)
743{
744 const auto meshFolder = getMeshFolder();
745 const auto extension = getMeshExtension();
746
747 return QString(meshFolder + name + extension);
748}
749
750static inline QString getTextureFolder() { return QStringLiteral("maps/"); }
751
752static inline QString getAnimationFolder() { return QStringLiteral("animations/"); }
753static inline QString getAnimationExtension() { return QStringLiteral(".qad"); }
754QString getAnimationSourceName(const QString &id, const QString &property, qsizetype index)
755{
756 const auto animationFolder = getAnimationFolder();
757 const auto extension = getAnimationExtension();
758 return QString(animationFolder + id + QStringLiteral("_")
759 + property + QStringLiteral("_")
760 + QString::number(index) + extension);
761}
762
763QString asString(const QVariant &var)
764{
765 return var.toString();
766}
767
768QString builtinQmlType(const QVariant &var)
769{
770 switch (var.metaType().id()) {
771 case QMetaType::QVector2D: {
772 const auto vec2 = qvariant_cast<QVector2D>(var);
773 return QLatin1String("Qt.vector2d(") + QString::number(vec2.x()) + QLatin1String(", ") + QString::number(vec2.y()) + QLatin1Char(')');
774 }
775 case QMetaType::QVector3D: {
776 const auto vec3 = qvariant_cast<QVector3D>(var);
777 return QLatin1String("Qt.vector3d(") + QString::number(vec3.x()) + QLatin1String(", ")
778 + QString::number(vec3.y()) + QLatin1String(", ")
779 + QString::number(vec3.z()) + QLatin1Char(')');
780 }
781 case QMetaType::QVector4D: {
782 const auto vec4 = qvariant_cast<QVector4D>(var);
783 return QLatin1String("Qt.vector4d(") + QString::number(vec4.x()) + QLatin1String(", ")
784 + QString::number(vec4.y()) + QLatin1String(", ")
785 + QString::number(vec4.z()) + QLatin1String(", ")
786 + QString::number(vec4.w()) + QLatin1Char(')');
787 }
788 case QMetaType::QColor: {
789 const auto color = qvariant_cast<QColor>(var);
790 return colorToQml(color);
791 }
792 case QMetaType::QQuaternion: {
793 const auto &quat = qvariant_cast<QQuaternion>(var);
794 return QLatin1String("Qt.quaternion(") + QString::number(quat.scalar()) + QLatin1String(", ")
795 + QString::number(quat.x()) + QLatin1String(", ")
796 + QString::number(quat.y()) + QLatin1String(", ")
797 + QString::number(quat.z()) + QLatin1Char(')');
798 }
799 case QMetaType::QMatrix4x4: {
800 const auto mat44 = qvariant_cast<QMatrix4x4>(var);
801 return QLatin1String("Qt.matrix4x4(")
802 + QString::number(mat44(0, 0)) + u", " + QString::number(mat44(0, 1)) + u", " + QString::number(mat44(0, 2)) + u", " + QString::number(mat44(0, 3)) + u", "
803 + QString::number(mat44(1, 0)) + u", " + QString::number(mat44(1, 1)) + u", " + QString::number(mat44(1, 2)) + u", " + QString::number(mat44(1, 3)) + u", "
804 + QString::number(mat44(2, 0)) + u", " + QString::number(mat44(2, 1)) + u", " + QString::number(mat44(2, 2)) + u", " + QString::number(mat44(2, 3)) + u", "
805 + QString::number(mat44(3, 0)) + u", " + QString::number(mat44(3, 1)) + u", " + QString::number(mat44(3, 2)) + u", " + QString::number(mat44(3, 3)) + u')';
806 }
807 case QMetaType::Float:
808 case QMetaType::Double:
809 case QMetaType::Int:
810 case QMetaType::Char:
811 case QMetaType::Long:
812 case QMetaType::LongLong:
813 case QMetaType::ULong:
814 case QMetaType::ULongLong:
815 case QMetaType::Bool:
816 return var.toString();
817 case QMetaType::QUrl: // QUrl needs special handling. Return empty string to trigger that.
818 default:
819 break;
820 }
821
822 return QString();
823}
824
826{
828 return QStringLiteral("position");
830 return QStringLiteral("rotation");
832 return QStringLiteral("scale");
834 return QStringLiteral("weight");
835
836 return QStringLiteral("unknown");
837}
838
839static std::pair<QString, QString> meshAssetName(const QSSGSceneDesc::Scene &scene, const QSSGSceneDesc::Mesh &meshNode, const QDir &outdir)
840{
841 // Returns {name, notValidReason}
842
843 const auto meshFolder = getMeshFolder();
844 const auto meshId = QSSGQmlUtilities::getIdForNode(meshNode);
845 const auto meshSourceName = QSSGQmlUtilities::getMeshSourceName(meshId);
846 Q_ASSERT(scene.meshStorage.size() > meshNode.idx);
847 const auto &mesh = scene.meshStorage.at(meshNode.idx);
848
849 // If a mesh folder does not exist, then create one
850 if (!outdir.exists(meshFolder) && !outdir.mkdir(meshFolder)) {
851 qDebug() << "Failed to create meshes folder at" << outdir;
852 return {}; // Error out
853 }
854
855 const QString path = outdir.path() + QDir::separator() + meshSourceName;
856 QFile file(path);
857 if (!file.open(QIODevice::WriteOnly)) {
858 return {QString(), QStringLiteral("Failed to find mesh at ") + path};
859 }
860
861 if (mesh.save(&file) == 0) {
862 return {};
863 }
864
865 return {meshSourceName, QString()};
866};
867
868static std::pair<QString, QString> copyTextureAsset(const QUrl &texturePath, OutputContext &output)
869{
870 // Returns {path, notValidReason}
871
872 // TODO: Use QUrl::resolved() instead of manual string manipulation
873 QString assetPath = output.outdir.isAbsolutePath(texturePath.path()) ? texturePath.toString() : texturePath.path();
874 QFileInfo fi(assetPath);
875 if (fi.isRelative() && !output.sourceDir.isEmpty()) {
876 fi = QFileInfo(output.sourceDir + QChar(u'/') + assetPath);
877 }
878 if (!fi.exists()) {
879 indent(output) << comment() << "Source texture path expected: " << getTextureFolder() + texturePath.fileName() << "\n";
880 return {QString(), QStringLiteral("Failed to find texture at ") + assetPath};
881 }
882
883 const auto mapsFolder = getTextureFolder();
884 // If a maps folder does not exist, then create one
885 if (!output.outdir.exists(mapsFolder) && !output.outdir.mkdir(mapsFolder)) {
886 qDebug() << "Failed to create maps folder at" << output.outdir;
887 return {}; // Error out
888 }
889
890 const QString relpath = mapsFolder + fi.fileName();
891 const auto newfilepath = QString(output.outdir.canonicalPath() + QDir::separator() + relpath);
892 if (!QFile::exists(newfilepath) && !QFile::copy(fi.canonicalFilePath(), newfilepath)) {
893 qDebug() << "Failed to copy file from" << fi.canonicalFilePath() << "to" << newfilepath;
894 return {};
895 }
896
897 return {relpath, QString()};
898};
899
900static QStringList expandComponents(const QString &value, QMetaType mt)
901{
902 static const QRegularExpression re(QLatin1String("^Qt.[a-z0-9]*\\‍(([0-9.e\\+\\-, ]*)\\‍)"));
903 Q_ASSERT(re.isValid());
904
905 switch (mt.id()) {
906 case QMetaType::QVector2D: {
907 QRegularExpressionMatch match = re.match(value);
908 if (match.hasMatch()) {
909 const auto comp = match.captured(1).split(QLatin1Char(','));
910 if (comp.size() == 2) {
911 return { QLatin1String(".x: ") + comp.at(0).trimmed(),
912 QLatin1String(".y: ") + comp.at(1).trimmed() };
913 }
914 }
915 break;
916 }
917 case QMetaType::QVector3D: {
918 QRegularExpressionMatch match = re.match(value);
919 if (match.hasMatch()) {
920 const auto comp = match.captured(1).split(QLatin1Char(','));
921 if (comp.size() == 3) {
922 return { QLatin1String(".x: ") + comp.at(0).trimmed(),
923 QLatin1String(".y: ") + comp.at(1).trimmed(),
924 QLatin1String(".z: ") + comp.at(2).trimmed() };
925 }
926 }
927 break;
928 }
929 case QMetaType::QVector4D: {
930 QRegularExpressionMatch match = re.match(value);
931 if (match.hasMatch()) {
932 const auto comp = match.captured(1).split(QLatin1Char(','));
933 if (comp.size() == 4) {
934 return { QLatin1String(".x: ") + comp.at(0).trimmed(),
935 QLatin1String(".y: ") + comp.at(1).trimmed(),
936 QLatin1String(".z: ") + comp.at(2).trimmed(),
937 QLatin1String(".w: ") + comp.at(3).trimmed() };
938 }
939 }
940 break;
941 }
942 case QMetaType::QQuaternion: {
943 QRegularExpressionMatch match = re.match(value);
944 if (match.hasMatch()) {
945 const auto comp = match.captured(1).split(QLatin1Char(','));
946 if (comp.size() == 4) {
947 return { QLatin1String(".x: ") + comp.at(0).trimmed(),
948 QLatin1String(".y: ") + comp.at(1).trimmed(),
949 QLatin1String(".z: ") + comp.at(2).trimmed(),
950 QLatin1String(".scalar: ") + comp.at(3).trimmed() };
951 }
952 }
953 break;
954 }
955 default:
956 break;
957 }
958
959 return { value };
960}
961
962static QStringList expandComponentsPartially(const QString &value, QMetaType mt)
963{
964 // Workaround for DS
965 if (mt.id() != QMetaType::QQuaternion)
966 return expandComponents(value, mt);
967
968 return { value };
969}
970
972 bool ok = false;
973 QString name;
974 QString value;
976 bool isDynamicProperty = false;
978};
979
980static ValueToQmlResult valueToQml(const QSSGSceneDesc::Node &target, const QSSGSceneDesc::Property &property, OutputContext &output)
981{
982 ValueToQmlResult result;
983 if (property.value.isNull()) {
984 result.ok = false;
985 result.notValidReason = QStringLiteral("Property value is null");
986 return result;
987 }
988
989 const QVariant &value = property.value;
990 result.name = QString::fromUtf8(property.name);
992
993 // Built-in types
994 QString valueAsString = builtinQmlType(value);
995 if (valueAsString.size() > 0) {
996 result.value = valueAsString;
997 result.ok = true;
998 } else if (value.metaType().flags() & (QMetaType::IsEnumeration | QMetaType::IsUnsignedEnumeration)) {
999 static const auto qmlEnumString = [](const QLatin1String &element, const QString &enumString) {
1000 return QStringLiteral("%1.%2").arg(element).arg(enumString);
1001 };
1002 QLatin1String qmlElementName(getQmlElementName(target));
1003 QString enumValue = asString(value);
1004 if (enumValue.size() > 0) {
1005 result.value = qmlEnumString(qmlElementName, enumValue);
1006 result.ok = true;
1007 }
1008 } else if (value.metaType().id() == qMetaTypeId<QSSGSceneDesc::Flag>()) {
1009 QByteArray element(getQmlElementName(target));
1010 if (element.size() > 0) {
1011 const auto flag = qvariant_cast<QSSGSceneDesc::Flag>(value);
1012 QByteArray keysString = flag.me.valueToKeys(int(flag.value));
1013 if (keysString.size() > 0) {
1014 keysString.prepend(element + '.');
1015 QByteArray replacement(" | " + element + '.');
1016 keysString.replace('|', replacement);
1017 result.value = QString::fromLatin1(keysString);
1018 result.ok = true;
1019 }
1020 }
1021 } else if (value.metaType().id() == qMetaTypeId<QSSGSceneDesc::NodeList *>()) {
1022 const auto *list = qvariant_cast<QSSGSceneDesc::NodeList *>(value);
1023 if (list->count > 0) {
1024 const QString indentStr = indentString(output);
1025 QSSGQmlScopedIndent scopedIndent(output);
1026 const QString listIndentStr = indentString(output);
1027
1028 QString str;
1029 str.append(u"[\n");
1030
1031 for (int i = 0, end = list->count; i != end; ++i) {
1032 if (i != 0)
1033 str.append(u",\n");
1034 str.append(listIndentStr);
1035 str.append(getIdForNode(*(list->head[i])));
1036 }
1037
1038 str.append(u'\n' + indentStr + u']');
1039
1040 result.value = str;
1041 result.ok = true;
1042 }
1043 } else if (value.metaType().id() == qMetaTypeId<QSSGSceneDesc::ListView *>()) {
1044 const auto &list = *qvariant_cast<QSSGSceneDesc::ListView *>(value);
1045 if (list.count > 0) {
1046 const QString indentStr = indentString(output);
1047 QSSGQmlScopedIndent scopedIndent(output);
1048 const QString listIndentStr = indentString(output);
1049
1050 QString str;
1051 str.append(u"[\n");
1052
1053 char *vptr = reinterpret_cast<char *>(list.data);
1054 auto size = list.mt.sizeOf();
1055
1056 for (int i = 0, end = list.count; i != end; ++i) {
1057 if (i != 0)
1058 str.append(u",\n");
1059
1060 const QVariant var{list.mt, reinterpret_cast<void *>(vptr + (size * i))};
1061 QString valueString = builtinQmlType(var);
1062 if (valueString.isEmpty())
1063 valueString = asString(var);
1064
1065 str.append(listIndentStr);
1066 str.append(valueString);
1067 }
1068
1069 str.append(u'\n' + indentStr + u']');
1070
1071 result.value = str;
1072 result.ok = true;
1073 }
1074 } else if (value.metaType().id() == qMetaTypeId<QSSGSceneDesc::Node *>()) {
1075 if (const auto node = qvariant_cast<QSSGSceneDesc::Node *>(value)) {
1076 // If this assert is triggerd it likely means that the node never got added
1077 // to the scene tree (see: addNode()) or that it's a type not handled as a resource, see:
1078 // writeQmlForResources()
1079 Q_ASSERT(node->id != 0);
1080 // The 'TextureData' node will have its data written out and become
1081 // a source url.
1082
1083 if (node->runtimeType == QSSGSceneDesc::Node::RuntimeType::TextureData) {
1084 result.name = QStringLiteral("source");
1085 result.value = getIdForNode(*node->scene->root) + QLatin1Char('.') + getIdForNode(*node);
1086 } else {
1087 result.value = getIdForNode(*node);
1088 }
1089 result.ok = true;
1090 }
1091 } else if (value.metaType() == QMetaType::fromType<QSSGSceneDesc::Mesh *>()) {
1092 if (const auto meshNode = qvariant_cast<const QSSGSceneDesc::Mesh *>(value)) {
1093 Q_ASSERT(meshNode->nodeType == QSSGSceneDesc::Node::Type::Mesh);
1094 Q_ASSERT(meshNode->scene);
1095 const auto &scene = *meshNode->scene;
1096 const auto& [meshSourceName, notValidReason] = meshAssetName(scene, *meshNode, output.outdir);
1097 result.notValidReason = notValidReason;
1098 if (!meshSourceName.isEmpty()) {
1099 result.value = toQuotedString(meshSourceName);
1100 result.ok = true;
1101 }
1102 }
1103 } else if (value.metaType() == QMetaType::fromType<QUrl>()) {
1104 if (const auto url = qvariant_cast<QUrl>(value); !url.isEmpty()) {
1105 // We need to adjust source url(s) as those should contain the canonical path
1106 QString path;
1107 if (QSSGRenderGraphObject::isTexture(target.runtimeType)) {
1108 const auto& [relpath, notValidReason] = copyTextureAsset(url, output);
1109 result.notValidReason = notValidReason;
1110 if (!relpath.isEmpty()) {
1111 path = relpath;
1112 }
1113 } else
1114 path = url.path();
1115
1116 if (!path.isEmpty()) {
1117 result.value = toQuotedString(path);
1118 result.ok = true;
1119 }
1120 }
1121 } else if (target.runtimeType == QSSGSceneDesc::Material::RuntimeType::CustomMaterial) {
1122 // Workaround the TextureInput item that wraps textures for the Custom material.
1123 if (value.metaType().id() == qMetaTypeId<QSSGSceneDesc::Texture *>()) {
1124 if (const auto texture = qvariant_cast<QSSGSceneDesc::Texture *>(value)) {
1125 Q_ASSERT(QSSGRenderGraphObject::isTexture(texture->runtimeType));
1126 result.value = QLatin1String("TextureInput { texture: ") +
1127 getIdForNode(*texture) + QLatin1String(" }");
1128 result.ok = true;
1129 }
1130 }
1131 } else if (value.metaType() == QMetaType::fromType<QString>()) {
1132 // Plain strings in the scenedesc should map to QML string values
1133 result.value = toQuotedString(value.toString());
1134 result.ok = true;
1135 } else {
1136 result.notValidReason = QStringLiteral("Unsupported value type: ") + QString::fromUtf8(value.metaType().name());
1137 qWarning() << result.notValidReason;
1138 result.ok = false;
1139 }
1140
1141 if (result.ok && (output.options & OutputContext::Options::ExpandValueComponents)) {
1142 result.expandedProperties = ((output.options & OutputContext::Options::DesignStudioWorkarounds) == OutputContext::Options::DesignStudioWorkarounds)
1143 ? expandComponentsPartially(result.value, value.metaType())
1144 : expandComponents(result.value, value.metaType());
1145 }
1146
1147 return result;
1148}
1149
1150static void writeNodeProperties(const QSSGSceneDesc::Node &node, OutputContext &output,
1151 const char *skipProperty = nullptr)
1152{
1153 QSSGQmlScopedIndent scopedIndent(output);
1154
1155 indent(output) << u"id: "_s << getIdForNode(node) << u'\n';
1156
1157 // Set Object Name if one exists
1158 if (node.name.size()) {
1159 const QString objectName = QString::fromLocal8Bit(node.name);
1160 if (!objectName.startsWith(u'*'))
1161 indent(output) << u"objectName: \""_s << node.name << u"\"\n"_s;
1162 }
1163
1164 const auto &properties = node.properties;
1165 auto it = properties.begin();
1166 const auto end = properties.end();
1167 for (; it != end; ++it) {
1168 const auto &property = *it;
1169 if (skipProperty && qstrcmp(property->name, skipProperty) == 0)
1170 continue;
1171
1172 const ValueToQmlResult result = valueToQml(node, *property, output);
1173 if (result.ok) {
1174 if (result.isDynamicProperty) {
1175 indent(output) << "property " << typeName(property->value.metaType()).toByteArray() << ' ' << result.name << u": "_s << result.value << u'\n';
1176 } else if (!QSSGQmlUtilities::PropertyMap::instance()->isDefaultValue(node.runtimeType, property->name, property->value)) {
1177 if (result.expandedProperties.size() > 1) {
1178 for (const auto &va : result.expandedProperties)
1179 indent(output) << result.name << va << u'\n';
1180 } else {
1181 indent(output) << result.name << u": "_s << result.value << u'\n';
1182 }
1183 }
1184 } else if (!result.isDynamicProperty) {
1185 QString message = u"Skipped property: "_s + QString::fromUtf8(property->name);
1186 if (!result.notValidReason.isEmpty())
1187 message.append(u", reason: "_s + result.notValidReason);
1188 qDebug() << message;
1189 indent(output) << comment() << message + u'\n';
1190 }
1191 }
1192}
1193
1194static void writeQml(const QSSGSceneDesc::Node &transform, OutputContext &output)
1195{
1196 using namespace QSSGSceneDesc;
1197 Q_ASSERT(transform.nodeType == QSSGSceneDesc::Node::Type::Transform && transform.runtimeType == QSSGSceneDesc::Node::RuntimeType::Node);
1198 indent(output) << qmlElementName<QSSGSceneDesc::Node::RuntimeType::Node>() << blockBegin(output);
1199 writeNodeProperties(transform, output);
1200}
1201
1202void writeQml(const QSSGSceneDesc::Material &material, OutputContext &output)
1203{
1204 using namespace QSSGSceneDesc;
1205 Q_ASSERT(material.nodeType == QSSGSceneDesc::Model::Type::Material);
1206 if (material.runtimeType == QSSGSceneDesc::Model::RuntimeType::SpecularGlossyMaterial) {
1207 indent(output) << qmlElementName<Material::RuntimeType::SpecularGlossyMaterial>() << blockBegin(output);
1208 } else if (material.runtimeType == Model::RuntimeType::PrincipledMaterial) {
1209 indent(output) << qmlElementName<Material::RuntimeType::PrincipledMaterial>() << blockBegin(output);
1210 } else if (material.runtimeType == Material::RuntimeType::CustomMaterial) {
1211 indent(output) << qmlElementName<Material::RuntimeType::CustomMaterial>() << blockBegin(output);
1212 } else if (material.runtimeType == Material::RuntimeType::SpecularGlossyMaterial) {
1213 indent(output) << qmlElementName<Material::RuntimeType::SpecularGlossyMaterial>() << blockBegin(output);
1214 } else {
1215 Q_UNREACHABLE();
1216 }
1217
1218 writeNodeProperties(material, output);
1219}
1220
1221static QString toQmlStringLiteral(const QString &value)
1222{
1223 QString escaped = value;
1224 escaped.replace(u'\\', u"\\\\"_s);
1225 escaped.replace(u'"', u"\\\""_s);
1226 escaped.replace(u'\n', u"\\n"_s);
1227 escaped.replace(u'\r', u"\\r"_s);
1228 return u'"' + escaped + u'"';
1229}
1230
1231static void writeQml(const QSSGSceneDesc::Model &model, OutputContext &output)
1232{
1233 using namespace QSSGSceneDesc;
1234 Q_ASSERT(model.nodeType == Node::Type::Model);
1235 indent(output) << qmlElementName<QSSGSceneDesc::Node::RuntimeType::Model>() << blockBegin(output);
1236 const bool hasVariants = !model.variantMaterials.isEmpty() && model.scene
1237 && !model.scene->materialVariants.isEmpty();
1238 writeNodeProperties(model, output, hasVariants ? "materials" : nullptr);
1239 if (hasVariants) {
1240 // Unknown variant names select the default materials
1241 const auto materialListString = [](const QList<Node *> &materials) {
1242 QStringList ids;
1243 for (const Node *material : materials)
1244 ids.append(getIdForNode(*material));
1245 return u'[' + ids.join(u", "_s) + u']';
1246 };
1247 QString expression;
1248 const QStringList &names = model.scene->materialVariants;
1249 const QString rootId = getIdForNode(*model.scene->root);
1250 for (qsizetype variant = 0; variant < model.variantMaterials.size() && variant < names.size(); ++variant) {
1251 expression += rootId + u".materialVariant === "_s + toQmlStringLiteral(names.at(variant)) + u" ? "_s
1252 + materialListString(model.variantMaterials.at(variant)) + u" : "_s;
1253 }
1254 expression += materialListString(model.defaultMaterials);
1255 QSSGQmlScopedIndent scopedIndent(output);
1256 indent(output) << u"materials: "_s << expression << u'\n';
1257 }
1258}
1259
1260static void writeQml(const QSSGSceneDesc::Camera &camera, OutputContext &output)
1261{
1262 using namespace QSSGSceneDesc;
1263 Q_ASSERT(camera.nodeType == Node::Type::Camera);
1264 if (camera.runtimeType == Camera::RuntimeType::PerspectiveCamera)
1265 indent(output) << qmlElementName<Camera::RuntimeType::PerspectiveCamera>() << blockBegin(output);
1266 else if (camera.runtimeType == Camera::RuntimeType::OrthographicCamera)
1267 indent(output) << qmlElementName<Camera::RuntimeType::OrthographicCamera>() << blockBegin(output);
1268 else
1269 Q_UNREACHABLE();
1270 writeNodeProperties(camera, output);
1271}
1272
1273static void writeQml(const QSSGSceneDesc::Texture &texture, OutputContext &output)
1274{
1275 using namespace QSSGSceneDesc;
1276 Q_ASSERT(texture.nodeType == Node::Type::Texture && QSSGRenderGraphObject::isTexture(texture.runtimeType));
1277 if (texture.runtimeType == Texture::RuntimeType::Image2D)
1278 indent(output) << qmlElementName<Texture::RuntimeType::Image2D>() << blockBegin(output);
1279 else if (texture.runtimeType == Texture::RuntimeType::ImageCube)
1280 indent(output) << qmlElementName<Texture::RuntimeType::ImageCube>() << blockBegin(output);
1281 writeNodeProperties(texture, output);
1282}
1283
1284static void writeQml(const QSSGSceneDesc::Skin &skin, OutputContext &output)
1285{
1286 using namespace QSSGSceneDesc;
1287 Q_ASSERT(skin.nodeType == Node::Type::Skin && skin.runtimeType == Node::RuntimeType::Skin);
1288 indent(output) << qmlElementName<Node::RuntimeType::Skin>() << blockBegin(output);
1289 writeNodeProperties(skin, output);
1290}
1291
1292static void writeQml(const QSSGSceneDesc::MorphTarget &morphTarget, OutputContext &output)
1293{
1294 using namespace QSSGSceneDesc;
1295 Q_ASSERT(morphTarget.nodeType == Node::Type::MorphTarget);
1296 indent(output) << qmlElementName<QSSGSceneDesc::Node::RuntimeType::MorphTarget>() << blockBegin(output);
1297 writeNodeProperties(morphTarget, output);
1298}
1299
1300QString getTextureSourceName(const QString &name, const QString &fmt)
1301{
1302 const auto textureFolder = getTextureFolder();
1303
1304 const auto sanitizedName = QSSGQmlUtilities::sanitizeQmlId(name);
1305 // Raw pixel data has no fmt and is written as PNG
1306 const auto ext = (fmt.isEmpty() || fmt.length() > 4) ? u".png"_s
1307 : u"."_s + fmt;
1308
1309 return QString(textureFolder + sanitizedName + ext);
1310}
1311
1312static QString outputTextureAsset(const QSSGSceneDesc::TextureData &textureData, const QDir &outdir)
1313{
1314 if (textureData.data.isEmpty())
1315 return QString();
1316
1317 const auto mapsFolder = getTextureFolder();
1318 const auto id = getIdForNode(textureData);
1319 const bool isCompressed = ((textureData.flgs & quint8(QSSGSceneDesc::TextureData::Flags::Compressed)) != 0);
1320 const QString textureSourceName = getTextureSourceName(id, isCompressed ? QString::fromUtf8(textureData.fmt)
1321 : QString());
1322
1323 // If a maps folder does not exist, then create one
1324 if (!outdir.exists(mapsFolder) && !outdir.mkdir(mapsFolder))
1325 return QString(); // Error out
1326
1327 const auto imagePath = QString(outdir.path() + QDir::separator() + textureSourceName);
1328
1329 if (isCompressed) {
1330 QFile file(imagePath);
1331 if (!file.open(QIODevice::WriteOnly)) {
1332 qWarning("Failed to open file %s: %s",
1333 qPrintable(file.fileName()), qPrintable(file.errorString()));
1334 return {};
1335 } else {
1336 file.write(textureData.data);
1337 file.close();
1338 }
1339 } else {
1340 const auto &texData = textureData.data;
1341 const auto &size = textureData.sz;
1342 QImage image;
1343 image = QImage(reinterpret_cast<const uchar *>(texData.data()), size.width(), size.height(), QImage::Format::Format_RGBA8888);
1344 if (!image.save(imagePath))
1345 return QString();
1346 }
1347
1348 return textureSourceName;
1349}
1350
1351static void writeQml(const QSSGSceneDesc::TextureData &textureData, OutputContext &output)
1352{
1353 using namespace QSSGSceneDesc;
1354 Q_ASSERT(textureData.nodeType == Node::Type::Texture && textureData.runtimeType == Node::RuntimeType::TextureData);
1355
1356 QString textureSourcePath = outputTextureAsset(textureData, output.outdir);
1357
1358 static const auto writeProperty = [](const QString &type, const QString &name, const QString &value) {
1359 return QString::fromLatin1("property %1 %2: %3").arg(type, name, value);
1360 };
1361
1362 if (!textureSourcePath.isEmpty()) {
1363 const auto type = QLatin1String("url");
1364 const auto name = getIdForNode(textureData);
1365
1366 indent(output) << writeProperty(type, name, toQuotedString(textureSourcePath)) << '\n';
1367 }
1368}
1369
1370static inline QString getInstancesFolder() { return QStringLiteral("instances/"); }
1371
1372static QString outputInstanceTableAsset(const QSSGSceneDesc::Instancing &instancing, const QDir &outdir)
1373{
1374 const QString folder = getInstancesFolder();
1375 if (!outdir.exists(folder) && !outdir.mkdir(folder)) {
1376 qWarning() << "Failed to create instances folder at" << outdir;
1377 return {};
1378 }
1379 const QString sourceName = folder + getIdForNode(instancing) + QStringLiteral(".bin");
1380 QFile file(outdir.path() + QDir::separator() + sourceName);
1381 if (!file.open(QIODevice::WriteOnly)) {
1382 qWarning("Failed to open file %s: %s", qPrintable(file.fileName()), qPrintable(file.errorString()));
1383 return {};
1384 }
1385 if (!QQuick3DFileInstancing::writeInstanceTable(&file, instancing.instanceData, int(instancing.instanceCount)))
1386 return {};
1387 return sourceName;
1388}
1389
1390static void writeQml(const QSSGSceneDesc::Instancing &instancing, OutputContext &output)
1391{
1392 using namespace QSSGSceneDesc;
1393 Q_ASSERT(instancing.nodeType == Node::Type::Instancing
1394 && instancing.runtimeType == Node::RuntimeType::ModelInstance);
1395
1396 const QString instanceSourcePath = outputInstanceTableAsset(instancing, output.outdir);
1397
1398 indent(output) << qmlElementName<Node::RuntimeType::ModelInstance>() << blockBegin(output);
1399 writeNodeProperties(instancing, output);
1400 if (!instanceSourcePath.isEmpty()) {
1401 QSSGQmlScopedIndent scopedIndent(output);
1402 indent(output) << u"source: "_s << toQuotedString(instanceSourcePath) << u'\n';
1403 }
1404}
1405
1406static void writeQml(const QSSGSceneDesc::Light &light, OutputContext &output)
1407{
1408 using namespace QSSGSceneDesc;
1409 Q_ASSERT(light.nodeType == Node::Type::Light);
1410 if (light.runtimeType == Light::RuntimeType::DirectionalLight)
1411 indent(output) << qmlElementName<Light::RuntimeType::DirectionalLight>() << blockBegin(output);
1412 else if (light.runtimeType == Light::RuntimeType::SpotLight)
1413 indent(output) << qmlElementName<Light::RuntimeType::SpotLight>() << blockBegin(output);
1414 else if (light.runtimeType == Light::RuntimeType::PointLight)
1415 indent(output) << qmlElementName<Light::RuntimeType::PointLight>() << blockBegin(output);
1416 else
1417 Q_UNREACHABLE();
1418 writeNodeProperties(light, output);
1419}
1420
1421static void writeQml(const QSSGSceneDesc::Skeleton &skeleton, OutputContext &output)
1422{
1423 using namespace QSSGSceneDesc;
1424 Q_ASSERT(skeleton.nodeType == Node::Type::Skeleton && skeleton.runtimeType == Node::RuntimeType::Skeleton);
1425 indent(output) << qmlElementName<Node::RuntimeType::Skeleton>() << blockBegin(output);
1426 writeNodeProperties(skeleton, output);
1427}
1428
1429static void writeQml(const QSSGSceneDesc::Joint &joint, OutputContext &output)
1430{
1431 using namespace QSSGSceneDesc;
1432 Q_ASSERT(joint.nodeType == Node::Type::Joint && joint.runtimeType == Node::RuntimeType::Joint);
1433 indent(output) << qmlElementName<Node::RuntimeType::Joint>() << blockBegin(output);
1434 writeNodeProperties(joint, output);
1435}
1436
1437static void writeQmlForResourceNode(const QSSGSceneDesc::Node &node, OutputContext &output)
1438{
1439 using namespace QSSGSceneDesc;
1440 Q_ASSERT(output.type == OutputContext::Resource);
1441 Q_ASSERT(QSSGRenderGraphObject::isResource(node.runtimeType) || node.nodeType == Node::Type::Mesh || node.nodeType == Node::Type::Skeleton);
1442
1443 const bool processNode = !node.properties.isEmpty() || (output.type == OutputContext::Resource);
1444 if (processNode) {
1445 QSSGQmlScopedIndent scopedIndent(output);
1446 switch (node.nodeType) {
1447 case Node::Type::Skin:
1448 writeQml(static_cast<const Skin &>(node), output);
1449 break;
1450 case Node::Type::MorphTarget:
1451 writeQml(static_cast<const MorphTarget &>(node), output);
1452 break;
1453 case Node::Type::Instancing:
1454 writeQml(static_cast<const Instancing &>(node), output);
1455 break;
1456 case Node::Type::Skeleton:
1457 writeQml(static_cast<const Skeleton &>(node), output);
1458 break;
1459 case Node::Type::Texture:
1460 if (node.runtimeType == Node::RuntimeType::Image2D)
1461 writeQml(static_cast<const Texture &>(node), output);
1462 else if (node.runtimeType == Node::RuntimeType::ImageCube)
1463 writeQml(static_cast<const Texture &>(node), output);
1464 else if (node.runtimeType == Node::RuntimeType::TextureData)
1465 writeQml(static_cast<const TextureData &>(node), output);
1466 else
1467 Q_UNREACHABLE();
1468 break;
1469 case Node::Type::Material:
1470 writeQml(static_cast<const Material &>(node), output);
1471 break;
1472 case Node::Type::Mesh:
1473 // Only handled as a property (see: valueToQml())
1474 break;
1475 default:
1476 qWarning("Unhandled resource type \'%d\'?", int(node.runtimeType));
1477 break;
1478 }
1479 }
1480
1481 // Do something more convenient if this starts expending to more types...
1482 // NOTE: The TextureData type is written out as a url property...
1483 const bool skipBlockEnd = (node.runtimeType == Node::RuntimeType::TextureData || node.nodeType == Node::Type::Mesh);
1484 if (!skipBlockEnd && processNode && output.scopeDepth != 0) {
1485 QSSGQmlScopedIndent scopedIndent(output);
1486 indent(output) << blockEnd(output);
1487 }
1488}
1489
1490static void writeQmlForNode(const QSSGSceneDesc::Node &node, OutputContext &output)
1491{
1492 using namespace QSSGSceneDesc;
1493
1494 const bool processNode = !(node.properties.isEmpty() && node.children.isEmpty())
1495 || (output.type == OutputContext::Resource);
1496 if (processNode) {
1497 QSSGQmlScopedIndent scopedIndent(output);
1498 switch (node.nodeType) {
1499 case Node::Type::Skeleton:
1500 writeQml(static_cast<const Skeleton &>(node), output);
1501 break;
1502 case Node::Type::Joint:
1503 writeQml(static_cast<const Joint &>(node), output);
1504 break;
1505 case Node::Type::Light:
1506 writeQml(static_cast<const Light &>(node), output);
1507 break;
1508 case Node::Type::Transform:
1509 writeQml(node, output);
1510 break;
1511 case Node::Type::Camera:
1512 writeQml(static_cast<const Camera &>(node), output);
1513 break;
1514 case Node::Type::Model:
1515 writeQml(static_cast<const Model &>(node), output);
1516 break;
1517 default:
1518 break;
1519 }
1520 }
1521
1522 for (const auto &cld : node.children) {
1523 if (!QSSGRenderGraphObject::isResource(cld->runtimeType) && output.type == OutputContext::NodeTree) {
1524 QSSGQmlScopedIndent scopedIndent(output);
1525 writeQmlForNode(*cld, output);
1526 }
1527 }
1528
1529 // Do something more convenient if this starts expending to more types...
1530 // NOTE: The TextureData type is written out as a url property...
1531 const bool skipBlockEnd = (node.runtimeType == Node::RuntimeType::TextureData || node.nodeType == Node::Type::Mesh);
1532 if (!skipBlockEnd && processNode && output.scopeDepth != 0) {
1533 QSSGQmlScopedIndent scopedIndent(output);
1534 indent(output) << blockEnd(output);
1535 }
1536}
1537
1538void writeQmlForResources(const QSSGSceneDesc::Scene::ResourceNodes &resources, OutputContext &output)
1539{
1540 auto sortedResources = resources;
1541 std::sort(sortedResources.begin(), sortedResources.end(), [](const QSSGSceneDesc::Node *a, const QSSGSceneDesc::Node *b) {
1542 using RType = QSSGSceneDesc::Node::RuntimeType;
1543 if (a->runtimeType == RType::TextureData && b->runtimeType != RType::TextureData)
1544 return true;
1545 if (a->runtimeType == RType::ImageCube && (b->runtimeType != RType::TextureData && b->runtimeType != RType::ImageCube))
1546 return true;
1547 if (a->runtimeType == RType::Image2D && (b->runtimeType != RType::TextureData && b->runtimeType != RType::Image2D))
1548 return true;
1549
1550 return false;
1551 });
1552 for (const auto &res : std::as_const(sortedResources))
1553 writeQmlForResourceNode(*res, output);
1554}
1555
1556static void generateKeyframeData(const QSSGSceneDesc::Animation::Channel &channel, QByteArray &keyframeData)
1557{
1558#ifdef QT_QUICK3D_ENABLE_RT_ANIMATIONS
1559 QCborStreamWriter writer(&keyframeData);
1560 // Start root array
1561 writer.startArray();
1562 // header name
1563 writer.append("QTimelineKeyframes");
1564 // file version. Increase this if the format changes.
1565 const int keyframesDataVersion = 1;
1566 writer.append(keyframesDataVersion);
1567 writer.append(int(channel.keys.at(0)->getValueQMetaType()));
1568
1569 // Start Keyframes array
1570 writer.startArray();
1571 quint8 compEnd = quint8(channel.keys.at(0)->getValueType());
1572 bool isQuaternion = false;
1573 if (compEnd == quint8(QSSGSceneDesc::Animation::KeyPosition::ValueType::Quaternion)) {
1574 isQuaternion = true;
1575 compEnd = 3;
1576 } else {
1577 compEnd++;
1578 }
1579 for (const auto &key : channel.keys) {
1580 writer.append(key->time);
1581 // Easing always linear
1582 writer.append(QEasingCurve::Linear);
1583 if (isQuaternion)
1584 writer.append(key->value[3]);
1585 for (quint8 i = 0; i < compEnd; ++i)
1586 writer.append(key->value[i]);
1587 }
1588 // End Keyframes array
1589 writer.endArray();
1590 // End root array
1591 writer.endArray();
1592#else
1593 Q_UNUSED(channel)
1594 Q_UNUSED(keyframeData)
1595#endif // QT_QUICK3D_ENABLE_RT_ANIMATIONS
1596}
1597
1598QPair<QString, QString> writeQmlForAnimation(const QSSGSceneDesc::Animation &anim, qsizetype index, OutputContext &output, bool useBinaryKeyframes = true, bool generateTimelineAnimations = true)
1599{
1600 indent(output) << "Timeline {\n";
1601
1602 QSSGQmlScopedIndent scopedIndent(output);
1603 // The duration property of the TimelineAnimation is an int...
1604 const int duration = qCeil(anim.length);
1605 // Use the same name for objectName and id
1606 const QString animationId = getIdForAnimation(anim.name);
1607 indent(output) << "id: " << animationId << "\n";
1608 QString animationName = animationId;
1609 if (!anim.name.isEmpty())
1610 animationName = QString::fromLocal8Bit(anim.name);
1611 indent(output) << "objectName: \"" << animationName << "\"\n";
1612 indent(output) << "property real framesPerSecond: " << anim.framesPerSecond << "\n";
1613 indent(output) << "startFrame: 0\n";
1614 indent(output) << "endFrame: " << duration << "\n";
1615 indent(output) << "currentFrame: 0\n";
1616 // Only generate the TimelineAnimation component here if requested
1617 // enabled is only set to true up front if we expect to autoplay
1618 // the generated TimelineAnimation
1619 if (generateTimelineAnimations) {
1620 indent(output) << "enabled: true\n";
1621 indent(output) << "animations: TimelineAnimation {\n";
1622 {
1623 QSSGQmlScopedIndent scopedIndent(output);
1624 indent(output) << "duration: " << duration << "\n";
1625 indent(output) << "from: 0\n";
1626 indent(output) << "to: " << duration << "\n";
1627 indent(output) << "running: true\n";
1628 indent(output) << "loops: Animation.Infinite\n";
1629 }
1630 indent(output) << blockEnd(output);
1631 }
1632
1633 for (const auto &channel : anim.channels) {
1634 QString id = getIdForNode(*channel->target);
1635 QString propertyName = asString(channel->targetProperty);
1636
1637 indent(output) << "KeyframeGroup {\n";
1638 {
1639 QSSGQmlScopedIndent scopedIndent(output);
1640 indent(output) << "target: " << id << "\n";
1641 indent(output) << "property: " << toQuotedString(propertyName) << "\n";
1642 if (useBinaryKeyframes && channel->keys.size() != 1) {
1643 const auto animFolder = getAnimationFolder();
1644 const auto animSourceName = getAnimationSourceName(id, propertyName, index);
1645 if (!output.outdir.exists(animFolder) && !output.outdir.mkdir(animFolder)) {
1646 // Make a warning
1647 continue;
1648 }
1649 QFile file(output.outdir.path() + QDir::separator() + animSourceName);
1650 if (!file.open(QIODevice::WriteOnly))
1651 continue;
1652 QByteArray keyframeData;
1653 // It is possible to store this keyframeData but we have to consider
1654 // all the cases including runtime only or writeQml only.
1655 // For now, we will generate it for each case.
1656 generateKeyframeData(*channel, keyframeData);
1657 file.write(keyframeData);
1658 file.close();
1659 indent(output) << "keyframeSource: " << toQuotedString(animSourceName) << "\n";
1660 } else {
1661 Q_ASSERT(!channel->keys.isEmpty());
1662 for (const auto &key : std::as_const(channel->keys)) {
1663 indent(output) << "Keyframe {\n";
1664 {
1665 QSSGQmlScopedIndent scopedIndent(output);
1666 indent(output) << "frame: " << key->time << "\n";
1667 indent(output) << "value: " << variantToQml(key->getValue()) << "\n";
1668 }
1669 indent(output) << blockEnd(output);
1670 }
1671 }
1672 }
1673 indent(output) << blockEnd(output);
1674 }
1675 return {animationName, animationId};
1676}
1677
1678void writeQml(const QSSGSceneDesc::Scene &scene, QTextStream &stream, const QDir &outdir, const QJsonObject &optionsObject)
1679{
1680 static const auto checkBooleanOption = [](const QLatin1String &optionName, const QJsonObject &options, bool defaultValue = false) {
1681 const auto it = options.constFind(optionName);
1682 const auto end = options.constEnd();
1683 QJsonValue value;
1684 if (it != end) {
1685 if (it->isObject())
1686 value = it->toObject().value(QLatin1String("value"));
1687 else
1688 value = it.value();
1689 }
1690 return value.toBool(defaultValue);
1691 };
1692
1693 auto root = scene.root;
1694 Q_ASSERT(root);
1695
1697
1698 QJsonObject options = optionsObject;
1699
1700 if (auto it = options.constFind(QLatin1String("options")), end = options.constEnd(); it != end)
1701 options = it->toObject();
1702
1703 quint8 outputOptions{ OutputContext::Options::None };
1704 if (checkBooleanOption(QLatin1String("expandValueComponents"), options))
1706
1707 // Workaround for design studio type components
1708 if (checkBooleanOption(QLatin1String("designStudioWorkarounds"), options))
1710
1711 const bool useBinaryKeyframes = checkBooleanOption("useBinaryKeyframes"_L1, options);
1712 const bool generateTimelineAnimations = !checkBooleanOption("manualAnimations"_L1, options);
1713
1714 OutputContext output { stream, outdir, scene.sourceDir, 0, OutputContext::Header, outputOptions };
1715
1716 writeImportHeader(output, scene.animations.count() > 0);
1717
1719 writeQml(*root, output); // Block scope will be left open!
1720
1721 if (!scene.materialVariants.isEmpty()) {
1722 // Models with variant materials bind to these
1723 QSSGQmlScopedIndent scopedIndent(output);
1724 QStringList variantNames;
1725 for (const QString &name : scene.materialVariants)
1726 variantNames.append(toQmlStringLiteral(name));
1727 indent(output) << u"property string materialVariant: \"\"\n"_s;
1728 indent(output) << u"readonly property list<string> materialVariants: ["_s << variantNames.join(u", "_s)
1729 << u"]\n"_s;
1730 }
1731
1732 stream << "\n";
1733 stream << indent() << "// Resources\n";
1735 writeQmlForResources(scene.resources, output);
1737 stream << "\n";
1738 stream << indent() << "// Nodes:\n";
1739 for (const auto &cld : std::as_const(root->children))
1740 writeQmlForNode(*cld, output);
1741
1742 // animations
1743 qsizetype animId = 0;
1744 stream << "\n";
1745 stream << indent() << "// Animations:\n";
1746 QList<QPair<QString, QString>> animationMap;
1747 for (const auto &cld : scene.animations) {
1748 QSSGQmlScopedIndent scopedIndent(output);
1749 auto mapValues = writeQmlForAnimation(*cld, animId++, output, useBinaryKeyframes, generateTimelineAnimations);
1750 animationMap.append(mapValues);
1751 indent(output) << blockEnd(output);
1752 }
1753
1754 if (!generateTimelineAnimations) {
1755 // Expose a map of timelines
1756 stream << "\n";
1757 stream << indent() << "// An exported mapping of Timelines (--manualAnimations)\n";
1758 stream << indent() << "property var timelineMap: {\n";
1759 QSSGQmlScopedIndent scopedIndent(output);
1760 for (const auto &mapValues : animationMap) {
1761 QSSGQmlScopedIndent scopedIndent(output);
1762 indent(output) << "\"" << mapValues.first << "\": " << mapValues.second << ",\n";
1763 }
1764 indent(output) << blockEnd(output);
1765 stream << indent() << "// A simple list of Timelines (--manualAnimations)\n";
1766 stream << indent() << "property var timelineList: [\n";
1767 for (const auto &mapValues : animationMap) {
1768 QSSGQmlScopedIndent scopedIndent(output);
1769 indent(output) << mapValues.second << ",\n";
1770 }
1771 indent(output) << "]\n";
1772 }
1773
1774
1775 // close the root
1776 indent(output) << blockEnd(output);
1777}
1778
1779void createTimelineAnimation(const QSSGSceneDesc::Animation &anim, QObject *parent, bool isEnabled, bool useBinaryKeyframes)
1780{
1781#ifdef QT_QUICK3D_ENABLE_RT_ANIMATIONS
1782 auto timeline = new QQuickTimeline(parent);
1783 auto timelineKeyframeGroup = timeline->keyframeGroups();
1784 for (const auto &channel : anim.channels) {
1785 auto keyframeGroup = new QQuickKeyframeGroup(timeline);
1786 keyframeGroup->setTargetObject(channel->target->obj);
1787 keyframeGroup->setProperty(asString(channel->targetProperty));
1788
1789 Q_ASSERT(!channel->keys.isEmpty());
1790 if (useBinaryKeyframes) {
1791 QByteArray keyframeData;
1792 generateKeyframeData(*channel, keyframeData);
1793
1794 keyframeGroup->setKeyframeData(keyframeData);
1795 } else {
1796 auto keyframes = keyframeGroup->keyframes();
1797 for (const auto &key : std::as_const(channel->keys)) {
1798 auto keyframe = new QQuickKeyframe(keyframeGroup);
1799 keyframe->setFrame(key->time);
1800 keyframe->setValue(key->getValue());
1801 keyframes.append(&keyframes, keyframe);
1802 }
1803 }
1804 (qobject_cast<QQmlParserStatus *>(keyframeGroup))->componentComplete();
1805 timelineKeyframeGroup.append(&timelineKeyframeGroup, keyframeGroup);
1806 }
1807 timeline->setEndFrame(anim.length);
1808 timeline->setEnabled(isEnabled);
1809
1810 auto timelineAnimation = new QQuickTimelineAnimation(timeline);
1811 timelineAnimation->setObjectName(anim.name);
1812 timelineAnimation->setDuration(int(anim.length));
1813 timelineAnimation->setFrom(0.0f);
1814 timelineAnimation->setTo(anim.length);
1815 timelineAnimation->setLoops(QQuickTimelineAnimation::Infinite);
1816 timelineAnimation->setTargetObject(timeline);
1817
1818 (qobject_cast<QQmlParserStatus *>(timeline))->componentComplete();
1819
1820 timelineAnimation->setRunning(true);
1821#else // QT_QUICK3D_ENABLE_RT_ANIMATIONS
1822 Q_UNUSED(anim)
1823 Q_UNUSED(parent)
1824 Q_UNUSED(isEnabled)
1825 Q_UNUSED(useBinaryKeyframes)
1826#endif // QT_QUICK3D_ENABLE_RT_ANIMATIONS
1827}
1828
1829void writeQmlComponent(const QSSGSceneDesc::Node &node, QTextStream &stream, const QDir &outDir)
1830{
1831 using namespace QSSGSceneDesc;
1832
1833 QSSG_ASSERT(node.scene != nullptr, return);
1834
1836
1837 if (node.runtimeType == Material::RuntimeType::CustomMaterial) {
1838 QString sourceDir = node.scene->sourceDir;
1839 OutputContext output { stream, outDir, sourceDir, 0, OutputContext::Resource };
1840 writeImportHeader(output);
1841 writeQml(static_cast<const Material &>(node), output);
1842 // Resources, if any, are written out as properties on the component
1843 const auto &resources = node.scene->resources;
1844 writeQmlForResources(resources, output);
1845 indent(output) << blockEnd(output);
1846 } else {
1847 Q_UNREACHABLE(); // Only implemented for Custom material at this point.
1848 }
1849}
1850
1851}
1852
1853QT_END_NAMESPACE
bool isDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property, const QVariant &value)
PropertiesMap propertiesForType(QSSGSceneDesc::Node::RuntimeType type)
static PropertyMap * instance()
QVariant getDefaultValue(QSSGSceneDesc::Node::RuntimeType type, const char *property)
QHash< QByteArray, QVariant > PropertiesMap
The QVector2D class represents a vector or vertex in 2D space.
Definition qvectornd.h:34
The QVector3D class represents a vector or vertex in 3D space.
Definition qvectornd.h:178
The QVector4D class represents a vector or vertex in 4D space.
Definition qvectornd.h:341
static QString getInstancesFolder()
static const char * blockEnd()
static constexpr QByteArrayView qml_basic_types[]
QString builtinQmlType(const QVariant &var)
static void generateKeyframeData(const QSSGSceneDesc::Animation::Channel &channel, QByteArray &keyframeData)
void writeQmlComponent(const QSSGSceneDesc::Node &node, QTextStream &stream, const QDir &outDir)
static QString getIdForNode(const QSSGSceneDesc::Node &node)
QString asString(const QVariant &var)
static void writeNodeProperties(const QSSGSceneDesc::Node &node, OutputContext &output, const char *skipProperty=nullptr)
static QString getTextureFolder()
QString qmlComponentName(const QString &name)
static PropertyMap::PropertiesMap getObjectPropertiesMap(QObject *object)
static QString getAnimationFolder()
static QString getAnimationExtension()
static ValueToQmlResult valueToQml(const QSSGSceneDesc::Node &target, const QSSGSceneDesc::Property &property, OutputContext &output)
static QString outputInstanceTableAsset(const QSSGSceneDesc::Instancing &instancing, const QDir &outdir)
static void writeQml(const QSSGSceneDesc::Model &model, OutputContext &output)
QString colorToQml(const QColor &color)
void createTimelineAnimation(const QSSGSceneDesc::Animation &anim, QObject *parent, bool isEnabled, bool useBinaryKeyframes)
static QString getMeshExtension()
static const char * blockBegin()
static const char * blockBegin(OutputContext &output)
static void writeQml(const QSSGSceneDesc::Node &transform, OutputContext &output)
static QStringList expandComponents(const QString &value, QMetaType mt)
void writeQmlForResources(const QSSGSceneDesc::Scene::ResourceNodes &resources, OutputContext &output)
const char * qmlElementName()
QString sanitizeQmlId(const QString &id)
static QString toQmlStringLiteral(const QString &value)
static const char * blockEnd(OutputContext &output)
static QString outputTextureAsset(const QSSGSceneDesc::TextureData &textureData, const QDir &outdir)
static const char * comment()
static QTextStream & indent(OutputContext &output)
static QString toQuotedString(const QString &text)
static QString getIdForAnimation(const QByteArray &inName)
static QString getMeshFolder()
static void writeImportHeader(OutputContext &output, bool hasAnimation=false)
static QStringList expandComponentsPartially(const QString &value, QMetaType mt)
QPair< QString, QString > writeQmlForAnimation(const QSSGSceneDesc::Animation &anim, qsizetype index, OutputContext &output, bool useBinaryKeyframes=true, bool generateTimelineAnimations=true)
const char * getQmlElementName(const QSSGSceneDesc::Node &node)
static std::pair< QString, QString > copyTextureAsset(const QUrl &texturePath, OutputContext &output)
static std::pair< QString, QString > meshAssetName(const QSSGSceneDesc::Scene &scene, const QSSGSceneDesc::Mesh &meshNode, const QDir &outdir)
static const char * indent()
QString getAnimationSourceName(const QString &id, const QString &property, qsizetype index)
QString getMeshSourceName(const QString &name)
QString variantToQml(const QVariant &variant)
QString stripParentDirectory(const QString &filePath)
QString asString(QSSGSceneDesc::Animation::Channel::TargetProperty prop)
static void writeQmlForResourceNode(const QSSGSceneDesc::Node &node, OutputContext &output)
QString sanitizeQmlSourcePath(const QString &source, bool removeParentDirectory)
QString getTextureSourceName(const QString &name, const QString &fmt)
static void resetIdAllocator()
static QByteArrayView typeName(QMetaType mt)
QUrl urlForFilePath(const QString &path)
void writeQml(const QSSGSceneDesc::Scene &scene, QTextStream &stream, const QDir &outdir, const QJsonObject &optionsObject)
static QString indentString(OutputContext &output)
void writeQml(const QSSGSceneDesc::Material &material, OutputContext &output)
static void writeQmlForNode(const QSSGSceneDesc::Node &node, OutputContext &output)
Combined button and popup list for selecting options.