aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/scenegraph/qsgdistancefieldglyphnode_p.cpp
blob: 30b4a2f9b8ebeea3daa52d877fb0299184c4ba99 (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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml 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 "qsgdistancefieldglyphnode_p_p.h"
#include <QtQuick/private/qsgdistancefieldutil_p.h>
#include <QtQuick/private/qsgtexture_p.h>
#include <QtGui/qopenglfunctions.h>
#include <qmath.h>

QT_BEGIN_NAMESPACE

class QSGDistanceFieldTextMaterialShader : public QSGMaterialShader
{
public:
    QSGDistanceFieldTextMaterialShader();

    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
    virtual char const *const *attributeNames() const;

protected:
    virtual void initialize();
    virtual const char *vertexShader() const;
    virtual const char *fragmentShader() const;

    void updateAlphaRange(ThresholdFunc thresholdFunc, AntialiasingSpreadFunc spreadFunc);

    float m_fontScale;
    float m_matrixScale;

    int m_matrix_id;
    int m_textureScale_id;
    int m_alphaMin_id;
    int m_alphaMax_id;
    int m_color_id;
};

const char *QSGDistanceFieldTextMaterialShader::vertexShader() const {
    return
        "uniform highp mat4 matrix;                     \n"
        "uniform highp vec2 textureScale;               \n"
        "attribute highp vec4 vCoord;                   \n"
        "attribute highp vec2 tCoord;                   \n"
        "varying highp vec2 sampleCoord;                \n"
        "void main() {                                  \n"
        "     sampleCoord = tCoord * textureScale;      \n"
        "     gl_Position = matrix * vCoord;            \n"
        "}";
}

const char *QSGDistanceFieldTextMaterialShader::fragmentShader() const {
    return
        "varying highp vec2 sampleCoord;                                             \n"
        "uniform sampler2D texture;                                                  \n"
        "uniform lowp vec4 color;                                                    \n"
        "uniform mediump float alphaMin;                                             \n"
        "uniform mediump float alphaMax;                                             \n"
        "void main() {                                                               \n"
        "    gl_FragColor = color * smoothstep(alphaMin,                             \n"
        "                                      alphaMax,                             \n"
        "                                      texture2D(texture, sampleCoord).a);   \n"
        "}";
}

char const *const *QSGDistanceFieldTextMaterialShader::attributeNames() const {
    static char const *const attr[] = { "vCoord", "tCoord", 0 };
    return attr;
}

QSGDistanceFieldTextMaterialShader::QSGDistanceFieldTextMaterialShader()
    : m_fontScale(1.0)
    , m_matrixScale(1.0)
{
}

void QSGDistanceFieldTextMaterialShader::updateAlphaRange(ThresholdFunc thresholdFunc, AntialiasingSpreadFunc spreadFunc)
{
    float combinedScale = m_fontScale * m_matrixScale;
    float base = thresholdFunc(combinedScale);
    float range = spreadFunc(combinedScale);

    float alphaMin = qMax(0.0f, base - range);
    float alphaMax = qMin(base + range, 1.0f);
    program()->setUniformValue(m_alphaMin_id, GLfloat(alphaMin));
    program()->setUniformValue(m_alphaMax_id, GLfloat(alphaMax));
}

void QSGDistanceFieldTextMaterialShader::initialize()
{
    QSGMaterialShader::initialize();
    m_matrix_id = program()->uniformLocation("matrix");
    m_textureScale_id = program()->uniformLocation("textureScale");
    m_color_id = program()->uniformLocation("color");
    m_alphaMin_id = program()->uniformLocation("alphaMin");
    m_alphaMax_id = program()->uniformLocation("alphaMax");
}

void QSGDistanceFieldTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
    QSGDistanceFieldTextMaterial *material = static_cast<QSGDistanceFieldTextMaterial *>(newEffect);
    QSGDistanceFieldTextMaterial *oldMaterial = static_cast<QSGDistanceFieldTextMaterial *>(oldEffect);

    bool updated = material->updateTextureSize();

    if (oldMaterial == 0
           || material->color() != oldMaterial->color()
           || state.isOpacityDirty()) {
        QVector4D color(material->color().redF(), material->color().greenF(),
                        material->color().blueF(), material->color().alphaF());
        color *= state.opacity();
        program()->setUniformValue(m_color_id, color);
    }

    bool updateRange = false;
    if (oldMaterial == 0
            || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale()) {
        m_fontScale = material->glyphCache()->fontScale();
        updateRange = true;
    }
    if (state.isMatrixDirty()) {
        program()->setUniformValue(m_matrix_id, state.combinedMatrix());
        m_matrixScale = qSqrt(qAbs(state.determinant()));
        updateRange = true;
    }
    if (updateRange) {
        updateAlphaRange(material->glyphCache()->manager()->thresholdFunc(),
                         material->glyphCache()->manager()->antialiasingSpreadFunc());
    }

    Q_ASSERT(material->glyphCache());

    if (updated
            || oldMaterial == 0
            || oldMaterial->texture()->textureId != material->texture()->textureId) {
        program()->setUniformValue(m_textureScale_id, QVector2D(1.0 / material->textureSize().width(),
                                                                1.0 / material->textureSize().height()));
        glBindTexture(GL_TEXTURE_2D, material->texture()->textureId);

        if (updated) {
            // Set the mag/min filters to be linear. We only need to do this when the texture
            // has been recreated.
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        }
    }
}

QSGDistanceFieldTextMaterial::QSGDistanceFieldTextMaterial()
    : m_glyph_cache(0)
    , m_texture(0)
{
   setFlag(Blending | RequiresDeterminant, true);
}

QSGDistanceFieldTextMaterial::~QSGDistanceFieldTextMaterial()
{
}

QSGMaterialType *QSGDistanceFieldTextMaterial::type() const
{
    static QSGMaterialType type;
    return &type;
}

QSGMaterialShader *QSGDistanceFieldTextMaterial::createShader() const
{
    return new QSGDistanceFieldTextMaterialShader;
}

bool QSGDistanceFieldTextMaterial::updateTextureSize()
{
    if (!m_texture)
        m_texture = m_glyph_cache->glyphTexture(-1); // invalid texture

    if (m_texture->size != m_size) {
        m_size = m_texture->size;
        return true;
    } else {
        return false;
    }
}

int QSGDistanceFieldTextMaterial::compare(const QSGMaterial *o) const
{
    Q_ASSERT(o && type() == o->type());
    const QSGDistanceFieldTextMaterial *other = static_cast<const QSGDistanceFieldTextMaterial *>(o);
    if (m_glyph_cache != other->m_glyph_cache)
        return m_glyph_cache - other->m_glyph_cache;
    if (m_glyph_cache->fontScale() != other->m_glyph_cache->fontScale()) {
        qreal s1 = m_glyph_cache->fontScale();
        qreal s2 = other->m_glyph_cache->fontScale();
        return int(s2 < s1) - int(s1 < s2);
    }
    QRgb c1 = m_color.rgba();
    QRgb c2 = other->m_color.rgba();
    return int(c2 < c1) - int(c1 < c2);
}


class DistanceFieldStyledTextMaterialShader : public QSGDistanceFieldTextMaterialShader
{
public:
    DistanceFieldStyledTextMaterialShader();

    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);

protected:
    virtual void initialize();
    virtual const char *fragmentShader() const = 0;

    int m_styleColor_id;
};

DistanceFieldStyledTextMaterialShader::DistanceFieldStyledTextMaterialShader()
    : QSGDistanceFieldTextMaterialShader()
{
}

void DistanceFieldStyledTextMaterialShader::initialize()
{
    QSGDistanceFieldTextMaterialShader::initialize();
    m_styleColor_id = program()->uniformLocation("styleColor");
}

void DistanceFieldStyledTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    QSGDistanceFieldTextMaterialShader::updateState(state, newEffect, oldEffect);

    QSGDistanceFieldStyledTextMaterial *material = static_cast<QSGDistanceFieldStyledTextMaterial *>(newEffect);
    QSGDistanceFieldStyledTextMaterial *oldMaterial = static_cast<QSGDistanceFieldStyledTextMaterial *>(oldEffect);

    if (oldMaterial == 0
           || material->styleColor() != oldMaterial->styleColor()
           || (state.isOpacityDirty())) {
        QVector4D color(material->styleColor().redF(), material->styleColor().greenF(),
                        material->styleColor().blueF(), material->styleColor().alphaF());
        color *= state.opacity();
        program()->setUniformValue(m_styleColor_id, color);
    }
}

QSGDistanceFieldStyledTextMaterial::QSGDistanceFieldStyledTextMaterial()
    : QSGDistanceFieldTextMaterial()
{
}

QSGDistanceFieldStyledTextMaterial::~QSGDistanceFieldStyledTextMaterial()
{
}

int QSGDistanceFieldStyledTextMaterial::compare(const QSGMaterial *o) const
{
    Q_ASSERT(o && type() == o->type());
    const QSGDistanceFieldStyledTextMaterial *other = static_cast<const QSGDistanceFieldStyledTextMaterial *>(o);
    if (m_styleColor != other->m_styleColor) {
        QRgb c1 = m_styleColor.rgba();
        QRgb c2 = other->m_styleColor.rgba();
        return int(c2 < c1) - int(c1 < c2);
    }
    return QSGDistanceFieldTextMaterial::compare(o);
}


class DistanceFieldOutlineTextMaterialShader : public DistanceFieldStyledTextMaterialShader
{
public:
    DistanceFieldOutlineTextMaterialShader();

    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);

protected:
    virtual void initialize();
    virtual const char *fragmentShader() const;

    void updateOutlineAlphaRange(int dfRadius);

    int m_outlineAlphaMax0_id;
    int m_outlineAlphaMax1_id;
};

const char *DistanceFieldOutlineTextMaterialShader::fragmentShader() const {
    return
            "varying highp vec2 sampleCoord;                                                      \n"
            "uniform sampler2D texture;                                                           \n"
            "uniform lowp vec4 color;                                                             \n"
            "uniform lowp vec4 styleColor;                                                        \n"
            "uniform mediump float alphaMin;                                                      \n"
            "uniform mediump float alphaMax;                                                      \n"
            "uniform mediump float outlineAlphaMax0;                                              \n"
            "uniform mediump float outlineAlphaMax1;                                              \n"
            "void main() {                                                                        \n"
            "    mediump float d = texture2D(texture, sampleCoord).a;                             \n"
            "    gl_FragColor = mix(styleColor, color, smoothstep(alphaMin, alphaMax, d))         \n"
            "                       * smoothstep(outlineAlphaMax0, outlineAlphaMax1, d);          \n"
            "}";
}

DistanceFieldOutlineTextMaterialShader::DistanceFieldOutlineTextMaterialShader()
    : DistanceFieldStyledTextMaterialShader()
{
}

void DistanceFieldOutlineTextMaterialShader::initialize()
{
    DistanceFieldStyledTextMaterialShader::initialize();
    m_outlineAlphaMax0_id = program()->uniformLocation("outlineAlphaMax0");
    m_outlineAlphaMax1_id = program()->uniformLocation("outlineAlphaMax1");
}

void DistanceFieldOutlineTextMaterialShader::updateOutlineAlphaRange(int dfRadius)
{
    qreal outlineLimit = qMax(qreal(0.2), qreal(0.5 - 0.5 / dfRadius / m_fontScale));

    qreal combinedScale = m_fontScale * m_matrixScale;
    qreal alphaMin = qMax(0.0, 0.5 - 0.07 / combinedScale);
    qreal styleAlphaMin0 = qMax(0.0, outlineLimit - 0.07 / combinedScale);
    qreal styleAlphaMin1 = qMin(qreal(outlineLimit + 0.07 / combinedScale), alphaMin);
    program()->setUniformValue(m_outlineAlphaMax0_id, GLfloat(styleAlphaMin0));
    program()->setUniformValue(m_outlineAlphaMax1_id, GLfloat(styleAlphaMin1));
}

void DistanceFieldOutlineTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    DistanceFieldStyledTextMaterialShader::updateState(state, newEffect, oldEffect);

    QSGDistanceFieldOutlineTextMaterial *material = static_cast<QSGDistanceFieldOutlineTextMaterial *>(newEffect);
    QSGDistanceFieldOutlineTextMaterial *oldMaterial = static_cast<QSGDistanceFieldOutlineTextMaterial *>(oldEffect);

    if (oldMaterial == 0
            || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale()
            || state.isMatrixDirty())
        updateOutlineAlphaRange(material->glyphCache()->distanceFieldRadius());
}


QSGDistanceFieldOutlineTextMaterial::QSGDistanceFieldOutlineTextMaterial()
    : QSGDistanceFieldStyledTextMaterial()
{
}

QSGDistanceFieldOutlineTextMaterial::~QSGDistanceFieldOutlineTextMaterial()
{
}

QSGMaterialType *QSGDistanceFieldOutlineTextMaterial::type() const
{
    static QSGMaterialType type;
    return &type;
}

QSGMaterialShader *QSGDistanceFieldOutlineTextMaterial::createShader() const
{
    return new DistanceFieldOutlineTextMaterialShader;
}


class DistanceFieldShiftedStyleTextMaterialShader : public DistanceFieldStyledTextMaterialShader
{
public:
    DistanceFieldShiftedStyleTextMaterialShader();

    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);

protected:
    virtual void initialize();
    virtual const char *vertexShader() const;
    virtual const char *fragmentShader() const;

    void updateShift(const QSGDistanceFieldGlyphCache *cache, const QPointF& shift);

    int m_shift_id;
};

DistanceFieldShiftedStyleTextMaterialShader::DistanceFieldShiftedStyleTextMaterialShader()
    : DistanceFieldStyledTextMaterialShader()
{
}

void DistanceFieldShiftedStyleTextMaterialShader::initialize()
{
    DistanceFieldStyledTextMaterialShader::initialize();
    m_shift_id = program()->uniformLocation("shift");
}

void DistanceFieldShiftedStyleTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    DistanceFieldStyledTextMaterialShader::updateState(state, newEffect, oldEffect);

    QSGDistanceFieldShiftedStyleTextMaterial *material = static_cast<QSGDistanceFieldShiftedStyleTextMaterial *>(newEffect);
    QSGDistanceFieldShiftedStyleTextMaterial *oldMaterial = static_cast<QSGDistanceFieldShiftedStyleTextMaterial *>(oldEffect);

    if (oldMaterial == 0
            || oldMaterial->glyphCache()->fontScale() != material->glyphCache()->fontScale()
            || oldMaterial->shift() != material->shift()
            || oldMaterial->textureSize() != material->textureSize()) {
        updateShift(material->glyphCache(), material->shift());
    }
}

void DistanceFieldShiftedStyleTextMaterialShader::updateShift(const QSGDistanceFieldGlyphCache *cache, const QPointF &shift)
{
    QPointF texel(1.0 / cache->fontScale() * shift.x(),
                  1.0 / cache->fontScale() * shift.y());
    program()->setUniformValue(m_shift_id, texel);
}

const char *DistanceFieldShiftedStyleTextMaterialShader::vertexShader() const
{
    return
            "uniform highp mat4 matrix;                                 \n"
            "uniform highp vec2 textureScale;                           \n"
            "attribute highp vec4 vCoord;                               \n"
            "attribute highp vec2 tCoord;                               \n"
            "uniform highp vec2 shift;                                  \n"
            "varying highp vec2 sampleCoord;                            \n"
            "varying highp vec2 shiftedSampleCoord;                     \n"
            "void main() {                                              \n"
            "     sampleCoord = tCoord * textureScale;                  \n"
            "     shiftedSampleCoord = (tCoord - shift) * textureScale; \n"
            "     gl_Position = matrix * vCoord;                        \n"
            "}";
}

const char *DistanceFieldShiftedStyleTextMaterialShader::fragmentShader() const {
    return
            "varying highp vec2 sampleCoord;                                                       \n"
            "varying highp vec2 shiftedSampleCoord;                                                \n"
            "uniform sampler2D texture;                                                            \n"
            "uniform lowp vec4 color;                                                              \n"
            "uniform lowp vec4 styleColor;                                                         \n"
            "uniform mediump float alphaMin;                                                       \n"
            "uniform mediump float alphaMax;                                                       \n"
            "void main() {                                                                         \n"
            "    highp float a = smoothstep(alphaMin, alphaMax, texture2D(texture, sampleCoord).a);\n"
            "    highp vec4 shifted = styleColor * smoothstep(alphaMin,                            \n"
            "                                                 alphaMax,                            \n"
            "                                                 texture2D(texture, shiftedSampleCoord).a); \n"
            "    gl_FragColor = mix(shifted, color, a);                                            \n"
            "}";
}

QSGDistanceFieldShiftedStyleTextMaterial::QSGDistanceFieldShiftedStyleTextMaterial()
    : QSGDistanceFieldStyledTextMaterial()
{
}

QSGDistanceFieldShiftedStyleTextMaterial::~QSGDistanceFieldShiftedStyleTextMaterial()
{
}

QSGMaterialType *QSGDistanceFieldShiftedStyleTextMaterial::type() const
{
    static QSGMaterialType type;
    return &type;
}

QSGMaterialShader *QSGDistanceFieldShiftedStyleTextMaterial::createShader() const
{
    return new DistanceFieldShiftedStyleTextMaterialShader;
}


class QSGHiQSubPixelDistanceFieldTextMaterialShader : public QSGDistanceFieldTextMaterialShader
{
public:
    virtual void initialize();
    virtual void activate();
    virtual void deactivate();
    virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);

protected:
    virtual const char *vertexShader() const;
    virtual const char *fragmentShader() const;

private:
    int m_fontScale_id;
    int m_vecDelta_id;
};

const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::vertexShader() const {
    return
        "uniform highp mat4 matrix;                                             \n"
        "uniform highp vec2 textureScale;                                       \n"
        "uniform highp float fontScale;                                         \n"
        "uniform highp vec4 vecDelta;                                           \n"
        "attribute highp vec4 vCoord;                                           \n"
        "attribute highp vec2 tCoord;                                           \n"
        "varying highp vec2 sampleCoord;                                        \n"
        "varying highp vec3 sampleFarLeft;                                      \n"
        "varying highp vec3 sampleNearLeft;                                     \n"
        "varying highp vec3 sampleNearRight;                                    \n"
        "varying highp vec3 sampleFarRight;                                     \n"
        "void main() {                                                          \n"
        "     sampleCoord = tCoord * textureScale;                              \n"
        "     gl_Position = matrix * vCoord;                                    \n"
        // Calculate neighbour pixel position in item space.
        "     highp vec3 wDelta = gl_Position.w * vecDelta.xyw;                 \n"
        "     highp vec3 farLeft = vCoord.xyw - 0.667 * wDelta;                 \n"
        "     highp vec3 nearLeft = vCoord.xyw - 0.333 * wDelta;                \n"
        "     highp vec3 nearRight = vCoord.xyw + 0.333 * wDelta;               \n"
        "     highp vec3 farRight = vCoord.xyw + 0.667 * wDelta;                \n"
        // Calculate neighbour texture coordinate.
        "     highp vec2 scale = textureScale / fontScale;                      \n"
        "     highp vec2 base = sampleCoord - scale * vCoord.xy;                \n"
        "     sampleFarLeft = vec3(base * farLeft.z + scale * farLeft.xy, farLeft.z); \n"
        "     sampleNearLeft = vec3(base * nearLeft.z + scale * nearLeft.xy, nearLeft.z); \n"
        "     sampleNearRight = vec3(base * nearRight.z + scale * nearRight.xy, nearRight.z); \n"
        "     sampleFarRight = vec3(base * farRight.z + scale * farRight.xy, farRight.z); \n"
        "}";
}

const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
    return
        "varying highp vec2 sampleCoord;                                        \n"
        "varying highp vec3 sampleFarLeft;                                      \n"
        "varying highp vec3 sampleNearLeft;                                     \n"
        "varying highp vec3 sampleNearRight;                                    \n"
        "varying highp vec3 sampleFarRight;                                     \n"
        "uniform sampler2D texture;                                             \n"
        "uniform lowp vec4 color;                                               \n"
        "uniform mediump float alphaMin;                                        \n"
        "uniform mediump float alphaMax;                                        \n"
        "void main() {                                                          \n"
        "    highp vec4 n;                                                      \n"
        "    n.x = texture2DProj(texture, sampleFarLeft).a;                     \n"
        "    n.y = texture2DProj(texture, sampleNearLeft).a;                    \n"
        "    highp float c = texture2D(texture, sampleCoord).a;                 \n"
        "    n.z = texture2DProj(texture, sampleNearRight).a;                   \n"
        "    n.w = texture2DProj(texture, sampleFarRight).a;                    \n"
#if 0
        // Blurrier, faster.
        "    n = smoothstep(alphaMin, alphaMax, n);                             \n"
        "    c = smoothstep(alphaMin, alphaMax, c);                             \n"
#else
        // Sharper, slower.
        "    highp vec2 d = min(abs(n.yw - n.xz) * 2., 0.67);                   \n"
        "    highp vec2 lo = mix(vec2(alphaMin), vec2(0.5), d);                 \n"
        "    highp vec2 hi = mix(vec2(alphaMax), vec2(0.5), d);                 \n"
        "    n = smoothstep(lo.xxyy, hi.xxyy, n);                               \n"
        "    c = smoothstep(lo.x + lo.y, hi.x + hi.y, 2. * c);                  \n"
#endif
        "    gl_FragColor = vec4(0.333 * (n.xyz + n.yzw + c), c) * color.w;     \n"
        "}";
}

//const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
//    return
//        "#extension GL_OES_standard_derivatives: enable                         \n"
//        "varying highp vec2 sampleCoord;                                        \n"
//        "uniform sampler2D texture;                                             \n"
//        "uniform lowp vec4 color;                                               \n"
//        "uniform highp float alphaMin;                                          \n"
//        "uniform highp float alphaMax;                                          \n"
//        "void main() {                                                          \n"
//        "    highp vec2 delta = dFdx(sampleCoord);                              \n"
//        "    highp vec4 n;                                                      \n"
//        "    n.x = texture2D(texture, sampleCoord - 0.667 * delta).a;           \n"
//        "    n.y = texture2D(texture, sampleCoord - 0.333 * delta).a;           \n"
//        "    highp float c = texture2D(texture, sampleCoord).a;                 \n"
//        "    n.z = texture2D(texture, sampleCoord + 0.333 * delta).a;           \n"
//        "    n.w = texture2D(texture, sampleCoord + 0.667 * delta).a;           \n"
//        "    n = smoothstep(alphaMin, alphaMax, n);                             \n"
//        "    c = smoothstep(alphaMin, alphaMax, c);                             \n"
//        "    gl_FragColor = vec4(0.333 * (n.xyz + n.yzw + c), c) * color.w;     \n"
//        "}";
//}

void QSGHiQSubPixelDistanceFieldTextMaterialShader::initialize()
{
    QSGDistanceFieldTextMaterialShader::initialize();
    m_fontScale_id = program()->uniformLocation("fontScale");
    m_vecDelta_id = program()->uniformLocation("vecDelta");
}

void QSGHiQSubPixelDistanceFieldTextMaterialShader::activate()
{
    QSGDistanceFieldTextMaterialShader::activate();
    glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
}

void QSGHiQSubPixelDistanceFieldTextMaterialShader::deactivate()
{
    QSGDistanceFieldTextMaterialShader::deactivate();
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

void QSGHiQSubPixelDistanceFieldTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
    QSGDistanceFieldTextMaterial *material = static_cast<QSGDistanceFieldTextMaterial *>(newEffect);
    QSGDistanceFieldTextMaterial *oldMaterial = static_cast<QSGDistanceFieldTextMaterial *>(oldEffect);

    if (oldMaterial == 0 || material->color() != oldMaterial->color()) {
        QColor c = material->color();
        state.context()->functions()->glBlendColor(c.redF(), c.greenF(), c.blueF(), 1.0f);
    }

    if (oldMaterial == 0 || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale())
        program()->setUniformValue(m_fontScale_id, GLfloat(material->glyphCache()->fontScale()));

    if (oldMaterial == 0 || state.isMatrixDirty()) {
        int viewportWidth = state.viewportRect().width();
        QMatrix4x4 mat = state.combinedMatrix().inverted();
        program()->setUniformValue(m_vecDelta_id, mat.column(0) * (qreal(2) / viewportWidth));
    }

    QSGDistanceFieldTextMaterialShader::updateState(state, newEffect, oldEffect);
}

QSGMaterialType *QSGHiQSubPixelDistanceFieldTextMaterial::type() const
{
    static QSGMaterialType type;
    return &type;
}

QSGMaterialShader *QSGHiQSubPixelDistanceFieldTextMaterial::createShader() const
{
    return new QSGHiQSubPixelDistanceFieldTextMaterialShader;
}


class QSGLoQSubPixelDistanceFieldTextMaterialShader : public QSGHiQSubPixelDistanceFieldTextMaterialShader
{
protected:
    virtual const char *vertexShader() const;
    virtual const char *fragmentShader() const;
};

const char *QSGLoQSubPixelDistanceFieldTextMaterialShader::vertexShader() const {
    return
        "uniform highp mat4 matrix;                                             \n"
        "uniform highp vec2 textureScale;                                       \n"
        "uniform highp float fontScale;                                         \n"
        "uniform highp vec4 vecDelta;                                           \n"
        "attribute highp vec4 vCoord;                                           \n"
        "attribute highp vec2 tCoord;                                           \n"
        "varying highp vec3 sampleNearLeft;                                     \n"
        "varying highp vec3 sampleNearRight;                                    \n"
        "void main() {                                                          \n"
        "     highp vec2 sampleCoord = tCoord * textureScale;                   \n"
        "     gl_Position = matrix * vCoord;                                    \n"
        // Calculate neighbour pixel position in item space.
        "     highp vec3 wDelta = gl_Position.w * vecDelta.xyw;                 \n"
        "     highp vec3 nearLeft = vCoord.xyw - 0.25 * wDelta;                 \n"
        "     highp vec3 nearRight = vCoord.xyw + 0.25 * wDelta;                \n"
        // Calculate neighbour texture coordinate.
        "     highp vec2 scale = textureScale / fontScale;                      \n"
        "     highp vec2 base = sampleCoord - scale * vCoord.xy;                \n"
        "     sampleNearLeft = vec3(base * nearLeft.z + scale * nearLeft.xy, nearLeft.z); \n"
        "     sampleNearRight = vec3(base * nearRight.z + scale * nearRight.xy, nearRight.z); \n"
        "}";
}

const char *QSGLoQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
    return
        "varying highp vec3 sampleNearLeft;                                     \n"
        "varying highp vec3 sampleNearRight;                                    \n"
        "uniform sampler2D texture;                                             \n"
        "uniform lowp vec4 color;                                               \n"
        "uniform mediump float alphaMin;                                        \n"
        "uniform mediump float alphaMax;                                        \n"
        "void main() {                                                          \n"
        "    highp vec2 n;                                                      \n"
        "    n.x = texture2DProj(texture, sampleNearLeft).a;                    \n"
        "    n.y = texture2DProj(texture, sampleNearRight).a;                   \n"
        "    n = smoothstep(alphaMin, alphaMax, n);                             \n"
        "    highp float c = 0.5 * (n.x + n.y);                                 \n"
        "    gl_FragColor = vec4(n.x, c, n.y, c) * color.w;                     \n"
        "}";
}

QSGMaterialType *QSGLoQSubPixelDistanceFieldTextMaterial::type() const
{
    static QSGMaterialType type;
    return &type;
}

QSGMaterialShader *QSGLoQSubPixelDistanceFieldTextMaterial::createShader() const
{
    return new QSGLoQSubPixelDistanceFieldTextMaterialShader;
}

QT_END_NAMESPACE