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