summaryrefslogtreecommitdiffstats
path: root/src/plugins/sceneformats/obj/qglobjscenehandler.cpp
blob: 04140f293b70e29eb485ffa3959900cbcb06ee01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtQuick3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qglobjscenehandler.h"
#include "qglobjscene.h"
#include "qvector2darray.h"
#include "qvector3darray.h"
#include "qglbuilder.h"

#include <QtCore/qiodevice.h>
#include <QtCore/qfile.h>
#include <QtGui/qimage.h>

QT_BEGIN_NAMESPACE

QGLObjSceneHandler::QGLObjSceneHandler()
    : QGLSceneFormatHandler()
    , palette(0)
    , smoothing(QGL::Faceted)
    , smoothingForced(false)
{
}

// Documentation for OBJ and MTL files from:
// http://www.fileformat.info/format/wavefrontobj/egff.htm
// http://www.fileformat.info/format/material/

static int objSkipWS(const QByteArray& line, int posn)
{
    while (posn < line.size() && (line[posn] == ' ' || line[posn] == '\t'))
        ++posn;
    return posn;
}

static int objSkipNonWS(const QByteArray& line, int posn, int stopch)
{
    while (posn < line.size() &&
            line[posn] != ' ' && line[posn] != '\t' && line[posn] != stopch)
        ++posn;
    return posn;
}

static qreal objReadFloat(const QByteArray& line, int *posn)
{
    *posn = objSkipWS(line, *posn);
    int end = objSkipNonWS(line, *posn, 0);
    qreal value;
    if (end > *posn)
        value = qreal(line.mid(*posn, end - *posn).toDouble());
    else
        value = 0.0f;
    *posn = end;
    return value;
}

static int objReadInteger(const QByteArray& line, int *posn)
{
    *posn = objSkipWS(line, *posn);
    int end = objSkipNonWS(line, *posn, '/');
    int value;
    if (end > *posn)
        value = line.mid(*posn, end - *posn).toInt();
    else
        value = 0;
    //*posn = objSkipNonWS(line, end, 0);
    *posn = end;
    return value;
}

static int objReadSlashInteger(const QByteArray& line, int *posn)
{
    if (*posn >= line.size() || line[*posn] != '/')
        return 0;
    ++(*posn);
    int end = objSkipNonWS(line, *posn, '/');
    int value;
    if (end > *posn)
        value = line.mid(*posn, end - *posn).toInt();
    else
        value = 0;
    //*posn = objSkipNonWS(line, end, 0);
    *posn = end;
    return value;
}

static QColor objReadColor(const QByteArray& line, int posn)
{
    qreal red = objReadFloat(line, &posn);
    qreal green = objReadFloat(line, &posn);
    qreal blue = objReadFloat(line, &posn);
    qreal alpha = 1.0f;
    posn = objSkipWS(line, posn);
    if (posn < line.size())
        alpha = objReadFloat(line, &posn);
    return QColor::fromRgbF(red, green, blue, alpha);
}

void QGLObjSceneHandler::decodeOptions(const QString &options)
{
    if (options.contains(QLatin1String("ForceSmooth")))
    {
        smoothingForced = true;
        smoothing = QGL::Smooth;
    }
    else
    {
        smoothingForced = true;
        smoothing = QGL::Faceted;
    }
}

QGLAbstractScene *QGLObjSceneHandler::read()
{
    QByteArray line;
    QByteArray keyword;
    int posn, index, count;
    int tindex, nindex;
    QVector3DArray positions;
    QVector2DArray texCoords;
    QVector3DArray normals;
    qreal x, y, z;
    quint32 fields = 0;
    QGLMaterial *material = 0;
    QGLSceneNode *defaultNode;

    // Create the geometry builder and start an initial Faceted section.
    QGLBuilder builder;
    builder.newSection(smoothing);
    QGLSceneNode *root = builder.sceneNode();
    palette = root->palette();
    defaultNode = root;
    defaultNode->setObjectName(QLatin1String("__main"));
    builder.pushNode();

    QGeometryData op;

    while (!device()->atEnd()) {
        // Read the next line, including any backslash continuations.
        line = device()->readLine().trimmed();
        while (line.endsWith('\\')) {
            line.truncate(line.size() - 1);
            if (device()->atEnd())
                break;
            line += device()->readLine().trimmed();
        }
        if (line.startsWith('#') || line.isEmpty())
            continue;   // Skip comments and blank lines.

        // Extract the keyword at the start of the line.
        posn = 0;
        while (posn < line.size() &&
               line[posn] != ' ' && line[posn] != '\t')
            ++posn;
        keyword = line.left(posn);

        // Determine how to process this line from the keyword.
        if (keyword == "v") {
            x = objReadFloat(line, &posn);
            y = objReadFloat(line, &posn);
            z = objReadFloat(line, &posn);
            positions.append(x, y, z);
        } else if (keyword == "vt") {
            x = objReadFloat(line, &posn);
            y = objReadFloat(line, &posn);
            texCoords.append(x, y);
        } else if (keyword == "vn") {
            x = objReadFloat(line, &posn);
            y = objReadFloat(line, &posn);
            z = objReadFloat(line, &posn);
            normals.append(x, y, z);
        } else if (keyword == "f") {
            posn = objSkipWS(line, posn);
            count = 0;
            //QGeometryData op; //(dlist, QGL::TRIANGLE_FAN);
            op = QGeometryData();  // clear leaves field definitions
            while (posn < line.size()) {
                // Note: we currently only read the initial vertex
                // index and also use it for texture co-ordinates
                // and normals.  e.g. "2/2", "3/3", etc.  This will
                // need to be fixed to handle "2/1", "3/7", etc.
                index = objReadInteger(line, &posn);
                tindex = objReadSlashInteger(line, &posn);
                nindex = objReadSlashInteger(line, &posn);
                if (index < 0)
                    index = positions.count() + index;
                else if (index > 0)
                    --index;        // Indices in obj are 1-based.
                if (index >= 0 && index < positions.count())
                    op.appendVertex(positions[index]);
                if (tindex < 0)
                    tindex = texCoords.count() + tindex;
                else if (tindex > 0)
                    --tindex;        // Indices in obj are 1-based.
                else
                    tindex = -1;
                if (tindex >= 0 && tindex < texCoords.count())
                    op.appendTexCoord(texCoords[tindex]);
                if (nindex < 0)
                    nindex = normals.count() + nindex;
                else if (nindex > 0)
                    --nindex;        // Indices in obj are 1-based.
                else
                    nindex = -1;
                if (nindex >= 0 && nindex < normals.count())
                    op.appendNormal(normals[nindex]);
                ++count;
                posn = objSkipNonWS(line, posn, 0);
                posn = objSkipWS(line, posn);
            }
            // if geometry has already been added with a different combination
            // of fields start a new section
            // the primitive doesn't get posted to the section until op.end()
            if (op.fields() != fields)
            {
                if (fields && builder.currentNode()->count() > 0)
                    builder.newSection(smoothing);
                fields = op.fields();
            }
            builder.addTriangleFan(op);
        } else if (keyword == "usemtl") {
            // Specify a material for the faces that follow.
            posn = objSkipWS(line, posn);
            QByteArray rest = line.mid(posn);
            QString materialName = QString::fromLocal8Bit(rest.constData(), rest.size());
            if (!materialName.isEmpty() &&
                materialName != QLatin1String("(null)")) {
                index = palette->indexOf(materialName);
                if (index != -1) {
                    QGLSceneNode *node = builder.newNode();
                    node->setMaterialIndex(index);
                    QGLMaterial *material = palette->material(index);
                    if (material->texture())
                        node->setEffect(QGL::LitDecalTexture2D);
                    else
                        node->setEffect(QGL::LitMaterial);
                } else {
                    qWarning() << "obj material" << materialName << "not found";
                    material = 0;
                }
            }
        } else if (keyword == "mtllib") {
            // Load a material library.
            posn = objSkipWS(line, posn);
            QByteArray filename = line.mid(posn);
            loadMaterialLibrary(QString::fromLocal8Bit(filename.constData(), filename.size()));
        } else if (keyword == "s") {
            if (!smoothingForced)
            {
                // Set smoothing on or off.
                posn = objSkipWS(line, posn);
                index = objSkipNonWS(line, posn, 0);
                QByteArray arg = line.mid(posn, index - posn);
                QGL::Smoothing smooth;
                if (arg == "on" || arg == "1")
                    smooth = QGL::Smooth;
                else
                    smooth = QGL::Faceted;
                if (smoothing != smooth) {
                    smoothing = smooth;
                    builder.newSection(smooth);
                }
            }
        } else if (keyword == "g" || keyword == "o") {
            // Label the faces that follow as part of a named group or object.
            posn = objSkipWS(line, posn);
            QByteArray rest = line.mid(posn);
            QString objectName = QString::fromLocal8Bit(rest.constData(), rest.size());
            QGLSceneNode *node = builder.currentNode();
            // if content has already been added to a current group, then
            // create a new node in the scene graph for the group, otherwise
            // just label the existing group with this name
            QGLSceneNode *p = qobject_cast<QGLSceneNode*>(node->parent());
            if (node->count() > 0 && p && p->objectName().isEmpty())
            {
                node = p;
            }
            else
            {
                builder.popNode();
                node = builder.currentNode();
                builder.pushNode();
            }
            node->setObjectName(objectName);
        } else {
            qWarning() << "unsupported obj command: " << keyword.constData();
        }
    }

    // Create a scene from the geometry
    return new QGLObjScene(builder.finalizedSceneNode());
}

QGLAbstractScene *QGLObjSceneHandler::download()
{
    qWarning() << "Network loading of obj files using this plugin is not implemented.";
    return NULL;
}

void QGLObjSceneHandler::loadMaterialLibrary(const QString& name)
{
    QUrl materialUrl = url().resolved(name);
    if (materialUrl.scheme() == QLatin1String("file")) {
        QFile file(materialUrl.toLocalFile());
        if (!file.open(QIODevice::ReadOnly))
            qWarning() << "QGLObjSceneHandler::loadMaterialLibrary: could not open:" << materialUrl.toLocalFile();
        else
            loadMaterials(&file);
    } else {
        // TODO
        qWarning("QGLObjSceneHandler::loadMaterialLibrary: non-file urls not supported");
    }
}

void QGLObjSceneHandler::loadMaterials(QIODevice *device)
{
    QByteArray line;
    QByteArray keyword;
    int posn, index;
    QGLMaterial *material = 0;
    QString materialName;
    QString textureName;

    while (!device->atEnd()) {
        // Read the next line, including any backslash continuations.
        line = device->readLine().trimmed();
        while (line.endsWith('\\')) {
            line.truncate(line.size() - 1);
            if (device->atEnd())
                break;
            line += device->readLine().trimmed();
        }
        if (line.startsWith('#') || line.isEmpty())
            continue;   // Skip comments and blank lines.

        // Extract the keyword at the start of the line.
        posn = 0;
        while (posn < line.size() &&
               line[posn] != ' ' && line[posn] != '\t')
            ++posn;
        keyword = line.left(posn);

        // Determine how to process this line from the keyword.
        if (keyword == "newmtl") {
            // Start a new material definition.
            posn = objSkipWS(line, posn);
            QByteArray rest = line.mid(posn);
            materialName = QString::fromLocal8Bit(rest.constData(), rest.size());
            index = palette->indexOf(materialName);
            if (index != -1) {
                qWarning() << "redefining obj material:" << materialName;
                material = palette->material(index);
            } else {
                material = new QGLMaterial();
                material->setObjectName(materialName);
                palette->addMaterial(material);
            }
        } else if (keyword == "Ka") {
            // Ambient color of the material.
            if (material)
                material->setAmbientColor(objReadColor(line, posn));
        } else if (keyword == "Kd") {
            // Diffuse color of the material.
            if (material)
                material->setDiffuseColor(objReadColor(line, posn));
        } else if (keyword == "Ks") {
            // Specular color of the material.
            if (material)
                material->setSpecularColor(objReadColor(line, posn));
        } else if (keyword == "map_Kd") {
            // Texture associated with the material.
            posn = objSkipWS(line, posn);
            QByteArray rest = line.mid(posn);
            textureName = QString::fromLocal8Bit(rest.constData(), rest.size());
            QGLTexture2D *texture = loadTexture(textureName);
            if (texture) {
                index = palette->indexOf(materialName);
                if (index >= 0) {
                    QGLMaterial *material = palette->material(index);
                    texture->setParent(material);
                    material->setTexture(texture);
                } else {
                    delete texture;
                }
            }
        } else if (keyword == "d") {
            // "Dissolve factor" of the material, which is its opacity.
            if (material) {
                qreal alpha = objReadFloat(line, &posn);
                QColor ambient = material->ambientColor();
                QColor diffuse = material->diffuseColor();
                ambient.setAlphaF(alpha);
                diffuse.setAlphaF(alpha);
                material->setAmbientColor(ambient);
                material->setDiffuseColor(diffuse);
            }
        } else if (keyword == "Ns") {
            // Specular exponent of the material.
            if (material)
                material->setShininess(qRound(objReadFloat(line, &posn)));
        } else if (keyword == "illum") {
            // Illumination model - ignored at present.
        } else if (keyword == "Ni") {
            // Optical density - ignored at present.
        } else {
            qWarning() << "unsupported obj material command: " << keyword.constData();
        }
    }
}

QGLTexture2D *QGLObjSceneHandler::loadTexture(const QString& name)
{
    QUrl textureUrl = url().resolved(name);
    if (textureUrl.scheme() == QLatin1String("file")) {
        QFile file(textureUrl.toLocalFile());
        if (!file.open(QIODevice::ReadOnly)) {
            qWarning() << "QGLObjSceneHandler::loadTexture: could not open:" << textureUrl.toLocalFile();
            return 0;
        } else {
            file.close();
            QImage image(textureUrl.toLocalFile());
            QGLTexture2D *tex = new QGLTexture2D();
            tex->setImage(image);
            return tex;
        }
    } else {
        // TODO
        qWarning("QGLObjSceneHandler::loadTexture: non-file urls not supported");
        return 0;
    }
}

QT_END_NAMESPACE