summaryrefslogtreecommitdiffstats
path: root/src/plugins/geometryloaders/default/basegeometryloader.cpp
blob: 09e4ba3a8b28663df66122cff45b1df8fafb6e37 (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
// Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB).
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "basegeometryloader_p.h"

#include <Qt3DCore/qattribute.h>
#include <Qt3DCore/qbuffer.h>
#include <Qt3DCore/qgeometry.h>

#include <Qt3DRender/private/qaxisalignedboundingbox_p.h>
#include <Qt3DRender/private/renderlogging_p.h>

QT_BEGIN_NAMESPACE

using namespace Qt3DCore;

namespace Qt3DRender {

Q_LOGGING_CATEGORY(BaseGeometryLoaderLog, "Qt3D.BaseGeometryLoader", QtWarningMsg)

BaseGeometryLoader::BaseGeometryLoader()
    : m_loadTextureCoords(true)
    , m_generateTangents(true)
    , m_centerMesh(false)
    , m_geometry(nullptr)
{
}

Qt3DCore::QGeometry *BaseGeometryLoader::geometry() const
{
    return m_geometry;
}

bool BaseGeometryLoader::load(QIODevice *ioDev, const QString &subMesh)
{
    if (!doLoad(ioDev, subMesh))
        return false;

    if (m_normals.empty())
        generateAveragedNormals(m_points, m_normals, m_indices);

    if (m_generateTangents && !m_texCoords.empty())
        generateTangents(m_points, m_normals, m_indices, m_texCoords, m_tangents);

    if (m_centerMesh)
        center(m_points);

    qCDebug(BaseGeometryLoaderLog) << "Loaded mesh:";
    qCDebug(BaseGeometryLoaderLog) << " " << m_points.size() << "points";
    qCDebug(BaseGeometryLoaderLog) << " " << m_indices.size() / 3 << "triangles.";
    qCDebug(BaseGeometryLoaderLog) << " " << m_normals.size() << "normals";
    qCDebug(BaseGeometryLoaderLog) << " " << m_tangents.size() << "tangents ";
    qCDebug(BaseGeometryLoaderLog) << " " << m_texCoords.size() << "texture coordinates.";

    generateGeometry();

    return true;
}

void BaseGeometryLoader::generateAveragedNormals(const std::vector<QVector3D> &points,
                                                 std::vector<QVector3D> &normals,
                                                 const std::vector<unsigned int> &faces) const
{
    for (size_t i = 0; i < points.size(); ++i)
        normals.push_back(QVector3D());

    for (size_t i = 0; i < faces.size(); i += 3) {
        const QVector3D &p1 = points[ faces[i]   ];
        const QVector3D &p2 = points[ faces[i+1] ];
        const QVector3D &p3 = points[ faces[i+2] ];

        const QVector3D a = p2 - p1;
        const QVector3D b = p3 - p1;
        const QVector3D n = QVector3D::crossProduct(a, b).normalized();

        normals[ faces[i]   ] += n;
        normals[ faces[i+1] ] += n;
        normals[ faces[i+2] ] += n;
    }

    for (size_t i = 0; i < normals.size(); ++i)
        normals[i].normalize();
}

void BaseGeometryLoader::generateGeometry()
{
    QByteArray bufferBytes;
    const uint count = uint(m_points.size());
    const quint32 elementSize = 3 + (hasTextureCoordinates() ? 2 : 0)
        + (hasNormals() ? 3 : 0)
        + (hasTangents() ? 4 : 0);
    const quint32 stride = elementSize * sizeof(float);
    bufferBytes.resize(stride * count);
    float *fptr = reinterpret_cast<float*>(bufferBytes.data());

    for (size_t index = 0; index < count; ++index) {
        *fptr++ = m_points.at(index).x();
        *fptr++ = m_points.at(index).y();
        *fptr++ = m_points.at(index).z();

        if (hasTextureCoordinates()) {
            *fptr++ = m_texCoords.at(index).x();
            *fptr++ = m_texCoords.at(index).y();
        }

        if (hasNormals()) {
            *fptr++ = m_normals.at(index).x();
            *fptr++ = m_normals.at(index).y();
            *fptr++ = m_normals.at(index).z();
        }

        if (hasTangents()) {
            *fptr++ = m_tangents.at(index).x();
            *fptr++ = m_tangents.at(index).y();
            *fptr++ = m_tangents.at(index).z();
            *fptr++ = m_tangents.at(index).w();
        }
    } // of buffer filling loop

    auto *buf = new Qt3DCore::QBuffer();
    buf->setData(bufferBytes);

    if (m_geometry)
        qDebug(BaseGeometryLoaderLog, "Existing geometry instance getting overridden.");
    m_geometry = new QGeometry();

    QAttribute *positionAttribute = new QAttribute(buf, QAttribute::defaultPositionAttributeName(), QAttribute::Float, 3, count, 0, stride);
    m_geometry->addAttribute(positionAttribute);
    quint32 offset = sizeof(float) * 3;

    if (hasTextureCoordinates()) {
        QAttribute *texCoordAttribute = new QAttribute(buf, QAttribute::defaultTextureCoordinateAttributeName(),  QAttribute::Float, 2, count, offset, stride);
        m_geometry->addAttribute(texCoordAttribute);
        offset += sizeof(float) * 2;
    }

    if (hasNormals()) {
        QAttribute *normalAttribute = new QAttribute(buf, QAttribute::defaultNormalAttributeName(), QAttribute::Float, 3, count, offset, stride);
        m_geometry->addAttribute(normalAttribute);
        offset += sizeof(float) * 3;
    }

    if (hasTangents()) {
        QAttribute *tangentAttribute = new QAttribute(buf, QAttribute::defaultTangentAttributeName(),QAttribute::Float, 4, count, offset, stride);
        m_geometry->addAttribute(tangentAttribute);
        offset += sizeof(float) * 4;
    }

    QByteArray indexBytes;
    QAttribute::VertexBaseType ty;
    if (m_indices.size() < 65536) {
        // we can use USHORT
        ty = QAttribute::UnsignedShort;
        indexBytes.resize(m_indices.size() * sizeof(quint16));
        quint16 *usptr = reinterpret_cast<quint16*>(indexBytes.data());
        for (int i = 0; i < int(m_indices.size()); ++i)
            *usptr++ = static_cast<quint16>(m_indices.at(i));
    } else {
        // use UINT - no conversion needed, but let's ensure int is 32-bit!
        ty = QAttribute::UnsignedInt;
        Q_ASSERT(sizeof(int) == sizeof(quint32));
        indexBytes.resize(m_indices.size() * sizeof(quint32));
        memcpy(indexBytes.data(), reinterpret_cast<const char*>(m_indices.data()), indexBytes.size());
    }

    auto *indexBuffer = new Qt3DCore::QBuffer();
    indexBuffer->setData(indexBytes);
    QAttribute *indexAttribute = new QAttribute(indexBuffer, ty, 1, uint(m_indices.size()));
    indexAttribute->setAttributeType(QAttribute::IndexAttribute);
    m_geometry->addAttribute(indexAttribute);
}

void BaseGeometryLoader::generateTangents(const std::vector<QVector3D> &points,
                                          const std::vector<QVector3D> &normals,
                                          const std::vector<unsigned int> &faces,
                                          const std::vector<QVector2D> &texCoords,
                                          std::vector<QVector4D> &tangents) const
{
    tangents.clear();
    std::vector<QVector3D> tan1Accum;
    std::vector<QVector3D> tan2Accum;

    tan1Accum.resize(points.size());
    tan2Accum.resize(points.size());
    tangents.resize(points.size());

    // Compute the tangent vector
    for (size_t i = 0; i < faces.size(); i += 3) {
        const QVector3D &p1 = points[ faces[i] ];
        const QVector3D &p2 = points[ faces[i+1] ];
        const QVector3D &p3 = points[ faces[i+2] ];

        const QVector2D &tc1 = texCoords[ faces[i] ];
        const QVector2D &tc2 = texCoords[ faces[i+1] ];
        const QVector2D &tc3 = texCoords[ faces[i+2] ];

        const QVector3D q1 = p2 - p1;
        const QVector3D q2 = p3 - p1;
        const float s1 = tc2.x() - tc1.x(), s2 = tc3.x() - tc1.x();
        const float t1 = tc2.y() - tc1.y(), t2 = tc3.y() - tc1.y();
        const float r = 1.0f / (s1 * t2 - s2 * t1);
        const QVector3D tan1((t2 * q1.x() - t1 * q2.x()) * r,
                             (t2 * q1.y() - t1 * q2.y()) * r,
                             (t2 * q1.z() - t1 * q2.z()) * r);
        const QVector3D tan2((s1 * q2.x() - s2 * q1.x()) * r,
                             (s1 * q2.y() - s2 * q1.y()) * r,
                             (s1 * q2.z() - s2 * q1.z()) * r);
        tan1Accum[ faces[i]   ] += tan1;
        tan1Accum[ faces[i+1] ] += tan1;
        tan1Accum[ faces[i+2] ] += tan1;
        tan2Accum[ faces[i]   ] += tan2;
        tan2Accum[ faces[i+1] ] += tan2;
        tan2Accum[ faces[i+2] ] += tan2;
    }

    for (size_t i = 0; i < points.size(); ++i) {
        const QVector3D &n = normals[i];
        const QVector3D &t1 = tan1Accum[i];
        const QVector3D &t2 = tan2Accum[i];

        // Gram-Schmidt orthogonalize
        tangents[i] = QVector4D(QVector3D(t1 - QVector3D::dotProduct(n, t1) * n).normalized(), 0.0f);

        // Store handedness in w
        tangents[i].setW((QVector3D::dotProduct(QVector3D::crossProduct(n, t1), t2) < 0.0f) ? -1.0f : 1.0f);
    }
}

void BaseGeometryLoader::center(std::vector<QVector3D> &points)
{
    if (points.empty())
        return;

    const QAxisAlignedBoundingBox bb(points);
    const QVector3D center = bb.center();

    // Translate center of the AABB to the origin
    for (size_t i = 0; i < points.size(); ++i) {
        QVector3D &point = points[i];
        point = point - center;
    }
}

} // namespace Qt3DRender

QT_END_NAMESPACE

#include "moc_basegeometryloader_p.cpp"