Debian Codegraph @

src/plugins/sceneparsers/gltf/gltfio.cpp

raw symbols SCIP
1 // Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
2 // Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies).
3 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
5 #include <Qt3DCore/QEntity>
6 #include <Qt3DCore/QTransform>
7 #include <Qt3DExtras/QDiffuseMapMaterial>
8 #include <Qt3DExtras/QDiffuseSpecularMapMaterial>
9 #include <Qt3DExtras/QNormalDiffuseMapMaterial>
10 #include <Qt3DExtras/QNormalDiffuseSpecularMapMaterial>
11 #include <Qt3DExtras/QPhongMaterial>
12 #include <Qt3DRender/QAlphaCoverage>
13 #include <Qt3DRender/QBlendEquation>
14 #include <Qt3DRender/QBlendEquationArguments>
15 #include <Qt3DRender/QCameraLens>
16 #include <Qt3DRender/QColorMask>
17 #include <Qt3DRender/QCullFace>
18 #include <Qt3DRender/QDepthTest>
19 #include <Qt3DRender/QEffect>
20 #include <Qt3DRender/QFrontFace>
21 #include <Qt3DRender/QGeometry>
22 #include <Qt3DRender/QGeometryRenderer>
23 #include <Qt3DRender/QGraphicsApiFilter>
24 #include <Qt3DRender/QMaterial>
25 #include <Qt3DRender/QNoDepthMask>
26 #include <Qt3DRender/QParameter>
27 #include <Qt3DRender/QPolygonOffset>
28 #include <Qt3DRender/QRenderState>
29 #include <Qt3DRender/QScissorTest>
30 #include <Qt3DRender/QShaderProgram>
31 #include <Qt3DRender/QTechnique>
32 #include <Qt3DRender/QTexture>
33 #include <QtCore/QDir>
34 #include <QtCore/QFileInfo>
35 #include <QtCore/QJsonArray>
36 #include <QtCore/QJsonObject>
37
38 #include <QtGui/qquaternion.h>
39 #include <QtGui/QVector2D>
40
41 #include "gltfio.h"
42
43 #include <Qt3DRender/private/qurlhelper_p.h>
44
45 #ifndef qUtf16PrintableImpl // -Impl is a Qt 5.8 feature
46 # define qUtf16PrintableImpl(string) \
47 static_cast<const wchar_t*>(static_cast<const void*>(string.utf16()))
48 #endif
49
50 QT_BEGIN_NAMESPACE
51
52 using namespace Qt3DCore;
53 using namespace Qt3DExtras;
54
55 namespace Qt3DRender {
56
57 Q_LOGGING_CATEGORY(GLTFIOLog, "Qt3D.GLTFIO")
58
59 #define KEY_CAMERA QLatin1String("camera")
60 #define KEY_CAMERAS QLatin1String("cameras")
61 #define KEY_SCENES QLatin1String("scenes")
62 #define KEY_NODES QLatin1String("nodes")
63 #define KEY_MESHES QLatin1String("meshes")
64 #define KEY_CHILDREN QLatin1String("children")
65 #define KEY_MATRIX QLatin1String("matrix")
66 #define KEY_ROTATION QLatin1String("rotation")
67 #define KEY_SCALE QLatin1String("scale")
68 #define KEY_TRANSLATION QLatin1String("translation")
69 #define KEY_TYPE QLatin1String("type")
70 #define KEY_PERSPECTIVE QLatin1String("perspective")
71 #define KEY_NAME QLatin1String("name")
72 #define KEY_COUNT QLatin1String("count")
73 #define KEY_YFOV QLatin1String("yfov")
74 #define KEY_ZNEAR QLatin1String("znear")
75 #define KEY_ZFAR QLatin1String("zfar")
76 #define KEY_MATERIALS QLatin1String("materials")
77 #define KEY_EXTENSIONS QLatin1String("extensions")
78 #define KEY_COMMON_MAT QLatin1String("KHR_materials_common")
79 #define KEY_TECHNIQUE QLatin1String("technique")
80 #define KEY_VALUES QLatin1String("values")
81 #define KEY_BUFFERS QLatin1String("buffers")
82 #define KEY_SHADERS QLatin1String("shaders")
83 #define KEY_PROGRAMS QLatin1String("programs")
84 #define KEY_PROGRAM QLatin1String("program")
85 #define KEY_TECHNIQUES QLatin1String("techniques")
86 #define KEY_ACCESSORS QLatin1String("accessors")
87 #define KEY_IMAGES QLatin1String("images")
88 #define KEY_TEXTURES QLatin1String("textures")
89 #define KEY_SCENE QLatin1String("scene")
90 #define KEY_BUFFER QLatin1String("buffer")
91 #define KEY_TARGET QLatin1String("target")
92 #define KEY_BYTE_OFFSET QLatin1String("byteOffset")
93 #define KEY_BYTE_LENGTH QLatin1String("byteLength")
94 #define KEY_BYTE_STRIDE QLatin1String("byteStride")
95 #define KEY_PRIMITIVES QLatin1String("primitives")
96 #define KEY_MODE QLatin1String("mode")
97 #define KEY_MATERIAL QLatin1String("material")
98 #define KEY_ATTRIBUTES QLatin1String("attributes")
99 #define KEY_INDICES QLatin1String("indices")
100 #define KEY_URI QLatin1String("uri")
101 #define KEY_FORMAT QLatin1String("format")
102 #define KEY_PASSES QLatin1String("passes")
103 #define KEY_SOURCE QLatin1String("source")
104 #define KEY_SAMPLER QLatin1String("sampler")
105 #define KEY_SAMPLERS QLatin1String("samplers")
106 #define KEY_SEMANTIC QLatin1String("semantic")
107 #define KEY_STATES QLatin1String("states")
108 #define KEY_UNIFORMS QLatin1String("uniforms")
109 #define KEY_PARAMETERS QLatin1String("parameters")
110 #define KEY_WRAP_S QLatin1String("wrapS")
111 #define KEY_MIN_FILTER QLatin1String("minFilter")
112 #define KEY_MAG_FILTER QLatin1String("magFilter")
113
114 #define KEY_INSTANCE_TECHNIQUE QLatin1String("instanceTechnique")
115 #define KEY_INSTANCE_PROGRAM QLatin1String("instanceProgram")
116 #define KEY_BUFFER_VIEWS QLatin1String("bufferViews")
117 #define KEY_BUFFER_VIEW QLatin1String("bufferView")
118 #define KEY_VERTEX_SHADER QLatin1String("vertexShader")
119 #define KEY_FRAGMENT_SHADER QLatin1String("fragmentShader")
120 #define KEY_INTERNAL_FORMAT QLatin1String("internalFormat")
121 #define KEY_COMPONENT_TYPE QLatin1String("componentType")
122 #define KEY_ASPECT_RATIO QLatin1String("aspect_ratio")
123 #define KEY_VALUE QLatin1String("value")
124 #define KEY_ENABLE QLatin1String("enable")
125 #define KEY_FUNCTIONS QLatin1String("functions")
126 #define KEY_TECHNIQUE_CORE QLatin1String("techniqueCore")
127 #define KEY_TECHNIQUE_GL2 QLatin1String("techniqueGL2")
128
129 GLTFIO::GLTFIO() : QSceneIOHandler(),
130 m_parseDone(false)
131 {
132 }
133
134 GLTFIO::~GLTFIO()
135 {
136
137 }
138
139 void GLTFIO::setBasePath(const QString& path)
140 {
141 m_basePath = path;
142 }
143
144 bool GLTFIO::setJSON(const QJsonDocument &json )
145 {
146 if ( !json.isObject() ) {
147 return false;
148 }
149
150 m_json = json;
151 m_parseDone = false;
152
153 cleanup();
154
155 return true;
156 }
157
158 /*
159 * Sets the \a path used by the parser to load the scene file.
160 * If the file is valid, parsing is automatically triggered.
161 */
162 void GLTFIO::setSource(const QUrl &source)
163 {
164 const QString path = QUrlHelper::urlToLocalFileOrQrc(source);
165 QFileInfo finfo(path);
166 if (Q_UNLIKELY(!finfo.exists())) {
167 qCWarning(GLTFIOLog, "missing file: %ls", qUtf16PrintableImpl(path));
168 return;
169 }
170 QFile f(path);
171 f.open(QIODevice::ReadOnly);
172
173 QByteArray jsonData = f.readAll();
174 QJsonDocument sceneDocument = QJsonDocument::fromBinaryData(jsonData);
175 if (sceneDocument.isNull())
176 sceneDocument = QJsonDocument::fromJson(jsonData);
177
178 if (Q_UNLIKELY(!setJSON(sceneDocument))) {
179 qCWarning(GLTFIOLog, "not a JSON document");
180 return;
181 }
182
183 setBasePath(finfo.dir().absolutePath());
184 }
185
186 /*
187 * Returns true if the extension of \a path is supported by the
188 * GLTF parser.
189 */
190 bool GLTFIO::isFileTypeSupported(const QUrl &source) const
191 {
192 const QString path = QUrlHelper::urlToLocalFileOrQrc(source);
193 return GLTFIO::isGLTFPath(path);
194 }
195
196 Qt3DCore::QEntity* GLTFIO::node(const QString &id)
197 {
198 QJsonObject nodes = m_json.object().value(KEY_NODES).toObject();
199 const auto jsonVal = nodes.value(id);
200 if (Q_UNLIKELY(jsonVal.isUndefined())) {
201 qCWarning(GLTFIOLog, "unknown node %ls in GLTF file %ls",
202 qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
203 return NULL;
204 }
205
206 const QJsonObject jsonObj = jsonVal.toObject();
207 QEntity* result = nullptr;
208
209 // Qt3D has a limitation that a QEntity can only have 1 mesh and 1 material component
210 // So if the node has only 1 mesh, we only create 1 QEntity
211 // Otherwise if there are n meshes, there is 1 QEntity, with n children for each mesh/material combo
212 {
213 QList<QEntity *> entities;
214
215 const auto meshes = jsonObj.value(KEY_MESHES).toArray();
216 for (const QJsonValue &mesh : meshes) {
217 const QString meshName = mesh.toString();
218 const auto geometryRenderers = std::as_const(m_meshDict).equal_range(meshName);
219 if (Q_UNLIKELY(geometryRenderers.first == geometryRenderers.second)) {
220 qCWarning(GLTFIOLog, "node %ls references unknown mesh %ls",
221 qUtf16PrintableImpl(id), qUtf16PrintableImpl(meshName));
222 continue;
223 }
224
225 for (auto it = geometryRenderers.first; it != geometryRenderers.second; ++it) {
226 QGeometryRenderer *geometryRenderer = it.value();
227 QEntity *entity = new QEntity;
228 entity->addComponent(geometryRenderer);
229 QMaterial *mat = material(m_meshMaterialDict[geometryRenderer]);
230 if (mat)
231 entity->addComponent(mat);
232 entities.append(entity);
233 }
234
235 }
236
237 switch (entities.size()) {
238 case 0:
239 break;
240 case 1:
241 result = std::as_const(entities).first();
242 break;
243 default:
244 result = new QEntity;
245 for (QEntity *entity : std::as_const(entities))
246 entity->setParent(result);
247 }
248 }
249
250 //If the entity contains no meshes, results will still be null here
251 if (result == nullptr)
252 result = new QEntity;
253
254 {
255 const auto children = jsonObj.value(KEY_CHILDREN).toArray();
256 for (const QJsonValue &c : children) {
257 QEntity* child = node(c.toString());
258 if (!child)
259 continue;
260 child->setParent(result);
261 }
262 }
263
264 renameFromJson(jsonObj, result);
265
266
267 // Node Transforms
268 Qt3DCore::QTransform *trans = nullptr;
269 const auto matrix = jsonObj.value(KEY_MATRIX);
270 if (!matrix.isUndefined()) {
271 QMatrix4x4 m(Qt::Uninitialized);
272
273 QJsonArray matrixValues = matrix.toArray();
274 for (int i=0; i<16; ++i) {
275 double v = matrixValues.at( i ).toDouble();
276 m(i % 4, i >> 2) = v;
277 }
278
279 // ADD MATRIX TRANSFORM COMPONENT TO ENTITY
280 if (trans == nullptr)
281 trans = new Qt3DCore::QTransform;
282 trans->setMatrix(m);
283 }
284
285 // Rotation quaternion
286 const auto rotation = jsonObj.value(KEY_ROTATION);
287 if (!rotation.isUndefined()) {
288 if (!trans)
289 trans = new Qt3DCore::QTransform;
290
291 const QJsonArray quaternionValues = rotation.toArray();
292 QQuaternion quaternion(quaternionValues[0].toDouble(),
293 quaternionValues[1].toDouble(),
294 quaternionValues[2].toDouble(),
295 quaternionValues[3].toDouble());
296 trans->setRotation(quaternion);
297 }
298
299 // Translation
300 const auto translation = jsonObj.value(KEY_TRANSLATION);
301 if (!translation.isUndefined()) {
302 if (!trans)
303 trans = new Qt3DCore::QTransform;
304
305 const QJsonArray translationValues = translation.toArray();
306 trans->setTranslation(QVector3D(translationValues[0].toDouble(),
307 translationValues[1].toDouble(),
308 translationValues[2].toDouble()));
309 }
310
311 // Scale
312 const auto scale = jsonObj.value(KEY_SCALE);
313 if (!scale.isUndefined()) {
314 if (!trans)
315 trans = new Qt3DCore::QTransform;
316
317 const QJsonArray scaleValues = scale.toArray();
318 trans->setScale3D(QVector3D(scaleValues[0].toDouble(),
319 scaleValues[1].toDouble(),
320 scaleValues[2].toDouble()));
321 }
322
323 // Add the Transform component
324 if (trans != nullptr)
325 result->addComponent(trans);
326
327 const auto cameraVal = jsonObj.value(KEY_CAMERA);
328 if (!cameraVal.isUndefined()) {
329 QCameraLens* cam = camera(cameraVal.toString());
330 if (Q_UNLIKELY(!cam)) {
331 qCWarning(GLTFIOLog) << "failed to build camera:" << cameraVal
332 << "on node" << id;
333 } else {
334 result->addComponent(cam);
335 }
336 } // of have camera attribute
337
338 return result;
339 }
340
341 Qt3DCore::QEntity* GLTFIO::scene(const QString &id)
342 {
343 parse();
344
345 QJsonObject scenes = m_json.object().value(KEY_SCENES).toObject();
346 const auto sceneVal = scenes.value(id);
347 if (Q_UNLIKELY(sceneVal.isUndefined())) {
348 if (Q_UNLIKELY(!id.isNull()))
349 qCWarning(GLTFIOLog, "GLTF: no such scene %ls in file %ls",
350 qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
351 return defaultScene();
352 }
353
354 QJsonObject sceneObj = sceneVal.toObject();
355 QEntity* sceneEntity = new QEntity;
356 const auto nodes = sceneObj.value(KEY_NODES).toArray();
357 for (const QJsonValue &nnv : nodes) {
358 QString nodeName = nnv.toString();
359 QEntity* child = node(nodeName);
360 if (!child)
361 continue;
362 child->setParent(sceneEntity);
363 }
364
365 return sceneEntity;
366 }
367
368 GLTFIO::BufferData::BufferData()
369 : length(0)
370 , data(nullptr)
371 {
372 }
373
374 GLTFIO::BufferData::BufferData(const QJsonObject &json)
375 : length(json.value(KEY_BYTE_LENGTH).toInt()),
376 path(json.value(KEY_URI).toString()),
377 data(nullptr)
378 {
379 }
380
381 GLTFIO::ParameterData::ParameterData() :
382 type(0)
383 {
384
385 }
386
387 GLTFIO::ParameterData::ParameterData(const QJsonObject &json)
388 : semantic(json.value(KEY_SEMANTIC).toString()),
389 type(json.value(KEY_TYPE).toInt())
390 {
391 }
392
393 GLTFIO::AccessorData::AccessorData()
394 : type(QAttribute::Float)
395 , dataSize(0)
396 , count(0)
397 , offset(0)
398 , stride(0)
399 {
400
401 }
402
403 GLTFIO::AccessorData::AccessorData(const QJsonObject &json)
404 : bufferViewName(json.value(KEY_BUFFER_VIEW).toString()),
405 type(accessorTypeFromJSON(json.value(KEY_COMPONENT_TYPE).toInt())),
406 dataSize(accessorDataSizeFromJson(json.value(KEY_TYPE).toString())),
407 count(json.value(KEY_COUNT).toInt()),
408 offset(0),
409 stride(0)
410 {
411 const auto byteOffset = json.value(KEY_BYTE_OFFSET);
412 if (!byteOffset.isUndefined())
413 offset = byteOffset.toInt();
414 const auto byteStride = json.value(KEY_BYTE_STRIDE);
415 if (!byteStride.isUndefined())
416 stride = byteStride.toInt();
417 }
418
419 bool GLTFIO::isGLTFPath(const QString& path)
420 {
421 QFileInfo finfo(path);
422 if (!finfo.exists())
423 return false;
424
425 // might need to detect other things in the future, but would
426 // prefer to avoid doing a full parse.
427 QString suffix = finfo.suffix().toLower();
428 return suffix == QLatin1String("json") || suffix == QLatin1String("gltf") || suffix == QLatin1String("qgltf");
429 }
430
431 void GLTFIO::renameFromJson(const QJsonObject &json, QObject * const object)
432 {
433 const auto name = json.value(KEY_NAME);
434 if (!name.isUndefined())
435 object->setObjectName(name.toString());
436 }
437
438 bool GLTFIO::hasStandardUniformNameFromSemantic(const QString &semantic)
439 {
440 //Standard Uniforms
441 if (semantic.isEmpty())
442 return false;
443 switch (semantic.at(0).toLatin1()) {
444 case 'L':
445 // return semantic == QLatin1String("LOCAL");
446 return false;
447 case 'M':
448 return semantic == QLatin1String("MODEL")
449 || semantic == QLatin1String("MODELVIEW")
450 || semantic == QLatin1String("MODELVIEWPROJECTION")
451 || semantic == QLatin1String("MODELINVERSE")
452 || semantic == QLatin1String("MODELVIEWPROJECTIONINVERSE")
453 || semantic == QLatin1String("MODELINVERSETRANSPOSE")
454 || semantic == QLatin1String("MODELVIEWINVERSETRANSPOSE");
455 case 'V':
456 return semantic == QLatin1String("VIEW")
457 || semantic == QLatin1String("VIEWINVERSE")
458 || semantic == QLatin1String("VIEWPORT");
459 case 'P':
460 return semantic == QLatin1String("PROJECTION")
461 || semantic == QLatin1String("PROJECTIONINVERSE");
462 }
463 return false;
464 }
465
466 QString GLTFIO::standardAttributeNameFromSemantic(const QString &semantic)
467 {
468 //Standard Attributes
469 if (semantic.startsWith(QLatin1String("POSITION")))
470 return QAttribute::defaultPositionAttributeName();
471 if (semantic.startsWith(QLatin1String("NORMAL")))
472 return QAttribute::defaultNormalAttributeName();
473 if (semantic.startsWith(QLatin1String("TEXCOORD")))
474 return QAttribute::defaultTextureCoordinateAttributeName();
475 if (semantic.startsWith(QLatin1String("COLOR")))
476 return QAttribute::defaultColorAttributeName();
477 if (semantic.startsWith(QLatin1String("TANGENT")))
478 return QAttribute::defaultTangentAttributeName();
479
480 // if (semantic.startsWith(QLatin1String("JOINT")));
481 // if (semantic.startsWith(QLatin1String("JOINTMATRIX")));
482 // if (semantic.startsWith(QLatin1String("WEIGHT")));
483
484 return QString();
485 }
486
487 QParameter *GLTFIO::parameterFromTechnique(QTechnique *technique, const QString &parameterName)
488 {
489 const auto parameters = technique->parameters();
490 for (QParameter *parameter : parameters) {
491 if (parameter->name() == parameterName) {
492 return parameter;
493 }
494 }
495
496 return nullptr;
497 }
498
499 Qt3DCore::QEntity* GLTFIO::defaultScene()
500 {
501 if (Q_UNLIKELY(m_defaultScene.isEmpty())) {
502 qCWarning(GLTFIOLog, "no default scene");
503 return NULL;
504 }
505
506 return scene(m_defaultScene);
507 }
508
509 QMaterial *GLTFIO::materialWithCustomShader(const QString &id, const QJsonObject &jsonObj)
510 {
511 //Default ES2 Technique
512 QString techniqueName = jsonObj.value(KEY_TECHNIQUE).toString();
513 const auto it = std::as_const(m_techniques).find(techniqueName);
514 if (Q_UNLIKELY(it == m_techniques.cend())) {
515 qCWarning(GLTFIOLog, "unknown technique %ls for material %ls in GLTF file %ls",
516 qUtf16PrintableImpl(techniqueName), qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
517 return NULL;
518 }
519 QTechnique *technique = *it;
520 technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGLES);
521 technique->graphicsApiFilter()->setMajorVersion(2);
522 technique->graphicsApiFilter()->setMinorVersion(0);
523 technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
524
525
526 //Optional Core technique
527 QTechnique *coreTechnique = nullptr;
528 QTechnique *gl2Technique = nullptr;
529 QString coreTechniqueName = jsonObj.value(KEY_TECHNIQUE_CORE).toString();
530 if (!coreTechniqueName.isNull()) {
531 const auto it = std::as_const(m_techniques).find(coreTechniqueName);
532 if (Q_UNLIKELY(it == m_techniques.cend())) {
533 qCWarning(GLTFIOLog, "unknown technique %ls for material %ls in GLTF file %ls",
534 qUtf16PrintableImpl(coreTechniqueName), qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
535 } else {
536 coreTechnique = it.value();
537 coreTechnique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
538 coreTechnique->graphicsApiFilter()->setMajorVersion(3);
539 coreTechnique->graphicsApiFilter()->setMinorVersion(1);
540 coreTechnique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile);
541 }
542 }
543 //Optional GL2 technique
544 QString gl2TechniqueName = jsonObj.value(KEY_TECHNIQUE_GL2).toString();
545 if (!gl2TechniqueName.isNull()) {
546 const auto it = std::as_const(m_techniques).find(gl2TechniqueName);
547 if (Q_UNLIKELY(it == m_techniques.cend())) {
548 qCWarning(GLTFIOLog, "unknown technique %ls for material %ls in GLTF file %ls",
549 qUtf16PrintableImpl(gl2TechniqueName), qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
550 } else {
551 gl2Technique = it.value();
552 gl2Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
553 gl2Technique->graphicsApiFilter()->setMajorVersion(2);
554 gl2Technique->graphicsApiFilter()->setMinorVersion(0);
555 gl2Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
556 }
557 }
558
559
560 // glTF doesn't deal in effects, but we need a trivial one to wrap
561 // up our techniques
562 // However we need to create a unique effect for each material instead
563 // of caching because QMaterial does not keep up with effects
564 // its not the parent of.
565 QEffect* effect = new QEffect;
566 effect->setObjectName(techniqueName);
567 effect->addTechnique(technique);
568 if (coreTechnique != nullptr)
569 effect->addTechnique(coreTechnique);
570 if (gl2Technique != nullptr)
571 effect->addTechnique(gl2Technique);
572
573 QMaterial* mat = new QMaterial;
574 mat->setEffect(effect);
575
576 renameFromJson(jsonObj, mat);
577
578 const QJsonObject values = jsonObj.value(KEY_VALUES).toObject();
579 for (auto it = values.begin(), end = values.end(); it != end; ++it) {
580 const QString vName = it.key();
581 QParameter *param = parameterFromTechnique(technique, vName);
582
583 if (param == nullptr && coreTechnique != nullptr) {
584 param = parameterFromTechnique(coreTechnique, vName);
585 }
586
587 if (param == nullptr && gl2Technique != nullptr) {
588 param = parameterFromTechnique(gl2Technique, vName);
589 }
590
591 if (Q_UNLIKELY(!param)) {
592 qCWarning(GLTFIOLog, "unknown parameter: %ls in technique %ls processing material %ls",
593 qUtf16PrintableImpl(vName), qUtf16PrintableImpl(techniqueName), qUtf16PrintableImpl(id));
594 continue;
595 }
596
597 ParameterData paramData = m_parameterDataDict.value(param);
598 QVariant var = parameterValueFromJSON(paramData.type, it.value());
599
600 mat->addParameter(new QParameter(param->name(), var));
601 } // of material technique-instance values iteration
602
603 return mat;
604 }
605
606 static inline QVariant vec4ToRgb(const QVariant &vec4Var)
607 {
608 const QVector4D v = vec4Var.value<QVector4D>();
609 return QVariant(QColor::fromRgbF(v.x(), v.y(), v.z()));
610 }
611
612 QMaterial *GLTFIO::commonMaterial(const QJsonObject &jsonObj)
613 {
614 QVariantHash params;
615 bool hasDiffuseMap = false;
616 bool hasSpecularMap = false;
617 bool hasNormalMap = false;
618
619 const QJsonObject values = jsonObj.value(KEY_VALUES).toObject();
620 for (auto it = values.begin(), end = values.end(); it != end; ++it) {
621 const QString vName = it.key();
622 const QJsonValue val = it.value();
623 QVariant var;
624 QString propertyName = vName;
625 if (vName == QLatin1String("ambient") && val.isArray()) {
626 var = vec4ToRgb(parameterValueFromJSON(GL_FLOAT_VEC4, val));
627 } else if (vName == QLatin1String("diffuse")) {
628 if (val.isString()) {
629 var = parameterValueFromJSON(GL_SAMPLER_2D, val);
630 hasDiffuseMap = true;
631 } else if (val.isArray()) {
632 var = vec4ToRgb(parameterValueFromJSON(GL_FLOAT_VEC4, val));
633 }
634 } else if (vName == QLatin1String("specular")) {
635 if (val.isString()) {
636 var = parameterValueFromJSON(GL_SAMPLER_2D, val);
637 hasSpecularMap = true;
638 } else if (val.isArray()) {
639 var = vec4ToRgb(parameterValueFromJSON(GL_FLOAT_VEC4, val));
640 }
641 } else if (vName == QLatin1String("shininess") && val.isDouble()) {
642 var = parameterValueFromJSON(GL_FLOAT, val);
643 } else if (vName == QLatin1String("normalmap") && val.isString()) {
644 var = parameterValueFromJSON(GL_SAMPLER_2D, val);
645 propertyName = QStringLiteral("normal");
646 hasNormalMap = true;
647 } else if (vName == QLatin1String("transparency")) {
648 qCWarning(GLTFIOLog, "Semi-transparent common materials are not currently supported, ignoring alpha");
649 }
650 if (var.isValid())
651 params[propertyName] = var;
652 }
653
654 QMaterial *mat = nullptr;
655 if (hasNormalMap) {
656 if (hasSpecularMap) {
657 mat = new QNormalDiffuseSpecularMapMaterial;
658 } else {
659 if (Q_UNLIKELY(!hasDiffuseMap))
660 qCWarning(GLTFIOLog, "Common material with normal and specular maps needs a diffuse map as well");
661 else
662 mat = new QNormalDiffuseMapMaterial;
663 }
664 } else {
665 if (hasSpecularMap) {
666 if (Q_UNLIKELY(!hasDiffuseMap))
667 qCWarning(GLTFIOLog, "Common material with specular map needs a diffuse map as well");
668 else
669 mat = new QDiffuseSpecularMapMaterial;
670 } else if (hasDiffuseMap) {
671 mat = new QDiffuseMapMaterial;
672 } else {
673 mat = new QPhongMaterial;
674 }
675 }
676
677 if (Q_UNLIKELY(!mat)) {
678 qCWarning(GLTFIOLog, "Could not find a suitable built-in material for KHR_materials_common");
679 } else {
680 for (QVariantHash::const_iterator it = params.constBegin(), itEnd = params.constEnd(); it != itEnd; ++it)
681 mat->setProperty(it.key().toUtf8(), it.value());
682 }
683
684 return mat;
685 }
686
687 QMaterial* GLTFIO::material(const QString &id)
688 {
689 const auto it = std::as_const(m_materialCache).find(id);
690 if (it != m_materialCache.cend())
691 return it.value();
692
693 QJsonObject mats = m_json.object().value(KEY_MATERIALS).toObject();
694 const auto jsonVal = mats.value(id);
695 if (Q_UNLIKELY(jsonVal.isUndefined())) {
696 qCWarning(GLTFIOLog, "unknown material %ls in GLTF file %ls",
697 qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
698 return NULL;
699 }
700
701 const QJsonObject jsonObj = jsonVal.toObject();
702
703 QMaterial *mat = nullptr;
704
705 // Prefer common materials over custom shaders.
706 const auto extensionMat = jsonObj.value(KEY_EXTENSIONS).toObject().value(KEY_COMMON_MAT);
707 if (!extensionMat.isUndefined())
708 mat = commonMaterial(extensionMat.toObject());
709
710 if (!mat)
711 mat = materialWithCustomShader(id, jsonObj);
712
713 m_materialCache[id] = mat;
714 return mat;
715 }
716
717 QCameraLens* GLTFIO::camera(const QString &id) const
718 {
719 const auto jsonVal = m_json.object().value(KEY_CAMERAS).toObject().value(id);
720 if (Q_UNLIKELY(jsonVal.isUndefined())) {
721 qCWarning(GLTFIOLog, "unknown camera %ls in GLTF file %ls",
722 qUtf16PrintableImpl(id), qUtf16PrintableImpl(m_basePath));
723 return nullptr;
724 }
725
726 QJsonObject jsonObj = jsonVal.toObject();
727 QString camTy = jsonObj.value(KEY_TYPE).toString();
728
729 if (camTy == QLatin1String("perspective")) {
730 const auto pVal = jsonObj.value(KEY_PERSPECTIVE);
731 if (Q_UNLIKELY(pVal.isUndefined())) {
732 qCWarning(GLTFIOLog, "camera: %ls missing 'perspective' object",
733 qUtf16PrintableImpl(id));
734 return nullptr;
735 }
736
737 const QJsonObject pObj = pVal.toObject();
738 double aspectRatio = pObj.value(KEY_ASPECT_RATIO).toDouble();
739 double yfov = pObj.value(KEY_YFOV).toDouble();
740 double frustumNear = pObj.value(KEY_ZNEAR).toDouble();
741 double frustumFar = pObj.value(KEY_ZFAR).toDouble();
742
743 QCameraLens* result = new QCameraLens;
744 result->setPerspectiveProjection(yfov, aspectRatio, frustumNear, frustumFar);
745 return result;
746 } else if (camTy == QLatin1String("orthographic")) {
747 qCWarning(GLTFIOLog, "implement me");
748
749 return nullptr;
750 } else {
751 qCWarning(GLTFIOLog, "camera: %ls has unsupported type: %ls",
752 qUtf16PrintableImpl(id), qUtf16PrintableImpl(camTy));
753 return nullptr;
754 }
755 }
756
757
758 void GLTFIO::parse()
759 {
760 if (m_parseDone)
761 return;
762
763 const QJsonObject buffers = m_json.object().value(KEY_BUFFERS).toObject();
764 for (auto it = buffers.begin(), end = buffers.end(); it != end; ++it)
765 processJSONBuffer(it.key(), it.value().toObject());
766
767 const QJsonObject views = m_json.object().value(KEY_BUFFER_VIEWS).toObject();
768 loadBufferData();
769 for (auto it = views.begin(), end = views.end(); it != end; ++it)
770 processJSONBufferView(it.key(), it.value().toObject());
771 unloadBufferData();
772
773 const QJsonObject shaders = m_json.object().value(KEY_SHADERS).toObject();
774 for (auto it = shaders.begin(), end = shaders.end(); it != end; ++it)
775 processJSONShader(it.key(), it.value().toObject());
776
777 const QJsonObject programs = m_json.object().value(KEY_PROGRAMS).toObject();
778 for (auto it = programs.begin(), end = programs.end(); it != end; ++it)
779 processJSONProgram(it.key(), it.value().toObject());
780
781 const QJsonObject techniques = m_json.object().value(KEY_TECHNIQUES).toObject();
782 for (auto it = techniques.begin(), end = techniques.end(); it != end; ++it)
783 processJSONTechnique(it.key(), it.value().toObject());
784
785 const QJsonObject attrs = m_json.object().value(KEY_ACCESSORS).toObject();
786 for (auto it = attrs.begin(), end = attrs.end(); it != end; ++it)
787 processJSONAccessor(it.key(), it.value().toObject());
788
789 const QJsonObject meshes = m_json.object().value(KEY_MESHES).toObject();
790 for (auto it = meshes.begin(), end = meshes.end(); it != end; ++it)
791 processJSONMesh(it.key(), it.value().toObject());
792
793 const QJsonObject images = m_json.object().value(KEY_IMAGES).toObject();
794 for (auto it = images.begin(), end = images.end(); it != end; ++it)
795 processJSONImage(it.key(), it.value().toObject());
796
797 const QJsonObject textures = m_json.object().value(KEY_TEXTURES).toObject();
798 for (auto it = textures.begin(), end = textures.end(); it != end; ++it)
799 processJSONTexture(it.key(), it.value().toObject());
800
801 m_defaultScene = m_json.object().value(KEY_SCENE).toString();
802 m_parseDone = true;
803 }
804
805 namespace {
806 template <typename C>
807 void delete_if_without_parent(const C &c)
808 {
809 for (const auto *e : c) {
810 if (!e->parent())
811 delete e;
812 }
813 }
814 } // unnamed namespace
815
816 void GLTFIO::cleanup()
817 {
818 m_meshDict.clear();
819 m_meshMaterialDict.clear();
820 m_accessorDict.clear();
821 delete_if_without_parent(m_materialCache);
822 m_materialCache.clear();
823 m_bufferDatas.clear();
824 m_buffers.clear();
825 m_shaderPaths.clear();
826 delete_if_without_parent(m_programs);
827 m_programs.clear();
828 delete_if_without_parent(m_techniques);
829 m_techniques.clear();
830 delete_if_without_parent(m_textures);
831 m_textures.clear();
832 m_imagePaths.clear();
833 m_defaultScene.clear();
834 m_parameterDataDict.clear();
835 }
836
837 void GLTFIO::processJSONBuffer(const QString &id, const QJsonObject& json)
838 {
839 // simply cache buffers for lookup by buffer-views
840 m_bufferDatas[id] = BufferData(json);
841 }
842
843 void GLTFIO::processJSONBufferView(const QString &id, const QJsonObject& json)
844 {
845 QString bufName = json.value(KEY_BUFFER).toString();
846 const auto it = std::as_const(m_bufferDatas).find(bufName);
847 if (Q_UNLIKELY(it == m_bufferDatas.cend())) {
848 qCWarning(GLTFIOLog, "unknown buffer: %ls processing view: %ls",
849 qUtf16PrintableImpl(bufName), qUtf16PrintableImpl(id));
850 return;
851 }
852 const auto &bufferData = *it;
853
854 int target = json.value(KEY_TARGET).toInt();
855 Qt3DRender::QBuffer::BufferType ty(Qt3DRender::QBuffer::VertexBuffer);
856
857 switch (target) {
858 case GL_ARRAY_BUFFER: ty = Qt3DRender::QBuffer::VertexBuffer; break;
859 case GL_ELEMENT_ARRAY_BUFFER: ty = Qt3DRender::QBuffer::IndexBuffer; break;
860 default:
861 qCWarning(GLTFIOLog, "buffer %ls unsupported target: %d",
862 qUtf16PrintableImpl(id), target);
863 return;
864 }
865
866 quint64 offset = 0;
867 const auto byteOffset = json.value(KEY_BYTE_OFFSET);
868 if (!byteOffset.isUndefined()) {
869 offset = byteOffset.toInt();
870 qCDebug(GLTFIOLog, "bv: %ls has offset: %lld", qUtf16PrintableImpl(id), offset);
871 }
872
873 quint64 len = json.value(KEY_BYTE_LENGTH).toInt();
874
875 QByteArray bytes = bufferData.data->mid(offset, len);
876 if (Q_UNLIKELY(bytes.size() != qsizetype(len))) {
877 qCWarning(GLTFIOLog, "failed to read sufficient bytes from: %ls for view %ls",
878 qUtf16PrintableImpl(bufferData.path), qUtf16PrintableImpl(id));
879 }
880
881 Qt3DRender::QBuffer *b(new Qt3DRender::QBuffer(ty));
882 b->setData(bytes);
883 m_buffers[id] = b;
884 }
885
886 void GLTFIO::processJSONShader(const QString &id, const QJsonObject &jsonObject)
887 {
888 // shaders are trivial for the moment, defer the real work
889 // to the program section
890 QString path = jsonObject.value(KEY_URI).toString();
891
892 QFileInfo info(m_basePath, path);
893 if (Q_UNLIKELY(!info.exists())) {
894 qCWarning(GLTFIOLog, "can't find shader %ls from path %ls",
895 qUtf16PrintableImpl(id), qUtf16PrintableImpl(path));
896 return;
897 }
898
899 m_shaderPaths[id] = info.absoluteFilePath();
900 }
901
902 void GLTFIO::processJSONProgram(const QString &id, const QJsonObject &jsonObject)
903 {
904 QString fragName = jsonObject.value(KEY_FRAGMENT_SHADER).toString(),
905 vertName = jsonObject.value(KEY_VERTEX_SHADER).toString();
906 const auto fragIt = std::as_const(m_shaderPaths).find(fragName),
907 vertIt = std::as_const(m_shaderPaths).find(vertName);
908 if (Q_UNLIKELY(fragIt == m_shaderPaths.cend() || vertIt == m_shaderPaths.cend())) {
909 qCWarning(GLTFIOLog, "program: %ls missing shader: %ls %ls",
910 qUtf16PrintableImpl(id), qUtf16PrintableImpl(fragName), qUtf16PrintableImpl(vertName));
911 return;
912 }
913
914 QShaderProgram* prog = new QShaderProgram;
915 prog->setObjectName(id);
916 prog->setFragmentShaderCode(QShaderProgram::loadSource(QUrl::fromLocalFile(fragIt.value())));
917 prog->setVertexShaderCode(QShaderProgram::loadSource(QUrl::fromLocalFile(vertIt.value())));
918 m_programs[id] = prog;
919 }
920
921 void GLTFIO::processJSONTechnique(const QString &id, const QJsonObject &jsonObject )
922 {
923 QTechnique *t = new QTechnique;
924 t->setObjectName(id);
925
926 // Parameters
927 QHash<QString, QParameter*> paramDict;
928 const QJsonObject params = jsonObject.value(KEY_PARAMETERS).toObject();
929 for (auto it = params.begin(), end = params.end(); it != end; ++it) {
930 const QString pname = it.key();
931 const QJsonObject po = it.value().toObject();
932
933 //QString semantic = po.value(KEY_SEMANTIC).toString();
934 QParameter *p = new QParameter(t);
935 p->setName(pname);
936 m_parameterDataDict.insert(p, ParameterData(po));
937
938 //If the parameter has default value, set it
939 QJsonValue value = po.value(KEY_VALUE);
940 if (!value.isUndefined()) {
941 int dataType = po.value(KEY_TYPE).toInt();
942 p->setValue(parameterValueFromJSON(dataType, value));
943 }
944
945 t->addParameter(p);
946
947 paramDict[pname] = p;
948 } // of parameters iteration
949
950 // Program
951 QRenderPass* pass = new QRenderPass;
952 QString programName = jsonObject.value(KEY_PROGRAM).toString();
953 const auto progIt = std::as_const(m_programs).find(programName);
954 if (Q_UNLIKELY(progIt == m_programs.cend())) {
955 qCWarning(GLTFIOLog, "technique %ls: missing program %ls",
956 qUtf16PrintableImpl(id), qUtf16PrintableImpl(programName));
957 } else {
958 pass->setShaderProgram(progIt.value());
959 }
960
961 // Attributes
962 const QJsonObject attrs = jsonObject.value(KEY_ATTRIBUTES).toObject();
963 for (auto it = attrs.begin(), end = attrs.end(); it != end; ++it) {
964 QString pname = it.value().toString();
965 QParameter *parameter = paramDict.value(pname, nullptr);
966 QString attributeName = pname;
967 if (Q_UNLIKELY(!parameter)) {
968 qCWarning(GLTFIOLog, "attribute %ls defined in instanceProgram but not as parameter",
969 qUtf16PrintableImpl(pname));
970 continue;
971 }
972 //Check if the parameter has a standard attribute semantic
973 const auto paramDataIt = m_parameterDataDict.find(parameter);
974 QString standardAttributeName = standardAttributeNameFromSemantic(paramDataIt->semantic);
975 if (!standardAttributeName.isNull()) {
976 attributeName = standardAttributeName;
977 t->removeParameter(parameter);
978 m_parameterDataDict.erase(paramDataIt);
979 delete parameter;
980 }
981
982 } // of program-instance attributes
983
984 // Uniforms
985 const QJsonObject uniforms = jsonObject.value(KEY_UNIFORMS).toObject();
986 for (auto it = uniforms.begin(), end = uniforms.end(); it != end; ++it) {
987 const QString pname = it.value().toString();
988 QParameter *parameter = paramDict.value(pname, nullptr);
989 if (Q_UNLIKELY(!parameter)) {
990 qCWarning(GLTFIOLog, "uniform %ls defined in instanceProgram but not as parameter",
991 qUtf16PrintableImpl(pname));
992 continue;
993 }
994 //Check if the parameter has a standard uniform semantic
995 const auto paramDataIt = m_parameterDataDict.find(parameter);
996 if (hasStandardUniformNameFromSemantic(paramDataIt->semantic)) {
997 t->removeParameter(parameter);
998 m_parameterDataDict.erase(paramDataIt);
999 delete parameter;
1000 }
1001 } // of program-instance uniforms
1002
1003
1004 // States
1005 QJsonObject states = jsonObject.value(KEY_STATES).toObject();
1006
1007 //Process states to enable
1008 const QJsonArray enableStatesArray = states.value(KEY_ENABLE).toArray();
1009 QList<int> enableStates;
1010 for (const QJsonValue &enableValue : enableStatesArray)
1011 enableStates.append(enableValue.toInt());
1012
1013 //Process the list of state functions
1014 const QJsonObject functions = states.value(KEY_FUNCTIONS).toObject();
1015 for (auto it = functions.begin(), end = functions.end(); it != end; ++it) {
1016 int enableStateType = 0;
1017 QRenderState *renderState = buildState(it.key(), it.value(), enableStateType);
1018 if (renderState != nullptr) {
1019 //Remove the need to set a default state values for enableStateType
1020 enableStates.removeOne(enableStateType);
1021 pass->addRenderState(renderState);
1022 }
1023 }
1024
1025 //Create render states with default values for any remaining enable states
1026 for (int enableState : std::as_const(enableStates)) {
1027 QRenderState *renderState = buildStateEnable(enableState);
1028 if (renderState != nullptr)
1029 pass->addRenderState(renderState);
1030 }
1031
1032
1033 t->addRenderPass(pass);
1034
1035 m_techniques[id] = t;
1036 }
1037
1038 void GLTFIO::processJSONAccessor( const QString &id, const QJsonObject& json )
1039 {
1040 m_accessorDict[id] = AccessorData(json);
1041 }
1042
1043 void GLTFIO::processJSONMesh(const QString &id, const QJsonObject &json)
1044 {
1045 const QJsonArray primitivesArray = json.value(KEY_PRIMITIVES).toArray();
1046 for (const QJsonValue &primitiveValue : primitivesArray) {
1047 QJsonObject primitiveObject = primitiveValue.toObject();
1048 int type = primitiveObject.value(KEY_MODE).toInt();
1049 QString material = primitiveObject.value(KEY_MATERIAL).toString();
1050
1051 if (Q_UNLIKELY(material.isEmpty())) {
1052 qCWarning(GLTFIOLog, "malformed primitive on %ls, missing material value %ls",
1053 qUtf16PrintableImpl(id), qUtf16PrintableImpl(material));
1054 continue;
1055 }
1056
1057 QGeometryRenderer *geometryRenderer = new QGeometryRenderer;
1058 QGeometry *meshGeometry = new QGeometry(geometryRenderer);
1059
1060 //Set Primitive Type
1061 geometryRenderer->setPrimitiveType(static_cast<QGeometryRenderer::PrimitiveType>(type));
1062
1063 //Save Material for mesh
1064 m_meshMaterialDict[geometryRenderer] = material;
1065
1066 const QJsonObject attrs = primitiveObject.value(KEY_ATTRIBUTES).toObject();
1067 for (auto it = attrs.begin(), end = attrs.end(); it != end; ++it) {
1068 QString k = it.value().toString();
1069 const auto accessorIt = std::as_const(m_accessorDict).find(k);
1070 if (Q_UNLIKELY(accessorIt == m_accessorDict.cend())) {
1071 qCWarning(GLTFIOLog, "unknown attribute accessor: %ls on mesh %ls",
1072 qUtf16PrintableImpl(k), qUtf16PrintableImpl(id));
1073 continue;
1074 }
1075
1076 const QString attrName = it.key();
1077 QString attributeName = standardAttributeNameFromSemantic(attrName);
1078 if (attributeName.isEmpty())
1079 attributeName = attrName;
1080
1081 //Get buffer handle for accessor
1082 Qt3DRender::QBuffer *buffer = m_buffers.value(accessorIt->bufferViewName, nullptr);
1083 if (Q_UNLIKELY(!buffer)) {
1084 qCWarning(GLTFIOLog, "unknown buffer-view: %ls processing accessor: %ls",
1085 qUtf16PrintableImpl(accessorIt->bufferViewName), qUtf16PrintableImpl(id));
1086 continue;
1087 }
1088
1089 QAttribute *attribute = new QAttribute(buffer,
1090 attributeName,
1091 accessorIt->type,
1092 accessorIt->dataSize,
1093 accessorIt->count,
1094 accessorIt->offset,
1095 accessorIt->stride);
1096 attribute->setAttributeType(QAttribute::VertexAttribute);
1097 meshGeometry->addAttribute(attribute);
1098 }
1099
1100 const auto indices = primitiveObject.value(KEY_INDICES);
1101 if (!indices.isUndefined()) {
1102 QString k = indices.toString();
1103 const auto accessorIt = std::as_const(m_accessorDict).find(k);
1104 if (Q_UNLIKELY(accessorIt == m_accessorDict.cend())) {
1105 qCWarning(GLTFIOLog, "unknown index accessor: %ls on mesh %ls",
1106 qUtf16PrintableImpl(k), qUtf16PrintableImpl(id));
1107 } else {
1108 //Get buffer handle for accessor
1109 Qt3DRender::QBuffer *buffer = m_buffers.value(accessorIt->bufferViewName, nullptr);
1110 if (Q_UNLIKELY(!buffer)) {
1111 qCWarning(GLTFIOLog, "unknown buffer-view: %ls processing accessor: %ls",
1112 qUtf16PrintableImpl(accessorIt->bufferViewName), qUtf16PrintableImpl(id));
1113 continue;
1114 }
1115
1116 QAttribute *attribute = new QAttribute(buffer,
1117 accessorIt->type,
1118 accessorIt->dataSize,
1119 accessorIt->count,
1120 accessorIt->offset,
1121 accessorIt->stride);
1122 attribute->setAttributeType(QAttribute::IndexAttribute);
1123 meshGeometry->addAttribute(attribute);
1124 }
1125 } // of has indices
1126
1127 geometryRenderer->setGeometry(meshGeometry);
1128
1129 m_meshDict.insert( id, geometryRenderer);
1130 } // of primitives iteration
1131 }
1132
1133 void GLTFIO::processJSONImage(const QString &id, const QJsonObject &jsonObject)
1134 {
1135 QString path = jsonObject.value(KEY_URI).toString();
1136 QFileInfo info(m_basePath, path);
1137 if (Q_UNLIKELY(!info.exists())) {
1138 qCWarning(GLTFIOLog, "can't find image %ls from path %ls",
1139 qUtf16PrintableImpl(id), qUtf16PrintableImpl(path));
1140 return;
1141 }
1142
1143 m_imagePaths[id] = info.absoluteFilePath();
1144 }
1145
1146 void GLTFIO::processJSONTexture(const QString &id, const QJsonObject &jsonObject)
1147 {
1148 int target = jsonObject.value(KEY_TARGET).toInt(GL_TEXTURE_2D);
1149 //TODO: support other targets that GL_TEXTURE_2D (though the spec doesn't support anything else)
1150 if (Q_UNLIKELY(target != GL_TEXTURE_2D)) {
1151 qCWarning(GLTFIOLog, "unsupported texture target: %d", target);
1152 return;
1153 }
1154
1155 QTextureLoader* tex = new QTextureLoader;
1156 tex->setMirrored(false);
1157
1158 QString samplerId = jsonObject.value(KEY_SAMPLER).toString();
1159 QString source = jsonObject.value(KEY_SOURCE).toString();
1160 const auto imagIt = std::as_const(m_imagePaths).find(source);
1161 if (Q_UNLIKELY(imagIt == m_imagePaths.cend())) {
1162 qCWarning(GLTFIOLog, "texture %ls references missing image %ls",
1163 qUtf16PrintableImpl(id), qUtf16PrintableImpl(source));
1164 return;
1165 }
1166
1167 tex->setSource(QUrl::fromLocalFile(imagIt.value()));
1168
1169 const auto samplersDictValue = m_json.object().value(KEY_SAMPLERS).toObject().value(samplerId);
1170 if (Q_UNLIKELY(samplersDictValue.isUndefined())) {
1171 qCWarning(GLTFIOLog, "texture %ls references unknown sampler %ls",
1172 qUtf16PrintableImpl(id), qUtf16PrintableImpl(samplerId));
1173 return;
1174 }
1175
1176 QJsonObject sampler = samplersDictValue.toObject();
1177
1178 tex->setWrapMode(QTextureWrapMode(static_cast<QTextureWrapMode::WrapMode>(sampler.value(KEY_WRAP_S).toInt())));
1179 tex->setMinificationFilter(static_cast<QAbstractTexture::Filter>(sampler.value(KEY_MIN_FILTER).toInt()));
1180 if (tex->minificationFilter() == QAbstractTexture::NearestMipMapLinear ||
1181 tex->minificationFilter() == QAbstractTexture::LinearMipMapNearest ||
1182 tex->minificationFilter() == QAbstractTexture::NearestMipMapNearest ||
1183 tex->minificationFilter() == QAbstractTexture::LinearMipMapLinear) {
1184
1185 tex->setGenerateMipMaps(true);
1186 }
1187 tex->setMagnificationFilter(static_cast<QAbstractTexture::Filter>(sampler.value(KEY_MAG_FILTER).toInt()));
1188
1189 m_textures[id] = tex;
1190 }
1191
1192 void GLTFIO::loadBufferData()
1193 {
1194 for (auto &bufferData : m_bufferDatas) {
1195 if (!bufferData.data) {
1196 bufferData.data = new QByteArray(resolveLocalData(bufferData.path));
1197 }
1198 }
1199 }
1200
1201 void GLTFIO::unloadBufferData()
1202 {
1203 for (const auto &bufferData : std::as_const(m_bufferDatas)) {
1204 QByteArray *data = bufferData.data;
1205 delete data;
1206 }
1207 }
1208
1209 QByteArray GLTFIO::resolveLocalData(const QString &path) const
1210 {
1211 QDir d(m_basePath);
1212 Q_ASSERT(d.exists());
1213
1214 QString absPath = d.absoluteFilePath(path);
1215 QFile f(absPath);
1216 f.open(QIODevice::ReadOnly);
1217 return f.readAll();
1218 }
1219
1220 QVariant GLTFIO::parameterValueFromJSON(int type, const QJsonValue &value) const
1221 {
1222 if (value.isBool()) {
1223 if (type == GL_BOOL)
1224 return QVariant(static_cast<GLboolean>(value.toBool()));
1225 } else if (value.isString()) {
1226 if (type == GL_SAMPLER_2D) {
1227 //Textures are special because we need to do a lookup to return the
1228 //QAbstractTexture
1229 QString textureId = value.toString();
1230 const auto it = m_textures.find(textureId);
1231 if (Q_UNLIKELY(it == m_textures.end())) {
1232 qCWarning(GLTFIOLog, "unknown texture %ls", qUtf16PrintableImpl(textureId));
1233 return QVariant();
1234 } else {
1235 return QVariant::fromValue(it.value());
1236 }
1237 }
1238 } else if (value.isDouble()) {
1239 switch (type) {
1240 case GL_BYTE:
1241 return QVariant(static_cast<GLbyte>(value.toInt()));
1242 case GL_UNSIGNED_BYTE:
1243 return QVariant(static_cast<GLubyte>(value.toInt()));
1244 case GL_SHORT:
1245 return QVariant(static_cast<GLshort>(value.toInt()));
1246 case GL_UNSIGNED_SHORT:
1247 return QVariant(static_cast<GLushort>(value.toInt()));
1248 case GL_INT:
1249 return QVariant(static_cast<GLint>(value.toInt()));
1250 case GL_UNSIGNED_INT:
1251 return QVariant(static_cast<GLuint>(value.toInt()));
1252 case GL_FLOAT:
1253 return QVariant(static_cast<GLfloat>(value.toDouble()));
1254 }
1255 } else if (value.isArray()) {
1256
1257 const QJsonArray valueArray = value.toArray();
1258
1259 QVector2D vector2D;
1260 QVector3D vector3D;
1261 QVector4D vector4D;
1262 QList<float> dataMat2(4, 0.0f);
1263 QList<float> dataMat3(9, 0.0f);
1264
1265 switch (type) {
1266 case GL_BYTE:
1267 return QVariant(static_cast<GLbyte>(valueArray.first().toInt()));
1268 case GL_UNSIGNED_BYTE:
1269 return QVariant(static_cast<GLubyte>(valueArray.first().toInt()));
1270 case GL_SHORT:
1271 return QVariant(static_cast<GLshort>(valueArray.first().toInt()));
1272 case GL_UNSIGNED_SHORT:
1273 return QVariant(static_cast<GLushort>(valueArray.first().toInt()));
1274 case GL_INT:
1275 return QVariant(static_cast<GLint>(valueArray.first().toInt()));
1276 case GL_UNSIGNED_INT:
1277 return QVariant(static_cast<GLuint>(valueArray.first().toInt()));
1278 case GL_FLOAT:
1279 return QVariant(static_cast<GLfloat>(valueArray.first().toDouble()));
1280 case GL_FLOAT_VEC2:
1281 vector2D.setX(static_cast<GLfloat>(valueArray.at(0).toDouble()));
1282 vector2D.setY(static_cast<GLfloat>(valueArray.at(1).toDouble()));
1283 return QVariant(vector2D);
1284 case GL_FLOAT_VEC3:
1285 vector3D.setX(static_cast<GLfloat>(valueArray.at(0).toDouble()));
1286 vector3D.setY(static_cast<GLfloat>(valueArray.at(1).toDouble()));
1287 vector3D.setZ(static_cast<GLfloat>(valueArray.at(2).toDouble()));
1288 return QVariant(vector3D);
1289 case GL_FLOAT_VEC4:
1290 vector4D.setX(static_cast<GLfloat>(valueArray.at(0).toDouble()));
1291 vector4D.setY(static_cast<GLfloat>(valueArray.at(1).toDouble()));
1292 vector4D.setZ(static_cast<GLfloat>(valueArray.at(2).toDouble()));
1293 vector4D.setW(static_cast<GLfloat>(valueArray.at(3).toDouble()));
1294 return QVariant(vector4D);
1295 case GL_INT_VEC2:
1296 vector2D.setX(static_cast<GLint>(valueArray.at(0).toInt()));
1297 vector2D.setY(static_cast<GLint>(valueArray.at(1).toInt()));
1298 return QVariant(vector2D);
1299 case GL_INT_VEC3:
1300 vector3D.setX(static_cast<GLint>(valueArray.at(0).toInt()));
1301 vector3D.setY(static_cast<GLint>(valueArray.at(1).toInt()));
1302 vector3D.setZ(static_cast<GLint>(valueArray.at(2).toInt()));
1303 return QVariant(vector3D);
1304 case GL_INT_VEC4:
1305 vector4D.setX(static_cast<GLint>(valueArray.at(0).toInt()));
1306 vector4D.setY(static_cast<GLint>(valueArray.at(1).toInt()));
1307 vector4D.setZ(static_cast<GLint>(valueArray.at(2).toInt()));
1308 vector4D.setW(static_cast<GLint>(valueArray.at(3).toInt()));
1309 return QVariant(vector4D);
1310 case GL_BOOL:
1311 return QVariant(static_cast<GLboolean>(valueArray.first().toBool()));
1312 case GL_BOOL_VEC2:
1313 vector2D.setX(static_cast<GLboolean>(valueArray.at(0).toBool()));
1314 vector2D.setY(static_cast<GLboolean>(valueArray.at(1).toBool()));
1315 return QVariant(vector2D);
1316 case GL_BOOL_VEC3:
1317 vector3D.setX(static_cast<GLboolean>(valueArray.at(0).toBool()));
1318 vector3D.setY(static_cast<GLboolean>(valueArray.at(1).toBool()));
1319 vector3D.setZ(static_cast<GLboolean>(valueArray.at(2).toBool()));
1320 return QVariant(vector3D);
1321 case GL_BOOL_VEC4:
1322 vector4D.setX(static_cast<GLboolean>(valueArray.at(0).toBool()));
1323 vector4D.setY(static_cast<GLboolean>(valueArray.at(1).toBool()));
1324 vector4D.setZ(static_cast<GLboolean>(valueArray.at(2).toBool()));
1325 vector4D.setW(static_cast<GLboolean>(valueArray.at(3).toBool()));
1326 return QVariant(vector4D);
1327 case GL_FLOAT_MAT2:
1328 //Matrix2x2 is in Row Major ordering (so we need to convert)
1329 dataMat2[0] = static_cast<GLfloat>(valueArray.at(0).toDouble());
1330 dataMat2[1] = static_cast<GLfloat>(valueArray.at(2).toDouble());
1331 dataMat2[2] = static_cast<GLfloat>(valueArray.at(1).toDouble());
1332 dataMat2[3] = static_cast<GLfloat>(valueArray.at(3).toDouble());
1333 return QVariant::fromValue(QMatrix2x2(dataMat2.constData()));
1334 case GL_FLOAT_MAT3:
1335 //Matrix3x3 is in Row Major ordering (so we need to convert)
1336 dataMat3[0] = static_cast<GLfloat>(valueArray.at(0).toDouble());
1337 dataMat3[1] = static_cast<GLfloat>(valueArray.at(3).toDouble());
1338 dataMat3[2] = static_cast<GLfloat>(valueArray.at(6).toDouble());
1339 dataMat3[3] = static_cast<GLfloat>(valueArray.at(1).toDouble());
1340 dataMat3[4] = static_cast<GLfloat>(valueArray.at(4).toDouble());
1341 dataMat3[5] = static_cast<GLfloat>(valueArray.at(7).toDouble());
1342 dataMat3[6] = static_cast<GLfloat>(valueArray.at(2).toDouble());
1343 dataMat3[7] = static_cast<GLfloat>(valueArray.at(5).toDouble());
1344 dataMat3[8] = static_cast<GLfloat>(valueArray.at(8).toDouble());
1345 return QVariant::fromValue(QMatrix3x3(dataMat3.constData()));
1346 case GL_FLOAT_MAT4:
1347 //Matrix4x4 is Column Major ordering
1348 return QVariant(QMatrix4x4(static_cast<GLfloat>(valueArray.at(0).toDouble()),
1349 static_cast<GLfloat>(valueArray.at(1).toDouble()),
1350 static_cast<GLfloat>(valueArray.at(2).toDouble()),
1351 static_cast<GLfloat>(valueArray.at(3).toDouble()),
1352 static_cast<GLfloat>(valueArray.at(4).toDouble()),
1353 static_cast<GLfloat>(valueArray.at(5).toDouble()),
1354 static_cast<GLfloat>(valueArray.at(6).toDouble()),
1355 static_cast<GLfloat>(valueArray.at(7).toDouble()),
1356 static_cast<GLfloat>(valueArray.at(8).toDouble()),
1357 static_cast<GLfloat>(valueArray.at(9).toDouble()),
1358 static_cast<GLfloat>(valueArray.at(10).toDouble()),
1359 static_cast<GLfloat>(valueArray.at(11).toDouble()),
1360 static_cast<GLfloat>(valueArray.at(12).toDouble()),
1361 static_cast<GLfloat>(valueArray.at(13).toDouble()),
1362 static_cast<GLfloat>(valueArray.at(14).toDouble()),
1363 static_cast<GLfloat>(valueArray.at(15).toDouble())));
1364 case GL_SAMPLER_2D:
1365 return QVariant(valueArray.at(0).toString());
1366 }
1367 }
1368 return QVariant();
1369 }
1370
1371 QAttribute::VertexBaseType GLTFIO::accessorTypeFromJSON(int componentType)
1372 {
1373 if (componentType == GL_BYTE) {
1374 return QAttribute::Byte;
1375 } else if (componentType == GL_UNSIGNED_BYTE) {
1376 return QAttribute::UnsignedByte;
1377 } else if (componentType == GL_SHORT) {
1378 return QAttribute::Short;
1379 } else if (componentType == GL_UNSIGNED_SHORT) {
1380 return QAttribute::UnsignedShort;
1381 } else if (componentType == GL_UNSIGNED_INT) {
1382 return QAttribute::UnsignedInt;
1383 } else if (componentType == GL_FLOAT) {
1384 return QAttribute::Float;
1385 }
1386
1387 //There shouldn't be an invalid case here
1388 qCWarning(GLTFIOLog, "unsupported accessor type %d", componentType);
1389 return QAttribute::Float;
1390 }
1391
1392 uint GLTFIO::accessorDataSizeFromJson(const QString &type)
1393 {
1394 QString typeName = type.toUpper();
1395 if (typeName == QLatin1String("SCALAR"))
1396 return 1;
1397 if (typeName == QLatin1String("VEC2"))
1398 return 2;
1399 if (typeName == QLatin1String("VEC3"))
1400 return 3;
1401 if (typeName == QLatin1String("VEC4"))
1402 return 4;
1403 if (typeName == QLatin1String("MAT2"))
1404 return 4;
1405 if (typeName == QLatin1String("MAT3"))
1406 return 9;
1407 if (typeName == QLatin1String("MAT4"))
1408 return 16;
1409
1410 return 0;
1411 }
1412
1413 QRenderState *GLTFIO::buildStateEnable(int state)
1414 {
1415 int type = 0;
1416 //By calling buildState with QJsonValue(), a Render State with
1417 //default values is created.
1418
1419 if (state == GL_BLEND) {
1420 //It doesn't make sense to handle this state alone
1421 return nullptr;
1422 }
1423
1424 if (state == GL_CULL_FACE) {
1425 return buildState(QStringLiteral("cullFace"), QJsonValue(), type);
1426 }
1427
1428 if (state == GL_DEPTH_TEST) {
1429 return buildState(QStringLiteral("depthFunc"), QJsonValue(), type);
1430 }
1431
1432 if (state == GL_POLYGON_OFFSET_FILL) {
1433 return buildState(QStringLiteral("polygonOffset"), QJsonValue(), type);
1434 }
1435
1436 if (state == GL_SAMPLE_ALPHA_TO_COVERAGE) {
1437 return new QAlphaCoverage();
1438 }
1439
1440 if (state == GL_SCISSOR_TEST) {
1441 return buildState(QStringLiteral("scissor"), QJsonValue(), type);
1442 }
1443
1444 qCWarning(GLTFIOLog, "unsupported render state: %d", state);
1445
1446 return nullptr;
1447 }
1448
1449 QRenderState* GLTFIO::buildState(const QString& functionName, const QJsonValue &value, int &type)
1450 {
1451 type = -1;
1452 QJsonArray values = value.toArray();
1453
1454 if (functionName == QLatin1String("blendColor")) {
1455 type = GL_BLEND;
1456 //TODO: support render state blendColor
1457 qCWarning(GLTFIOLog, "unsupported render state: %ls", qUtf16PrintableImpl(functionName));
1458 return nullptr;
1459 }
1460
1461 if (functionName == QLatin1String("blendEquationSeparate")) {
1462 type = GL_BLEND;
1463 //TODO: support settings blendEquation alpha
1464 QBlendEquation *blendEquation = new QBlendEquation;
1465 blendEquation->setBlendFunction((QBlendEquation::BlendFunction)values.at(0).toInt(GL_FUNC_ADD));
1466 return blendEquation;
1467 }
1468
1469 if (functionName == QLatin1String("blendFuncSeparate")) {
1470 type = GL_BLEND;
1471 QBlendEquationArguments *blendArgs = new QBlendEquationArguments;
1472 blendArgs->setSourceRgb((QBlendEquationArguments::Blending)values.at(0).toInt(GL_ONE));
1473 blendArgs->setSourceAlpha((QBlendEquationArguments::Blending)values.at(1).toInt(GL_ONE));
1474 blendArgs->setDestinationRgb((QBlendEquationArguments::Blending)values.at(2).toInt(GL_ZERO));
1475 blendArgs->setDestinationAlpha((QBlendEquationArguments::Blending)values.at(3).toInt(GL_ZERO));
1476 return blendArgs;
1477 }
1478
1479 if (functionName == QLatin1String("colorMask")) {
1480 QColorMask *colorMask = new QColorMask;
1481 colorMask->setRedMasked(values.at(0).toBool(true));
1482 colorMask->setGreenMasked(values.at(1).toBool(true));
1483 colorMask->setBlueMasked(values.at(2).toBool(true));
1484 colorMask->setAlphaMasked(values.at(3).toBool(true));
1485 return colorMask;
1486 }
1487
1488 if (functionName == QLatin1String("cullFace")) {
1489 type = GL_CULL_FACE;
1490 QCullFace *cullFace = new QCullFace;
1491 cullFace->setMode((QCullFace::CullingMode)values.at(0).toInt(GL_BACK));
1492 return cullFace;
1493 }
1494
1495 if (functionName == QLatin1String("depthFunc")) {
1496 type = GL_DEPTH_TEST;
1497 QDepthTest *depthTest = new QDepthTest;
1498 depthTest->setDepthFunction((QDepthTest::DepthFunction)values.at(0).toInt(GL_LESS));
1499 return depthTest;
1500 }
1501
1502 if (functionName == QLatin1String("depthMask")) {
1503 if (!values.at(0).toBool(true)) {
1504 QNoDepthMask *depthMask = new QNoDepthMask;
1505 return depthMask;
1506 }
1507 return nullptr;
1508 }
1509
1510 if (functionName == QLatin1String("depthRange")) {
1511 //TODO: support render state depthRange
1512 qCWarning(GLTFIOLog, "unsupported render state: %ls", qUtf16PrintableImpl(functionName));
1513 return nullptr;
1514 }
1515
1516 if (functionName == QLatin1String("frontFace")) {
1517 QFrontFace *frontFace = new QFrontFace;
1518 frontFace->setDirection((QFrontFace::WindingDirection)values.at(0).toInt(GL_CCW));
1519 return frontFace;
1520 }
1521
1522 if (functionName == QLatin1String("lineWidth")) {
1523 //TODO: support render state lineWidth
1524 qCWarning(GLTFIOLog, "unsupported render state: %ls", qUtf16PrintableImpl(functionName));
1525 return nullptr;
1526 }
1527
1528 if (functionName == QLatin1String("polygonOffset")) {
1529 type = GL_POLYGON_OFFSET_FILL;
1530 QPolygonOffset *polygonOffset = new QPolygonOffset;
1531 polygonOffset->setScaleFactor((float)values.at(0).toDouble(0.0f));
1532 polygonOffset->setDepthSteps((float)values.at(1).toDouble(0.0f));
1533 return polygonOffset;
1534 }
1535
1536 if (functionName == QLatin1String("scissor")) {
1537 type = GL_SCISSOR_TEST;
1538 QScissorTest *scissorTest = new QScissorTest;
1539 scissorTest->setLeft(values.at(0).toDouble(0.0f));
1540 scissorTest->setBottom(values.at(1).toDouble(0.0f));
1541 scissorTest->setWidth(values.at(2).toDouble(0.0f));
1542 scissorTest->setHeight(values.at(3).toDouble(0.0f));
1543 return scissorTest;
1544 }
1545
1546 qCWarning(GLTFIOLog, "unsupported render state: %ls", qUtf16PrintableImpl(functionName));
1547 return nullptr;
1548 }
1549
1550 } // namespace Qt3DRender
1551
1552 QT_END_NAMESPACE
1553
1554 #include "moc_gltfio.cpp"