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
assimpimporter_rt.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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
7
8#include <assimputils.h>
9
10#include <QtCore/qurl.h>
11#include <QtCore/qbytearrayalgorithms.h>
12#include <QtGui/QQuaternion>
13#include <QtQml/QQmlFile>
14
15#include <QtQuick3DAssetImport/private/qssgassetimporterfactory_p.h>
16#include <QtQuick3DAssetImport/private/qssgassetimporter_p.h>
17#include <QtQuick3DAssetUtils/private/qssgscenedesc_p.h>
18#include <QtQuick3DAssetUtils/private/qssgsceneedit_p.h>
19
20#include <QtQuick3DUtils/private/qssgutils_p.h>
21
22// ASSIMP INC
23#include <assimp/Importer.hpp>
24#include <assimp/scene.h>
25#include <assimp/Logger.hpp>
26#include <assimp/DefaultLogger.hpp>
27#include <assimp/postprocess.h>
28#include <assimp/material.h>
29#include <assimp/GltfMaterial.h>
30#include <assimp/importerdesc.h>
31#include <assimp/IOSystem.hpp>
32#include <assimp/IOStream.hpp>
33
34// ASSIMP INC
35
36QT_BEGIN_NAMESPACE
37
38//////////////////////// ASSIMP IMP
39
40#define AI_GLTF_FILTER_NEAREST 0x2600
41#define AI_GLTF_FILTER_LINEAR 0x2601
42#define AI_GLTF_FILTER_NEAREST_MIPMAP_NEAREST 0x2700
43#define AI_GLTF_FILTER_LINEAR_MIPMAP_NEAREST 0x2701
44#define AI_GLTF_FILTER_NEAREST_MIPMAP_LINEAR 0x2702
45#define AI_GLTF_FILTER_LINEAR_MIPMAP_LINEAR 0x2703
46
47Q_REQUIRED_RESULT static inline QColor aiColorToQColor(const aiColor3D &color)
48{
49 return QColor::fromRgbF(color.r, color.g, color.b, 1.0f);
50}
51
52Q_REQUIRED_RESULT static inline QColor aiColorToQColor(const aiColor4D &color)
53{
54 return QColor::fromRgbF(color.r, color.g, color.b, color.a);
55}
56
57static QByteArray fromAiString(const aiString &string)
58{
59 const qsizetype length = string.length;
60 return QByteArray(string.data, length);
61}
62
69
71
72using NodeMap = QHash<const aiNode *, NodeInfo>;
73
74using AnimationNodeMap = QHash<QByteArray, QSSGSceneDesc::Node *>;
75
76[[nodiscard]] static inline bool isEqual(const aiUVTransform &a, const aiUVTransform &b)
77{
78 return (a.mTranslation == b.mTranslation && a.mScaling == b.mScaling && a.mRotation == b.mRotation);
79};
80
82{
83 aiTextureMapMode modes[3] {};
84 aiTextureMapping mapping = aiTextureMapping::aiTextureMapping_UV;
87 uint uvIndex { 0 };
88 aiUVTransform transform;
89};
90
91bool operator==(const TextureInfo &a, const TextureInfo &b)
92{
93 return (a.mapping == b.mapping)
94 && (std::memcmp(a.modes, b.modes, sizeof(a.modes)) == 0)
95 && (a.minFilter == b.minFilter)
96 && (a.magFilter == b.magFilter)
97 && (a.uvIndex == b.uvIndex)
98 && isEqual(a.transform, b.transform);
99}
100
107
108size_t qHash(const TextureEntry &key, size_t seed)
109{
110 static_assert(std::is_same_v<decltype(key.info.transform), aiUVTransform>, "Unexpected type");
111 const auto infoKey = quintptr(key.info.mapping)
112 ^ (quintptr(key.info.modes[0]) ^ quintptr(key.info.modes[1]) ^ quintptr(key.info.modes[2]))
113 ^ quintptr(key.info.minFilter ^ key.info.magFilter)
114 ^ quintptr(key.info.uvIndex)
115 ^ qHashBits(&key.info.transform, sizeof(aiUVTransform), seed);
116
117 return qHash(key.name, seed) ^ infoKey;
118}
119
120bool operator==(const TextureEntry &a, const TextureEntry &b)
121{
122 return (a.name == b.name) && (a.info == b.info);
123}
124
166
167class ResourceIOStream : public Assimp::IOStream
168{
169public:
170 ResourceIOStream(const char *pFile, const char *pMode);
171
172 // IOStream interface
173 size_t Read(void *pvBuffer, size_t pSize, size_t pCount) override;
174 size_t Write(const void *pvBuffer, size_t pSize, size_t pCount) override;
175 aiReturn Seek(size_t pOffset, aiOrigin pOrigin) override;
176 size_t Tell() const override;
177 size_t FileSize() const override;
178 void Flush() override;
179
180private:
181 QFile file;
182};
183
184ResourceIOStream::ResourceIOStream(const char *pFile, const char *pMode) : file(QString::fromStdString(pFile))
185{
186 QByteArray mode = QByteArray(pMode);
187 QFile::OpenMode openMode = QFile::NotOpen;
188 if (mode.startsWith("r"))
189 openMode |= QFile::ReadOnly;
190 else if (mode.startsWith("w"))
191 openMode |= QFile::WriteOnly;
192 if (mode.endsWith("t"))
193 openMode |= QFile::Text;
194 if (!file.open(openMode)) {
195 qWarning("Failed to open file %s: %s",
196 qPrintable(file.fileName()), qPrintable(file.errorString()));
197 }
198}
199
200size_t ResourceIOStream::Read(void *pvBuffer, size_t pSize, size_t pCount)
201{
202 size_t ret = 0;
203 auto buffer = static_cast<char *>(pvBuffer);
204 for (ret = 0; ret < pCount; ret++) {
205 size_t read = file.read(buffer, pSize);
206 if (read != pSize)
207 return ret;
208 buffer += read;
209 }
210 return ret;
211}
212
213size_t ResourceIOStream::Write(const void *pvBuffer, size_t pSize, size_t pCount)
214{
215 Q_UNUSED(pvBuffer);
216 Q_UNUSED(pSize);
217 Q_UNUSED(pCount);
218 Q_UNIMPLEMENTED();
219 return 0;
220}
221
222aiReturn ResourceIOStream::Seek(size_t pOffset, aiOrigin pOrigin)
223{
224 switch (pOrigin) {
225 case aiOrigin_SET:
226 file.seek(pOffset);
227 break;
228 case aiOrigin_CUR:
229 file.seek(file.pos() + pOffset);
230 break;
231 case aiOrigin_END:
232 file.seek(file.size() + pOffset);
233 break;
234 default:
235 return aiReturn_FAILURE;
236 }
237 return aiReturn_SUCCESS;
238}
239
241{
242 return file.pos();
243}
244
246{
247 return file.size();
248}
249
251{
252}
253
254class ResourceIOSystem : public Assimp::IOSystem
255{
256public:
258 // IOSystem interface
259 bool Exists(const char *pFile) const override;
260 char getOsSeparator() const override;
261 Assimp::IOStream *Open(const char *pFile, const char *pMode) override;
262 void Close(Assimp::IOStream *pFile) override;
263};
264
265ResourceIOSystem::ResourceIOSystem() : Assimp::IOSystem() { }
266
267bool ResourceIOSystem::Exists(const char *pFile) const
268{
269 return QFile::exists(QString::fromStdString(pFile));
270}
271
273{
274 return QDir::separator().toLatin1();
275}
276
277Assimp::IOStream *ResourceIOSystem::Open(const char *pFile, const char *pMode)
278{
279 return new ResourceIOStream(pFile, pMode);
280}
281
282void ResourceIOSystem::Close(Assimp::IOStream *pFile)
283{
284 delete pFile;
285}
286
287static void setNodeProperties(QSSGSceneDesc::Node &target,
288 const aiNode &source,
289 const SceneInfo &sceneInfo,
290 aiMatrix4x4 *transformCorrection)
291{
292 // objectName
293 if (target.name.isNull())
294 target.name = fromAiString(source.mName);
295
296 // Apply correction if necessary
297 aiMatrix4x4 transformMatrix;
298 if (transformCorrection)
299 transformMatrix = source.mTransformation * *transformCorrection;
300 else
301 transformMatrix = source.mTransformation;
302
303 // Decompose Transform Matrix to get properties
304 aiVector3D scaling;
305 aiQuaternion rotation;
306 aiVector3D translation;
307 transformMatrix.Decompose(scaling, rotation, translation);
308
309 // translate
310 if (!sceneInfo.opt.designStudioWorkarounds) {
311 QSSGSceneDesc::setProperty(target, "position", &QQuick3DNode::setPosition, QVector3D { translation.x, translation.y, translation.z });
312 } else {
313 QSSGSceneDesc::setProperty(target, "x", &QQuick3DNode::setX, translation.x);
314 QSSGSceneDesc::setProperty(target, "y", &QQuick3DNode::setY, translation.y);
315 QSSGSceneDesc::setProperty(target, "z", &QQuick3DNode::setZ, translation.z);
316 }
317
318
319 // rotation
320 const QQuaternion rot(rotation.w, rotation.x, rotation.y, rotation.z);
321 QSSGSceneDesc::setProperty(target, "rotation", &QQuick3DNode::setRotation, rot);
322
323 // scale
324 QSSGSceneDesc::setProperty(target, "scale", &QQuick3DNode::setScale, QVector3D { scaling.x, scaling.y, scaling.z });
325 // pivot
326
327 // opacity
328
329 // visible
330}
331
332static void setTextureProperties(QSSGSceneDesc::Texture &target, const TextureInfo &texInfo, const SceneInfo &sceneInfo)
333{
334 const bool forceMipMapGeneration = sceneInfo.opt.forceMipMapGeneration;
335
336 if (texInfo.uvIndex > 0) {
337 // Quick3D supports 2 tex coords.
338 // According to gltf's khronos default implementation,
339 // the index will be selected to the nearest one.
340 QSSGSceneDesc::setProperty(target, "indexUV", &QQuick3DTexture::setIndexUV, 1);
341 }
342
343 // mapping
344 if (texInfo.mapping == aiTextureMapping_UV) {
345 // So we should be able to always hit this case by passing the right flags
346 // at import.
347 QSSGSceneDesc::setProperty(target, "mappingMode", &QQuick3DTexture::setMappingMode, QQuick3DTexture::MappingMode::UV);
348 // It would be possible to use another channel than UV0 to map texture data
349 // but for now we force everything to use UV0
350 //int uvSource;
351 //material->Get(AI_MATKEY_UVWSRC(textureType, index), uvSource);
352 } // else (not supported)
353
354 static const auto asQtTilingMode = [](aiTextureMapMode mode) {
355 switch (mode) {
356 case aiTextureMapMode_Wrap:
357 return QQuick3DTexture::TilingMode::Repeat;
358 case aiTextureMapMode_Clamp:
359 return QQuick3DTexture::TilingMode::ClampToEdge;
360 case aiTextureMapMode_Mirror:
361 return QQuick3DTexture::TilingMode::MirroredRepeat;
362 default:
363 break;
364 }
365
366 return QQuick3DTexture::TilingMode::Repeat;
367 };
368
369 // mapping mode U
370 QSSGSceneDesc::setProperty(target, "tilingModeHorizontal", &QQuick3DTexture::setHorizontalTiling, asQtTilingMode(texInfo.modes[0]));
371
372 // mapping mode V
373 QSSGSceneDesc::setProperty(target, "tilingModeVertical", &QQuick3DTexture::setVerticalTiling, asQtTilingMode(texInfo.modes[1]));
374
375 const bool applyUvTransform = !isEqual(texInfo.transform, aiUVTransform());
376 if (applyUvTransform) {
377 // UV origins -
378 // glTF: 0, 1 (top left of texture)
379 // Assimp, Collada?, FBX?: 0.5, 0.5
380 // Quick3D: 0, 0 (bottom left of texture)
381 // Assimp already tries to fix it but it's not correct.
382 // So, we restore original values and then use pivot
383 const auto &transform = texInfo.transform;
384 float rotation = -transform.mRotation;
385 float rotationUV = qRadiansToDegrees(rotation);
386 float posU = transform.mTranslation.x;
387 float posV = transform.mTranslation.y;
388 if (sceneInfo.opt.gltfMode) {
389 const float rcos = std::cos(rotation);
390 const float rsin = std::sin(rotation);
391 posU -= 0.5f * transform.mScaling.x * (-rcos + rsin + 1.0f);
392 posV -= (0.5f * transform.mScaling.y * (rcos + rsin - 1.0f) + 1.0f - transform.mScaling.y);
393 QSSGSceneDesc::setProperty(target, "pivotV", &QQuick3DTexture::setPivotV, 1.0f);
394 } else {
395 QSSGSceneDesc::setProperty(target, "pivotU", &QQuick3DTexture::setPivotV, 0.5f);
396 QSSGSceneDesc::setProperty(target, "pivotV", &QQuick3DTexture::setPivotV, 0.5f);
397 }
398
399 QSSGSceneDesc::setProperty(target, "positionU", &QQuick3DTexture::setPositionU, posU);
400 QSSGSceneDesc::setProperty(target, "positionV", &QQuick3DTexture::setPositionV, posV);
401 QSSGSceneDesc::setProperty(target, "rotationUV", &QQuick3DTexture::setRotationUV, rotationUV);
402 QSSGSceneDesc::setProperty(target, "scaleU", &QQuick3DTexture::setScaleU, transform.mScaling.x);
403 QSSGSceneDesc::setProperty(target, "scaleV", &QQuick3DTexture::setScaleV, transform.mScaling.y);
404 }
405 // We don't make use of the data here, but there are additional flags
406 // available for example the usage of the alpha channel
407 // texture flags
408 //int textureFlags;
409 //material->Get(AI_MATKEY_TEXFLAGS(textureType, index), textureFlags);
410
411 // Always generate and use mipmaps for imported assets
412 bool generateMipMaps = forceMipMapGeneration;
413 auto mipFilter = forceMipMapGeneration ? QQuick3DTexture::Filter::Linear : QQuick3DTexture::Filter::None;
414
415 // magFilter
416 auto filter = (texInfo.magFilter == AI_GLTF_FILTER_NEAREST) ? QQuick3DTexture::Filter::Nearest : QQuick3DTexture::Filter::Linear;
417 QSSGSceneDesc::setProperty(target, "magFilter", &QQuick3DTexture::setMagFilter, filter);
418
419 // minFilter
420 if (texInfo.minFilter == AI_GLTF_FILTER_NEAREST) {
421 filter = QQuick3DTexture::Filter::Nearest;
422 } else if (texInfo.minFilter == AI_GLTF_FILTER_LINEAR) {
423 filter = QQuick3DTexture::Filter::Linear;
425 filter = QQuick3DTexture::Filter::Nearest;
426 mipFilter = QQuick3DTexture::Filter::Nearest;
428 filter = QQuick3DTexture::Filter::Linear;
429 mipFilter = QQuick3DTexture::Filter::Nearest;
431 filter = QQuick3DTexture::Filter::Nearest;
432 mipFilter = QQuick3DTexture::Filter::Linear;
433 } else if (texInfo.minFilter == AI_GLTF_FILTER_LINEAR_MIPMAP_LINEAR) {
434 filter = QQuick3DTexture::Filter::Linear;
435 mipFilter = QQuick3DTexture::Filter::Linear;
436 }
437 QSSGSceneDesc::setProperty(target, "minFilter", &QQuick3DTexture::setMinFilter, filter);
438
439 // mipFilter
440 generateMipMaps = (mipFilter != QQuick3DTexture::Filter::None);
441
442 if (generateMipMaps) {
443 QSSGSceneDesc::setProperty(target, "generateMipmaps", &QQuick3DTexture::setGenerateMipmaps, true);
444 QSSGSceneDesc::setProperty(target, "mipFilter", &QQuick3DTexture::setMipFilter, mipFilter);
445 }
446}
447
448static void setMaterialProperties(QSSGSceneDesc::Material &target, const aiMaterial &source, const SceneInfo &sceneInfo, QSSGSceneDesc::Material::RuntimeType type)
449{
450 if (target.name.isNull()) {
451 aiString materialName = source.GetName();
452 target.name = fromAiString(materialName);
453 }
454
455 const auto createTextureNode = [&sceneInfo, &target](const aiMaterial &material, aiTextureType textureType, unsigned int index) {
456 const auto &srcScene = sceneInfo.scene;
457 QSSGSceneDesc::Texture *tex = nullptr;
458 aiString texturePath;
459 TextureInfo texInfo;
460
461 if (material.GetTexture(textureType, index, &texturePath, &texInfo.mapping, &texInfo.uvIndex, nullptr, nullptr, texInfo.modes) == aiReturn_SUCCESS) {
462 if (texturePath.length > 0) {
463 aiUVTransform transform;
464 if (material.Get(AI_MATKEY_UVTRANSFORM(textureType, index), transform) == aiReturn_SUCCESS)
465 texInfo.transform = transform;
466
467 material.Get(AI_MATKEY_UVWSRC(textureType, index), texInfo.uvIndex);
468 material.Get(AI_MATKEY_GLTF_MAPPINGFILTER_MIN(textureType, index), texInfo.minFilter);
469 material.Get(AI_MATKEY_GLTF_MAPPINGFILTER_MAG(textureType, index), texInfo.magFilter);
470
471 auto &textureMap = sceneInfo.textureMap;
472
473 QByteArray texName = QByteArray(texturePath.C_Str(), texturePath.length);
474 // Check if we already processed this texture
475 const auto it = textureMap.constFind(TextureEntry{texName, texInfo});
476 if (it != textureMap.cend()) {
477 Q_ASSERT(it->texture);
478 tex = it->texture;
479 } else {
480 // Two types, externally referenced or embedded
481 // Use the source file name as the identifier, since that will hopefully be fairly stable for re-import.
482 tex = new QSSGSceneDesc::Texture(QSSGSceneDesc::Texture::RuntimeType::Image2D, texName);
483 textureMap.insert(TextureEntry{fromAiString(texturePath), texInfo, tex});
484 QSSGSceneDesc::addNode(target, *tex);
485 setTextureProperties(*tex, texInfo, sceneInfo); // both
486
487 auto aEmbeddedTex = srcScene.GetEmbeddedTextureAndIndex(texturePath.C_Str());
488 const auto &embeddedTexId = aEmbeddedTex.second;
489 if (embeddedTexId > -1) {
490 QSSGSceneDesc::TextureData *textureData = nullptr;
491 auto &embeddedTextures = sceneInfo.embeddedTextureMap;
492 textureData = embeddedTextures[embeddedTexId];
493 if (!textureData) {
494 const auto *sourceTexture = aEmbeddedTex.first;
495 Q_ASSERT(sourceTexture->pcData);
496 // Two cases of embedded textures, uncompress and compressed.
497 const bool isCompressed = (sourceTexture->mHeight == 0);
498
499 // For compressed textures this is the size of the image buffer (in bytes)
500 const qsizetype asize = (isCompressed) ? sourceTexture->mWidth : (sourceTexture->mHeight * sourceTexture->mWidth) * sizeof(aiTexel);
501 const QSize size = (!isCompressed) ? QSize(int(sourceTexture->mWidth), int(sourceTexture->mHeight)) : QSize();
502 QByteArray imageData { reinterpret_cast<const char *>(sourceTexture->pcData), asize };
503 const auto format = (isCompressed) ? QByteArray(sourceTexture->achFormatHint) : QByteArrayLiteral("rgba8888");
504 const quint8 flags = isCompressed ? quint8(QSSGSceneDesc::TextureData::Flags::Compressed) : 0;
505 textureData = new QSSGSceneDesc::TextureData(imageData, size, format, flags);
506 QSSGSceneDesc::addNode(*tex, *textureData);
507 embeddedTextures[embeddedTexId] = textureData;
508 }
509
510 if (textureData)
511 QSSGSceneDesc::setProperty(*tex, "textureData", &QQuick3DTexture::setTextureData, textureData);
512 } else {
513 auto relativePath = QString::fromUtf8(texturePath.C_Str());
514 // Replace Windows separator to Unix separator
515 // so that assets including Windows relative path can be converted on Unix.
516 relativePath.replace("\\","/");
517 const auto path = sceneInfo.workingDir.absoluteFilePath(relativePath);
518 QSSGSceneDesc::setProperty(*tex, "source", &QQuick3DTexture::setSource, QUrl{ path });
519 }
520 }
521 }
522 }
523
524 return tex;
525 };
526
527 aiReturn result;
528
529 if (type == QSSGSceneDesc::Material::RuntimeType::PrincipledMaterial) {
530 {
531 aiColor4D baseColorFactor;
532 result = source.Get(AI_MATKEY_BASE_COLOR, baseColorFactor);
533 if (result == aiReturn_SUCCESS) {
534 // Some special handling required since baseColorFactor's are stored as linear factors and need to be converted for Qt Quick
535 const QColor sRGBBaseColorFactor = QSSGUtils::color::linearTosRGB(QVector4D(baseColorFactor.r, baseColorFactor.g, baseColorFactor.b, baseColorFactor.a));
536 QSSGSceneDesc::setProperty(target, "baseColor", &QQuick3DPrincipledMaterial::setBaseColor, sRGBBaseColorFactor);
537 } else {
538 // Also try diffuse color as a fallback
539 aiColor3D diffuseColor;
540 result = source.Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor);
541 if (result == aiReturn_SUCCESS)
542 QSSGSceneDesc::setProperty(target, "baseColor", &QQuick3DPrincipledMaterial::setBaseColor, aiColorToQColor(diffuseColor));
543 }
544 }
545
546 if (auto baseColorTexture = createTextureNode(source, AI_MATKEY_BASE_COLOR_TEXTURE)) {
547 QSSGSceneDesc::setProperty(target, "baseColorMap", &QQuick3DPrincipledMaterial::setBaseColorMap, baseColorTexture);
548 QSSGSceneDesc::setProperty(target, "opacityChannel", &QQuick3DPrincipledMaterial::setOpacityChannel, QQuick3DPrincipledMaterial::TextureChannelMapping::A);
549 } else if (auto diffuseMapTexture = createTextureNode(source, aiTextureType_DIFFUSE, 0)) {
550 // Also try to legacy diffuse texture as an alternative
551 QSSGSceneDesc::setProperty(target, "baseColorMap", &QQuick3DPrincipledMaterial::setBaseColorMap, diffuseMapTexture);
552 }
553
554 if (auto metalicRoughnessTexture = createTextureNode(source, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE)) {
555 QSSGSceneDesc::setProperty(target, "metalnessMap", &QQuick3DPrincipledMaterial::setMetalnessMap, metalicRoughnessTexture);
556 QSSGSceneDesc::setProperty(target, "metalnessChannel", &QQuick3DPrincipledMaterial::setMetalnessChannel, QQuick3DPrincipledMaterial::TextureChannelMapping::B);
557 QSSGSceneDesc::setProperty(target, "roughnessMap", &QQuick3DPrincipledMaterial::setRoughnessMap, metalicRoughnessTexture);
558 QSSGSceneDesc::setProperty(target, "roughnessChannel", &QQuick3DPrincipledMaterial::setRoughnessChannel, QQuick3DPrincipledMaterial::TextureChannelMapping::G);
559 }
560
561 {
562 ai_real metallicFactor;
563 result = source.Get(AI_MATKEY_METALLIC_FACTOR, metallicFactor);
564 if (result == aiReturn_SUCCESS)
565 QSSGSceneDesc::setProperty(target, "metalness", &QQuick3DPrincipledMaterial::setMetalness, float(metallicFactor));
566 }
567
568 {
569 ai_real roughnessFactor;
570 result = source.Get(AI_MATKEY_ROUGHNESS_FACTOR, roughnessFactor);
571 if (result == aiReturn_SUCCESS)
572 QSSGSceneDesc::setProperty(target, "roughness", &QQuick3DPrincipledMaterial::setRoughness, float(roughnessFactor));
573 }
574
575 if (auto normalTexture = createTextureNode(source, aiTextureType_NORMALS, 0)) {
576 QSSGSceneDesc::setProperty(target, "normalMap", &QQuick3DPrincipledMaterial::setNormalMap, normalTexture);
577 {
578 ai_real normalScale;
579 result = source.Get(AI_MATKEY_GLTF_TEXTURE_SCALE(aiTextureType_NORMALS, 0), normalScale);
580 if (result == aiReturn_SUCCESS)
581 QSSGSceneDesc::setProperty(target, "normalStrength", &QQuick3DPrincipledMaterial::setNormalStrength, float(normalScale));
582 }
583 }
584
585 // Occlusion Textures are not implimented (yet)
586 if (auto occlusionTexture = createTextureNode(source, aiTextureType_LIGHTMAP, 0)) {
587 QSSGSceneDesc::setProperty(target, "occlusionMap", &QQuick3DPrincipledMaterial::setOcclusionMap, occlusionTexture);
588 QSSGSceneDesc::setProperty(target, "occlusionChannel", &QQuick3DPrincipledMaterial::setOcclusionChannel, QQuick3DPrincipledMaterial::TextureChannelMapping::R);
589 {
590 ai_real occlusionAmount;
591 result = source.Get(AI_MATKEY_GLTF_TEXTURE_STRENGTH(aiTextureType_LIGHTMAP, 0), occlusionAmount);
592 if (result == aiReturn_SUCCESS)
593 QSSGSceneDesc::setProperty(target, "occlusionAmount", &QQuick3DPrincipledMaterial::setOcclusionAmount, float(occlusionAmount));
594 }
595 }
596
597 if (auto emissiveTexture = createTextureNode(source, aiTextureType_EMISSIVE, 0))
598 QSSGSceneDesc::setProperty(target, "emissiveMap", &QQuick3DPrincipledMaterial::setEmissiveMap, emissiveTexture);
599
600 {
601 aiColor3D emissiveColorFactor;
602 result = source.Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColorFactor);
603 if (result == aiReturn_SUCCESS)
604 QSSGSceneDesc::setProperty(target, "emissiveFactor", &QQuick3DPrincipledMaterial::setEmissiveFactor, QVector3D { emissiveColorFactor.r, emissiveColorFactor.g, emissiveColorFactor.b });
605 }
606
607 {
608 bool isDoubleSided;
609 result = source.Get(AI_MATKEY_TWOSIDED, isDoubleSided);
610 if (result == aiReturn_SUCCESS && isDoubleSided)
611 QSSGSceneDesc::setProperty(target, "cullMode", &QQuick3DPrincipledMaterial::setCullMode, QQuick3DPrincipledMaterial::CullMode::NoCulling);
612 }
613
614 {
615 aiString alphaMode;
616 result = source.Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode);
617 if (result == aiReturn_SUCCESS) {
618 auto mode = QQuick3DPrincipledMaterial::AlphaMode::Default;
619 if (QByteArrayView(alphaMode.C_Str()) == "OPAQUE")
620 mode = QQuick3DPrincipledMaterial::AlphaMode::Opaque;
621 else if (QByteArrayView(alphaMode.C_Str()) == "MASK")
622 mode = QQuick3DPrincipledMaterial::AlphaMode::Mask;
623 else if (QByteArrayView(alphaMode.C_Str()) == "BLEND")
624 mode = QQuick3DPrincipledMaterial::AlphaMode::Blend;
625
626 if (mode != QQuick3DPrincipledMaterial::AlphaMode::Default) {
627 QSSGSceneDesc::setProperty(target, "alphaMode", &QQuick3DPrincipledMaterial::setAlphaMode, mode);
628 // If the mode is mask, we also need to force OpaquePrePassDepthDraw mode
629 if (mode == QQuick3DPrincipledMaterial::AlphaMode::Mask)
630 QSSGSceneDesc::setProperty(target, "depthDrawMode", &QQuick3DPrincipledMaterial::setDepthDrawMode, QQuick3DMaterial::OpaquePrePassDepthDraw);
631 }
632 }
633 }
634
635 {
636 ai_real alphaCutoff;
637 result = source.Get(AI_MATKEY_GLTF_ALPHACUTOFF, alphaCutoff);
638 if (result == aiReturn_SUCCESS)
639 QSSGSceneDesc::setProperty(target, "alphaCutoff", &QQuick3DPrincipledMaterial::setAlphaCutoff, float(alphaCutoff));
640 }
641
642 {
643 int shadingModel = 0;
644 result = source.Get(AI_MATKEY_SHADING_MODEL, shadingModel);
645 if (result == aiReturn_SUCCESS && shadingModel == aiShadingMode_Unlit)
646 QSSGSceneDesc::setProperty(target, "lighting", &QQuick3DPrincipledMaterial::setLighting, QQuick3DPrincipledMaterial::Lighting::NoLighting);
647 }
648
649
650 {
651 // Clearcoat Properties (KHR_materials_clearcoat)
652 // factor
653 {
654 ai_real clearcoatFactor = 0.0f;
655 result = source.Get(AI_MATKEY_CLEARCOAT_FACTOR, clearcoatFactor);
656 if (result == aiReturn_SUCCESS)
657 QSSGSceneDesc::setProperty(target,
658 "clearcoatAmount",
659 &QQuick3DPrincipledMaterial::setClearcoatAmount,
660 float(clearcoatFactor));
661 }
662
663 // roughness
664 {
665 ai_real clearcoatRoughnessFactor = 0.0f;
666 result = source.Get(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR, clearcoatRoughnessFactor);
667 if (result == aiReturn_SUCCESS)
668 QSSGSceneDesc::setProperty(target,
669 "clearcoatRoughnessAmount",
670 &QQuick3DPrincipledMaterial::setClearcoatRoughnessAmount,
671 float(clearcoatRoughnessFactor));
672 }
673
674 // texture
675 if (auto clearcoatTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_TEXTURE))
676 QSSGSceneDesc::setProperty(target, "clearcoatMap", &QQuick3DPrincipledMaterial::setClearcoatMap, clearcoatTexture);
677
678 // roughness texture
679 if (auto clearcoatRoughnessTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE))
680 QSSGSceneDesc::setProperty(target,
681 "clearcoatRoughnessMap",
682 &QQuick3DPrincipledMaterial::setClearcoatRoughnessMap,
683 clearcoatRoughnessTexture);
684
685 // normal texture
686 if (auto clearcoatNormalTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE))
687 QSSGSceneDesc::setProperty(target, "clearcoatNormalMap", &QQuick3DPrincipledMaterial::setClearcoatNormalMap, clearcoatNormalTexture);
688 }
689
690 {
691 // Transmission Properties (KHR_materials_transmission)
692 // factor
693 {
694 ai_real transmissionFactor = 0.0f;
695 result = source.Get(AI_MATKEY_TRANSMISSION_FACTOR, transmissionFactor);
696 if (result == aiReturn_SUCCESS)
697 QSSGSceneDesc::setProperty(target,
698 "transmissionFactor",
699 &QQuick3DPrincipledMaterial::setTransmissionFactor,
700 float(transmissionFactor));
701 }
702
703 // texture
704 {
705 if (auto transmissionImage = createTextureNode(source, AI_MATKEY_TRANSMISSION_TEXTURE))
706 QSSGSceneDesc::setProperty(target,
707 "transmissionMap",
708 &QQuick3DPrincipledMaterial::setTransmissionMap,
709 transmissionImage);
710 }
711
712 }
713
714 {
715 // Volume Properties (KHR_materials_volume) [only used with transmission]
716 // thicknessFactor
717 {
718 ai_real thicknessFactor = 0.0f;
719 result = source.Get(AI_MATKEY_VOLUME_THICKNESS_FACTOR, thicknessFactor);
720 if (result == aiReturn_SUCCESS)
721 QSSGSceneDesc::setProperty(target, "thicknessFactor", &QQuick3DPrincipledMaterial::setThicknessFactor, float(thicknessFactor));
722 }
723
724 // thicknessMap
725 {
726 if (auto thicknessImage = createTextureNode(source, AI_MATKEY_VOLUME_THICKNESS_TEXTURE))
727 QSSGSceneDesc::setProperty(target, "thicknessMap", &QQuick3DPrincipledMaterial::setThicknessMap, thicknessImage);
728 }
729
730 // attenuationDistance
731 {
732 ai_real attenuationDistance = 0.0f;
733 result = source.Get(AI_MATKEY_VOLUME_ATTENUATION_DISTANCE, attenuationDistance);
734 if (result == aiReturn_SUCCESS)
735 QSSGSceneDesc::setProperty(target,
736 "attenuationDistance",
737 &QQuick3DPrincipledMaterial::setAttenuationDistance,
738 float(attenuationDistance));
739 }
740
741 // attenuationColor
742 {
743 aiColor3D attenuationColor;
744 result = source.Get(AI_MATKEY_VOLUME_ATTENUATION_COLOR, attenuationColor);
745 if (result == aiReturn_SUCCESS)
746 QSSGSceneDesc::setProperty(target,
747 "attenuationColor",
748 &QQuick3DPrincipledMaterial::setAttenuationColor,
749 aiColorToQColor(attenuationColor));
750 }
751 }
752
753
754 // KHR_materials_ior
755 {
756 ai_real ior = 0.0f;
757 result = source.Get(AI_MATKEY_REFRACTI, ior);
758 if (result == aiReturn_SUCCESS)
759 QSSGSceneDesc::setProperty(target,
760 "indexOfRefraction",
761 &QQuick3DPrincipledMaterial::setIndexOfRefraction,
762 float(ior));
763 }
764
765 } else if (type == QSSGSceneDesc::Material::RuntimeType::DefaultMaterial) { // Ver1
766 int shadingModel = 0;
767 auto material = &source;
768 result = material->Get(AI_MATKEY_SHADING_MODEL, shadingModel);
769 // lighting
770 if (result == aiReturn_SUCCESS && (shadingModel == aiShadingMode_NoShading))
771 QSSGSceneDesc::setProperty(target, "lighting", &QQuick3DDefaultMaterial::setLighting, QQuick3DDefaultMaterial::Lighting::NoLighting);
772
773 if (auto diffuseMapTexture = createTextureNode(source, aiTextureType_DIFFUSE, 0)) {
774 QSSGSceneDesc::setProperty(target, "diffuseMap", &QQuick3DDefaultMaterial::setDiffuseMap, diffuseMapTexture);
775 } else {
776 // For some reason the normal behavior is that either you have a diffuseMap[s] or a diffuse color
777 // but no a mix of both... So only set the diffuse color if none of the diffuse maps are set:
778 aiColor3D diffuseColor;
779 result = material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor);
780 if (result == aiReturn_SUCCESS)
781 QSSGSceneDesc::setProperty(target, "diffuseColor", &QQuick3DDefaultMaterial::setDiffuseColor, aiColorToQColor(diffuseColor));
782 }
783
784 if (auto emissiveTexture = createTextureNode(source, aiTextureType_EMISSIVE, 0))
785 QSSGSceneDesc::setProperty(target, "emissiveMap", &QQuick3DDefaultMaterial::setEmissiveMap, emissiveTexture);
786
787 // specularReflectionMap
788 if (auto specularTexture = createTextureNode(source, aiTextureType_SPECULAR, 0))
789 QSSGSceneDesc::setProperty(target, "specularMap", &QQuick3DDefaultMaterial::setSpecularMap, specularTexture);
790
791 // opacity AI_MATKEY_OPACITY
792 ai_real opacity;
793 result = material->Get(AI_MATKEY_OPACITY, opacity);
794 if (result == aiReturn_SUCCESS)
795 QSSGSceneDesc::setProperty(target, "opacity", &QQuick3DDefaultMaterial::setOpacity, float(opacity));
796
797 // opacityMap aiTextureType_OPACITY 0
798 if (auto opacityTexture = createTextureNode(source, aiTextureType_OPACITY, 0))
799 QSSGSceneDesc::setProperty(target, "opacityMap", &QQuick3DDefaultMaterial::setOpacityMap, opacityTexture);
800
801 // bumpMap aiTextureType_HEIGHT 0
802 if (auto bumpTexture = createTextureNode(source, aiTextureType_HEIGHT, 0)) {
803 QSSGSceneDesc::setProperty(target, "bumpMap", &QQuick3DDefaultMaterial::setBumpMap, bumpTexture);
804 // bumpAmount AI_MATKEY_BUMPSCALING
805 ai_real bumpAmount;
806 result = material->Get(AI_MATKEY_BUMPSCALING, bumpAmount);
807 if (result == aiReturn_SUCCESS)
808 QSSGSceneDesc::setProperty(target, "bumpAmount", &QQuick3DDefaultMaterial::setBumpAmount, float(bumpAmount));
809 }
810
811 // normalMap aiTextureType_NORMALS 0
812 if (auto normalTexture = createTextureNode(source, aiTextureType_NORMALS, 0))
813 QSSGSceneDesc::setProperty(target, "normalMap", &QQuick3DDefaultMaterial::setNormalMap, normalTexture);
814 } else if (type == QSSGSceneDesc::Material::RuntimeType::SpecularGlossyMaterial) {
815 {
816 aiColor4D albedoFactor;
817 result = source.Get(AI_MATKEY_COLOR_DIFFUSE, albedoFactor);
818 if (result == aiReturn_SUCCESS)
819 QSSGSceneDesc::setProperty(target, "albedoColor", &QQuick3DSpecularGlossyMaterial::setAlbedoColor, aiColorToQColor(albedoFactor));
820 }
821
822 if (auto albedoTexture = createTextureNode(source, aiTextureType_DIFFUSE, 0)) {
823 QSSGSceneDesc::setProperty(target, "albedoMap", &QQuick3DSpecularGlossyMaterial::setAlbedoMap, albedoTexture);
824 QSSGSceneDesc::setProperty(target, "opacityChannel", &QQuick3DSpecularGlossyMaterial::setOpacityChannel, QQuick3DSpecularGlossyMaterial::TextureChannelMapping::A);
825 }
826
827 if (auto specularGlossinessTexture = createTextureNode(source, aiTextureType_SPECULAR, 0)) {
828 QSSGSceneDesc::setProperty(target, "specularMap", &QQuick3DSpecularGlossyMaterial::setSpecularMap, specularGlossinessTexture);
829 QSSGSceneDesc::setProperty(target, "glossinessMap", &QQuick3DSpecularGlossyMaterial::setGlossinessMap, specularGlossinessTexture);
830 QSSGSceneDesc::setProperty(target, "glossinessChannel", &QQuick3DSpecularGlossyMaterial::setGlossinessChannel, QQuick3DSpecularGlossyMaterial::TextureChannelMapping::A);
831 }
832
833 {
834 aiColor4D specularColorFactor;
835 result = source.Get(AI_MATKEY_COLOR_SPECULAR, specularColorFactor);
836 if (result == aiReturn_SUCCESS)
837 QSSGSceneDesc::setProperty(target, "specularColor", &QQuick3DSpecularGlossyMaterial::setSpecularColor, aiColorToQColor(specularColorFactor));
838 }
839
840 {
841 ai_real glossinessFactor;
842 result = source.Get(AI_MATKEY_GLOSSINESS_FACTOR, glossinessFactor);
843 if (result == aiReturn_SUCCESS)
844 QSSGSceneDesc::setProperty(target, "glossiness", &QQuick3DSpecularGlossyMaterial::setGlossiness, float(glossinessFactor));
845 }
846
847 if (auto normalTexture = createTextureNode(source, aiTextureType_NORMALS, 0)) {
848 QSSGSceneDesc::setProperty(target, "normalMap", &QQuick3DSpecularGlossyMaterial::setNormalMap, normalTexture);
849 {
850 ai_real normalScale;
851 result = source.Get(AI_MATKEY_GLTF_TEXTURE_SCALE(aiTextureType_NORMALS, 0), normalScale);
852 if (result == aiReturn_SUCCESS)
853 QSSGSceneDesc::setProperty(target, "normalStrength", &QQuick3DSpecularGlossyMaterial::setNormalStrength, float(normalScale));
854 }
855 }
856
857 // Occlusion Textures are not implimented (yet)
858 if (auto occlusionTexture = createTextureNode(source, aiTextureType_LIGHTMAP, 0)) {
859 QSSGSceneDesc::setProperty(target, "occlusionMap", &QQuick3DSpecularGlossyMaterial::setOcclusionMap, occlusionTexture);
860 QSSGSceneDesc::setProperty(target, "occlusionChannel", &QQuick3DSpecularGlossyMaterial::setOcclusionChannel, QQuick3DSpecularGlossyMaterial::TextureChannelMapping::R);
861 {
862 ai_real occlusionAmount;
863 result = source.Get(AI_MATKEY_GLTF_TEXTURE_STRENGTH(aiTextureType_LIGHTMAP, 0), occlusionAmount);
864 if (result == aiReturn_SUCCESS)
865 QSSGSceneDesc::setProperty(target, "occlusionAmount", &QQuick3DSpecularGlossyMaterial::setOcclusionAmount, float(occlusionAmount));
866 }
867 }
868
869 if (auto emissiveTexture = createTextureNode(source, aiTextureType_EMISSIVE, 0))
870 QSSGSceneDesc::setProperty(target, "emissiveMap", &QQuick3DSpecularGlossyMaterial::setEmissiveMap, emissiveTexture);
871
872 {
873 aiColor3D emissiveColorFactor;
874 result = source.Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColorFactor);
875 if (result == aiReturn_SUCCESS)
876 QSSGSceneDesc::setProperty(target, "emissiveFactor", &QQuick3DSpecularGlossyMaterial::setEmissiveFactor, QVector3D { emissiveColorFactor.r, emissiveColorFactor.g, emissiveColorFactor.b });
877 }
878
879 {
880 bool isDoubleSided;
881 result = source.Get(AI_MATKEY_TWOSIDED, isDoubleSided);
882 if (result == aiReturn_SUCCESS && isDoubleSided)
883 QSSGSceneDesc::setProperty(target, "cullMode", &QQuick3DSpecularGlossyMaterial::setCullMode, QQuick3DSpecularGlossyMaterial::CullMode::NoCulling);
884 }
885
886 {
887 aiString alphaMode;
888 result = source.Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode);
889 if (result == aiReturn_SUCCESS) {
890 auto mode = QQuick3DSpecularGlossyMaterial::AlphaMode::Default;
891 if (QByteArrayView(alphaMode.C_Str()) == "OPAQUE")
892 mode = QQuick3DSpecularGlossyMaterial::AlphaMode::Opaque;
893 else if (QByteArrayView(alphaMode.C_Str()) == "MASK")
894 mode = QQuick3DSpecularGlossyMaterial::AlphaMode::Mask;
895 else if (QByteArrayView(alphaMode.C_Str()) == "BLEND")
896 mode = QQuick3DSpecularGlossyMaterial::AlphaMode::Blend;
897
898 if (mode != QQuick3DSpecularGlossyMaterial::AlphaMode::Default) {
899 QSSGSceneDesc::setProperty(target, "alphaMode", &QQuick3DSpecularGlossyMaterial::setAlphaMode, mode);
900 // If the mode is mask, we also need to force OpaquePrePassDepthDraw mode
901 if (mode == QQuick3DSpecularGlossyMaterial::AlphaMode::Mask)
902 QSSGSceneDesc::setProperty(target, "depthDrawMode", &QQuick3DSpecularGlossyMaterial::setDepthDrawMode, QQuick3DMaterial::OpaquePrePassDepthDraw);
903 }
904 }
905 }
906
907 {
908 ai_real alphaCutoff;
909 result = source.Get(AI_MATKEY_GLTF_ALPHACUTOFF, alphaCutoff);
910 if (result == aiReturn_SUCCESS)
911 QSSGSceneDesc::setProperty(target, "alphaCutoff", &QQuick3DSpecularGlossyMaterial::setAlphaCutoff, float(alphaCutoff));
912 }
913
914 {
915 int shadingModel = 0;
916 result = source.Get(AI_MATKEY_SHADING_MODEL, shadingModel);
917 if (result == aiReturn_SUCCESS && shadingModel == aiShadingMode_Unlit)
918 QSSGSceneDesc::setProperty(target, "lighting", &QQuick3DSpecularGlossyMaterial::setLighting, QQuick3DSpecularGlossyMaterial::Lighting::NoLighting);
919 }
920
921
922 {
923 // Clearcoat Properties (KHR_materials_clearcoat)
924 // factor
925 {
926 ai_real clearcoatFactor = 0.0f;
927 result = source.Get(AI_MATKEY_CLEARCOAT_FACTOR, clearcoatFactor);
928 if (result == aiReturn_SUCCESS)
929 QSSGSceneDesc::setProperty(target,
930 "clearcoatAmount",
931 &QQuick3DSpecularGlossyMaterial::setClearcoatAmount,
932 float(clearcoatFactor));
933 }
934
935 // roughness
936 {
937 ai_real clearcoatRoughnessFactor = 0.0f;
938 result = source.Get(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR, clearcoatRoughnessFactor);
939 if (result == aiReturn_SUCCESS)
940 QSSGSceneDesc::setProperty(target,
941 "clearcoatRoughnessAmount",
942 &QQuick3DSpecularGlossyMaterial::setClearcoatRoughnessAmount,
943 float(clearcoatRoughnessFactor));
944 }
945
946 // texture
947 if (auto clearcoatTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_TEXTURE))
948 QSSGSceneDesc::setProperty(target, "clearcoatMap", &QQuick3DSpecularGlossyMaterial::setClearcoatMap, clearcoatTexture);
949
950 // roughness texture
951 if (auto clearcoatRoughnessTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE))
952 QSSGSceneDesc::setProperty(target,
953 "clearcoatRoughnessMap",
954 &QQuick3DSpecularGlossyMaterial::setClearcoatRoughnessMap,
955 clearcoatRoughnessTexture);
956
957 // normal texture
958 if (auto clearcoatNormalTexture = createTextureNode(source, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE))
959 QSSGSceneDesc::setProperty(target, "clearcoatNormalMap", &QQuick3DSpecularGlossyMaterial::setClearcoatNormalMap, clearcoatNormalTexture);
960 }
961
962 {
963 // Transmission Properties (KHR_materials_transmission)
964 // factor
965 {
966 ai_real transmissionFactor = 0.0f;
967 result = source.Get(AI_MATKEY_TRANSMISSION_FACTOR, transmissionFactor);
968 if (result == aiReturn_SUCCESS)
969 QSSGSceneDesc::setProperty(target,
970 "transmissionFactor",
971 &QQuick3DSpecularGlossyMaterial::setTransmissionFactor,
972 float(transmissionFactor));
973 }
974
975 // texture
976 {
977 if (auto transmissionImage = createTextureNode(source, AI_MATKEY_TRANSMISSION_TEXTURE))
978 QSSGSceneDesc::setProperty(target,
979 "transmissionMap",
980 &QQuick3DSpecularGlossyMaterial::setTransmissionMap,
981 transmissionImage);
982 }
983
984 }
985
986 {
987 // Volume Properties (KHR_materials_volume) [only used with transmission]
988 // thicknessFactor
989 {
990 ai_real thicknessFactor = 0.0f;
991 result = source.Get(AI_MATKEY_VOLUME_THICKNESS_FACTOR, thicknessFactor);
992 if (result == aiReturn_SUCCESS)
993 QSSGSceneDesc::setProperty(target, "thicknessFactor", &QQuick3DSpecularGlossyMaterial::setThicknessFactor, float(thicknessFactor));
994 }
995
996 // thicknessMap
997 {
998 if (auto thicknessImage = createTextureNode(source, AI_MATKEY_VOLUME_THICKNESS_TEXTURE))
999 QSSGSceneDesc::setProperty(target, "thicknessMap", &QQuick3DSpecularGlossyMaterial::setThicknessMap, thicknessImage);
1000 }
1001
1002 // attenuationDistance
1003 {
1004 ai_real attenuationDistance = 0.0f;
1005 result = source.Get(AI_MATKEY_VOLUME_ATTENUATION_DISTANCE, attenuationDistance);
1006 if (result == aiReturn_SUCCESS)
1007 QSSGSceneDesc::setProperty(target,
1008 "attenuationDistance",
1009 &QQuick3DSpecularGlossyMaterial::setAttenuationDistance,
1010 float(attenuationDistance));
1011 }
1012
1013 // attenuationColor
1014 {
1015 aiColor3D attenuationColor;
1016 result = source.Get(AI_MATKEY_VOLUME_ATTENUATION_COLOR, attenuationColor);
1017 if (result == aiReturn_SUCCESS)
1018 QSSGSceneDesc::setProperty(target,
1019 "attenuationColor",
1020 &QQuick3DSpecularGlossyMaterial::setAttenuationColor,
1021 aiColorToQColor(attenuationColor));
1022 }
1023 }
1024 }
1025}
1026
1027static void setCameraProperties(QSSGSceneDesc::Camera &target, const aiCamera &source, const aiNode &sourceNode, const SceneInfo &sceneInfo)
1028{
1029 using namespace QSSGSceneDesc;
1030
1031 // assimp does not have a camera type but it works for gltf2 format.
1032 target.runtimeType = (source.mHorizontalFOV == 0.0f) ? Node::RuntimeType::OrthographicCamera
1033 : Node::RuntimeType::PerspectiveCamera;
1034
1035 // We assume these default forward and up vectors, so if this isn't
1036 // the case we have to do additional transform
1037 aiMatrix4x4 correctionMatrix;
1038 bool needsCorrection = false;
1039
1040 // Workaround For FBX,
1041 // assimp has a problem to set properties, mLookAt ans mUp
1042 // and it takes too much time for correction.
1043 // Quick3D will ignore these value and just use
1044 // the initial differences between FBX and Quick3D.
1045 if (sceneInfo.opt.fbxMode) {
1046 aiMatrix4x4::RotationY(ai_real(M_PI / 2), correctionMatrix);
1047 needsCorrection = true;
1048 } else {
1049 aiVector3D upQuick3D = aiVector3D(0, 1, 0);
1050 if (source.mLookAt != aiVector3D(0, 0, -1)) {
1051 aiMatrix4x4 lookAtCorrection;
1052 aiMatrix4x4::FromToMatrix(aiVector3D(0, 0, -1), source.mLookAt, lookAtCorrection);
1053 correctionMatrix *= lookAtCorrection;
1054 needsCorrection = true;
1055 upQuick3D *= lookAtCorrection;
1056 }
1057 if (source.mUp != upQuick3D) {
1058 aiMatrix4x4 upCorrection;
1059 aiMatrix4x4::FromToMatrix(upQuick3D, source.mUp, upCorrection);
1060 correctionMatrix = upCorrection * correctionMatrix;
1061 needsCorrection = true;
1062 }
1063 }
1064
1065 setNodeProperties(target, sourceNode, sceneInfo, needsCorrection ? &correctionMatrix : nullptr);
1066
1067 // clipNear and clipFar
1068 if (target.runtimeType == Node::RuntimeType::PerspectiveCamera) {
1069 setProperty(target, "clipNear", &QQuick3DPerspectiveCamera::setClipNear, source.mClipPlaneNear);
1070 setProperty(target, "clipFar", &QQuick3DPerspectiveCamera::setClipFar, source.mClipPlaneFar);
1071 } else { //OrthographicCamera
1072 setProperty(target, "clipNear", &QQuick3DOrthographicCamera::setClipNear, source.mClipPlaneNear);
1073 setProperty(target, "clipFar", &QQuick3DOrthographicCamera::setClipFar, source.mClipPlaneFar);
1074 }
1075
1076 if (target.runtimeType == Node::RuntimeType::PerspectiveCamera) {
1077 // fieldOfView
1078 // mHorizontalFOV is defined as a half horizontal fov
1079 // in the assimp header but it seems not half now.
1080 const float fov = qRadiansToDegrees(source.mHorizontalFOV);
1081 setProperty(target, "fieldOfView", &QQuick3DPerspectiveCamera::setFieldOfView, fov);
1082
1083 // isFieldOfViewHorizontal
1084 setProperty(target, "fieldOfViewOrientation", &QQuick3DPerspectiveCamera::setFieldOfViewOrientation,
1085 QQuick3DPerspectiveCamera::FieldOfViewOrientation::Horizontal);
1086 } else { //OrthographicCamera
1087 const float width = source.mOrthographicWidth * 2.0f;
1088 const float height = width / source.mAspect;
1089 setProperty(target, "horizontalMagnification", &QQuick3DOrthographicCamera::setHorizontalMagnification, width);
1090 setProperty(target, "verticalMagnification", &QQuick3DOrthographicCamera::setVerticalMagnification, height);
1091 }
1092 // projectionMode
1093
1094 // scaleMode
1095
1096 // scaleAnchor
1097
1098 // frustomScaleX
1099
1100 // frustomScaleY
1101}
1102
1103static void setLightProperties(QSSGSceneDesc::Light &target, const aiLight &source, const aiNode &sourceNode, const SceneInfo &sceneInfo)
1104{
1105 // We assume that the direction vector for a light is (0, 0, -1)
1106 // so if the direction vector is non-null, but not (0, 0, -1) we
1107 // need to correct the translation
1108 aiMatrix4x4 correctionMatrix;
1109 bool needsCorrection = false;
1110 if (source.mDirection != aiVector3D(0, 0, 0)) {
1111 if (source.mDirection != aiVector3D(0, 0, -1)) {
1112 aiMatrix4x4::FromToMatrix(aiVector3D(0, 0, -1), source.mDirection, correctionMatrix);
1113 needsCorrection = true;
1114 }
1115 }
1116
1117 // lightType
1118 static const auto asQtLightType = [](aiLightSourceType type) {
1119 switch (type) {
1120 case aiLightSource_AMBIENT:
1121 Q_FALLTHROUGH();
1122 case aiLightSource_DIRECTIONAL:
1123 return QSSGSceneDesc::Light::RuntimeType::DirectionalLight;
1124 case aiLightSource_POINT:
1125 return QSSGSceneDesc::Light::RuntimeType::PointLight;
1126 case aiLightSource_SPOT:
1127 return QSSGSceneDesc::Light::RuntimeType::SpotLight;
1128 default:
1129 return QSSGSceneDesc::Light::RuntimeType::PointLight;
1130 }
1131 };
1132
1133 target.runtimeType = asQtLightType(source.mType);
1134
1135 setNodeProperties(target, sourceNode, sceneInfo, needsCorrection ? &correctionMatrix : nullptr);
1136
1137 // brightness
1138 // Assimp has no property related to brightness or intensity.
1139 // They are multiplied to diffuse, ambient and specular colors.
1140 // For extracting the property value, we will check the maximum value of them.
1141 // (In most cases, Assimp uses the same specular values with diffuse values,
1142 // so we will compare just components of the diffuse and the ambient)
1143 float brightness = qMax(qMax(1.0f, source.mColorDiffuse.r),
1144 qMax(source.mColorDiffuse.g, source.mColorDiffuse.b));
1145
1146 // ambientColor
1147 if (source.mType == aiLightSource_AMBIENT) {
1148 brightness = qMax(qMax(brightness, source.mColorAmbient.r),
1149 qMax(source.mColorAmbient.g, source.mColorAmbient.b));
1150
1151 // We only want ambient light color if it is explicit
1152 const QColor ambientColor = QColor::fromRgbF(source.mColorAmbient.r / brightness,
1153 source.mColorAmbient.g / brightness,
1154 source.mColorAmbient.b / brightness);
1155 QSSGSceneDesc::setProperty(target, "ambientColor", &QQuick3DAbstractLight::setAmbientColor, ambientColor);
1156 }
1157
1158 // diffuseColor
1159 const QColor diffuseColor = QColor::fromRgbF(source.mColorDiffuse.r / brightness,
1160 source.mColorDiffuse.g / brightness,
1161 source.mColorDiffuse.b / brightness);
1162 QSSGSceneDesc::setProperty(target, "color", &QQuick3DAbstractLight::setColor, diffuseColor);
1163
1164 // describe brightness here
1165 QSSGSceneDesc::setProperty(target, "brightness", &QQuick3DAbstractLight::setBrightness, brightness);
1166
1167 const bool isSpot = (source.mType == aiLightSource_SPOT);
1168 if (source.mType == aiLightSource_POINT || isSpot) {
1169 // constantFade
1170 // Some assets have this constant attenuation value as 0.0f and it makes light attenuation makes infinite at distance 0.
1171 // In that case, we will use the default constant attenuation, 1.0f.
1172 const bool hasAttConstant = !qFuzzyIsNull(source.mAttenuationConstant);
1173
1174 if (isSpot) {
1175 if (hasAttConstant)
1176 QSSGSceneDesc::setProperty(target, "constantFade", &QQuick3DSpotLight::setConstantFade, source.mAttenuationConstant);
1177 QSSGSceneDesc::setProperty(target, "linearFade", &QQuick3DSpotLight::setLinearFade, source.mAttenuationLinear * 100.0f);
1178 QSSGSceneDesc::setProperty(target, "quadraticFade", &QQuick3DSpotLight::setQuadraticFade, source.mAttenuationQuadratic * 10000.0f);
1179 QSSGSceneDesc::setProperty(target, "coneAngle", &QQuick3DSpotLight::setConeAngle, qRadiansToDegrees(source.mAngleOuterCone) * 2.0f);
1180 QSSGSceneDesc::setProperty(target, "innerConeAngle", &QQuick3DSpotLight::setInnerConeAngle, qRadiansToDegrees(source.mAngleInnerCone) * 2.0f);
1181 } else {
1182 if (hasAttConstant)
1183 QSSGSceneDesc::setProperty(target, "constantFade", &QQuick3DPointLight::setConstantFade, source.mAttenuationConstant);
1184 QSSGSceneDesc::setProperty(target, "linearFade", &QQuick3DPointLight::setLinearFade, source.mAttenuationLinear * 100.0f);
1185 QSSGSceneDesc::setProperty(target, "quadraticFade", &QQuick3DPointLight::setQuadraticFade, source.mAttenuationQuadratic * 10000.0f);
1186 }
1187 }
1188 // castShadow
1189
1190 // shadowBias
1191
1192 // shadowFactor
1193
1194 // shadowMapResolution
1195
1196 // shadowMapFar
1197
1198 // shadowMapFieldOfView
1199
1200 // shadowFilter
1201}
1202
1203using MorphAttributes = QQuick3DMorphTarget::MorphTargetAttributes;
1209
1210static void setModelProperties(QSSGSceneDesc::Model &target, const aiNode &source, const SceneInfo &sceneInfo)
1211{
1212 if (source.mNumMeshes == 0)
1213 return;
1214
1215 auto &targetScene = target.scene;
1216 const auto &srcScene = sceneInfo.scene;
1217 // TODO: Correction and scale
1218 setNodeProperties(target, source, sceneInfo, nullptr);
1219
1220 auto &meshStorage = targetScene->meshStorage;
1221 auto &materialMap = sceneInfo.materialMap;
1222 auto &meshMap = sceneInfo.meshMap;
1223 auto &skinMap = sceneInfo.skinMap;
1224 auto &mesh2skin = sceneInfo.mesh2skin;
1225
1226 QVarLengthArray<QSSGSceneDesc::Material *> materials;
1227 materials.reserve(source.mNumMeshes); // Assumig there's max one material per mesh.
1228
1229 QString errorString;
1230
1231 const auto ensureMaterial = [&](qsizetype materialIndex) {
1232 // Get the material for the mesh
1233 auto &material = materialMap[materialIndex];
1234 // Check if we need to create a new scene node for this material
1235 auto targetMat = material.second;
1236 if (targetMat == nullptr) {
1237 const aiMaterial *sourceMat = material.first;
1238
1239 auto currentMaterialType = QSSGSceneDesc::Material::RuntimeType::PrincipledMaterial;
1240 ai_real glossinessFactor;
1241 aiReturn result = sourceMat->Get(AI_MATKEY_GLOSSINESS_FACTOR, glossinessFactor);
1242 if (result == aiReturn_SUCCESS)
1243 currentMaterialType = QSSGSceneDesc::Material::RuntimeType::SpecularGlossyMaterial;
1244
1245 targetMat = new QSSGSceneDesc::Material(currentMaterialType);
1246 QSSGSceneDesc::addNode(target, *targetMat);
1247 setMaterialProperties(*targetMat, *sourceMat, sceneInfo, currentMaterialType);
1248 material.second = targetMat;
1249 }
1250
1251 Q_ASSERT(targetMat != nullptr && material.second != nullptr);
1252 // If these don't match then somethings broken...
1253 Q_ASSERT(srcScene.mMaterials[materialIndex] == material.first);
1254 materials.push_back(targetMat);
1255 };
1256
1257 AssimpUtils::MeshList meshes;
1258 qint16 skinIdx = -1;
1259 // Combine all the meshes referenced by this model into a single MultiMesh file
1260 // For the morphing, the target mesh must have the same AnimMeshes.
1261 // It means if only one mesh has a morphing animation, the other sub-meshes will
1262 // get null target attributes. However this case might not be common.
1263 // These submeshes will animate with the same morphing weight!
1264
1265 // If meshes have separate skins, they should not be combined. GLTF2 does not
1266 // seem to have problems related with this case, but When we use runtime asset
1267 // for other formats, this case must be checked again.
1268 // Here, we will use only the first skin in the mesh list
1269 const auto combineMeshes = [&](const aiNode &source, aiMesh **sceneMeshes) {
1270 for (qsizetype i = 0, end = source.mNumMeshes; i != end; ++i) {
1271 const aiMesh &mesh = *sceneMeshes[source.mMeshes[i]];
1272 ensureMaterial(mesh.mMaterialIndex);
1273 if (skinIdx == -1 && mesh.HasBones())
1274 skinIdx = mesh2skin[source.mMeshes[i]];
1275 meshes.push_back(&mesh);
1276 }
1277 };
1278
1279 const auto createMeshNode = [&](const aiString &name) {
1280 auto meshData = AssimpUtils::generateMeshData(srcScene,
1281 meshes,
1283 sceneInfo.opt.generateMeshLODs,
1284 sceneInfo.opt.lodNormalMergeAngle,
1285 sceneInfo.opt.lodNormalSplitAngle,
1286 errorString);
1287 meshStorage.push_back(std::move(meshData));
1288
1289 const auto idx = meshStorage.size() - 1;
1290 // For multimeshes we'll use the model name, but for single meshes we'll use the mesh name.
1291 return new QSSGSceneDesc::Mesh(fromAiString(name), idx);
1292 };
1293
1294 QSSGSceneDesc::Mesh *meshNode = nullptr;
1295
1296 const bool isMultiMesh = (source.mNumMeshes > 1);
1297 if (isMultiMesh) {
1298 // result is stored in 'meshes'
1299 combineMeshes(source, srcScene.mMeshes);
1300 Q_ASSERT(!meshes.isEmpty());
1301 meshNode = createMeshNode(source.mName);
1302 QSSGSceneDesc::addNode(target, *meshNode);
1303 } else { // single mesh (We shouldn't be here if there are no meshes...)
1304 Q_ASSERT(source.mNumMeshes == 1);
1305 auto &mesh = meshMap[*source.mMeshes];
1306 meshNode = mesh.second;
1307 if (meshNode == nullptr) {
1308 meshes = {mesh.first};
1309 if (mesh.first->HasBones())
1310 skinIdx = mesh2skin[*source.mMeshes];
1311 mesh.second = meshNode = createMeshNode(mesh.first->mName);
1312 QSSGSceneDesc::addNode(target, *meshNode); // We only add this the first time we create it.
1313 }
1314 ensureMaterial(mesh.first->mMaterialIndex);
1315 Q_ASSERT(meshNode != nullptr && mesh.second != nullptr);
1316 }
1317
1318 if (meshNode)
1319 QSSGSceneDesc::setProperty(target, "source", &QQuick3DModel::setSource, QVariant::fromValue(meshNode));
1320
1321 if (skinIdx != -1) {
1322 auto &skin = skinMap[skinIdx];
1323 skin.node = new QSSGSceneDesc::Skin;
1324 QSSGSceneDesc::setProperty(target, "skin", &QQuick3DModel::setSkin, skin.node);
1325 QSSGSceneDesc::addNode(target, *skin.node);
1326 // Skins' properties wil be set after all the nodes are processed
1327 }
1328
1329 // materials
1330 // Note that we use a QVector/QList here instead of a QQmlListProperty, as that would be really inconvenient.
1331 // Since we don't create any runtime objects at this point, the list also contains the node type that corresponds with the
1332 // type expected to be in the list (this is ensured at compile-time).
1333 QSSGSceneDesc::setProperty(target, "materials", &QQuick3DModel::materials, materials);
1334}
1335
1337 const aiNode &srcNode,
1338 QSSGSceneDesc::Node &parent,
1339 const SceneInfo &sceneInfo)
1340{
1341 QSSGSceneDesc::Node *node = nullptr;
1342 const auto &srcScene = sceneInfo.scene;
1343 switch (nodeInfo.type) {
1344 case QSSGSceneDesc::Node::Type::Camera:
1345 {
1346 const auto &srcType = *srcScene.mCameras[nodeInfo.index];
1347 // We set the initial rt-type to 'Custom', but we'll change it when updateing the properties.
1348 auto targetType = new QSSGSceneDesc::Camera(QSSGSceneDesc::Node::RuntimeType::CustomCamera);
1349 QSSGSceneDesc::addNode(parent, *targetType);
1350 setCameraProperties(*targetType, srcType, srcNode, sceneInfo);
1351 node = targetType;
1352 }
1353 break;
1354 case QSSGSceneDesc::Node::Type::Light:
1355 {
1356 const auto &srcType = *srcScene.mLights[nodeInfo.index];
1357 // Initial type is DirectonalLight, but will be change (if needed) when setting the properties.
1358 auto targetType = new QSSGSceneDesc::Light(QSSGSceneDesc::Node::RuntimeType::DirectionalLight);
1359 QSSGSceneDesc::addNode(parent, *targetType);
1360 setLightProperties(*targetType, srcType, srcNode, sceneInfo);
1361 node = targetType;
1362 }
1363 break;
1364 case QSSGSceneDesc::Node::Type::Model:
1365 {
1366 auto target = new QSSGSceneDesc::Model;
1367 QSSGSceneDesc::addNode(parent, *target);
1368 setModelProperties(*target, srcNode, sceneInfo);
1369 node = target;
1370 }
1371 break;
1372 case QSSGSceneDesc::Node::Type::Joint:
1373 {
1374 auto target = new QSSGSceneDesc::Joint;
1375 QSSGSceneDesc::addNode(parent, *target);
1376 setNodeProperties(*target, srcNode, sceneInfo, nullptr);
1377 QSSGSceneDesc::setProperty(*target, "index", &QQuick3DJoint::setIndex, qint32(nodeInfo.index));
1378 node = target;
1379 }
1380 break;
1381 case QSSGSceneDesc::Node::Type::Transform:
1382 {
1383 node = new QSSGSceneDesc::Node(QSSGSceneDesc::Node::Type::Transform, QSSGSceneDesc::Node::RuntimeType::Node);
1384 QSSGSceneDesc::addNode(parent, *node);
1385 // TODO: arguments for correction
1386 setNodeProperties(*node, srcNode, sceneInfo, nullptr);
1387 }
1388 break;
1389 default:
1390 break;
1391 }
1392
1393 return node;
1394}
1395
1396static void processNode(const SceneInfo &sceneInfo, const aiNode &source, QSSGSceneDesc::Node &parent, const NodeMap &nodeMap, AnimationNodeMap &animationNodes)
1397{
1398 QSSGSceneDesc::Node *node = nullptr;
1399 if (source.mNumMeshes != 0) {
1400 // Process morphTargets first and then add them to the modelNode
1401 using It = decltype(source.mNumMeshes);
1402 QVarLengthArray<MorphProperty> morphProps;
1403 for (It i = 0, end = source.mNumMeshes; i != end; ++i) {
1404 const auto &srcScene = sceneInfo.scene;
1405 const aiMesh &mesh = *srcScene.mMeshes[source.mMeshes[i]];
1406 const quint32 numMorphTargets = mesh.mNumAnimMeshes;
1407 if (numMorphTargets && mesh.mAnimMeshes) {
1408 morphProps.reserve(numMorphTargets);
1409 for (uint j = 0; j < numMorphTargets; ++j) {
1410 const auto &animMesh = mesh.mAnimMeshes[j];
1411 MorphAttributes attrib;
1412 if (animMesh->HasPositions())
1413 attrib |= QQuick3DMorphTarget::MorphTargetAttribute::Position;
1414 if (animMesh->HasNormals())
1415 attrib |= QQuick3DMorphTarget::MorphTargetAttribute::Normal;
1416 if (animMesh->HasTangentsAndBitangents()) {
1417 attrib |= QQuick3DMorphTarget::MorphTargetAttribute::Tangent;
1418 attrib |= QQuick3DMorphTarget::MorphTargetAttribute::Binormal;
1419 }
1420 morphProps.append({ fromAiString(animMesh->mName),
1421 attrib,
1422 animMesh->mWeight });
1423 }
1424 }
1425 }
1426 node = createSceneNode(NodeInfo { 0, QSSGSceneDesc::Node::Type::Model }, source, parent, sceneInfo);
1427 if (!morphProps.isEmpty()) {
1428 const QString nodeName(source.mName.C_Str());
1429 QVarLengthArray<QSSGSceneDesc::MorphTarget *> morphTargets;
1430 morphTargets.reserve(morphProps.size());
1431 for (int i = 0, end = morphProps.size(); i != end; ++i) {
1432 const auto morphProp = morphProps.at(i);
1433
1434 auto morphNode = new QSSGSceneDesc::MorphTarget;
1435 QSSGSceneDesc::addNode(*node, *morphNode);
1436 QSSGSceneDesc::setProperty(*morphNode, "weight", &QQuick3DMorphTarget::setWeight, morphProp.weight);
1437 QSSGSceneDesc::setProperty(*morphNode, "attributes", &QQuick3DMorphTarget::setAttributes, morphProp.attrib);
1438 morphNode->name = morphProp.name;
1439 morphTargets.push_back(morphNode);
1440
1441 if (!animationNodes.isEmpty()) {
1442 QString morphTargetName = nodeName + QStringLiteral("_morph") + QString::number(i);
1443 const auto aNodeIt = animationNodes.find(morphTargetName.toUtf8());
1444 if (aNodeIt != animationNodes.end() && aNodeIt.value() == nullptr)
1445 *aNodeIt = morphNode;
1446 }
1447 }
1448 QSSGSceneDesc::setProperty(*node, "morphTargets", &QQuick3DModel::morphTargets, morphTargets);
1449 }
1450 }
1451
1452 if (!node) {
1453 NodeInfo nodeInfo{ 0, QSSGSceneDesc::Node::Type::Transform };
1454 if (auto it = nodeMap.constFind(&source); it != nodeMap.constEnd())
1455 nodeInfo = (*it);
1456 node = createSceneNode(nodeInfo, source, parent, sceneInfo);
1457 }
1458
1459 if (!node)
1460 node = &parent;
1461
1462 Q_ASSERT(node->scene);
1463
1464 // Check if this node is a target for an animation
1465 if (!animationNodes.isEmpty()) {
1466 const auto &nodeName = source.mName;
1467 auto aNodeIt = animationNodes.find(QByteArray{nodeName.C_Str(), qsizetype(nodeName.length)});
1468 if (aNodeIt != animationNodes.end() && aNodeIt.value() == nullptr)
1469 *aNodeIt = node;
1470 }
1471
1472 // Process child nodes
1473 using It = decltype (source.mNumChildren);
1474 for (It i = 0, end = source.mNumChildren; i != end; ++i)
1475 processNode(sceneInfo, **(source.mChildren + i), *node, nodeMap, animationNodes);
1476}
1477
1478static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiVectorKey &key, qreal freq) {
1479 const auto flag = quint16(QSSGSceneDesc::Animation::KeyPosition::KeyType::Time) | quint16(QSSGSceneDesc::Animation::KeyPosition::ValueType::Vec3);
1480 return QSSGSceneDesc::Animation::KeyPosition { QVector4D{ key.mValue.x, key.mValue.y, key.mValue.z, 0.0f }, float(key.mTime * freq), flag };
1481}
1482
1483static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiQuatKey &key, qreal freq) {
1484 const auto flag = quint16(QSSGSceneDesc::Animation::KeyPosition::KeyType::Time) | quint16(QSSGSceneDesc::Animation::KeyPosition::ValueType::Quaternion);
1485 return QSSGSceneDesc::Animation::KeyPosition { QVector4D{ key.mValue.x, key.mValue.y, key.mValue.z, key.mValue.w }, float(key.mTime * freq), flag };
1486}
1487
1488static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiMeshMorphKey &key, qreal freq, uint morphId) {
1489 const auto flag = quint16(QSSGSceneDesc::Animation::KeyPosition::KeyType::Time) | quint16(QSSGSceneDesc::Animation::KeyPosition::ValueType::Number);
1490 return QSSGSceneDesc::Animation::KeyPosition { QVector4D{ float(key.mWeights[morphId]), 0.0f, 0.0f, 0.0f }, float(key.mTime * freq), flag };
1491}
1492
1493static bool checkBooleanOption(const QString &optionName, const QJsonObject &options)
1494{
1495 const auto it = options.constFind(optionName);
1496 const auto end = options.constEnd();
1497 QJsonValue value;
1498 if (it != end) {
1499 if (it->isObject())
1500 value = it->toObject().value("value");
1501 else
1502 value = it.value();
1503 }
1504 return value.toBool();
1505}
1506
1507static qreal getRealOption(const QString &optionName, const QJsonObject &options)
1508{
1509 const auto it = options.constFind(optionName);
1510 const auto end = options.constEnd();
1511 QJsonValue value;
1512 if (it != end) {
1513 if (it->isObject())
1514 value = it->toObject().value("value");
1515 else
1516 value = it.value();
1517 }
1518
1519 return value.toDouble();
1520}
1521
1522#define demonPostProcessPresets (
1523 aiProcess_CalcTangentSpace |
1524 aiProcess_JoinIdenticalVertices |
1525 aiProcess_ImproveCacheLocality |
1526 aiProcess_RemoveRedundantMaterials |
1527 aiProcess_SplitLargeMeshes |
1528 aiProcess_Triangulate |
1529 aiProcess_GenUVCoords |
1530 aiProcess_SortByPType |
1531 aiProcess_FindDegenerates |
1532 aiProcess_FindInvalidData |
1533 0 )
1534
1535static aiPostProcessSteps processOptions(const QJsonObject &optionsObject, std::unique_ptr<Assimp::Importer> &importer) {
1536 aiPostProcessSteps postProcessSteps = aiPostProcessSteps(aiProcess_Triangulate | aiProcess_SortByPType);;
1537
1538 // Setup import settings based given options
1539 // You can either pass the whole options object, or just the "options" object
1540 // so get the right scope.
1541 QJsonObject options = optionsObject;
1542
1543 if (auto it = options.constFind("options"), end = options.constEnd(); it != end)
1544 options = it->toObject();
1545
1546 if (options.isEmpty())
1547 return postProcessSteps;
1548
1549 // parse the options list for values
1550
1551 if (checkBooleanOption(QStringLiteral("calculateTangentSpace"), options))
1552 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_CalcTangentSpace);
1553
1554 if (checkBooleanOption(QStringLiteral("joinIdenticalVertices"), options))
1555 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_JoinIdenticalVertices);
1556
1557 if (checkBooleanOption(QStringLiteral("generateNormals"), options))
1558 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_GenNormals);
1559
1560 if (checkBooleanOption(QStringLiteral("generateSmoothNormals"), options))
1561 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_GenSmoothNormals);
1562
1563 if (checkBooleanOption(QStringLiteral("splitLargeMeshes"), options))
1564 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_SplitLargeMeshes);
1565
1566 if (checkBooleanOption(QStringLiteral("preTransformVertices"), options))
1567 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_PreTransformVertices);
1568
1569 if (checkBooleanOption(QStringLiteral("improveCacheLocality"), options))
1570 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_ImproveCacheLocality);
1571
1572 if (checkBooleanOption(QStringLiteral("removeRedundantMaterials"), options))
1573 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_RemoveRedundantMaterials);
1574
1575 if (checkBooleanOption(QStringLiteral("fixInfacingNormals"), options))
1576 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_FixInfacingNormals);
1577
1578 if (checkBooleanOption(QStringLiteral("findDegenerates"), options))
1579 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_FindDegenerates);
1580
1581 if (checkBooleanOption(QStringLiteral("findInvalidData"), options))
1582 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_FindInvalidData);
1583
1584 if (checkBooleanOption(QStringLiteral("transformUVCoordinates"), options))
1585 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_TransformUVCoords);
1586
1587 if (checkBooleanOption(QStringLiteral("findInstances"), options))
1588 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_FindInstances);
1589
1590 if (checkBooleanOption(QStringLiteral("optimizeMeshes"), options))
1591 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_OptimizeMeshes);
1592
1593 if (checkBooleanOption(QStringLiteral("optimizeGraph"), options))
1594 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_OptimizeGraph);
1595
1596 if (checkBooleanOption(QStringLiteral("dropNormals"), options))
1597 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_DropNormals);
1598
1599 aiComponent removeComponents = aiComponent(0);
1600
1601 if (checkBooleanOption(QStringLiteral("removeComponentNormals"), options))
1602 removeComponents = aiComponent(removeComponents | aiComponent_NORMALS);
1603
1604 if (checkBooleanOption(QStringLiteral("removeComponentTangentsAndBitangents"), options))
1605 removeComponents = aiComponent(removeComponents | aiComponent_TANGENTS_AND_BITANGENTS);
1606
1607 if (checkBooleanOption(QStringLiteral("removeComponentColors"), options))
1608 removeComponents = aiComponent(removeComponents | aiComponent_COLORS);
1609
1610 if (checkBooleanOption(QStringLiteral("removeComponentUVs"), options))
1611 removeComponents = aiComponent(removeComponents | aiComponent_TEXCOORDS);
1612
1613 if (checkBooleanOption(QStringLiteral("removeComponentBoneWeights"), options))
1614 removeComponents = aiComponent(removeComponents | aiComponent_BONEWEIGHTS);
1615
1616 if (checkBooleanOption(QStringLiteral("removeComponentAnimations"), options))
1617 removeComponents = aiComponent(removeComponents | aiComponent_ANIMATIONS);
1618
1619 if (checkBooleanOption(QStringLiteral("removeComponentTextures"), options))
1620 removeComponents = aiComponent(removeComponents | aiComponent_TEXTURES);
1621
1622 if (removeComponents != aiComponent(0)) {
1623 postProcessSteps = aiPostProcessSteps(postProcessSteps | aiProcess_RemoveComponent);
1624 importer->SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, removeComponents);
1625 }
1626
1627 bool preservePivots = checkBooleanOption(QStringLiteral("fbxPreservePivots"), options);
1628 importer->SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, preservePivots);
1629
1630 return postProcessSteps;
1631}
1632
1633static SceneInfo::Options processSceneOptions(const QJsonObject &optionsObject) {
1634 SceneInfo::Options sceneOptions;
1635
1636 // Setup import settings based given options
1637 // You can either pass the whole options object, or just the "options" object
1638 // so get the right scope.
1639 QJsonObject options = optionsObject;
1640
1641 if (auto it = options.constFind("options"), end = options.constEnd(); it != end)
1642 options = it->toObject();
1643
1644 if (options.isEmpty())
1645 return sceneOptions;
1646
1647 if (checkBooleanOption(QStringLiteral("globalScale"), options)) {
1648 sceneOptions.globalScaleValue = getRealOption(QStringLiteral("globalScaleValue"), options);
1649 if (sceneOptions.globalScaleValue == 0.0)
1650 sceneOptions.globalScaleValue = 1.0;
1651 }
1652
1653 sceneOptions.designStudioWorkarounds = checkBooleanOption(QStringLiteral("designStudioWorkarounds"), options);
1654 sceneOptions.useFloatJointIndices = checkBooleanOption(QStringLiteral("useFloatJointIndices"), options);
1655 sceneOptions.forceMipMapGeneration = checkBooleanOption(QStringLiteral("generateMipMaps"), options);
1656 sceneOptions.binaryKeyframes = checkBooleanOption(QStringLiteral("useBinaryKeyframes"), options);
1657 sceneOptions.generateMeshLODs = checkBooleanOption(QStringLiteral("generateMeshLevelsOfDetail"), options);
1658 if (sceneOptions.generateMeshLODs) {
1659 bool recalculateLODNormals = checkBooleanOption(QStringLiteral("recalculateLodNormals"), options);
1660 if (recalculateLODNormals) {
1661 qreal mergeAngle = getRealOption(QStringLiteral("recalculateLodNormalsMergeAngle"), options);
1662 sceneOptions.lodNormalMergeAngle = qBound(0.0, mergeAngle, 270.0);
1663 qreal splitAngle = getRealOption(QStringLiteral("recalculateLodNormalsSplitAngle"), options);
1664 sceneOptions.lodNormalSplitAngle = qBound(0.0, splitAngle, 270.0);
1665 } else {
1666 sceneOptions.lodNormalMergeAngle = 0.0;
1667 sceneOptions.lodNormalSplitAngle = 0.0;
1668 }
1669 }
1670 return sceneOptions;
1671}
1672
1673static QString importImp(const QUrl &url, const QJsonObject &options, QSSGSceneDesc::Scene &targetScene)
1674{
1675 auto filePath = url.path();
1676
1677 const bool maybeLocalFile = QQmlFile::isLocalFile(url);
1678 if (maybeLocalFile && !QFileInfo::exists(filePath))
1679 filePath = QQmlFile::urlToLocalFileOrQrc(url);
1680
1681 auto sourceFile = QFileInfo(filePath);
1682 if (!sourceFile.exists())
1683 return QLatin1String("File not found");
1684 targetScene.sourceDir = sourceFile.path();
1685
1686 std::unique_ptr<Assimp::Importer> importer(new Assimp::Importer());
1687
1688 // Setup import from Options
1689 aiPostProcessSteps postProcessSteps;
1690 if (options.isEmpty())
1691 postProcessSteps = aiPostProcessSteps(demonPostProcessPresets);
1692 else
1693 postProcessSteps = processOptions(options, importer);
1694
1695 // Remove primitives that are not Triangles
1696 importer->SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);
1697 importer->SetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_USE_COLLADA_NAMES, 1);
1698
1699 if (filePath.startsWith(":"))
1700 importer->SetIOHandler(new ResourceIOSystem);
1701
1702 auto sourceScene = importer->ReadFile(filePath.toStdString(), postProcessSteps);
1703 if (!sourceScene) {
1704 // Scene failed to load, use logger to get the reason
1705 return QString::fromLocal8Bit(importer->GetErrorString());
1706 }
1707
1708 // For simplicity, and convenience, we'll just use the file path as the id.
1709 // DO NOT USE it for anything else, once the scene is created there's no
1710 // real connection to the source asset file.
1711 targetScene.id = sourceFile.canonicalFilePath();
1712
1713 // Assuming consistent type usage
1714 using It = decltype(sourceScene->mNumMeshes);
1715
1716 // Before we can start processing the scene we start my mapping out the nodes
1717 // we can tell the type of.
1718 const auto &srcRootNode = *sourceScene->mRootNode;
1719 NodeMap nodeMap;
1720 // We need to know which nodes are animated so we can map _our_ animation data to
1721 // the target node (in Assimp this is string based mapping).
1722 AnimationNodeMap animatingNodes;
1723 {
1724 if (sourceScene->HasLights()) {
1725 for (It i = 0, end = sourceScene->mNumLights; i != end; ++i) {
1726 const auto &type = *sourceScene->mLights[i];
1727 if (auto node = srcRootNode.FindNode(type.mName))
1728 nodeMap[node] = { i, NodeInfo::Type::Light };
1729 }
1730 }
1731
1732 if (sourceScene->HasCameras()) {
1733 for (It i = 0, end = sourceScene->mNumCameras; i != end; ++i) {
1734 const auto &srcCam = *sourceScene->mCameras[i];
1735 if (auto node = srcRootNode.FindNode(srcCam.mName))
1736 nodeMap[node] = { i, NodeInfo::Type::Camera };
1737 }
1738 }
1739
1740 if (sourceScene->HasAnimations()) {
1741 for (It i = 0, end = sourceScene->mNumAnimations; i != end; ++i) {
1742 const auto &srcAnim = *sourceScene->mAnimations[i];
1743 const auto channelCount = srcAnim.mNumChannels;
1744 for (It cIdx = 0; cIdx != channelCount; ++cIdx) {
1745 const auto &srcChannel = srcAnim.mChannels[cIdx];
1746 const auto &nodeName = srcChannel->mNodeName;
1747 if (nodeName.length > 0) {
1748 // We'll update this once we've created the node!
1749 QByteArray name(nodeName.C_Str(), qsizetype(nodeName.length));
1750 if (!animatingNodes.contains(name))
1751 animatingNodes.insert(name, nullptr);
1752 }
1753 }
1754 const auto morphChannelCount = srcAnim.mNumMorphMeshChannels;
1755 for (It cIdx = 0; cIdx != morphChannelCount; ++cIdx) {
1756 const auto &srcChannel = srcAnim.mMorphMeshChannels[cIdx];
1757 const auto &nodeName = srcChannel->mName;
1758 if (nodeName.length > 0) {
1759 const auto morphKeys = srcChannel->mKeys;
1760 const auto numMorphTargets = morphKeys[0].mNumValuesAndWeights;
1761 // MorphTarget's animations are stored with a name,
1762 // "<nodeName> + '_morph' + <targetNumber>"
1763 for (It j = 0; j < numMorphTargets; ++j) {
1764 QString morphTargetName(nodeName.C_Str());
1765 morphTargetName += QStringLiteral("_morph") + QString::number(j);
1766 animatingNodes.insert(morphTargetName.toUtf8(), nullptr);
1767 }
1768 }
1769 }
1770 }
1771 }
1772 }
1773
1774 // We'll use these to ensure we don't re-create resources.
1775 const auto materialCount = sourceScene->mNumMaterials;
1776 SceneInfo::MaterialMap materials;
1777 materials.reserve(materialCount);
1778
1779 const auto meshCount = sourceScene->mNumMeshes;
1780 SceneInfo::MeshMap meshes;
1781 meshes.reserve(meshCount);
1782 SceneInfo::Mesh2SkinMap mesh2skin;
1783 mesh2skin.reserve(meshCount);
1784
1785 const auto embeddedTextureCount = sourceScene->mNumTextures;
1786 SceneInfo::EmbeddedTextureMap embeddedTextures;
1787
1788 SceneInfo::SkinMap skins;
1789
1790 for (It i = 0; i != materialCount; ++i)
1791 materials.push_back({sourceScene->mMaterials[i], nullptr});
1792
1793 for (It i = 0; i != meshCount; ++i) {
1794 meshes.push_back({sourceScene->mMeshes[i], nullptr});
1795 if (sourceScene->mMeshes[i]->HasBones()) {
1796 mesh2skin.push_back(skins.size());
1797 const auto boneCount = sourceScene->mMeshes[i]->mNumBones;
1798 auto bones = sourceScene->mMeshes[i]->mBones;
1799 skins.push_back(SceneInfo::skinData{ bones, boneCount, nullptr });
1800
1801 // For skinning, we need to get the joints list and their target nodes.
1802 // It is also done by the string based mapping and many of them will
1803 // be animated. So we will use existing AnimationNodeMap for the data.
1804 for (It j = 0; j != boneCount; ++j) {
1805 const auto &nodeName = bones[j]->mName;
1806 if (nodeName.length > 0) {
1807 animatingNodes.insert(QByteArray{ nodeName.C_Str(),
1808 qsizetype(nodeName.length) },
1809 nullptr);
1810 }
1811 }
1812 } else {
1813 mesh2skin.push_back(-1);
1814 }
1815 }
1816
1817 for (It i = 0; i != embeddedTextureCount; ++i)
1818 embeddedTextures.push_back(nullptr);
1819
1820 SceneInfo::TextureMap textureMap;
1821
1822 if (!targetScene.root) {
1823 auto root = new QSSGSceneDesc::Node(QSSGSceneDesc::Node::Type::Transform, QSSGSceneDesc::Node::RuntimeType::Node);
1824 QSSGSceneDesc::addNode(targetScene, *root);
1825 }
1826
1827 // Get Options
1828 auto opt = processSceneOptions(options);
1829 // check if the asset is GLTF format
1830 const auto extension = sourceFile.suffix().toLower();
1831 if (extension == QStringLiteral("gltf") || extension == QStringLiteral("glb"))
1832 opt.gltfMode = true;
1833 else if (extension == QStringLiteral("fbx"))
1834 opt.fbxMode = true;
1835
1836 SceneInfo sceneInfo { *sourceScene, materials, meshes, embeddedTextures,
1837 textureMap, skins, mesh2skin, sourceFile.dir(), opt };
1838
1839 if (!qFuzzyCompare(opt.globalScaleValue, 1.0f) && !qFuzzyCompare(opt.globalScaleValue, 0.0f)) {
1840 const auto gscale = opt.globalScaleValue;
1841 QSSGSceneDesc::setProperty(*targetScene.root, "scale", &QQuick3DNode::setScale, QVector3D { gscale, gscale, gscale });
1842 }
1843
1844 // Now lets go through the scene
1845 if (sourceScene->mRootNode)
1846 processNode(sceneInfo, *sourceScene->mRootNode, *targetScene.root, nodeMap, animatingNodes);
1847 // skins
1848 for (It i = 0, endI = skins.size(); i != endI; ++i) {
1849 const auto &skin = skins[i];
1850
1851 // It is possible that an asset has a unused mesh with a skin
1852 if (!skin.node)
1853 continue;
1854
1855 QList<QMatrix4x4> inverseBindPoses;
1856 QVarLengthArray<QSSGSceneDesc::Node *> joints;
1857 joints.reserve(skin.mNumBones);
1858 for (It j = 0, endJ = skin.mNumBones; j != endJ; ++j) {
1859 const auto &bone = *skin.mBones[j];
1860 const auto &nodeName = bone.mName;
1861 if (nodeName.length > 0) {
1862 auto targetNode = animatingNodes.value(QByteArray{ nodeName.C_Str(), qsizetype(nodeName.length) });
1863 joints.push_back(targetNode);
1864 const auto &osMat = bone.mOffsetMatrix;
1865 auto pose = QMatrix4x4(osMat[0][0], osMat[0][1], osMat[0][2], osMat[0][3],
1866 osMat[1][0], osMat[1][1], osMat[1][2], osMat[1][3],
1867 osMat[2][0], osMat[2][1], osMat[2][2], osMat[2][3],
1868 osMat[3][0], osMat[3][1], osMat[3][2], osMat[3][3]);
1869 inverseBindPoses.push_back(pose);
1870 }
1871 }
1872 QSSGSceneDesc::setProperty(*skin.node, "joints", &QQuick3DSkin::joints, joints);
1873 QSSGSceneDesc::setProperty(*skin.node, "inverseBindPoses", &QQuick3DSkin::setInverseBindPoses, inverseBindPoses);
1874 }
1875
1876 static const auto fuzzyComparePos = [](const aiVectorKey *pos, const aiVectorKey *prev){
1877 if (!prev)
1878 return false;
1879 return qFuzzyCompare(pos->mValue.x, prev->mValue.x)
1880 && qFuzzyCompare(pos->mValue.y, prev->mValue.y)
1881 && qFuzzyCompare(pos->mValue.z, prev->mValue.z);
1882 };
1883
1884 static const auto fuzzyCompareRot = [](const aiQuatKey *rot, const aiQuatKey *prev){
1885 if (!prev)
1886 return false;
1887 return qFuzzyCompare(rot->mValue.x, prev->mValue.x)
1888 && qFuzzyCompare(rot->mValue.y, prev->mValue.y)
1889 && qFuzzyCompare(rot->mValue.z, prev->mValue.z)
1890 && qFuzzyCompare(rot->mValue.w, prev->mValue.w);
1891 };
1892
1893 static const auto createAnimation = [](QSSGSceneDesc::Scene &targetScene, const aiAnimation &srcAnim, const AnimationNodeMap &animatingNodes) {
1894 using namespace QSSGSceneDesc;
1895 Animation targetAnimation;
1896 auto &channels = targetAnimation.channels;
1897 qreal freq = qFuzzyIsNull(srcAnim.mTicksPerSecond) ? 1.0
1898 : 1000.0 / srcAnim.mTicksPerSecond;
1899 targetAnimation.framesPerSecond = srcAnim.mTicksPerSecond;
1900 targetAnimation.name = fromAiString(srcAnim.mName);
1901 // Process property channels
1902 for (It i = 0, end = srcAnim.mNumChannels; i != end; ++i) {
1903 const auto &srcChannel = *srcAnim.mChannels[i];
1904
1905 const auto &nodeName = srcChannel.mNodeName;
1906 if (nodeName.length > 0) {
1907 const auto aNodeEnd = animatingNodes.cend();
1908 const auto aNodeIt = animatingNodes.constFind(QByteArray{ nodeName.C_Str(), qsizetype(nodeName.length) });
1909 if (aNodeIt != aNodeEnd && aNodeIt.value() != nullptr) {
1910 auto targetNode = aNodeIt.value();
1911 // Target propert[y|ies]
1912
1913 const auto currentPropertyValue = [targetNode](const char *propertyName) -> QVariant {
1914 for (auto *p : targetNode->properties) {
1915 if (!qstrcmp(propertyName, p->name))
1916 return p->value;
1917 }
1918 return {};
1919 };
1920
1921 { // Position
1922 const auto posKeyEnd = srcChannel.mNumPositionKeys;
1923 Animation::Channel targetChannel;
1924 targetChannel.targetProperty = Animation::Channel::TargetProperty::Position;
1925 targetChannel.target = targetNode;
1926 const aiVectorKey *prevPos = nullptr;
1927 for (It posKeyIdx = 0; posKeyIdx != posKeyEnd; ++posKeyIdx) {
1928 const auto &posKey = srcChannel.mPositionKeys[posKeyIdx];
1929 if (fuzzyComparePos(&posKey, prevPos))
1930 continue;
1931 targetChannel.keys.push_back(new Animation::KeyPosition(toAnimationKey(posKey, freq)));
1932 prevPos = &posKey;
1933 }
1934
1935 const auto isUnchanged = [&targetChannel, currentPropertyValue]() {
1936 if (targetChannel.keys.count() != 1)
1937 return false;
1938 auto currentPos = currentPropertyValue("position").value<QVector3D>();
1939 return qFuzzyCompare(targetChannel.keys[0]->value.toVector3D(), currentPos);
1940 };
1941 if (!targetChannel.keys.isEmpty()) {
1942 if (!isUnchanged()) {
1943 channels.push_back(new Animation::Channel(targetChannel));
1944 float endTime = float(srcChannel.mPositionKeys[posKeyEnd - 1].mTime) * freq;
1945 if (targetAnimation.length < endTime)
1946 targetAnimation.length = endTime;
1947 } else {
1948 // the keys will not be used.
1949 qDeleteAll(targetChannel.keys);
1950 }
1951 }
1952 }
1953
1954 { // Rotation
1955 const auto rotKeyEnd = srcChannel.mNumRotationKeys;
1956 Animation::Channel targetChannel;
1957 targetChannel.targetProperty = Animation::Channel::TargetProperty::Rotation;
1958 targetChannel.target = targetNode;
1959 const aiQuatKey *prevRot = nullptr;
1960 for (It rotKeyIdx = 0; rotKeyIdx != rotKeyEnd; ++rotKeyIdx) {
1961 const auto &rotKey = srcChannel.mRotationKeys[rotKeyIdx];
1962 if (fuzzyCompareRot(&rotKey, prevRot))
1963 continue;
1964 targetChannel.keys.push_back(new Animation::KeyPosition(toAnimationKey(rotKey, freq)));
1965 prevRot = &rotKey;
1966 }
1967
1968 const auto isUnchanged = [&targetChannel, currentPropertyValue]() {
1969 if (targetChannel.keys.count() != 1)
1970 return false;
1971 auto currentVal = currentPropertyValue("rotation");
1972 QQuaternion rot = currentVal.isValid() ? currentVal.value<QQuaternion>() : QQuaternion{};
1973 return qFuzzyCompare(QQuaternion(targetChannel.keys[0]->value), rot);
1974 };
1975 if (!targetChannel.keys.isEmpty()) {
1976 if (!isUnchanged()) {
1977 channels.push_back(new Animation::Channel(targetChannel));
1978 float endTime = float(srcChannel.mRotationKeys[rotKeyEnd - 1].mTime) * freq;
1979 if (targetAnimation.length < endTime)
1980 targetAnimation.length = endTime;
1981 } else {
1982 // the keys will not be used.
1983 qDeleteAll(targetChannel.keys);
1984 }
1985 }
1986 }
1987
1988 { // Scale
1989 const auto scaleKeyEnd = srcChannel.mNumScalingKeys;
1990 Animation::Channel targetChannel;
1991 targetChannel.targetProperty = Animation::Channel::TargetProperty::Scale;
1992 targetChannel.target = targetNode;
1993 const aiVectorKey *prevScale = nullptr;
1994 for (It scaleKeyIdx = 0; scaleKeyIdx != scaleKeyEnd; ++scaleKeyIdx) {
1995 const auto &scaleKey = srcChannel.mScalingKeys[scaleKeyIdx];
1996 if (fuzzyComparePos(&scaleKey, prevScale))
1997 continue;
1998 targetChannel.keys.push_back(new Animation::KeyPosition(toAnimationKey(scaleKey, freq)));
1999 prevScale = &scaleKey;
2000 }
2001
2002 const auto isUnchanged = [&targetChannel, currentPropertyValue]() {
2003 if (targetChannel.keys.count() != 1)
2004 return false;
2005 auto currentVal = currentPropertyValue("scale");
2006 QVector3D scale = currentVal.isValid() ? currentVal.value<QVector3D>() : QVector3D{ 1, 1, 1 };
2007 return qFuzzyCompare(targetChannel.keys[0]->value.toVector3D(), scale);
2008 };
2009
2010 if (!targetChannel.keys.isEmpty()) {
2011 if (!isUnchanged()) {
2012 channels.push_back(new Animation::Channel(targetChannel));
2013 float endTime = float(srcChannel.mScalingKeys[scaleKeyEnd - 1].mTime) * freq;
2014 if (targetAnimation.length < endTime)
2015 targetAnimation.length = endTime;
2016 } else {
2017 // the keys will not be used.
2018 qDeleteAll(targetChannel.keys);
2019 }
2020 }
2021 }
2022 }
2023 }
2024 }
2025 // Morphing Animations
2026 for (It i = 0, end = srcAnim.mNumMorphMeshChannels; i != end; ++i) {
2027 const auto &srcMorphChannel = *srcAnim.mMorphMeshChannels[i];
2028 const QString nodeName(srcMorphChannel.mName.C_Str());
2029 const auto *morphKeys = srcMorphChannel.mKeys;
2030 const auto numMorphTargets = qMin(morphKeys[0].mNumValuesAndWeights, 8U);
2031 for (It targetId = 0; targetId != numMorphTargets; ++targetId) {
2032 QString morphTargetName = nodeName + QStringLiteral("_morph") + QString::number(targetId);
2033 const auto aNodeEnd = animatingNodes.cend();
2034 const auto aNodeIt = animatingNodes.constFind(morphTargetName.toUtf8());
2035 if (aNodeIt != aNodeEnd && aNodeIt.value() != nullptr) {
2036 auto targetNode = aNodeIt.value();
2037 const auto weightKeyEnd = srcMorphChannel.mNumKeys;
2038 Animation::Channel targetChannel;
2039 targetChannel.targetProperty = Animation::Channel::TargetProperty::Weight;
2040 targetChannel.target = targetNode;
2041 for (It wId = 0; wId != weightKeyEnd; ++wId) {
2042 const auto &weightKey = srcMorphChannel.mKeys[wId];
2043 const auto animationKey = new Animation::KeyPosition(toAnimationKey(weightKey, freq, targetId));
2044 targetChannel.keys.push_back(animationKey);
2045 }
2046 if (!targetChannel.keys.isEmpty()) {
2047 channels.push_back(new Animation::Channel(targetChannel));
2048 float endTime = float(srcMorphChannel.mKeys[weightKeyEnd - 1].mTime) * freq;
2049 if (targetAnimation.length < endTime)
2050 targetAnimation.length = endTime;
2051 }
2052 }
2053 }
2054 }
2055
2056 // If we have data we need to make it persistent.
2057 if (!targetAnimation.channels.isEmpty())
2058 targetScene.animations.push_back(new Animation(targetAnimation));
2059 };
2060
2061 // All scene nodes should now be created (and ready), so let's go through the animation data.
2062 if (sourceScene->HasAnimations()) {
2063 const auto animationCount = sourceScene->mNumAnimations;
2064 targetScene.animations.reserve(animationCount);
2065 for (It i = 0, end = animationCount; i != end; ++i) {
2066 const auto &srcAnim = *sourceScene->mAnimations[i];
2067 createAnimation(targetScene, srcAnim, animatingNodes);
2068 }
2069 }
2070
2071 // TODO, FIX: Editing the scene after the import ought to be done by QSSGAssetImportManager
2072 // and not by the asset import plugin. However, the asset import module cannot use
2073 // the asset utils module because that would cause a circular dependency. This
2074 // needs a deeper architectural fix.
2075
2076 QSSGQmlUtilities::applyEdit(&targetScene, options);
2077
2078 return QString();
2079}
2080
2081////////////////////////
2082
2083QString AssimpImporter::import(const QUrl &url, const QJsonObject &options, QSSGSceneDesc::Scene &scene)
2084{
2085 // We'll simply use assimp to load the scene and then translate the Aassimp scene
2086 // into our own format.
2087 return importImp(url, options, scene);
2088}
2089
2090QString AssimpImporter::import(const QString &sourceFile, const QDir &savePath, const QJsonObject &options, QStringList *generatedFiles)
2091{
2092 QString errorString;
2093
2094 QSSGSceneDesc::Scene scene;
2095
2096 // Load scene data
2097 auto sourceUrl = QUrl::fromLocalFile(sourceFile);
2098 errorString = importImp(sourceUrl, options, scene);
2099
2100 if (!errorString.isEmpty())
2101 return errorString;
2102
2103 // Write out QML + Resources
2104 QFileInfo sourceFileInfo(sourceFile);
2105
2106 QString targetFileName = savePath.absolutePath() + QDir::separator() +
2107 QSSGQmlUtilities::qmlComponentName(sourceFileInfo.completeBaseName()) +
2108 QStringLiteral(".qml");
2109 QFile targetFile(targetFileName);
2110 if (!targetFile.open(QIODevice::WriteOnly)) {
2111 errorString += QString("Could not write to file: ") + targetFileName;
2112 } else {
2113 QTextStream output(&targetFile);
2114 QSSGQmlUtilities::writeQml(scene, output, savePath, options);
2115 if (generatedFiles)
2116 generatedFiles->append(targetFileName);
2117 }
2118 scene.cleanup();
2119
2120 return errorString;
2121}
2122
2123QT_END_NAMESPACE
#define AI_GLTF_FILTER_NEAREST_MIPMAP_NEAREST
static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiMeshMorphKey &key, qreal freq, uint morphId)
static Q_REQUIRED_RESULT QColor aiColorToQColor(const aiColor3D &color)
#define AI_GLTF_FILTER_NEAREST
static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiQuatKey &key, qreal freq)
#define AI_GLTF_FILTER_NEAREST_MIPMAP_LINEAR
static QSSGSceneDesc::Animation::KeyPosition toAnimationKey(const aiVectorKey &key, qreal freq)
static void processNode(const SceneInfo &sceneInfo, const aiNode &source, QSSGSceneDesc::Node &parent, const NodeMap &nodeMap, AnimationNodeMap &animationNodes)
static qreal getRealOption(const QString &optionName, const QJsonObject &options)
#define AI_GLTF_FILTER_LINEAR_MIPMAP_LINEAR
static QByteArray fromAiString(const aiString &string)
static void setModelProperties(QSSGSceneDesc::Model &target, const aiNode &source, const SceneInfo &sceneInfo)
static void setLightProperties(QSSGSceneDesc::Light &target, const aiLight &source, const aiNode &sourceNode, const SceneInfo &sceneInfo)
static void setMaterialProperties(QSSGSceneDesc::Material &target, const aiMaterial &source, const SceneInfo &sceneInfo, QSSGSceneDesc::Material::RuntimeType type)
bool operator==(const TextureInfo &a, const TextureInfo &b)
bool operator==(const TextureEntry &a, const TextureEntry &b)
static bool isEqual(const aiUVTransform &a, const aiUVTransform &b)
#define AI_GLTF_FILTER_LINEAR
static aiPostProcessSteps processOptions(const QJsonObject &optionsObject, std::unique_ptr< Assimp::Importer > &importer)
static void setNodeProperties(QSSGSceneDesc::Node &target, const aiNode &source, const SceneInfo &sceneInfo, aiMatrix4x4 *transformCorrection)
static QString importImp(const QUrl &url, const QJsonObject &options, QSSGSceneDesc::Scene &targetScene)
static void setTextureProperties(QSSGSceneDesc::Texture &target, const TextureInfo &texInfo, const SceneInfo &sceneInfo)
size_t qHash(const TextureEntry &key, size_t seed)
static QSSGSceneDesc::Node * createSceneNode(const NodeInfo &nodeInfo, const aiNode &srcNode, QSSGSceneDesc::Node &parent, const SceneInfo &sceneInfo)
#define demonPostProcessPresets
Q_DECLARE_TYPEINFO(NodeInfo, Q_PRIMITIVE_TYPE)
static SceneInfo::Options processSceneOptions(const QJsonObject &optionsObject)
static void setCameraProperties(QSSGSceneDesc::Camera &target, const aiCamera &source, const aiNode &sourceNode, const SceneInfo &sceneInfo)
static bool checkBooleanOption(const QString &optionName, const QJsonObject &options)
#define AI_GLTF_FILTER_LINEAR_MIPMAP_NEAREST
ResourceIOStream(const char *pFile, const char *pMode)
size_t FileSize() const override
void Flush() override
size_t Read(void *pvBuffer, size_t pSize, size_t pCount) override
size_t Tell() const override
size_t Write(const void *pvBuffer, size_t pSize, size_t pCount) override
aiReturn Seek(size_t pOffset, aiOrigin pOrigin) override
char getOsSeparator() const override
void Close(Assimp::IOStream *pFile) override
bool Exists(const char *pFile) const override
Assimp::IOStream * Open(const char *pFile, const char *pMode) override
#define M_PI
Definition qmath.h:200
MorphAttributes attrib
QSSGSceneDesc::Skin * node
EmbeddedTextureMap & embeddedTextureMap
MaterialMap & materialMap
Mesh2SkinMap & mesh2skin
TextureMap & textureMap
const aiScene & scene
QSSGSceneDesc::Texture * texture
unsigned int magFilter
aiUVTransform transform
aiTextureMapping mapping
aiTextureMapMode modes[3]
unsigned int minFilter