aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/items/qquickspriteimage.cpp
blob: 2a151d02a81f9f45509356ae0ca3ba0dddc78a8b (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
471
472
473
474
475
476
477
478
479
480
481
482
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Declarative 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 "qquickspriteimage_p.h"
#include "qquicksprite_p.h"
#include "qquickspriteengine_p.h"
#include <QtQuick/private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
#include <QtQuick/qsgnode.h>
#include <QtQuick/qsgengine.h>
#include <QtQuick/qsgtexturematerial.h>
#include <QtQuick/qsgtexture.h>
#include <QtQuick/qquickcanvas.h>
#include <QtQml/qqmlinfo.h>
#include <QFile>
#include <cmath>
#include <qmath.h>
#include <QDebug>

QT_BEGIN_NAMESPACE

static const char vertexShaderCode[] =
    "attribute highp vec2 vTex;\n"
    "uniform highp vec3 animData;// w,h(premultiplied of anim), interpolation progress\n"
    "uniform highp vec4 animPos;//x,y, x,y (two frames for interpolation)\n"
    "uniform highp vec2 size;//w,h of element\n"
    "\n"
    "uniform highp mat4 qt_Matrix;\n"
    "\n"
    "varying highp vec4 fTexS;\n"
    "varying lowp float progress;\n"
    "\n"
    "\n"
    "void main() {\n"
    "    progress = animData.z;\n"
    "    //Calculate frame location in texture\n"
    "    fTexS.xy = animPos.xy + vTex.xy * animData.xy;\n"
    "    //Next frame is also passed, for interpolation\n"
    "    fTexS.zw = animPos.zw + vTex.xy * animData.xy;\n"
    "\n"
    "    gl_Position = qt_Matrix * vec4(size.x * vTex.x, size.y * vTex.y, 0, 1);\n"
    "}\n";

static const char fragmentShaderCode[] =
    "uniform sampler2D texture;\n"
    "uniform lowp float qt_Opacity;\n"
    "\n"
    "varying highp vec4 fTexS;\n"
    "varying lowp float progress;\n"
    "\n"
    "void main() {\n"
    "    gl_FragColor = mix(texture2D(texture, fTexS.xy), texture2D(texture, fTexS.zw), progress) * qt_Opacity;\n"
    "}\n";

class QQuickSpriteImageMaterial : public QSGMaterial
{
public:
    QQuickSpriteImageMaterial();
    ~QQuickSpriteImageMaterial();
    virtual QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
    virtual QSGMaterialShader *createShader() const;
    virtual int compare(const QSGMaterial *other) const
    {
        return this - static_cast<const QQuickSpriteImageMaterial *>(other);
    }

    QSGTexture *texture;

    float animT;
    float animX1;
    float animY1;
    float animX2;
    float animY2;
    float animW;
    float animH;
    float elementWidth;
    float elementHeight;
};

QQuickSpriteImageMaterial::QQuickSpriteImageMaterial()
    : animT(0.0f)
    , animX1(0.0f)
    , animY1(0.0f)
    , animX2(0.0f)
    , animY2(0.0f)
    , animW(1.0f)
    , animH(1.0f)
    , elementWidth(1.0f)
    , elementHeight(1.0f)
{
    setFlag(Blending, true);
}

QQuickSpriteImageMaterial::~QQuickSpriteImageMaterial()
{
    delete texture;
}

class SpriteImageMaterialData : public QSGMaterialShader
{
public:
    SpriteImageMaterialData(const char * /* vertexFile */ = 0, const char * /* fragmentFile */ = 0)
    {
    }

    void deactivate() {
        QSGMaterialShader::deactivate();

        for (int i=0; i<8; ++i) {
            program()->setAttributeArray(i, GL_FLOAT, chunkOfBytes, 1, 0);
        }
    }

    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
    {
        QQuickSpriteImageMaterial *m = static_cast<QQuickSpriteImageMaterial *>(newEffect);
        m->texture->bind();

        program()->setUniformValue(m_opacity_id, state.opacity());
        program()->setUniformValue(m_animData_id, m->animW, m->animH, m->animT);
        program()->setUniformValue(m_animPos_id, m->animX1, m->animY1, m->animX2, m->animY2);
        program()->setUniformValue(m_size_id, m->elementWidth, m->elementHeight);

        if (state.isMatrixDirty())
            program()->setUniformValue(m_matrix_id, state.combinedMatrix());
    }

    virtual void initialize() {
        m_matrix_id = program()->uniformLocation("qt_Matrix");
        m_opacity_id = program()->uniformLocation("qt_Opacity");
        m_animData_id = program()->uniformLocation("animData");
        m_animPos_id = program()->uniformLocation("animPos");
        m_size_id = program()->uniformLocation("size");
    }

    virtual const char *vertexShader() const { return vertexShaderCode; }
    virtual const char *fragmentShader() const { return fragmentShaderCode; }

    virtual char const *const *attributeNames() const {
        static const char *attr[] = {
           "vTex",
            0
        };
        return attr;
    }

    int m_matrix_id;
    int m_opacity_id;
    int m_animData_id;
    int m_animPos_id;
    int m_size_id;

    static float chunkOfBytes[1024];
};

float SpriteImageMaterialData::chunkOfBytes[1024];

QSGMaterialShader *QQuickSpriteImageMaterial::createShader() const
{
    return new SpriteImageMaterialData;
}

struct SpriteVertex {
    float tx;
    float ty;
};

struct SpriteVertices {
    SpriteVertex v1;
    SpriteVertex v2;
    SpriteVertex v3;
    SpriteVertex v4;
};

/*!
    \qmlclass SpriteImage QQuickSpriteImage
    \inqmlmodule QtQuick 2
    \inherits Item
    \brief The SpriteImage element draws a sprite animation

*/
/*!
    \qmlproperty bool QtQuick2::SpriteImage::running

    Whether the sprite is animating or not.

    Default is true
*/
/*!
    \qmlproperty bool QtQuick2::SpriteImage::interpolate

    If true, interpolation will occur between sprite frames to make the
    animation appear smoother.

    Default is true.
*/
/*!
    \qmlproperty string QtQuick2::SpriteImage::goalSprite

    The name of the Sprite which is currently animating.
*/
/*!
    \qmlproperty string QtQuick2::SpriteImage::goalSprite

    The name of the Sprite which the animation should move to.

    Sprite states have defined durations and transitions between them, setting goalState
    will cause it to disregard any path weightings (including 0) and head down the path
    which will reach the goalState quickest (fewest animations). It will pass through
    intermediate states on that path, and animate them for their duration.

    If it is possible to return to the goalState from the starting point of the goalState
    it will continue to do so until goalState is set to "" or an unreachable state.
*/
/*! \qmlmethod void QtQuick2::SpriteImage::jumpTo(string sprite)

    This function causes the sprite to jump to the specified state immediately, intermediate
    states are not played.
*/
/*!
    \qmlproperty list<Sprite> QtQuick2::SpriteImage::sprites

    The sprite or sprites to draw. Sprites will be scaled to the size of this element.
*/

//TODO: Implicitly size element to size of first sprite? or currentSprite?
QQuickSpriteImage::QQuickSpriteImage(QQuickItem *parent) :
    QQuickItem(parent)
    , m_node(0)
    , m_material(0)
    , m_spriteEngine(0)
    , m_curFrame(0)
    , m_pleaseReset(false)
    , m_running(true)
    , m_interpolate(true)
    , m_curStateIdx(0)
{
    setFlag(ItemHasContents);
    connect(this, SIGNAL(runningChanged(bool)),
            this, SLOT(update()));
}

void QQuickSpriteImage::jumpTo(const QString &sprite)
{
    if (!m_spriteEngine)
        return;
    m_spriteEngine->setGoal(m_spriteEngine->stateIndex(sprite), 0, true);
}

void QQuickSpriteImage::setGoalSprite(const QString &sprite)
{
    if (m_goalState != sprite){
        m_goalState = sprite;
        emit goalSpriteChanged(sprite);
        m_spriteEngine->setGoal(m_spriteEngine->stateIndex(sprite));
    }
}

QQmlListProperty<QQuickSprite> QQuickSpriteImage::sprites()
{
    return QQmlListProperty<QQuickSprite>(this, &m_sprites, spriteAppend, spriteCount, spriteAt, spriteClear);
}

void QQuickSpriteImage::createEngine()
{
    //TODO: delay until component complete
    if (m_spriteEngine)
        delete m_spriteEngine;
    if (m_sprites.count())
        m_spriteEngine = new QQuickSpriteEngine(m_sprites, this);
    else
        m_spriteEngine = 0;
    reset();
}

static QSGGeometry::Attribute SpriteImage_Attributes[] = {
    QSGGeometry::Attribute::create(0, 2, GL_FLOAT),         // tex
};

static QSGGeometry::AttributeSet SpriteImage_AttributeSet =
{
    1, // Attribute Count
    2 * sizeof(float),
    SpriteImage_Attributes
};

QSGGeometryNode* QQuickSpriteImage::buildNode()
{
    if (!m_spriteEngine) {
        qmlInfo(this) << "No sprite engine...";
        return 0;
    } else if (m_spriteEngine->status() == QQuickPixmap::Null) {
        m_spriteEngine->startAssemblingImage();
        update();//Schedule another update, where we will check again
        return 0;
    } else if (m_spriteEngine->status() == QQuickPixmap::Loading) {
        update();//Schedule another update, where we will check again
        return 0;
    }

    m_material = new QQuickSpriteImageMaterial();

    QImage image = m_spriteEngine->assembledImage();
    if (image.isNull())
        return 0;
    m_sheetSize = QSizeF(image.size());
    m_material->texture = canvas()->createTextureFromImage(image);
    m_material->texture->setFiltering(QSGTexture::Linear);
    m_spriteEngine->start(0);
    m_material->animT = 0;
    m_material->animX1 = m_spriteEngine->spriteX() / m_sheetSize.width();
    m_material->animY1 = m_spriteEngine->spriteY() / m_sheetSize.height();
    m_material->animX2 = m_material->animX1;
    m_material->animY2 = m_material->animY1;
    m_material->animW = m_spriteEngine->spriteWidth() / m_sheetSize.width();
    m_material->animH = m_spriteEngine->spriteHeight() / m_sheetSize.height();
    m_material->elementWidth = width();
    m_material->elementHeight = height();
    m_curState = m_spriteEngine->state(m_spriteEngine->curState())->name();
    emit currentSpriteChanged(m_curState);

    int vCount = 4;
    int iCount = 6;
    QSGGeometry *g = new QSGGeometry(SpriteImage_AttributeSet, vCount, iCount);
    g->setDrawingMode(GL_TRIANGLES);

    SpriteVertices *p = (SpriteVertices *) g->vertexData();

    p->v1.tx = 0;
    p->v1.ty = 0;

    p->v2.tx = 1.0;
    p->v2.ty = 0;

    p->v3.tx = 0;
    p->v3.ty = 1.0;

    p->v4.tx = 1.0;
    p->v4.ty = 1.0;

    quint16 *indices = g->indexDataAsUShort();
    indices[0] = 0;
    indices[1] = 1;
    indices[2] = 2;
    indices[3] = 1;
    indices[4] = 3;
    indices[5] = 2;


    m_timestamp.start();
    m_node = new QSGGeometryNode();
    m_node->setGeometry(g);
    m_node->setMaterial(m_material);
    m_node->setFlag(QSGGeometryNode::OwnsMaterial);
    return m_node;
}

void QQuickSpriteImage::reset()
{
    m_pleaseReset = true;
}

QSGNode *QQuickSpriteImage::updatePaintNode(QSGNode *, UpdatePaintNodeData *)
{
    if (m_pleaseReset) {
        delete m_node;

        m_node = 0;
        m_material = 0;
        m_pleaseReset = false;
    }

    prepareNextFrame();

    if (m_running) {
        update();
        if (m_node)
            m_node->markDirty(QSGNode::DirtyMaterial);
    }

    return m_node;
}

void QQuickSpriteImage::prepareNextFrame()
{
    if (m_node == 0)
        m_node = buildNode();
    if (m_node == 0) //error creating node
        return;

    uint timeInt = m_timestamp.elapsed();
    qreal time =  timeInt / 1000.;
    m_material->elementHeight = height();
    m_material->elementWidth = width();

    //Advance State
    m_spriteEngine->updateSprites(timeInt);
    if (m_curStateIdx != m_spriteEngine->curState()) {
        m_curStateIdx = m_spriteEngine->curState();
        m_curState = m_spriteEngine->state(m_spriteEngine->curState())->name();
        emit currentSpriteChanged(m_curState);
        m_curFrame= -1;
    }

    //Advance Sprite
    qreal animT = m_spriteEngine->spriteStart()/1000.0;
    qreal frameCount = m_spriteEngine->spriteFrames();
    qreal frameDuration = m_spriteEngine->spriteDuration()/frameCount;
    double frameAt;
    qreal progress;
    if (frameDuration > 0) {
        qreal frame = (time - animT)/(frameDuration / 1000.0);
        frame = qBound(qreal(0.0), frame, frameCount - qreal(1.0));//Stop at count-1 frames until we have between anim interpolation
        progress = modf(frame,&frameAt);
    } else {
        m_curFrame++;
        if (m_curFrame >= frameCount){
            m_curFrame = 0;
            m_spriteEngine->advance();
        }
        frameAt = m_curFrame;
        progress = 0;
    }
    if (m_spriteEngine->sprite()->reverse())
        frameAt = (m_spriteEngine->spriteFrames() - 1) - frameAt;
    qreal y = m_spriteEngine->spriteY() / m_sheetSize.height();
    qreal w = m_spriteEngine->spriteWidth() / m_sheetSize.width();
    qreal h = m_spriteEngine->spriteHeight() / m_sheetSize.height();
    qreal x1 = m_spriteEngine->spriteX() / m_sheetSize.width();
    x1 += frameAt * w;
    qreal x2 = x1;
    if (frameAt < (frameCount-1))
        x2 += w;

    m_material->animX1 = x1;
    m_material->animY1 = y;
    m_material->animX2 = x2;
    m_material->animY2 = y;
    m_material->animW = w;
    m_material->animH = h;
    m_material->animT = m_interpolate ? progress : 0.0;
}

QT_END_NAMESPACE