Merge branch 'refactor'
[profile/ivi/qtbase.git] / src / gui / opengl / qopenglpaintengine.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtGui module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*
43     When the active program changes, we need to update it's uniforms.
44     We could track state for each program and only update stale uniforms
45         - Could lead to lots of overhead if there's a lot of programs
46     We could update all the uniforms when the program changes
47         - Could end up updating lots of uniforms which don't need updating
48
49     Updating uniforms should be cheap, so the overhead of updating up-to-date
50     uniforms should be minimal. It's also less complex.
51
52     Things which _may_ cause a different program to be used:
53         - Change in brush/pen style
54         - Change in painter opacity
55         - Change in composition mode
56
57     Whenever we set a mode on the shader manager - it needs to tell us if it had
58     to switch to a different program.
59
60     The shader manager should only switch when we tell it to. E.g. if we set a new
61     brush style and then switch to transparent painter, we only want it to compile
62     and use the correct program when we really need it.
63 */
64
65 // #define QT_OPENGL_CACHE_AS_VBOS
66
67 #include "qopenglgradientcache_p.h"
68 #include "qopengltexturecache_p.h"
69 #include "qopenglpaintengine_p.h"
70
71 #include <string.h> //for memcpy
72 #include <qmath.h>
73
74 #include <private/qopengl_p.h>
75 #include <private/qopenglcontext_p.h>
76 #include <private/qopenglextensions_p.h>
77 #include <private/qmath_p.h>
78 #include <private/qpaintengineex_p.h>
79 #include <QPaintEngine>
80 #include <private/qpainter_p.h>
81 #include <private/qfontengine_p.h>
82 #include <private/qdatabuffer_p.h>
83 #include <private/qstatictext_p.h>
84 #include <private/qtriangulator_p.h>
85
86 #include "qopenglengineshadermanager_p.h"
87 #include "qopengl2pexvertexarray_p.h"
88 #include "qopengltriangulatingstroker_p.h"
89 #include "qopengltextureglyphcache_p.h"
90
91 #include <QDebug>
92
93 QT_BEGIN_NAMESPACE
94
95 #if defined(Q_WS_WIN)
96 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
97 #endif
98
99 #ifdef Q_WS_MAC
100 extern bool qt_applefontsmoothing_enabled;
101 #endif
102
103 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
104
105 ////////////////////////////////// Private Methods //////////////////////////////////////////
106
107 QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
108 {
109     delete shaderManager;
110
111     while (pathCaches.size()) {
112         QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
113         e->cleanup(e->engine, e->data);
114         e->data = 0;
115         e->engine = 0;
116     }
117
118     if (elementIndicesVBOId != 0) {
119         funcs.glDeleteBuffers(1, &elementIndicesVBOId);
120         elementIndicesVBOId = 0;
121     }
122 }
123
124 void QOpenGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
125 {
126 //    funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
127     if (id != GLuint(-1) && id == lastTextureUsed)
128         return;
129
130     lastTextureUsed = id;
131
132     if (smoothPixmapTransform) {
133         glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
134         glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
135     } else {
136         glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
137         glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138     }
139     glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
140     glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
141 }
142
143
144 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
145 {
146     qreal alpha = c.alphaF() * opacity;
147     c.setAlphaF(alpha);
148     c.setRedF(c.redF() * alpha);
149     c.setGreenF(c.greenF() * alpha);
150     c.setBlueF(c.blueF() * alpha);
151     return c;
152 }
153
154
155 void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
156 {
157     if (qbrush_fast_equals(currentBrush, brush))
158         return;
159
160     const Qt::BrushStyle newStyle = qbrush_style(brush);
161     Q_ASSERT(newStyle != Qt::NoBrush);
162
163     currentBrush = brush;
164     if (!currentBrushPixmap.isNull())
165         currentBrushPixmap = QPixmap();
166     brushUniformsDirty = true; // All brushes have at least one uniform
167
168     if (newStyle > Qt::SolidPattern)
169         brushTextureDirty = true;
170
171     if (currentBrush.style() == Qt::TexturePattern
172         && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
173     {
174         shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
175     } else {
176         shaderManager->setSrcPixelType(newStyle);
177     }
178     shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
179 }
180
181
182 void QOpenGL2PaintEngineExPrivate::useSimpleShader()
183 {
184     shaderManager->useSimpleProgram();
185
186     if (matrixDirty)
187         updateMatrix();
188 }
189
190 void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
191 {
192     Q_Q(QOpenGL2PaintEngineEx);
193 //     qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
194     Qt::BrushStyle style = currentBrush.style();
195
196     if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
197         // Get the image data for the pattern
198         QImage texImage = qt_imageForBrush(style, false);
199
200         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
201         QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, texImage);
202         updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
203     }
204     else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
205         // Gradiant brush: All the gradiants use the same texture
206
207         const QGradient* g = currentBrush.gradient();
208
209         // We apply global opacity in the fragment shaders, so we always pass 1.0
210         // for opacity to the cache.
211         GLuint texId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
212
213         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
214         glBindTexture(GL_TEXTURE_2D, texId);
215
216         if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
217             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
218         else if (g->spread() == QGradient::ReflectSpread)
219             updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
220         else
221             updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
222     }
223     else if (style == Qt::TexturePattern) {
224         currentBrushPixmap = currentBrush.texture();
225
226         int max_texture_size = ctx->d_func()->maxTextureSize();
227         if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
228             currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
229
230         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
231         QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, currentBrushPixmap);
232         updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
233         textureInvertedY = false;
234     }
235     brushTextureDirty = false;
236 }
237
238
239 void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
240 {
241 //     qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
242     Qt::BrushStyle style = currentBrush.style();
243
244     if (style == Qt::NoBrush)
245         return;
246
247     QTransform brushQTransform = currentBrush.transform();
248
249     if (style == Qt::SolidPattern) {
250         QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
251         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
252     }
253     else {
254         // All other brushes have a transform and thus need the translation point:
255         QPointF translationPoint;
256
257         if (style <= Qt::DiagCrossPattern) {
258             QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
259
260             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
261
262             QVector2D halfViewportSize(width*0.5, height*0.5);
263             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
264         }
265         else if (style == Qt::LinearGradientPattern) {
266             const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
267
268             QPointF realStart = g->start();
269             QPointF realFinal = g->finalStop();
270             translationPoint = realStart;
271
272             QPointF l = realFinal - realStart;
273
274             QVector3D linearData(
275                 l.x(),
276                 l.y(),
277                 1.0f / (l.x() * l.x() + l.y() * l.y())
278             );
279
280             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);
281
282             QVector2D halfViewportSize(width*0.5, height*0.5);
283             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
284         }
285         else if (style == Qt::ConicalGradientPattern) {
286             const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
287             translationPoint   = g->center();
288
289             GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
290
291             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);
292
293             QVector2D halfViewportSize(width*0.5, height*0.5);
294             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
295         }
296         else if (style == Qt::RadialGradientPattern) {
297             const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
298             QPointF realCenter = g->center();
299             QPointF realFocal  = g->focalPoint();
300             qreal   realRadius = g->centerRadius() - g->focalRadius();
301             translationPoint   = realFocal;
302
303             QPointF fmp = realCenter - realFocal;
304             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);
305
306             GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
307             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
308             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
309                                                              GLfloat(1.0 / (2.0*fmp2_m_radius2)));
310             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
311                                                              GLfloat(g->focalRadius() * g->focalRadius()));
312             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BRadius),
313                                                              GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
314                                                              g->focalRadius(),
315                                                              g->centerRadius() - g->focalRadius());
316
317             QVector2D halfViewportSize(width*0.5, height*0.5);
318             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
319         }
320         else if (style == Qt::TexturePattern) {
321             const QPixmap& texPixmap = currentBrush.texture();
322
323             if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
324                 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
325                 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
326             }
327
328             QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
329             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
330
331             QVector2D halfViewportSize(width*0.5, height*0.5);
332             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
333         }
334         else
335             qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");
336
337         const QPointF &brushOrigin = q->state()->brushOrigin;
338         QTransform matrix = q->state()->matrix;
339         matrix.translate(brushOrigin.x(), brushOrigin.y());
340
341         QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
342         qreal m22 = -1;
343         qreal dy = height;
344         if (device->paintFlipped()) {
345             m22 = 1;
346             dy = 0;
347         }
348         QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
349         QTransform inv_matrix;
350         if (style == Qt::TexturePattern && textureInvertedY == -1)
351             inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
352         else
353             inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
354
355         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
356         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
357     }
358     brushUniformsDirty = false;
359 }
360
361
362 // This assumes the shader manager has already setup the correct shader program
363 void QOpenGL2PaintEngineExPrivate::updateMatrix()
364 {
365 //     qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");
366
367     const QTransform& transform = q->state()->matrix;
368
369     // The projection matrix converts from Qt's coordinate system to GL's coordinate system
370     //    * GL's viewport is 2x2, Qt's is width x height
371     //    * GL has +y -> -y going from bottom -> top, Qt is the other way round
372     //    * GL has [0,0] in the center, Qt has it in the top-left
373     //
374     // This results in the Projection matrix below, which is multiplied by the painter's
375     // transformation matrix, as shown below:
376     //
377     //                Projection Matrix                      Painter Transform
378     // ------------------------------------------------   ------------------------
379     // | 2.0 / width  |      0.0      |     -1.0      |   |  m11  |  m21  |  dx  |
380     // |     0.0      | -2.0 / height |      1.0      | * |  m12  |  m22  |  dy  |
381     // |     0.0      |      0.0      |      1.0      |   |  m13  |  m23  |  m33 |
382     // ------------------------------------------------   ------------------------
383     //
384     // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
385
386     const GLfloat wfactor = 2.0f / width;
387     GLfloat hfactor = -2.0f / height;
388
389     GLfloat dx = transform.dx();
390     GLfloat dy = transform.dy();
391
392     if (device->paintFlipped()) {
393         hfactor *= -1;
394         dy -= height;
395     }
396
397     // Non-integer translates can have strange effects for some rendering operations such as
398     // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
399     if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
400         // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
401         dx = ceilf(dx - 0.5f);
402         dy = ceilf(dy - 0.5f);
403     }
404     pmvMatrix[0][0] = (wfactor * transform.m11())  - transform.m13();
405     pmvMatrix[1][0] = (wfactor * transform.m21())  - transform.m23();
406     pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
407     pmvMatrix[0][1] = (hfactor * transform.m12())  + transform.m13();
408     pmvMatrix[1][1] = (hfactor * transform.m22())  + transform.m23();
409     pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
410     pmvMatrix[0][2] = transform.m13();
411     pmvMatrix[1][2] = transform.m23();
412     pmvMatrix[2][2] = transform.m33();
413
414     // 1/10000 == 0.0001, so we have good enough res to cover curves
415     // that span the entire widget...
416     inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
417                                   qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
418                         qreal(0.0001));
419
420     matrixDirty = false;
421     matrixUniformDirty = true;
422
423     // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
424     // need to do this once for every matrix change and persists across all shader programs.
425     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
426     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
427     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
428
429     dasher.setInvScale(inverseScale);
430     stroker.setInvScale(inverseScale);
431 }
432
433
434 void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
435 {
436     // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
437     //       composition modes look odd.
438 //     qDebug() << "QOpenGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
439     switch(q->state()->composition_mode) {
440     case QPainter::CompositionMode_SourceOver:
441         glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
442         break;
443     case QPainter::CompositionMode_DestinationOver:
444         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
445         break;
446     case QPainter::CompositionMode_Clear:
447         glBlendFunc(GL_ZERO, GL_ZERO);
448         break;
449     case QPainter::CompositionMode_Source:
450         glBlendFunc(GL_ONE, GL_ZERO);
451         break;
452     case QPainter::CompositionMode_Destination:
453         glBlendFunc(GL_ZERO, GL_ONE);
454         break;
455     case QPainter::CompositionMode_SourceIn:
456         glBlendFunc(GL_DST_ALPHA, GL_ZERO);
457         break;
458     case QPainter::CompositionMode_DestinationIn:
459         glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
460         break;
461     case QPainter::CompositionMode_SourceOut:
462         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
463         break;
464     case QPainter::CompositionMode_DestinationOut:
465         glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
466         break;
467     case QPainter::CompositionMode_SourceAtop:
468         glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
469         break;
470     case QPainter::CompositionMode_DestinationAtop:
471         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
472         break;
473     case QPainter::CompositionMode_Xor:
474         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
475         break;
476     case QPainter::CompositionMode_Plus:
477         glBlendFunc(GL_ONE, GL_ONE);
478         break;
479     default:
480         qWarning("Unsupported composition mode");
481         break;
482     }
483
484     compositionModeDirty = false;
485 }
486
487 static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
488 {
489     coords[0] = rect.left;
490     coords[1] = rect.top;
491     coords[2] = rect.right;
492     coords[3] = rect.top;
493     coords[4] = rect.right;
494     coords[5] = rect.bottom;
495     coords[6] = rect.left;
496     coords[7] = rect.bottom;
497 }
498
499 void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
500 {
501     // Setup for texture drawing
502     currentBrush = noBrush;
503     shaderManager->setSrcPixelType(pattern ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
504
505     if (snapToPixelGrid) {
506         snapToPixelGrid = false;
507         matrixDirty = true;
508     }
509
510     if (prepareForDraw(opaque))
511         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
512
513     if (pattern) {
514         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
515         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
516     }
517
518     GLfloat dx = 1.0 / textureSize.width();
519     GLfloat dy = 1.0 / textureSize.height();
520
521     QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
522
523     setCoords(staticVertexCoordinateArray, dest);
524     setCoords(staticTextureCoordinateArray, srcTextureRect);
525
526     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
527 }
528
529 void QOpenGL2PaintEngineEx::beginNativePainting()
530 {
531     Q_D(QOpenGL2PaintEngineEx);
532     ensureActive();
533     d->transferMode(BrushDrawingMode);
534
535     d->nativePaintingActive = true;
536
537     d->funcs.glUseProgram(0);
538
539     // Disable all the vertex attribute arrays:
540     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
541         d->funcs.glDisableVertexAttribArray(i);
542
543 #ifndef QT_OPENGL_ES_2
544     Q_ASSERT(QOpenGLContext::currentContext());
545     const QSurfaceFormat &fmt = d->device->context()->format();
546     if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
547         || fmt.profile() == QSurfaceFormat::CompatibilityProfile)
548     {
549         // be nice to people who mix OpenGL 1.x code with QPainter commands
550         // by setting modelview and projection matrices to mirror the GL 1
551         // paint engine
552         const QTransform& mtx = state()->matrix;
553
554         float mv_matrix[4][4] =
555         {
556             { float(mtx.m11()), float(mtx.m12()),     0, float(mtx.m13()) },
557             { float(mtx.m21()), float(mtx.m22()),     0, float(mtx.m23()) },
558             {                0,                0,     1,                0 },
559             {  float(mtx.dx()),  float(mtx.dy()),     0, float(mtx.m33()) }
560         };
561
562         const QSize sz = d->device->size();
563
564         glMatrixMode(GL_PROJECTION);
565         glLoadIdentity();
566         glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
567
568         glMatrixMode(GL_MODELVIEW);
569         glLoadMatrixf(&mv_matrix[0][0]);
570     }
571 #endif
572
573     d->lastTextureUsed = GLuint(-1);
574     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
575     d->resetGLState();
576
577     d->shaderManager->setDirty();
578
579     d->needsSync = true;
580 }
581
582 void QOpenGL2PaintEngineExPrivate::resetGLState()
583 {
584     glDisable(GL_BLEND);
585     funcs.glActiveTexture(GL_TEXTURE0);
586     glDisable(GL_STENCIL_TEST);
587     glDisable(GL_DEPTH_TEST);
588     glDisable(GL_SCISSOR_TEST);
589     glDepthMask(true);
590     glDepthFunc(GL_LESS);
591     funcs.glClearDepthf(1);
592     glStencilMask(0xff);
593     glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
594     glStencilFunc(GL_ALWAYS, 0, 0xff);
595     setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
596     setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
597     setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
598 #ifndef QT_OPENGL_ES_2
599     // gl_Color, corresponding to vertex attribute 3, may have been changed
600     float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
601     funcs.glVertexAttrib4fv(3, color);
602 #endif
603 }
604
605 void QOpenGL2PaintEngineEx::endNativePainting()
606 {
607     Q_D(QOpenGL2PaintEngineEx);
608     d->needsSync = true;
609     d->nativePaintingActive = false;
610 }
611
612 void QOpenGL2PaintEngineEx::invalidateState()
613 {
614     Q_D(QOpenGL2PaintEngineEx);
615     d->needsSync = true;
616 }
617
618 bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
619     Q_D(const QOpenGL2PaintEngineEx);
620     return d->nativePaintingActive;
621 }
622
623 void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
624 {
625     if (newMode == mode)
626         return;
627
628     if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
629         lastTextureUsed = GLuint(-1);
630     }
631
632     if (newMode == TextDrawingMode) {
633         shaderManager->setHasComplexGeometry(true);
634     } else {
635         shaderManager->setHasComplexGeometry(false);
636     }
637
638     if (newMode == ImageDrawingMode) {
639         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
640         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
641     }
642
643     if (newMode == ImageArrayDrawingMode) {
644         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
645         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
646         setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
647     }
648
649     // This needs to change when we implement high-quality anti-aliasing...
650     if (newMode != TextDrawingMode)
651         shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
652
653     mode = newMode;
654 }
655
656 struct QOpenGL2PEVectorPathCache
657 {
658 #ifdef QT_OPENGL_CACHE_AS_VBOS
659     GLuint vbo;
660     GLuint ibo;
661 #else
662     float *vertices;
663     void *indices;
664 #endif
665     int vertexCount;
666     int indexCount;
667     GLenum primitiveType;
668     qreal iscale;
669     QVertexIndexVector::Type indexType;
670 };
671
672 void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
673 {
674     QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
675 #ifdef QT_OPENGL_CACHE_AS_VBOS
676     Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
677     static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
678     if (c->ibo)
679         d->unusedIBOSToClean << c->ibo;
680 #else
681     Q_UNUSED(engine);
682     qFree(c->vertices);
683     qFree(c->indices);
684 #endif
685     delete c;
686 }
687
688 // Assumes everything is configured for the brush you want to use
689 void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
690 {
691     transferMode(BrushDrawingMode);
692
693     if (snapToPixelGrid) {
694         snapToPixelGrid = false;
695         matrixDirty = true;
696     }
697
698     // Might need to call updateMatrix to re-calculate inverseScale
699     if (matrixDirty)
700         updateMatrix();
701
702     const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
703
704     // Check to see if there's any hints
705     if (path.shape() == QVectorPath::RectangleHint) {
706         QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
707         prepareForDraw(currentBrush.isOpaque());
708         composite(rect);
709     } else if (path.isConvex()) {
710
711         if (path.isCacheable()) {
712             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
713             QOpenGL2PEVectorPathCache *cache;
714
715             bool updateCache = false;
716
717             if (data) {
718                 cache = (QOpenGL2PEVectorPathCache *) data->data;
719                 // Check if scale factor is exceeded for curved paths and generate curves if so...
720                 if (path.isCurved()) {
721                     qreal scaleFactor = cache->iscale / inverseScale;
722                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
723 #ifdef QT_OPENGL_CACHE_AS_VBOS
724                         glDeleteBuffers(1, &cache->vbo);
725                         cache->vbo = 0;
726                         Q_ASSERT(cache->ibo == 0);
727 #else
728                         qFree(cache->vertices);
729                         Q_ASSERT(cache->indices == 0);
730 #endif
731                         updateCache = true;
732                     }
733                 }
734             } else {
735                 cache = new QOpenGL2PEVectorPathCache;
736                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
737                 updateCache = true;
738             }
739
740             // Flatten the path at the current scale factor and fill it into the cache struct.
741             if (updateCache) {
742                 vertexCoordinateArray.clear();
743                 vertexCoordinateArray.addPath(path, inverseScale, false);
744                 int vertexCount = vertexCoordinateArray.vertexCount();
745                 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
746                 cache->vertexCount = vertexCount;
747                 cache->indexCount = 0;
748                 cache->primitiveType = GL_TRIANGLE_FAN;
749                 cache->iscale = inverseScale;
750 #ifdef QT_OPENGL_CACHE_AS_VBOS
751                 glGenBuffers(1, &cache->vbo);
752                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
753                 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
754                 cache->ibo = 0;
755 #else
756                 cache->vertices = (float *) qMalloc(floatSizeInBytes);
757                 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
758                 cache->indices = 0;
759 #endif
760             }
761
762             prepareForDraw(currentBrush.isOpaque());
763 #ifdef QT_OPENGL_CACHE_AS_VBOS
764             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
765             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
766 #else
767             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
768 #endif
769             glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
770
771         } else {
772       //        printf(" - Marking path as cachable...\n");
773             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
774             path.makeCacheable();
775             vertexCoordinateArray.clear();
776             vertexCoordinateArray.addPath(path, inverseScale, false);
777             prepareForDraw(currentBrush.isOpaque());
778             drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
779         }
780
781     } else {
782         bool useCache = path.isCacheable();
783         if (useCache) {
784             QRectF bbox = path.controlPointRect();
785             // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
786             useCache &= (bbox.left() > -0x8000 * inverseScale)
787                      && (bbox.right() < 0x8000 * inverseScale)
788                      && (bbox.top() > -0x8000 * inverseScale)
789                      && (bbox.bottom() < 0x8000 * inverseScale);
790         }
791
792         if (useCache) {
793             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
794             QOpenGL2PEVectorPathCache *cache;
795
796             bool updateCache = false;
797
798             if (data) {
799                 cache = (QOpenGL2PEVectorPathCache *) data->data;
800                 // Check if scale factor is exceeded for curved paths and generate curves if so...
801                 if (path.isCurved()) {
802                     qreal scaleFactor = cache->iscale / inverseScale;
803                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
804 #ifdef QT_OPENGL_CACHE_AS_VBOS
805                         glDeleteBuffers(1, &cache->vbo);
806                         glDeleteBuffers(1, &cache->ibo);
807 #else
808                         qFree(cache->vertices);
809                         qFree(cache->indices);
810 #endif
811                         updateCache = true;
812                     }
813                 }
814             } else {
815                 cache = new QOpenGL2PEVectorPathCache;
816                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
817                 updateCache = true;
818             }
819
820             // Flatten the path at the current scale factor and fill it into the cache struct.
821             if (updateCache) {
822                 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
823                 cache->vertexCount = polys.vertices.size() / 2;
824                 cache->indexCount = polys.indices.size();
825                 cache->primitiveType = GL_TRIANGLES;
826                 cache->iscale = inverseScale;
827                 cache->indexType = polys.indices.type();
828 #ifdef QT_OPENGL_CACHE_AS_VBOS
829                 glGenBuffers(1, &cache->vbo);
830                 glGenBuffers(1, &cache->ibo);
831                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
832                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
833
834                 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
835                     funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
836                 else
837                     funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
838
839                 QVarLengthArray<float> vertices(polys.vertices.size());
840                 for (int i = 0; i < polys.vertices.size(); ++i)
841                     vertices[i] = float(inverseScale * polys.vertices.at(i));
842                 funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
843 #else
844                 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
845                 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
846                     cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
847                     memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
848                 } else {
849                     cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
850                     memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
851                 }
852                 for (int i = 0; i < polys.vertices.size(); ++i)
853                     cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
854 #endif
855             }
856
857             prepareForDraw(currentBrush.isOpaque());
858 #ifdef QT_OPENGL_CACHE_AS_VBOS
859             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
860             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
861             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
862             if (cache->indexType == QVertexIndexVector::UnsignedInt)
863                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
864             else
865                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
866             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
867             glBindBuffer(GL_ARRAY_BUFFER, 0);
868 #else
869             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
870             if (cache->indexType == QVertexIndexVector::UnsignedInt)
871                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
872             else
873                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
874 #endif
875
876         } else {
877       //        printf(" - Marking path as cachable...\n");
878             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
879             path.makeCacheable();
880
881             if (device->context()->format().stencilBufferSize() == 0) {
882                 // If there is no stencil buffer, triangulate the path instead.
883
884                 QRectF bbox = path.controlPointRect();
885                 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
886                 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
887                                   && (bbox.right() < 0x8000 * inverseScale)
888                                   && (bbox.top() > -0x8000 * inverseScale)
889                                   && (bbox.bottom() < 0x8000 * inverseScale);
890                 if (withinLimits) {
891                     QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
892
893                     QVarLengthArray<float> vertices(polys.vertices.size());
894                     for (int i = 0; i < polys.vertices.size(); ++i)
895                         vertices[i] = float(inverseScale * polys.vertices.at(i));
896
897                     prepareForDraw(currentBrush.isOpaque());
898                     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
899                     if (funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint))
900                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
901                     else
902                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
903                 } else {
904                     // We can't handle big, concave painter paths with OpenGL without stencil buffer.
905                     qWarning("Painter path exceeds +/-32767 pixels.");
906                 }
907                 return;
908             }
909
910             // The path is too complicated & needs the stencil technique
911             vertexCoordinateArray.clear();
912             vertexCoordinateArray.addPath(path, inverseScale, false);
913
914             fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
915
916             glStencilMask(0xff);
917             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
918
919             if (q->state()->clipTestEnabled) {
920                 // Pass when high bit is set, replace stencil value with current clip
921                 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
922             } else if (path.hasWindingFill()) {
923                 // Pass when any bit is set, replace stencil value with 0
924                 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
925             } else {
926                 // Pass when high bit is set, replace stencil value with 0
927                 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
928             }
929             prepareForDraw(currentBrush.isOpaque());
930
931             // Stencil the brush onto the dest buffer
932             composite(vertexCoordinateArray.boundingRect());
933             glStencilMask(0);
934             updateClipScissorTest();
935         }
936     }
937 }
938
939
940 void QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
941                                                           int count,
942                                                           int *stops,
943                                                           int stopCount,
944                                                           const QOpenGLRect &bounds,
945                                                           StencilFillMode mode)
946 {
947     Q_ASSERT(count || stops);
948
949 //     qDebug("QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
950     glStencilMask(0xff); // Enable stencil writes
951
952     if (dirtyStencilRegion.intersects(currentScissorBounds)) {
953         QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
954         glClearStencil(0); // Clear to zero
955         for (int i = 0; i < clearRegion.size(); ++i) {
956 #ifndef QT_GL_NO_SCISSOR_TEST
957             setScissor(clearRegion.at(i));
958 #endif
959             glClear(GL_STENCIL_BUFFER_BIT);
960         }
961
962         dirtyStencilRegion -= currentScissorBounds;
963
964 #ifndef QT_GL_NO_SCISSOR_TEST
965         updateClipScissorTest();
966 #endif
967     }
968
969     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
970     useSimpleShader();
971     glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
972
973     if (mode == WindingFillMode) {
974         Q_ASSERT(stops && !count);
975         if (q->state()->clipTestEnabled) {
976             // Flatten clip values higher than current clip, and set high bit to match current clip
977             glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
978             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
979             composite(bounds);
980
981             glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
982         } else if (!stencilClean) {
983             // Clear stencil buffer within bounding rect
984             glStencilFunc(GL_ALWAYS, 0, 0xff);
985             glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
986             composite(bounds);
987         }
988
989         // Inc. for front-facing triangle
990         funcs.glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
991         // Dec. for back-facing "holes"
992         funcs.glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
993         glStencilMask(~GL_STENCIL_HIGH_BIT);
994         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
995
996         if (q->state()->clipTestEnabled) {
997             // Clear high bit of stencil outside of path
998             glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
999             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1000             glStencilMask(GL_STENCIL_HIGH_BIT);
1001             composite(bounds);
1002         }
1003     } else if (mode == OddEvenFillMode) {
1004         glStencilMask(GL_STENCIL_HIGH_BIT);
1005         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1006         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1007
1008     } else { // TriStripStrokeFillMode
1009         Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1010         glStencilMask(GL_STENCIL_HIGH_BIT);
1011 #if 0
1012         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1013         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1014         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1015 #else
1016
1017         glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1018         if (q->state()->clipTestEnabled) {
1019             glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1020                           ~GL_STENCIL_HIGH_BIT);
1021         } else {
1022             glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1023         }
1024         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1025         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1026 #endif
1027     }
1028
1029     // Enable color writes & disable stencil writes
1030     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1031 }
1032
1033 /*
1034     If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1035     restore the stencil buffer to a pristine state.  The current clip region
1036     is set to 1, and the rest to 0.
1037 */
1038 void QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
1039 {
1040     if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1041         return;
1042
1043     Q_Q(QOpenGL2PaintEngineEx);
1044
1045     useSimpleShader();
1046     glEnable(GL_STENCIL_TEST);
1047     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1048
1049     QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1050     QOpenGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1051
1052     // Set high bit on clip region
1053     glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1054     glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1055     glStencilMask(GL_STENCIL_HIGH_BIT);
1056     composite(rect);
1057
1058     // Reset clipping to 1 and everything else to zero
1059     glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1060     glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1061     glStencilMask(0xff);
1062     composite(rect);
1063
1064     q->state()->currentClip = 1;
1065     q->state()->canRestoreClip = false;
1066
1067     maxClip = 1;
1068
1069     glStencilMask(0x0);
1070     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1071 }
1072
1073 bool QOpenGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1074 {
1075     if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1076         updateBrushTexture();
1077
1078     if (compositionModeDirty)
1079         updateCompositionMode();
1080
1081     if (matrixDirty)
1082         updateMatrix();
1083
1084     const bool stateHasOpacity = q->state()->opacity < 0.99f;
1085     if (q->state()->composition_mode == QPainter::CompositionMode_Source
1086         || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1087             && srcPixelsAreOpaque && !stateHasOpacity))
1088     {
1089         glDisable(GL_BLEND);
1090     } else {
1091         glEnable(GL_BLEND);
1092     }
1093
1094     QOpenGLEngineShaderManager::OpacityMode opacityMode;
1095     if (mode == ImageArrayDrawingMode) {
1096         opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
1097     } else {
1098         opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
1099                                       : QOpenGLEngineShaderManager::NoOpacity;
1100         if (stateHasOpacity && (mode != ImageDrawingMode)) {
1101             // Using a brush
1102             bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1103                                   (currentBrush.style() <= Qt::DiagCrossPattern);
1104
1105             if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1106                 opacityMode = QOpenGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1107         }
1108     }
1109     shaderManager->setOpacityMode(opacityMode);
1110
1111     bool changed = shaderManager->useCorrectShaderProg();
1112     // If the shader program needs changing, we change it and mark all uniforms as dirty
1113     if (changed) {
1114         // The shader program has changed so mark all uniforms as dirty:
1115         brushUniformsDirty = true;
1116         opacityUniformDirty = true;
1117         matrixUniformDirty = true;
1118     }
1119
1120     if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1121         updateBrushUniforms();
1122
1123     if (opacityMode == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1124         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1125         opacityUniformDirty = false;
1126     }
1127
1128     if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1129         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
1130                                                          pmvMatrix);
1131         matrixUniformDirty = false;
1132     }
1133
1134     return changed;
1135 }
1136
1137 void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& boundingRect)
1138 {
1139     setCoords(staticVertexCoordinateArray, boundingRect);
1140     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1141     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1142 }
1143
1144 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1145 void QOpenGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1146                                                 GLenum primitive)
1147 {
1148     // Now setup the pointer to the vertex array:
1149     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1150
1151     int previousStop = 0;
1152     for (int i=0; i<stopCount; ++i) {
1153         int stop = stops[i];
1154 /*
1155         qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1156         for (int i=previousStop; i<stop; ++i)
1157             qDebug("   %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1158 */
1159         glDrawArrays(primitive, previousStop, stop - previousStop);
1160         previousStop = stop;
1161     }
1162 }
1163
1164 /////////////////////////////////// Public Methods //////////////////////////////////////////
1165
1166 QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
1167     : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
1168 {
1169 }
1170
1171 QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
1172 {
1173 }
1174
1175 void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1176 {
1177     Q_D(QOpenGL2PaintEngineEx);
1178
1179     if (qbrush_style(brush) == Qt::NoBrush)
1180         return;
1181     ensureActive();
1182     d->setBrush(brush);
1183     d->fill(path);
1184 }
1185
1186 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1187
1188
1189 void QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1190 {
1191     Q_D(QOpenGL2PaintEngineEx);
1192
1193     const QBrush &penBrush = qpen_brush(pen);
1194     if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1195         return;
1196
1197     QOpenGL2PaintEngineState *s = state();
1198     if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1199         // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1200         QPaintEngineEx::stroke(path, pen);
1201         return;
1202     }
1203
1204     ensureActive();
1205     d->setBrush(penBrush);
1206     d->stroke(path, pen);
1207 }
1208
1209 void QOpenGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1210 {
1211     const QOpenGL2PaintEngineState *s = q->state();
1212     if (snapToPixelGrid) {
1213         snapToPixelGrid = false;
1214         matrixDirty = true;
1215     }
1216
1217     const Qt::PenStyle penStyle = qpen_style(pen);
1218     const QBrush &penBrush = qpen_brush(pen);
1219     const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1220
1221     transferMode(BrushDrawingMode);
1222
1223     // updateMatrix() is responsible for setting the inverse scale on
1224     // the strokers, so we need to call it here and not wait for
1225     // prepareForDraw() down below.
1226     updateMatrix();
1227
1228     QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1229                                                         ? q->state()->rectangleClip
1230                                                         : QRectF(0, 0, width, height));
1231
1232     if (penStyle == Qt::SolidLine) {
1233         stroker.process(path, pen, clip);
1234
1235     } else { // Some sort of dash
1236         dasher.process(path, pen, clip);
1237
1238         QVectorPath dashStroke(dasher.points(),
1239                                dasher.elementCount(),
1240                                dasher.elementTypes());
1241         stroker.process(dashStroke, pen, clip);
1242     }
1243
1244     if (!stroker.vertexCount())
1245         return;
1246
1247     if (opaque) {
1248         prepareForDraw(opaque);
1249         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1250         glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1251
1252 //         QBrush b(Qt::green);
1253 //         d->setBrush(&b);
1254 //         d->prepareForDraw(true);
1255 //         glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1256
1257     } else {
1258         qreal width = qpen_widthf(pen) / 2;
1259         if (width == 0)
1260             width = 0.5;
1261         qreal extra = pen.joinStyle() == Qt::MiterJoin
1262                       ? qMax(pen.miterLimit() * width, width)
1263                       : width;
1264
1265         if (pen.isCosmetic())
1266             extra = extra * inverseScale;
1267
1268         QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1269
1270         fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1271                                       0, 0, bounds, QOpenGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1272
1273         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1274
1275         // Pass when any bit is set, replace stencil value with 0
1276         glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1277         prepareForDraw(false);
1278
1279         // Stencil the brush onto the dest buffer
1280         composite(bounds);
1281
1282         glStencilMask(0);
1283
1284         updateClipScissorTest();
1285     }
1286 }
1287
1288 void QOpenGL2PaintEngineEx::penChanged() { }
1289 void QOpenGL2PaintEngineEx::brushChanged() { }
1290 void QOpenGL2PaintEngineEx::brushOriginChanged() { }
1291
1292 void QOpenGL2PaintEngineEx::opacityChanged()
1293 {
1294 //    qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
1295     Q_D(QOpenGL2PaintEngineEx);
1296     state()->opacityChanged = true;
1297
1298     Q_ASSERT(d->shaderManager);
1299     d->brushUniformsDirty = true;
1300     d->opacityUniformDirty = true;
1301 }
1302
1303 void QOpenGL2PaintEngineEx::compositionModeChanged()
1304 {
1305 //     qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
1306     Q_D(QOpenGL2PaintEngineEx);
1307     state()->compositionModeChanged = true;
1308     d->compositionModeDirty = true;
1309 }
1310
1311 void QOpenGL2PaintEngineEx::renderHintsChanged()
1312 {
1313     state()->renderHintsChanged = true;
1314
1315 #if !defined(QT_OPENGL_ES_2)
1316     if ((state()->renderHints & QPainter::Antialiasing)
1317         || (state()->renderHints & QPainter::HighQualityAntialiasing))
1318         glEnable(GL_MULTISAMPLE);
1319     else
1320         glDisable(GL_MULTISAMPLE);
1321 #endif
1322
1323     Q_D(QOpenGL2PaintEngineEx);
1324     d->lastTextureUsed = GLuint(-1);
1325     d->brushTextureDirty = true;
1326 //    qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
1327 }
1328
1329 void QOpenGL2PaintEngineEx::transformChanged()
1330 {
1331     Q_D(QOpenGL2PaintEngineEx);
1332     d->matrixDirty = true;
1333     state()->matrixChanged = true;
1334 }
1335
1336
1337 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1338 {
1339     return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1340 }
1341
1342 void QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1343 {
1344     Q_D(QOpenGL2PaintEngineEx);
1345     QOpenGLContext *ctx = d->ctx;
1346
1347     int max_texture_size = ctx->d_func()->maxTextureSize();
1348     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1349         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1350
1351         const qreal sx = scaled.width() / qreal(pixmap.width());
1352         const qreal sy = scaled.height() / qreal(pixmap.height());
1353
1354         drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1355         return;
1356     }
1357
1358     ensureActive();
1359     d->transferMode(ImageDrawingMode);
1360
1361     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1362     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1363
1364     QOpenGLRect srcRect(src.left(), src.top(), src.right(), src.bottom());
1365
1366     bool isBitmap = pixmap.isQBitmap();
1367     bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1368
1369     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1370                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1371     d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1372 }
1373
1374 void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1375                         Qt::ImageConversionFlags)
1376 {
1377     Q_D(QOpenGL2PaintEngineEx);
1378     QOpenGLContext *ctx = d->ctx;
1379
1380     int max_texture_size = ctx->d_func()->maxTextureSize();
1381     if (image.width() > max_texture_size || image.height() > max_texture_size) {
1382         QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1383
1384         const qreal sx = scaled.width() / qreal(image.width());
1385         const qreal sy = scaled.height() / qreal(image.height());
1386
1387         drawImage(dest, scaled, scaleRect(src, sx, sy));
1388         return;
1389     }
1390
1391     ensureActive();
1392     d->transferMode(ImageDrawingMode);
1393
1394     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1395
1396     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
1397
1398     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1399                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1400     d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1401 }
1402
1403 void QOpenGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1404 {
1405     Q_D(QOpenGL2PaintEngineEx);
1406
1407     ensureActive();
1408
1409     QPainterState *s = state();
1410     float det = s->matrix.determinant();
1411
1412     // don't try to cache huge fonts or vastly transformed fonts
1413     QFontEngine *fontEngine = textItem->fontEngine();
1414     const qreal pixelSize = fontEngine->fontDef.pixelSize;
1415     if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f) {
1416         QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1417                                                 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1418                                                 : d->glyphCacheType;
1419         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1420             if (d->device->context()->format().alphaBufferSize() > 0 || s->matrix.type() > QTransform::TxTranslate
1421                 || (s->composition_mode != QPainter::CompositionMode_Source
1422                 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1423             {
1424                 glyphType = QFontEngineGlyphCache::Raster_A8;
1425             }
1426         }
1427
1428         d->drawCachedGlyphs(glyphType, textItem);
1429     } else {
1430         QPaintEngineEx::drawStaticTextItem(textItem);
1431     }
1432 }
1433
1434 bool QOpenGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1435 {
1436     Q_D(QOpenGL2PaintEngineEx);
1437     if (!d->shaderManager)
1438         return false;
1439
1440     ensureActive();
1441     d->transferMode(ImageDrawingMode);
1442
1443     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1444     glBindTexture(GL_TEXTURE_2D, textureId);
1445
1446     QOpenGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1447
1448     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1449                            state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1450     d->drawTexture(dest, srcRect, size, false);
1451     return true;
1452 }
1453
1454 void QOpenGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1455 {
1456     Q_D(QOpenGL2PaintEngineEx);
1457
1458     ensureActive();
1459     QOpenGL2PaintEngineState *s = state();
1460
1461     const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1462
1463     QTransform::TransformationType txtype = s->matrix.type();
1464
1465     float det = s->matrix.determinant();
1466     bool drawCached = txtype < QTransform::TxProject;
1467
1468     // don't try to cache huge fonts or vastly transformed fonts
1469     const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1470     if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f)
1471         drawCached = false;
1472
1473     QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1474                                             ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1475                                             : d->glyphCacheType;
1476
1477
1478     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1479         if (d->device->context()->format().alphaBufferSize() > 0 || txtype > QTransform::TxTranslate
1480             || (state()->composition_mode != QPainter::CompositionMode_Source
1481             && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1482         {
1483             glyphType = QFontEngineGlyphCache::Raster_A8;
1484         }
1485     }
1486
1487     if (drawCached) {
1488         QVarLengthArray<QFixedPoint> positions;
1489         QVarLengthArray<glyph_t> glyphs;
1490         QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1491         ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1492
1493         {
1494             QStaticTextItem staticTextItem;
1495             staticTextItem.chars = const_cast<QChar *>(ti.chars);
1496             staticTextItem.setFontEngine(ti.fontEngine);
1497             staticTextItem.glyphs = glyphs.data();
1498             staticTextItem.numChars = ti.num_chars;
1499             staticTextItem.numGlyphs = glyphs.size();
1500             staticTextItem.glyphPositions = positions.data();
1501
1502             d->drawCachedGlyphs(glyphType, &staticTextItem);
1503         }
1504         return;
1505     }
1506
1507     QPaintEngineEx::drawTextItem(p, ti);
1508 }
1509
1510 namespace {
1511
1512     class QOpenGLStaticTextUserData: public QStaticTextUserData
1513     {
1514     public:
1515         QOpenGLStaticTextUserData()
1516             : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1517         {
1518         }
1519
1520         ~QOpenGLStaticTextUserData()
1521         {
1522         }
1523
1524         QSize cacheSize;
1525         QOpenGL2PEXVertexArray vertexCoordinateArray;
1526         QOpenGL2PEXVertexArray textureCoordinateArray;
1527         QFontEngineGlyphCache::Type glyphType;
1528         int cacheSerialNumber;
1529     };
1530
1531 }
1532
1533 #if defined(Q_WS_WIN)
1534 static bool fontSmoothingApproximately(qreal target)
1535 {
1536     extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1537     return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1538 }
1539 #endif
1540
1541 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1542
1543 void QOpenGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1544                                                 QStaticTextItem *staticTextItem)
1545 {
1546     Q_Q(QOpenGL2PaintEngineEx);
1547
1548     QOpenGL2PaintEngineState *s = q->state();
1549
1550     void *cacheKey = ctx->shareGroup();
1551     bool recreateVertexArrays = false;
1552
1553     QOpenGLTextureGlyphCache *cache =
1554             (QOpenGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1555     if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1556         cache = new QOpenGLTextureGlyphCache(glyphType, QTransform());
1557         staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1558         recreateVertexArrays = true;
1559     }
1560
1561     if (staticTextItem->userDataNeedsUpdate) {
1562         recreateVertexArrays = true;
1563     } else if (staticTextItem->userData() == 0) {
1564         recreateVertexArrays = true;
1565     } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1566         recreateVertexArrays = true;
1567     } else {
1568         QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1569         if (userData->glyphType != glyphType) {
1570             recreateVertexArrays = true;
1571         } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1572             recreateVertexArrays = true;
1573         }
1574     }
1575
1576     // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1577     // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1578     // cache so this text is performed before we test if the cache size has changed.
1579     if (recreateVertexArrays) {
1580         cache->setPaintEnginePrivate(this);
1581         if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1582                              staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1583             // No space for glyphs in cache. We need to reset it and try again.
1584             cache->clear();
1585             cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1586                             staticTextItem->glyphs, staticTextItem->glyphPositions);
1587         }
1588         cache->fillInPendingGlyphs();
1589     }
1590
1591     if (cache->width() == 0 || cache->height() == 0)
1592         return;
1593
1594     transferMode(TextDrawingMode);
1595
1596     int margin = cache->glyphMargin();
1597
1598     GLfloat dx = 1.0 / cache->width();
1599     GLfloat dy = 1.0 / cache->height();
1600
1601     // Use global arrays by default
1602     QOpenGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1603     QOpenGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1604
1605     if (staticTextItem->useBackendOptimizations) {
1606         QOpenGLStaticTextUserData *userData = 0;
1607
1608         if (staticTextItem->userData() == 0
1609             || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1610
1611             userData = new QOpenGLStaticTextUserData();
1612             staticTextItem->setUserData(userData);
1613
1614         } else {
1615             userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1616         }
1617
1618         userData->glyphType = glyphType;
1619         userData->cacheSerialNumber = cache->serialNumber();
1620
1621         // Use cache if backend optimizations is turned on
1622         vertexCoordinates = &userData->vertexCoordinateArray;
1623         textureCoordinates = &userData->textureCoordinateArray;
1624
1625         QSize size(cache->width(), cache->height());
1626         if (userData->cacheSize != size) {
1627             recreateVertexArrays = true;
1628             userData->cacheSize = size;
1629         }
1630     }
1631
1632     if (recreateVertexArrays) {
1633         vertexCoordinates->clear();
1634         textureCoordinates->clear();
1635
1636         bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1637         for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1638             QFixed subPixelPosition;
1639             if (supportsSubPixelPositions)
1640                 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1641
1642             QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1643
1644             const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1645             if (c.isNull())
1646                 continue;
1647
1648             int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1649             int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1650
1651             vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1652             textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1653         }
1654
1655         staticTextItem->userDataNeedsUpdate = false;
1656     }
1657
1658     int numGlyphs = vertexCoordinates->vertexCount() / 4;
1659     if (numGlyphs == 0)
1660         return;
1661
1662     if (elementIndices.size() < numGlyphs*6) {
1663         Q_ASSERT(elementIndices.size() % 6 == 0);
1664         int j = elementIndices.size() / 6 * 4;
1665         while (j < numGlyphs*4) {
1666             elementIndices.append(j + 0);
1667             elementIndices.append(j + 0);
1668             elementIndices.append(j + 1);
1669             elementIndices.append(j + 2);
1670             elementIndices.append(j + 3);
1671             elementIndices.append(j + 3);
1672
1673             j += 4;
1674         }
1675
1676 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1677         if (elementIndicesVBOId == 0)
1678             glGenBuffers(1, &elementIndicesVBOId);
1679
1680         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1681         glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1682                      elementIndices.constData(), GL_STATIC_DRAW);
1683 #endif
1684     } else {
1685 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1686         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1687 #endif
1688     }
1689
1690     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1691     setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1692
1693     if (!snapToPixelGrid) {
1694         snapToPixelGrid = true;
1695         matrixDirty = true;
1696     }
1697
1698     QBrush pensBrush = q->state()->pen.brush();
1699     setBrush(pensBrush);
1700
1701     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1702
1703         // Subpixel antialiasing without gamma correction
1704
1705         QPainter::CompositionMode compMode = q->state()->composition_mode;
1706         Q_ASSERT(compMode == QPainter::CompositionMode_Source
1707             || compMode == QPainter::CompositionMode_SourceOver);
1708
1709         shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass1);
1710
1711         if (pensBrush.style() == Qt::SolidPattern) {
1712             // Solid patterns can get away with only one pass.
1713             QColor c = pensBrush.color();
1714             qreal oldOpacity = q->state()->opacity;
1715             if (compMode == QPainter::CompositionMode_Source) {
1716                 c = qt_premultiplyColor(c, q->state()->opacity);
1717                 q->state()->opacity = 1;
1718                 opacityUniformDirty = true;
1719             }
1720
1721             compositionModeDirty = false; // I can handle this myself, thank you very much
1722             prepareForDraw(false); // Text always causes src pixels to be transparent
1723
1724             // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1725             if (compMode == QPainter::CompositionMode_Source) {
1726                 q->state()->opacity = oldOpacity;
1727                 opacityUniformDirty = true;
1728             }
1729
1730             glEnable(GL_BLEND);
1731             glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1732             funcs.glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1733         } else {
1734             // Other brush styles need two passes.
1735
1736             qreal oldOpacity = q->state()->opacity;
1737             if (compMode == QPainter::CompositionMode_Source) {
1738                 q->state()->opacity = 1;
1739                 opacityUniformDirty = true;
1740                 pensBrush = Qt::white;
1741                 setBrush(pensBrush);
1742             }
1743
1744             compositionModeDirty = false; // I can handle this myself, thank you very much
1745             prepareForDraw(false); // Text always causes src pixels to be transparent
1746             glEnable(GL_BLEND);
1747             glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1748
1749             funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1750             glBindTexture(GL_TEXTURE_2D, cache->texture());
1751             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1752
1753 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1754             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1755 #else
1756             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1757 #endif
1758
1759             shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass2);
1760
1761             if (compMode == QPainter::CompositionMode_Source) {
1762                 q->state()->opacity = oldOpacity;
1763                 opacityUniformDirty = true;
1764                 pensBrush = q->state()->pen.brush();
1765                 setBrush(pensBrush);
1766             }
1767
1768             compositionModeDirty = false;
1769             prepareForDraw(false); // Text always causes src pixels to be transparent
1770             glEnable(GL_BLEND);
1771             glBlendFunc(GL_ONE, GL_ONE);
1772         }
1773         compositionModeDirty = true;
1774     } else {
1775         // Greyscale/mono glyphs
1776
1777         shaderManager->setMaskType(QOpenGLEngineShaderManager::PixelMask);
1778         prepareForDraw(false); // Text always causes src pixels to be transparent
1779     }
1780
1781     QOpenGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QOpenGLTextureGlyphCache::Linear:QOpenGLTextureGlyphCache::Nearest;
1782     if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1783
1784         funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1785         if (lastMaskTextureUsed != cache->texture()) {
1786             glBindTexture(GL_TEXTURE_2D, cache->texture());
1787             lastMaskTextureUsed = cache->texture();
1788         }
1789
1790         if (cache->filterMode() != filterMode) {
1791             if (filterMode == QOpenGLTextureGlyphCache::Linear) {
1792                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1793                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1794             } else {
1795                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1796                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1797             }
1798             cache->setFilterMode(filterMode);
1799         }
1800     }
1801
1802     bool srgbFrameBufferEnabled = false;
1803     if (funcs.hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer)) {
1804 #if defined(Q_WS_MAC)
1805         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1806 #elif defined(Q_WS_WIN)
1807         if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1808 #else
1809         if (false)
1810 #endif
1811         {
1812             glEnable(GL_FRAMEBUFFER_SRGB);
1813             srgbFrameBufferEnabled = true;
1814         }
1815     }
1816
1817 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1818     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1819     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1820 #else
1821     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1822 #endif
1823
1824     if (srgbFrameBufferEnabled)
1825         glDisable(GL_FRAMEBUFFER_SRGB);
1826
1827 }
1828
1829 void QOpenGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1830                                             QPainter::PixmapFragmentHints hints)
1831 {
1832     Q_D(QOpenGL2PaintEngineEx);
1833     // Use fallback for extended composition modes.
1834     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1835         QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1836         return;
1837     }
1838
1839     ensureActive();
1840     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1841     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1842         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1843         d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1844     } else {
1845         d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1846     }
1847 }
1848
1849
1850 void QOpenGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1851                                                    int fragmentCount, const QPixmap &pixmap,
1852                                                    QPainter::PixmapFragmentHints hints)
1853 {
1854     GLfloat dx = 1.0f / pixmap.size().width();
1855     GLfloat dy = 1.0f / pixmap.size().height();
1856
1857     vertexCoordinateArray.clear();
1858     textureCoordinateArray.clear();
1859     opacityArray.reset();
1860
1861     if (snapToPixelGrid) {
1862         snapToPixelGrid = false;
1863         matrixDirty = true;
1864     }
1865
1866     bool allOpaque = true;
1867
1868     for (int i = 0; i < fragmentCount; ++i) {
1869         qreal s = 0;
1870         qreal c = 1;
1871         if (fragments[i].rotation != 0) {
1872             s = qFastSin(fragments[i].rotation * Q_PI / 180);
1873             c = qFastCos(fragments[i].rotation * Q_PI / 180);
1874         }
1875
1876         qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1877         qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1878         QOpenGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1879         QOpenGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1880
1881         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1882         vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1883         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1884         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1885         vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1886         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1887
1888         QOpenGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1889                     (fragments[i].sourceLeft + fragments[i].width) * dx,
1890                     (fragments[i].sourceTop + fragments[i].height) * dy);
1891
1892         textureCoordinateArray.addVertex(src.right, src.bottom);
1893         textureCoordinateArray.addVertex(src.right, src.top);
1894         textureCoordinateArray.addVertex(src.left, src.top);
1895         textureCoordinateArray.addVertex(src.left, src.top);
1896         textureCoordinateArray.addVertex(src.left, src.bottom);
1897         textureCoordinateArray.addVertex(src.right, src.bottom);
1898
1899         qreal opacity = fragments[i].opacity * q->state()->opacity;
1900         opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1901         allOpaque &= (opacity >= 0.99f);
1902     }
1903
1904     funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1905     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1906     transferMode(ImageArrayDrawingMode);
1907
1908     bool isBitmap = pixmap.isQBitmap();
1909     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1910
1911     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1912                            q->state()->renderHints & QPainter::SmoothPixmapTransform, id);
1913
1914     // Setup for texture drawing
1915     currentBrush = noBrush;
1916     shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc
1917                                             : QOpenGLEngineShaderManager::ImageSrc);
1918     if (prepareForDraw(isOpaque))
1919         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1920
1921     if (isBitmap) {
1922         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1923         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
1924     }
1925
1926     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1927 }
1928
1929 bool QOpenGL2PaintEngineEx::begin(QPaintDevice *pdev)
1930 {
1931     Q_D(QOpenGL2PaintEngineEx);
1932
1933     Q_ASSERT(pdev->devType() == QInternal::OpenGL);
1934     d->device = static_cast<QOpenGLPaintDevice*>(pdev);
1935
1936     if (!d->device)
1937         return false;
1938
1939     if (d->device->context() != QOpenGLContext::currentContext()) {
1940         qWarning("QPainter::begin(): QOpenGLPaintDevice's context needs to be current");
1941         return false;
1942     }
1943
1944     d->ctx = QOpenGLContext::currentContext();
1945     d->ctx->d_func()->active_engine = this;
1946
1947     d->funcs.initializeGLFunctions();
1948
1949     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1950         d->vertexAttributeArraysEnabledState[i] = false;
1951
1952     const QSize sz = d->device->size();
1953     d->width = sz.width();
1954     d->height = sz.height();
1955     d->mode = BrushDrawingMode;
1956     d->brushTextureDirty = true;
1957     d->brushUniformsDirty = true;
1958     d->matrixUniformDirty = true;
1959     d->matrixDirty = true;
1960     d->compositionModeDirty = true;
1961     d->opacityUniformDirty = true;
1962     d->needsSync = true;
1963     d->useSystemClip = !systemClip().isEmpty();
1964     d->currentBrush = QBrush();
1965
1966     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1967     d->stencilClean = true;
1968
1969     d->shaderManager = new QOpenGLEngineShaderManager(d->ctx);
1970
1971     glDisable(GL_STENCIL_TEST);
1972     glDisable(GL_DEPTH_TEST);
1973     glDisable(GL_SCISSOR_TEST);
1974
1975 #if !defined(QT_OPENGL_ES_2)
1976     glDisable(GL_MULTISAMPLE);
1977 #endif
1978
1979     d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
1980
1981 #if !defined(QT_OPENGL_ES_2)
1982 #if defined(Q_WS_WIN)
1983     if (qt_cleartype_enabled
1984         && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
1985 #endif
1986 #if defined(Q_WS_MAC)
1987     if (qt_applefontsmoothing_enabled)
1988 #endif
1989         d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
1990 #endif
1991
1992 #if defined(QT_OPENGL_ES_2)
1993     // OpenGL ES can't switch MSAA off, so if the gl paint device is
1994     // multisampled, it's always multisampled.
1995     d->multisamplingAlwaysEnabled = d->device->context()->format().samples() > 1;
1996 #else
1997     d->multisamplingAlwaysEnabled = false;
1998 #endif
1999
2000     return true;
2001 }
2002
2003 bool QOpenGL2PaintEngineEx::end()
2004 {
2005     Q_D(QOpenGL2PaintEngineEx);
2006
2007     QOpenGLContext *ctx = d->ctx;
2008     d->funcs.glUseProgram(0);
2009     d->transferMode(BrushDrawingMode);
2010
2011     ctx->d_func()->active_engine = 0;
2012
2013     d->resetGLState();
2014
2015     delete d->shaderManager;
2016     d->shaderManager = 0;
2017     d->currentBrush = QBrush();
2018
2019 #ifdef QT_OPENGL_CACHE_AS_VBOS
2020     if (!d->unusedVBOSToClean.isEmpty()) {
2021         glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2022         d->unusedVBOSToClean.clear();
2023     }
2024     if (!d->unusedIBOSToClean.isEmpty()) {
2025         glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2026         d->unusedIBOSToClean.clear();
2027     }
2028 #endif
2029
2030     return false;
2031 }
2032
2033 void QOpenGL2PaintEngineEx::ensureActive()
2034 {
2035     Q_D(QOpenGL2PaintEngineEx);
2036     QOpenGLContext *ctx = d->ctx;
2037
2038     if (isActive() && ctx->d_func()->active_engine != this) {
2039         ctx->d_func()->active_engine = this;
2040         d->needsSync = true;
2041     }
2042
2043     if (d->needsSync) {
2044         d->transferMode(BrushDrawingMode);
2045         glViewport(0, 0, d->width, d->height);
2046         d->needsSync = false;
2047         d->lastMaskTextureUsed = 0;
2048         d->shaderManager->setDirty();
2049         d->syncGlState();
2050         for (int i = 0; i < 3; ++i)
2051             d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2052         setState(state());
2053     }
2054 }
2055
2056 void QOpenGL2PaintEngineExPrivate::updateClipScissorTest()
2057 {
2058     Q_Q(QOpenGL2PaintEngineEx);
2059     if (q->state()->clipTestEnabled) {
2060         glEnable(GL_STENCIL_TEST);
2061         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2062     } else {
2063         glDisable(GL_STENCIL_TEST);
2064         glStencilFunc(GL_ALWAYS, 0, 0xff);
2065     }
2066
2067 #ifdef QT_GL_NO_SCISSOR_TEST
2068     currentScissorBounds = QRect(0, 0, width, height);
2069 #else
2070     QRect bounds = q->state()->rectangleClip;
2071     if (!q->state()->clipEnabled) {
2072         if (useSystemClip)
2073             bounds = systemClip.boundingRect();
2074         else
2075             bounds = QRect(0, 0, width, height);
2076     } else {
2077         if (useSystemClip)
2078             bounds = bounds.intersected(systemClip.boundingRect());
2079         else
2080             bounds = bounds.intersected(QRect(0, 0, width, height));
2081     }
2082
2083     currentScissorBounds = bounds;
2084
2085     if (bounds == QRect(0, 0, width, height)) {
2086         glDisable(GL_SCISSOR_TEST);
2087     } else {
2088         glEnable(GL_SCISSOR_TEST);
2089         setScissor(bounds);
2090     }
2091 #endif
2092 }
2093
2094 void QOpenGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2095 {
2096     const int left = rect.left();
2097     const int width = rect.width();
2098     int bottom = height - (rect.top() + rect.height());
2099     if (device->paintFlipped()) {
2100         bottom = rect.top();
2101     }
2102     const int height = rect.height();
2103
2104     glScissor(left, bottom, width, height);
2105 }
2106
2107 void QOpenGL2PaintEngineEx::clipEnabledChanged()
2108 {
2109     Q_D(QOpenGL2PaintEngineEx);
2110
2111     state()->clipChanged = true;
2112
2113     if (painter()->hasClipping())
2114         d->regenerateClip();
2115     else
2116         d->systemStateChanged();
2117 }
2118
2119 void QOpenGL2PaintEngineExPrivate::clearClip(uint value)
2120 {
2121     dirtyStencilRegion -= currentScissorBounds;
2122
2123     glStencilMask(0xff);
2124     glClearStencil(value);
2125     glClear(GL_STENCIL_BUFFER_BIT);
2126     glStencilMask(0x0);
2127
2128     q->state()->needsClipBufferClear = false;
2129 }
2130
2131 void QOpenGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2132 {
2133     transferMode(BrushDrawingMode);
2134
2135     if (snapToPixelGrid) {
2136         snapToPixelGrid = false;
2137         matrixDirty = true;
2138     }
2139
2140     if (matrixDirty)
2141         updateMatrix();
2142
2143     stencilClean = false;
2144
2145     const bool singlePass = !path.hasWindingFill()
2146         && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2147             || q->state()->needsClipBufferClear);
2148     const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2149
2150     if (q->state()->needsClipBufferClear)
2151         clearClip(1);
2152
2153     if (path.isEmpty()) {
2154         glEnable(GL_STENCIL_TEST);
2155         glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2156         return;
2157     }
2158
2159     if (q->state()->clipTestEnabled)
2160         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2161     else
2162         glStencilFunc(GL_ALWAYS, 0, 0xff);
2163
2164     vertexCoordinateArray.clear();
2165     vertexCoordinateArray.addPath(path, inverseScale, false);
2166
2167     if (!singlePass)
2168         fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2169
2170     glColorMask(false, false, false, false);
2171     glEnable(GL_STENCIL_TEST);
2172     useSimpleShader();
2173
2174     if (singlePass) {
2175         // Under these conditions we can set the new stencil value in a single
2176         // pass, by using the current value and the "new value" as the toggles
2177
2178         glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2179         glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2180         glStencilMask(value ^ referenceClipValue);
2181
2182         drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2183     } else {
2184         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2185         glStencilMask(0xff);
2186
2187         if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2188             // Pass when any clip bit is set, set high bit
2189             glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2190             composite(vertexCoordinateArray.boundingRect());
2191         }
2192
2193         // Pass when high bit is set, replace stencil value with new clip value
2194         glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2195
2196         composite(vertexCoordinateArray.boundingRect());
2197     }
2198
2199     glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2200     glStencilMask(0);
2201
2202     glColorMask(true, true, true, true);
2203 }
2204
2205 void QOpenGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2206 {
2207 //     qDebug("QOpenGL2PaintEngineEx::clip()");
2208     Q_D(QOpenGL2PaintEngineEx);
2209
2210     state()->clipChanged = true;
2211
2212     ensureActive();
2213
2214     if (op == Qt::ReplaceClip) {
2215         op = Qt::IntersectClip;
2216         if (d->hasClipOperations()) {
2217             d->systemStateChanged();
2218             state()->canRestoreClip = false;
2219         }
2220     }
2221
2222 #ifndef QT_GL_NO_SCISSOR_TEST
2223     if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2224         const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2225         QRectF rect(points[0], points[2]);
2226
2227         if (state()->matrix.type() <= QTransform::TxScale
2228             || (state()->matrix.type() == QTransform::TxRotate
2229                 && qFuzzyIsNull(state()->matrix.m11())
2230                 && qFuzzyIsNull(state()->matrix.m22())))
2231         {
2232             state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2233             d->updateClipScissorTest();
2234             return;
2235         }
2236     }
2237 #endif
2238
2239     const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2240
2241     switch (op) {
2242     case Qt::NoClip:
2243         if (d->useSystemClip) {
2244             state()->clipTestEnabled = true;
2245             state()->currentClip = 1;
2246         } else {
2247             state()->clipTestEnabled = false;
2248         }
2249         state()->rectangleClip = QRect(0, 0, d->width, d->height);
2250         state()->canRestoreClip = false;
2251         d->updateClipScissorTest();
2252         break;
2253     case Qt::IntersectClip:
2254         state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2255         d->updateClipScissorTest();
2256         d->resetClipIfNeeded();
2257         ++d->maxClip;
2258         d->writeClip(path, d->maxClip);
2259         state()->currentClip = d->maxClip;
2260         state()->clipTestEnabled = true;
2261         break;
2262     default:
2263         break;
2264     }
2265 }
2266
2267 void QOpenGL2PaintEngineExPrivate::regenerateClip()
2268 {
2269     systemStateChanged();
2270     replayClipOperations();
2271 }
2272
2273 void QOpenGL2PaintEngineExPrivate::systemStateChanged()
2274 {
2275     Q_Q(QOpenGL2PaintEngineEx);
2276
2277     q->state()->clipChanged = true;
2278
2279     if (systemClip.isEmpty()) {
2280         useSystemClip = false;
2281     } else {
2282         if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2283             //QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2284             //useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2285             useSystemClip = true;
2286         } else {
2287             useSystemClip = true;
2288         }
2289     }
2290
2291     q->state()->clipTestEnabled = false;
2292     q->state()->needsClipBufferClear = true;
2293
2294     q->state()->currentClip = 1;
2295     maxClip = 1;
2296
2297     q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2298     updateClipScissorTest();
2299
2300     if (systemClip.rectCount() == 1) {
2301         if (systemClip.boundingRect() == QRect(0, 0, width, height))
2302             useSystemClip = false;
2303 #ifndef QT_GL_NO_SCISSOR_TEST
2304         // scissoring takes care of the system clip
2305         return;
2306 #endif
2307     }
2308
2309     if (useSystemClip) {
2310         clearClip(0);
2311
2312         QPainterPath path;
2313         path.addRegion(systemClip);
2314
2315         q->state()->currentClip = 0;
2316         writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2317         q->state()->currentClip = 1;
2318         q->state()->clipTestEnabled = true;
2319     }
2320 }
2321
2322 void QOpenGL2PaintEngineEx::setState(QPainterState *new_state)
2323 {
2324     //     qDebug("QOpenGL2PaintEngineEx::setState()");
2325
2326     Q_D(QOpenGL2PaintEngineEx);
2327
2328     QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2329     QOpenGL2PaintEngineState *old_state = state();
2330
2331     QPaintEngineEx::setState(s);
2332
2333     if (s->isNew) {
2334         // Newly created state object.  The call to setState()
2335         // will either be followed by a call to begin(), or we are
2336         // setting the state as part of a save().
2337         s->isNew = false;
2338         return;
2339     }
2340
2341     // Setting the state as part of a restore().
2342
2343     if (old_state == s || old_state->renderHintsChanged)
2344         renderHintsChanged();
2345
2346     if (old_state == s || old_state->matrixChanged)
2347         d->matrixDirty = true;
2348
2349     if (old_state == s || old_state->compositionModeChanged)
2350         d->compositionModeDirty = true;
2351
2352     if (old_state == s || old_state->opacityChanged)
2353         d->opacityUniformDirty = true;
2354
2355     if (old_state == s || old_state->clipChanged) {
2356         if (old_state && old_state != s && old_state->canRestoreClip) {
2357             d->updateClipScissorTest();
2358             glDepthFunc(GL_LEQUAL);
2359         } else {
2360             d->regenerateClip();
2361         }
2362     }
2363 }
2364
2365 QPainterState *QOpenGL2PaintEngineEx::createState(QPainterState *orig) const
2366 {
2367     if (orig)
2368         const_cast<QOpenGL2PaintEngineEx *>(this)->ensureActive();
2369
2370     QOpenGL2PaintEngineState *s;
2371     if (!orig)
2372         s = new QOpenGL2PaintEngineState();
2373     else
2374         s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2375
2376     s->matrixChanged = false;
2377     s->compositionModeChanged = false;
2378     s->opacityChanged = false;
2379     s->renderHintsChanged = false;
2380     s->clipChanged = false;
2381
2382     return s;
2383 }
2384
2385 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2386     : QPainterState(other)
2387 {
2388     isNew = true;
2389     needsClipBufferClear = other.needsClipBufferClear;
2390     clipTestEnabled = other.clipTestEnabled;
2391     currentClip = other.currentClip;
2392     canRestoreClip = other.canRestoreClip;
2393     rectangleClip = other.rectangleClip;
2394 }
2395
2396 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2397 {
2398     isNew = true;
2399     needsClipBufferClear = true;
2400     clipTestEnabled = false;
2401     canRestoreClip = true;
2402 }
2403
2404 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2405 {
2406 }
2407
2408 void QOpenGL2PaintEngineExPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
2409 {
2410     Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
2411
2412     if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
2413         funcs.glDisableVertexAttribArray(arrayIndex);
2414
2415     if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
2416         funcs.glEnableVertexAttribArray(arrayIndex);
2417
2418     vertexAttributeArraysEnabledState[arrayIndex] = enabled;
2419 }
2420
2421 void QOpenGL2PaintEngineExPrivate::syncGlState()
2422 {
2423     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
2424         if (vertexAttributeArraysEnabledState[i])
2425             funcs.glEnableVertexAttribArray(i);
2426         else
2427             funcs.glDisableVertexAttribArray(i);
2428     }
2429 }
2430
2431
2432 QT_END_NAMESPACE