summaryrefslogtreecommitdiffstats
path: root/src/runtime/dragon/jobs/dragonboundingvolumejobs.cpp
blob: 2b96f3b76a6256ae4fff1f1bd41b34ed4ee10082 (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
/****************************************************************************
**
** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB).
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** 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 https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "dragonboundingvolumejobs_p.h"

#include <Qt3DCore/QNodeId>

#include <Qt3DCore/private/matrix4x4_p.h>

#include <private/dragonentity_p.h>
#include <private/dragongeometry_p.h>
#include <private/dragongeometryrenderer_p.h>
#include <private/dragonattribute_p.h>
#include <private/dragontransform_p.h>
#include <private/dragonbuffervisitor_p.h>
#include <private/dragonjobs_common_p.h>

QT_BEGIN_NAMESPACE

using namespace Qt3DCore;

namespace Qt3DRender {
namespace Dragon {

namespace {

class BoundingVolumeCalculator
{
public:
    const Sphere &result() { return m_volume; }

    bool apply(const Attribute &positionAttribute,
               const LoadedBuffer &attributeBuffer,
               const Attribute &indexAttribute,
               const LoadedBuffer &indexBuffer,
               int drawVertexCount,
               bool primitiveRestartEnabled,
               int primitiveRestartIndex)
    {
        FindExtremePoints findExtremePoints;
        // TODO what about if we don't have an indexAttribute?
        if (!findExtremePoints.apply(positionAttribute, attributeBuffer, indexAttribute, indexBuffer, drawVertexCount,
                                     primitiveRestartEnabled, primitiveRestartIndex)) {
            return false;
        }

        // Calculate squared distance for the pairs of points
        const float xDist2 = (findExtremePoints.xMaxPt - findExtremePoints.xMinPt).lengthSquared();
        const float yDist2 = (findExtremePoints.yMaxPt - findExtremePoints.yMinPt).lengthSquared();
        const float zDist2 = (findExtremePoints.zMaxPt - findExtremePoints.zMinPt).lengthSquared();

        // Select most distant pair
        Vector3D p = findExtremePoints.xMinPt;
        Vector3D q = findExtremePoints.xMaxPt;
        if (yDist2 > xDist2 && yDist2 > zDist2) {
            p = findExtremePoints.yMinPt;
            q = findExtremePoints.yMaxPt;
        }
        if (zDist2 > xDist2 && zDist2 > yDist2) {
            p = findExtremePoints.zMinPt;
            q = findExtremePoints.zMaxPt;
        }

        const Vector3D c = 0.5f * (p + q);
        m_volume.setCenter(c);
        m_volume.setRadius((q - c).length());

        ExpandSphere expandSphere(m_volume);
        if (!expandSphere.apply(positionAttribute, attributeBuffer, indexAttribute, indexBuffer, drawVertexCount,
                                primitiveRestartEnabled, primitiveRestartIndex))
            return false;

        return true;
    }

private:
    Sphere m_volume;

    class FindExtremePoints : public Buffer3fVisitor
    {
    public:
        FindExtremePoints()
                : Buffer3fVisitor()
                , xMin(0.0f)
                , xMax(0.0f)
                , yMin(0.0f)
                , yMax(0.0f)
                , zMin(0.0f)
                , zMax(0.0f)
        {
        }

        float xMin, xMax, yMin, yMax, zMin, zMax;
        Vector3D xMinPt, xMaxPt, yMinPt, yMaxPt, zMinPt, zMaxPt;

        void visit(uint ndx, float x, float y, float z) override
        {
            if (ndx) {
                if (x < xMin) {
                    xMin = x;
                    xMinPt = Vector3D(x, y, z);
                }
                if (x > xMax) {
                    xMax = x;
                    xMaxPt = Vector3D(x, y, z);
                }
                if (y < yMin) {
                    yMin = y;
                    yMinPt = Vector3D(x, y, z);
                }
                if (y > yMax) {
                    yMax = y;
                    yMaxPt = Vector3D(x, y, z);
                }
                if (z < zMin) {
                    zMin = z;
                    zMinPt = Vector3D(x, y, z);
                }
                if (z > zMax) {
                    zMax = z;
                    zMaxPt = Vector3D(x, y, z);
                }
            } else {
                xMin = xMax = x;
                yMin = yMax = y;
                zMin = zMax = z;
                xMinPt = xMaxPt = yMinPt = yMaxPt = zMinPt = zMaxPt = Vector3D(x, y, z);
            }
        }
    };

    class ExpandSphere : public Buffer3fVisitor
    {
    public:
        ExpandSphere(Sphere &volume)
                : Buffer3fVisitor()
                , m_volume(volume)
        {
        }

        Sphere &m_volume;
        void visit(uint ndx, float x, float y, float z) override
        {
            Q_UNUSED(ndx);
            m_volume.expandToContain(Vector3D(x, y, z));
        }
    };
};

}

LocalBoundingVolumes calculateLocalBoundingVolumes(LocalBoundingVolumes localBoundingVolumes,
                                                   const ValueContainer<Entity> &entities,
                                                   const ValueContainer<Attribute> &attributes,
                                                   const ValueContainer<GeometryRenderer> &geometryRenderers,
                                                   const ValueContainer<Geometry> &geometries,
                                                   const ValueContainer<LoadedBuffer> &buffers)
{
    localBoundingVolumes.reset();

    if (!entities.anythingDirty() && !attributes.anythingDirty()
        && !geometryRenderers.anythingDirty() && !geometries.anythingDirty() && !buffers.anythingDirty())
        return localBoundingVolumes;

    auto calculateBoundingVolume = [=](const QNodeId &id,
                                       const Immutable<Entity> &entity) {
        // Reuse previous result as much as possible
        // TODO consider using an Optional here
        LocalBoundingVolumeResult result = *localBoundingVolumes[id];

        bool entityDirty = entities.dirtyOrNew().contains(id);
        if (entityDirty) {
            // TODO make all these asserts part of the [] operator
            Q_ASSERT(entities.contains(id));
            // TODO note that this is a bit awkward, since we already have the entity from above
            // Feel free to change this to result.entity = entity;
            result.entity = entities[id];
            result.geometryRendererId = entity->m_geometryRendererComponent;
        }

        if (!entity->isEnabled())
            return result;

        if (result.geometryRendererId.isNull())
            return result;

        // Geometry renderer is dirty if the entity is new, or if the geometry renderer itself changed
        // TODO repeated pattern - can we generalize this somehow?
        bool geometryRendererDirty = entityDirty || geometryRenderers.dirtyOrNew().contains(result.geometryRendererId);
        if (geometryRendererDirty) {
            Q_ASSERT(geometryRenderers.contains(result.geometryRendererId));
            const auto &geometryRenderer = geometryRenderers[result.geometryRendererId];
            result.geometryRenderer = geometryRenderer;
            result.geometryId = geometryRenderer->geometryId();
        }

        if (result.geometryId.isNull())
            return result;

        // TODO verify this
        if (result.geometryRenderer->primitiveType() == QGeometryRenderer::Patches)
            return result;

        // TODO what if we have a geometry factory?
        bool geometryDirty = geometryRendererDirty || geometries.dirtyOrNew().contains(result.geometryId);
        if (geometryDirty) {
            result.positionAttributeId = QNodeId(); // Reset the ID in case it was set previously
            result.indexAttributeId = QNodeId();
            Q_ASSERT(geometries.contains(result.geometryId));
            result.geometry = geometries[result.geometryId];

            // Use the default position attribute if attribute is null
            if (result.geometry->boundingPositionAttribute().isNull()) {
                const auto attrIds = result.geometry->attributes();
                for (const Qt3DCore::QNodeId &attrId : attrIds) {
                    Q_ASSERT(attributes.contains(attrId));
                    const auto &attribute = attributes[attrId];
                    if (attribute->name() == QAttribute::defaultPositionAttributeName()) {
                        result.positionAttributeId = attrId;
                        break;
                    }
                }
            } else {
                result.positionAttributeId = result.geometry->boundingPositionAttribute();
            }

            // Find index attribute Id
            const QVector<Qt3DCore::QNodeId> geometryAttributes = result.geometry->attributes();
            for (Qt3DCore::QNodeId attrNodeId : geometryAttributes) {
                Q_ASSERT(attributes.contains(attrNodeId));
                const auto &attribute = attributes[attrNodeId];
                if (attribute->attributeType() == Qt3DRender::QAttribute::IndexAttribute) {
                    result.indexAttributeId = attrNodeId;
                    break;
                }
            }
        }

        if (result.positionAttributeId.isNull()) {
            qWarning("WARNING: calculateLocalBoundingVolume: Position attribute not found. "
                     "Cannot perform bounding volume computation");
            return result;
        }

        bool positionAttributeDirty = geometryDirty || attributes.dirtyOrNew().contains(result.positionAttributeId);
        if (positionAttributeDirty) {
            Q_ASSERT(attributes.contains(result.positionAttributeId));
            result.positionAttribute = attributes[result.positionAttributeId];
            result.positionBufferId = result.positionAttribute->bufferId();
        }

        if (result.positionBufferId.isNull()) {
            qWarning("WARNING: calculateLocalBoundingVolume: Position attribute not referencing a valid buffer");
            return result;
        }

        if (result.positionAttribute->attributeType() != QAttribute::VertexAttribute
            || result.positionAttribute->vertexBaseType() != QAttribute::Float
            || result.positionAttribute->vertexSize() < 3) {
            qWarning("WARNING: calculateLocalBoundingVolume: Position attribute not suited for bounding volume computation");
            return result;
        }

        bool indexAttributeDirty = geometryDirty || attributes.dirtyOrNew().contains(result.indexAttributeId);
        if (indexAttributeDirty) {
            Q_ASSERT(attributes.contains(result.indexAttributeId));
            result.indexAttribute = attributes[result.indexAttributeId];
            result.indexBufferId = result.indexAttribute->bufferId();
        }

        if (result.indexAttribute->vertexBaseType() != QAttribute::UnsignedShort
            && result.indexAttribute->vertexBaseType() != QAttribute::UnsignedInt) {
            qWarning("WARNING: calculateLocalBoundingVolume: Unsupported index attribute type");
            return result;
        }

        int drawVertexCount = [result]() {
            if (result.geometryRenderer->vertexCount() > 0)
                return result.geometryRenderer->vertexCount();

            if (result.indexAttribute->count() > 0)
                return int(result.indexAttribute->count());
            return 0;
        }();

        bool indexBufferDirty = indexAttributeDirty || buffers.dirtyOrNew().contains(result.indexBufferId);
        if (indexBufferDirty) {
            result.indexBuffer = buffers[result.indexBufferId];
        }

        bool positionBufferDirty = positionAttributeDirty || buffers.dirtyOrNew().contains(result.positionBufferId);
        if (indexBufferDirty) {
            result.positionBuffer = buffers[result.positionBufferId];
        }

        BoundingVolumeCalculator reader;

        // TODO what about the case where we have no indexAttribute?
        if (positionAttributeDirty || positionBufferDirty || indexAttributeDirty
            || indexBufferDirty) {
            if (reader.apply(*result.positionAttribute, *result.positionBuffer, *result.indexAttribute, *result.indexBuffer, drawVertexCount,
                             result.geometryRenderer->primitiveRestartEnabled(), result.geometryRenderer->restartIndexValue())) {
                result.boundingVolume.setCenter(reader.result().center());
                result.boundingVolume.setRadius(reader.result().radius());
            }
        }

        return result;
    };

    localBoundingVolumes = rebuildAll(std::move(localBoundingVolumes),
                                      entities,
                                      calculateBoundingVolume);

    return localBoundingVolumes;
}

WorldBoundingVolumes calculateWorldBoundingVolumes(WorldBoundingVolumes worldBoundingVolumes,
                                                   const LocalBoundingVolumes &localBoundingVolumes,
                                                   const ValueContainer<Matrix4x4> &worldTransforms)
{
    worldBoundingVolumes.reset();

    if (!localBoundingVolumes.anythingDirty() && !worldTransforms.anythingDirty())
        return worldBoundingVolumes;

    auto calculateBoundingVolume = [=](const QNodeId &id,
                                       const Immutable<LocalBoundingVolumeResult> &localBoundingVolume) {
        BoundingVolume result;
            Q_ASSERT(worldTransforms.contains(id));
        result.local = localBoundingVolume->boundingVolume;
        result.world = result.local.transformed(*worldTransforms[id]);
        // TODO fix this
        result.worldWithChildren = result.world;

        return result;
    };

    worldBoundingVolumes = rebuildAll(std::move(worldBoundingVolumes),
                                      localBoundingVolumes,
                                      calculateBoundingVolume);

    return worldBoundingVolumes;
}
} // namespace Dragon
} // namespace Qt3DRender

QT_END_NAMESPACE