summaryrefslogtreecommitdiffstats
path: root/src/render/frontend/qitemmodelbuffer.cpp
blob: 8de31a818a52c2230f36342af0a51c450211d66d (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
/****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later 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 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qitemmodelbuffer.h"
#include <Qt3DRenderer/private/graphicscontext_p.h>
#include <QDebug>
#include <QColor>

QT_BEGIN_NAMESPACE

using namespace Qt3DCore;

namespace Qt3DRender {

void variantToBytes(void* dest, const QVariant& v, GLint type)
{
    int varType = v.type();
    switch (type) {
    case GL_FLOAT: {
        float f = v.toFloat();
        memcpy(dest, &f, sizeof(float));
        return;
    }

    case GL_INT: {
        GLint i = v.toInt();
        memcpy(dest, &i, sizeof(GLint));
        return;
    }

    case GL_UNSIGNED_INT: {
        GLuint i = v.toUInt();
        memcpy(dest, &i, sizeof(GLuint));
        return;
    }

    case GL_FLOAT_VEC3:
        if (varType == QVariant::Vector3D) {
            QVector3D v3(v.value<QVector3D>());
            memcpy(dest, &v3[0], sizeof(float) * 3);
            return;
        }

        break;

    case GL_FLOAT_VEC4:
        if (varType == QVariant::Vector4D) {
            QVector4D v4(v.value<QVector4D>());
            memcpy(dest, &v4[0], sizeof(float) * 4);
            return;
        }

        if (varType == QVariant::Color) {
            QColor c = v.value<QColor>();
            float* fptr = reinterpret_cast<float*>(dest);
            *fptr++ = c.redF();
            *fptr++ = c.greenF();
            *fptr++ = c.blueF();
            *fptr++ = c.alphaF();
            return;
        }

        if (varType == QVariant::Quaternion) {
            QVector4D qv = v.value<QQuaternion>().toVector4D();
            memcpy(dest, &qv[0], sizeof(float) * 4);
            return;
        }

        break;

    default:
        break;
    }

    qWarning() << Q_FUNC_INFO << "failed to convert" << v << "to GL type" <<
                  QString::number(type, 16);
}

namespace {

Qt3DCore::QAbstractAttribute::DataType typeFromGLType(GLint dataType, uint &dataCount)
{
    switch (dataType) {

    case GL_UNSIGNED_SHORT:
        dataCount = 1;
        return QAbstractAttribute::UnsignedShort;

    case GL_UNSIGNED_BYTE:
        dataCount = 1;
        return QAbstractAttribute::UnsignedByte;

    case GL_UNSIGNED_INT:
        dataCount = 1;
        return QAbstractAttribute::UnsignedInt;

    case GL_SHORT:
        dataCount = 1;
        return QAbstractAttribute::Short;

    case GL_BYTE:
        dataCount = 1;
        return QAbstractAttribute::Byte;

    case GL_INT:
        dataCount = 1;
        return QAbstractAttribute::Int;

    case GL_FLOAT:
        dataCount = 1;
        break;

    case GL_FLOAT_VEC2:
        dataCount = 2;
        break;

    case GL_FLOAT_VEC3:
        dataCount = 3;
        break;

    case GL_FLOAT_VEC4:
        dataCount = 4;
        break;

// TO DO: Handle doubles

    default:
        Q_UNREACHABLE();
    }

    return QAbstractAttribute::Float;
}

} // anonymous

QItemModelBuffer::QItemModelBuffer()
    : m_buffer(Q_NULLPTR)
{
}

void QItemModelBuffer::setModel(QAbstractItemModel *model)
{
    if (model == m_model)
        return;

    m_model = model;
    delete m_buffer;
    m_buffer = Q_NULLPTR;

    connect(m_model, SIGNAL(modelReset()), this, SLOT(onModelReset()));
    connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(onModelDataChanged(QModelIndex,QModelIndex)));
}

void QItemModelBuffer::setRoot(const QModelIndex &rootIndex)
{
    m_rootIndex = rootIndex;
    delete m_buffer;
    m_buffer = Q_NULLPTR;
}

void QItemModelBuffer::mapRoleName(QByteArray roleName, int elementType)
{
    mapRoleName(roleName, QString::fromLatin1(roleName), elementType);
}

void QItemModelBuffer::mapRoleName(QByteArray roleName, QString attributeName, int elementType)
{
    if (m_model) {
        if (!m_model->roleNames().values().contains(roleName)) {
            qWarning() << Q_FUNC_INFO << "unknown role name" << roleName;
        }
    }

    m_mappings.append(RoleMapping(roleName, attributeName, elementType));
    delete m_buffer;
    m_buffer = Q_NULLPTR;
}

QBuffer *QItemModelBuffer::buffer()
{
    if (!m_buffer) {
        if (!validateRoles())
            return m_buffer;

        qDeleteAll(m_attributes);
        m_attributes.clear();
        m_itemStride = 0;

        m_buffer = new QBuffer(QBuffer::VertexBuffer);
        // assume model will change
        m_buffer->setUsage(QBuffer::DynamicDraw);

        int rowCount = m_model->rowCount(m_rootIndex);
        int offset = 0;
        int mappingCount = m_mappings.count();
        for (int m=0; m<mappingCount; ++m)
            m_itemStride += m_mappings.at(m).byteSize;

        for (int m=0; m<mappingCount; ++m) {
            const RoleMapping mapping(m_mappings.at(m));
            uint dataSize = 0;
            QAttribute::DataType dataType = typeFromGLType(mapping.type, dataSize);
            QAttribute *attr(new QAttribute(m_buffer, dataType,
                                            dataSize, rowCount,
                                            offset, m_itemStride));
            m_attributes[mapping.attribute] = attr;
            offset += Render::GraphicsContext::byteSizeFromType(mapping.type);
        } // of mappings iteration

        m_buffer->setData(computeBufferData());
    }

    return m_buffer;
}

QStringList QItemModelBuffer::attributeNames() const
{
    return m_attributes.keys();
}

QAttribute *QItemModelBuffer::attributeByName(QString nm) const
{
    return m_attributes.value(nm);
}

void QItemModelBuffer::onModelDataChanged(const QModelIndex& topLeft,
                                          const QModelIndex& bottomRight)
{
    if (!m_buffer)
        return;

    if (topLeft.parent() != m_rootIndex)
        return;

    QByteArray newBytes = m_buffer->data();
    for (int row=topLeft.row(); row<=bottomRight.row(); ++row) {
        QModelIndex index = topLeft.sibling(row, topLeft.column());

        char* itemPtr = newBytes.data();
        itemPtr += m_itemStride * row;

        writeDataForIndex(index, m_mappings.count(), itemPtr);
    } // of rows changed iteration

    m_buffer->setData(newBytes);
}

void QItemModelBuffer::onModelReset()
{
    if (!m_buffer)
        return;

    QByteArray b = computeBufferData();
    m_buffer->setData(b);
}

QByteArray QItemModelBuffer::computeBufferData()
{
    int rowCount = m_model->rowCount(m_rootIndex);

    int mappingCount = m_mappings.count();
    QByteArray newData;
    newData.resize(m_itemStride * rowCount);
    char* bufferPtr = newData.data();

    for (int row=0; row<rowCount; ++row) {
        writeDataForIndex(m_model->index(row, 0, m_rootIndex), mappingCount, bufferPtr);
        bufferPtr += m_itemStride;
    } // of rows iteration

    return newData;
}

void QItemModelBuffer::writeDataForIndex(const QModelIndex& index, int mappingCount, char* bufferPtr)
{
    char* fieldPtr = bufferPtr;
    for (int m=0; m<mappingCount; ++m) {
        const RoleMapping& mapping(m_mappings.at(m));
        QVariant v = m_model->data(index, mapping.cachedRole);
        variantToBytes(fieldPtr, v, mapping.type);

        fieldPtr += mapping.byteSize;
    } // of mappings iteration
}

bool QItemModelBuffer::validateRoles()
{
    Q_ASSERT(m_model);

    QHash<int, QByteArray> roles(m_model->roleNames());
    // create a lookup that's the the way round we need
    QHash<QByteArray, int> inverseRoles;
    foreach (int r, roles.keys())
        inverseRoles[roles.value(r)] = r;

    for (int m=0; m<m_mappings.count(); ++m) {
        QByteArray rnm(m_mappings.at(m).roleName);
        if (!inverseRoles.contains(rnm)) {
            qWarning() << "unknown role:" << rnm;
            return false;
        }

        m_mappings[m].cachedRole = inverseRoles[rnm];
    } // of mappings iteration

    return true;
}

QItemModelBuffer::RoleMapping::RoleMapping(QByteArray rnm, QString nm, int ty) :
    roleName(rnm),
    cachedRole(-1),
    attribute(nm),
    type(ty)
{
    byteSize = Render::GraphicsContext::byteSizeFromType(ty);
}

} // namespace Qt3DRender

QT_END_NAMESPACE