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