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