Don't issue GL calls when the geometry is empty
[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     if (numGlyphs == 0)
1696         return;
1697
1698     if (elementIndices.size() < numGlyphs*6) {
1699         Q_ASSERT(elementIndices.size() % 6 == 0);
1700         int j = elementIndices.size() / 6 * 4;
1701         while (j < numGlyphs*4) {
1702             elementIndices.append(j + 0);
1703             elementIndices.append(j + 0);
1704             elementIndices.append(j + 1);
1705             elementIndices.append(j + 2);
1706             elementIndices.append(j + 3);
1707             elementIndices.append(j + 3);
1708
1709             j += 4;
1710         }
1711
1712 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1713         if (elementIndicesVBOId == 0)
1714             glGenBuffers(1, &elementIndicesVBOId);
1715
1716         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1717         glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1718                      elementIndices.constData(), GL_STATIC_DRAW);
1719 #endif
1720     } else {
1721 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1722         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1723 #endif
1724     }
1725
1726     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1727     setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1728
1729     if (!snapToPixelGrid) {
1730         snapToPixelGrid = true;
1731         matrixDirty = true;
1732     }
1733
1734     QBrush pensBrush = q->state()->pen.brush();
1735     setBrush(pensBrush);
1736
1737     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1738
1739         // Subpixel antialiasing without gamma correction
1740
1741         QPainter::CompositionMode compMode = q->state()->composition_mode;
1742         Q_ASSERT(compMode == QPainter::CompositionMode_Source
1743             || compMode == QPainter::CompositionMode_SourceOver);
1744
1745         shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1746
1747         if (pensBrush.style() == Qt::SolidPattern) {
1748             // Solid patterns can get away with only one pass.
1749             QColor c = pensBrush.color();
1750             qreal oldOpacity = q->state()->opacity;
1751             if (compMode == QPainter::CompositionMode_Source) {
1752                 c = qt_premultiplyColor(c, q->state()->opacity);
1753                 q->state()->opacity = 1;
1754                 opacityUniformDirty = true;
1755             }
1756
1757             compositionModeDirty = false; // I can handle this myself, thank you very much
1758             prepareForDraw(false); // Text always causes src pixels to be transparent
1759
1760             // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1761             if (compMode == QPainter::CompositionMode_Source) {
1762                 q->state()->opacity = oldOpacity;
1763                 opacityUniformDirty = true;
1764             }
1765
1766             glEnable(GL_BLEND);
1767             glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1768             glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1769         } else {
1770             // Other brush styles need two passes.
1771
1772             qreal oldOpacity = q->state()->opacity;
1773             if (compMode == QPainter::CompositionMode_Source) {
1774                 q->state()->opacity = 1;
1775                 opacityUniformDirty = true;
1776                 pensBrush = Qt::white;
1777                 setBrush(pensBrush);
1778             }
1779
1780             compositionModeDirty = false; // I can handle this myself, thank you very much
1781             prepareForDraw(false); // Text always causes src pixels to be transparent
1782             glEnable(GL_BLEND);
1783             glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1784
1785             glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1786             glBindTexture(GL_TEXTURE_2D, cache->texture());
1787             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1788
1789 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1790             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1791 #else
1792             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1793 #endif
1794
1795             shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1796
1797             if (compMode == QPainter::CompositionMode_Source) {
1798                 q->state()->opacity = oldOpacity;
1799                 opacityUniformDirty = true;
1800                 pensBrush = q->state()->pen.brush();
1801                 setBrush(pensBrush);
1802             }
1803
1804             compositionModeDirty = false;
1805             prepareForDraw(false); // Text always causes src pixels to be transparent
1806             glEnable(GL_BLEND);
1807             glBlendFunc(GL_ONE, GL_ONE);
1808         }
1809         compositionModeDirty = true;
1810     } else {
1811         // Greyscale/mono glyphs
1812
1813         shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1814         prepareForDraw(false); // Text always causes src pixels to be transparent
1815     }
1816
1817     QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1818     if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1819
1820         glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1821         if (lastMaskTextureUsed != cache->texture()) {
1822             glBindTexture(GL_TEXTURE_2D, cache->texture());
1823             lastMaskTextureUsed = cache->texture();
1824         }
1825
1826         if (cache->filterMode() != filterMode) {
1827             if (filterMode == QGLTextureGlyphCache::Linear) {
1828                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1829                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1830             } else {
1831                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1832                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1833             }
1834             cache->setFilterMode(filterMode);
1835         }
1836     }
1837
1838     bool srgbFrameBufferEnabled = false;
1839     if (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer) {
1840 #if defined(Q_WS_MAC)
1841         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1842 #elif defined(Q_WS_WIN)
1843         if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1844 #else
1845         if (false)
1846 #endif
1847         {
1848             glEnable(FRAMEBUFFER_SRGB_EXT);
1849             srgbFrameBufferEnabled = true;
1850         }
1851     }
1852
1853 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1854     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1855     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1856 #else
1857     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1858 #endif
1859
1860     if (srgbFrameBufferEnabled)
1861         glDisable(FRAMEBUFFER_SRGB_EXT);
1862
1863 }
1864
1865 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1866                                             QPainter::PixmapFragmentHints hints)
1867 {
1868     Q_D(QGL2PaintEngineEx);
1869     // Use fallback for extended composition modes.
1870     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1871         QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1872         return;
1873     }
1874
1875     ensureActive();
1876     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1877     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1878         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1879         d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1880     } else {
1881         d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1882     }
1883 }
1884
1885
1886 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1887                                                    int fragmentCount, const QPixmap &pixmap,
1888                                                    QPainter::PixmapFragmentHints hints)
1889 {
1890     GLfloat dx = 1.0f / pixmap.size().width();
1891     GLfloat dy = 1.0f / pixmap.size().height();
1892
1893     vertexCoordinateArray.clear();
1894     textureCoordinateArray.clear();
1895     opacityArray.reset();
1896
1897     if (snapToPixelGrid) {
1898         snapToPixelGrid = false;
1899         matrixDirty = true;
1900     }
1901
1902     bool allOpaque = true;
1903
1904     for (int i = 0; i < fragmentCount; ++i) {
1905         qreal s = 0;
1906         qreal c = 1;
1907         if (fragments[i].rotation != 0) {
1908             s = qFastSin(fragments[i].rotation * Q_PI / 180);
1909             c = qFastCos(fragments[i].rotation * Q_PI / 180);
1910         }
1911
1912         qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1913         qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1914         QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1915         QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1916
1917         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1918         vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1919         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1920         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1921         vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1922         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1923
1924         QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1925                     (fragments[i].sourceLeft + fragments[i].width) * dx,
1926                     (fragments[i].sourceTop + fragments[i].height) * dy);
1927
1928         textureCoordinateArray.addVertex(src.right, src.bottom);
1929         textureCoordinateArray.addVertex(src.right, src.top);
1930         textureCoordinateArray.addVertex(src.left, src.top);
1931         textureCoordinateArray.addVertex(src.left, src.top);
1932         textureCoordinateArray.addVertex(src.left, src.bottom);
1933         textureCoordinateArray.addVertex(src.right, src.bottom);
1934
1935         qreal opacity = fragments[i].opacity * q->state()->opacity;
1936         opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1937         allOpaque &= (opacity >= 0.99f);
1938     }
1939
1940     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1941     QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1942                                                      QGLContext::InternalBindOption
1943                                                      | QGLContext::CanFlipNativePixmapBindOption);
1944
1945     if (texture->options & QGLContext::InvertedYBindOption) {
1946         // Flip texture y-coordinate.
1947         QGLPoint *data = textureCoordinateArray.data();
1948         for (int i = 0; i < 6 * fragmentCount; ++i)
1949             data[i].y = 1 - data[i].y;
1950     }
1951
1952     transferMode(ImageArrayDrawingMode);
1953
1954     bool isBitmap = pixmap.isQBitmap();
1955     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1956
1957     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1958                            q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1959
1960     // Setup for texture drawing
1961     currentBrush = noBrush;
1962     shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1963                                             : QGLEngineShaderManager::ImageSrc);
1964     if (prepareForDraw(isOpaque))
1965         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1966
1967     if (isBitmap) {
1968         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1969         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1970     }
1971
1972     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1973 }
1974
1975 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1976 {
1977     Q_D(QGL2PaintEngineEx);
1978
1979 //     qDebug("QGL2PaintEngineEx::begin()");
1980     if (pdev->devType() == QInternal::OpenGL)
1981         d->device = static_cast<QGLPaintDevice*>(pdev);
1982     else
1983         d->device = QGLPaintDevice::getDevice(pdev);
1984
1985     if (!d->device)
1986         return false;
1987
1988     d->ctx = d->device->context();
1989     d->ctx->d_ptr->active_engine = this;
1990
1991     const QSize sz = d->device->size();
1992     d->width = sz.width();
1993     d->height = sz.height();
1994     d->mode = BrushDrawingMode;
1995     d->brushTextureDirty = true;
1996     d->brushUniformsDirty = true;
1997     d->matrixUniformDirty = true;
1998     d->matrixDirty = true;
1999     d->compositionModeDirty = true;
2000     d->opacityUniformDirty = true;
2001     d->needsSync = true;
2002     d->useSystemClip = !systemClip().isEmpty();
2003     d->currentBrush = QBrush();
2004
2005     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
2006     d->stencilClean = true;
2007
2008     // Calling begin paint should make the correct context current. So, any
2009     // code which calls into GL or otherwise needs a current context *must*
2010     // go after beginPaint:
2011     d->device->beginPaint();
2012
2013 #if !defined(QT_OPENGL_ES_2)
2014     bool success = qt_resolve_version_2_0_functions(d->ctx)
2015                    && qt_resolve_buffer_extensions(d->ctx);
2016     Q_ASSERT(success);
2017     Q_UNUSED(success);
2018 #endif
2019
2020     d->shaderManager = new QGLEngineShaderManager(d->ctx);
2021
2022     glDisable(GL_STENCIL_TEST);
2023     glDisable(GL_DEPTH_TEST);
2024     glDisable(GL_SCISSOR_TEST);
2025
2026 #if !defined(QT_OPENGL_ES_2)
2027     glDisable(GL_MULTISAMPLE);
2028 #endif
2029
2030     d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2031
2032 #if !defined(QT_OPENGL_ES_2)
2033 #if defined(Q_WS_WIN)
2034     if (qt_cleartype_enabled
2035         && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2036 #endif
2037 #if defined(Q_WS_MAC)
2038     if (qt_applefontsmoothing_enabled)
2039 #endif
2040         d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2041 #endif
2042
2043 #if defined(QT_OPENGL_ES_2)
2044     // OpenGL ES can't switch MSAA off, so if the gl paint device is
2045     // multisampled, it's always multisampled.
2046     d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2047 #else
2048     d->multisamplingAlwaysEnabled = false;
2049 #endif
2050
2051     return true;
2052 }
2053
2054 bool QGL2PaintEngineEx::end()
2055 {
2056     Q_D(QGL2PaintEngineEx);
2057     QGLContext *ctx = d->ctx;
2058
2059     glUseProgram(0);
2060     d->transferMode(BrushDrawingMode);
2061     d->device->endPaint();
2062
2063 #if defined(Q_WS_X11)
2064     // On some (probably all) drivers, deleting an X pixmap which has been bound to a texture
2065     // before calling glFinish/swapBuffers renders garbage. Presumably this is because X deletes
2066     // the pixmap behind the driver's back before it's had a chance to use it. To fix this, we
2067     // reference all QPixmaps which have been bound to stop them being deleted and only deref
2068     // them here, after swapBuffers, where they can be safely deleted.
2069     ctx->d_func()->boundPixmaps.clear();
2070 #endif
2071     d->ctx->d_ptr->active_engine = 0;
2072
2073     d->resetGLState();
2074
2075     delete d->shaderManager;
2076     d->shaderManager = 0;
2077     d->currentBrush = QBrush();
2078
2079 #ifdef QT_OPENGL_CACHE_AS_VBOS
2080     if (!d->unusedVBOSToClean.isEmpty()) {
2081         glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2082         d->unusedVBOSToClean.clear();
2083     }
2084     if (!d->unusedIBOSToClean.isEmpty()) {
2085         glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2086         d->unusedIBOSToClean.clear();
2087     }
2088 #endif
2089
2090     return false;
2091 }
2092
2093 void QGL2PaintEngineEx::ensureActive()
2094 {
2095     Q_D(QGL2PaintEngineEx);
2096     QGLContext *ctx = d->ctx;
2097
2098     if (isActive() && ctx->d_ptr->active_engine != this) {
2099         ctx->d_ptr->active_engine = this;
2100         d->needsSync = true;
2101     }
2102
2103     d->device->ensureActiveTarget();
2104
2105     if (d->needsSync) {
2106         d->transferMode(BrushDrawingMode);
2107         glViewport(0, 0, d->width, d->height);
2108         d->needsSync = false;
2109         d->lastMaskTextureUsed = 0;
2110         d->shaderManager->setDirty();
2111         d->ctx->d_func()->syncGlState();
2112         for (int i = 0; i < 3; ++i)
2113             d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2114         setState(state());
2115     }
2116 }
2117
2118 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2119 {
2120     Q_Q(QGL2PaintEngineEx);
2121     if (q->state()->clipTestEnabled) {
2122         glEnable(GL_STENCIL_TEST);
2123         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2124     } else {
2125         glDisable(GL_STENCIL_TEST);
2126         glStencilFunc(GL_ALWAYS, 0, 0xff);
2127     }
2128
2129 #ifdef QT_GL_NO_SCISSOR_TEST
2130     currentScissorBounds = QRect(0, 0, width, height);
2131 #else
2132     QRect bounds = q->state()->rectangleClip;
2133     if (!q->state()->clipEnabled) {
2134         if (useSystemClip)
2135             bounds = systemClip.boundingRect();
2136         else
2137             bounds = QRect(0, 0, width, height);
2138     } else {
2139         if (useSystemClip)
2140             bounds = bounds.intersected(systemClip.boundingRect());
2141         else
2142             bounds = bounds.intersected(QRect(0, 0, width, height));
2143     }
2144
2145     currentScissorBounds = bounds;
2146
2147     if (bounds == QRect(0, 0, width, height)) {
2148         glDisable(GL_SCISSOR_TEST);
2149     } else {
2150         glEnable(GL_SCISSOR_TEST);
2151         setScissor(bounds);
2152     }
2153 #endif
2154 }
2155
2156 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2157 {
2158     const int left = rect.left();
2159     const int width = rect.width();
2160     int bottom = height - (rect.top() + rect.height());
2161     if (device->isFlipped()) {
2162         bottom = rect.top();
2163     }
2164     const int height = rect.height();
2165
2166     glScissor(left, bottom, width, height);
2167 }
2168
2169 void QGL2PaintEngineEx::clipEnabledChanged()
2170 {
2171     Q_D(QGL2PaintEngineEx);
2172
2173     state()->clipChanged = true;
2174
2175     if (painter()->hasClipping())
2176         d->regenerateClip();
2177     else
2178         d->systemStateChanged();
2179 }
2180
2181 void QGL2PaintEngineExPrivate::clearClip(uint value)
2182 {
2183     dirtyStencilRegion -= currentScissorBounds;
2184
2185     glStencilMask(0xff);
2186     glClearStencil(value);
2187     glClear(GL_STENCIL_BUFFER_BIT);
2188     glStencilMask(0x0);
2189
2190     q->state()->needsClipBufferClear = false;
2191 }
2192
2193 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2194 {
2195     transferMode(BrushDrawingMode);
2196
2197     if (snapToPixelGrid) {
2198         snapToPixelGrid = false;
2199         matrixDirty = true;
2200     }
2201
2202     if (matrixDirty)
2203         updateMatrix();
2204
2205     stencilClean = false;
2206
2207     const bool singlePass = !path.hasWindingFill()
2208         && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2209             || q->state()->needsClipBufferClear);
2210     const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2211
2212     if (q->state()->needsClipBufferClear)
2213         clearClip(1);
2214
2215     if (path.isEmpty()) {
2216         glEnable(GL_STENCIL_TEST);
2217         glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2218         return;
2219     }
2220
2221     if (q->state()->clipTestEnabled)
2222         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2223     else
2224         glStencilFunc(GL_ALWAYS, 0, 0xff);
2225
2226     vertexCoordinateArray.clear();
2227     vertexCoordinateArray.addPath(path, inverseScale, false);
2228
2229     if (!singlePass)
2230         fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2231
2232     glColorMask(false, false, false, false);
2233     glEnable(GL_STENCIL_TEST);
2234     useSimpleShader();
2235
2236     if (singlePass) {
2237         // Under these conditions we can set the new stencil value in a single
2238         // pass, by using the current value and the "new value" as the toggles
2239
2240         glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2241         glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2242         glStencilMask(value ^ referenceClipValue);
2243
2244         drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2245     } else {
2246         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2247         glStencilMask(0xff);
2248
2249         if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2250             // Pass when any clip bit is set, set high bit
2251             glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2252             composite(vertexCoordinateArray.boundingRect());
2253         }
2254
2255         // Pass when high bit is set, replace stencil value with new clip value
2256         glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2257
2258         composite(vertexCoordinateArray.boundingRect());
2259     }
2260
2261     glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2262     glStencilMask(0);
2263
2264     glColorMask(true, true, true, true);
2265 }
2266
2267 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2268 {
2269 //     qDebug("QGL2PaintEngineEx::clip()");
2270     Q_D(QGL2PaintEngineEx);
2271
2272     state()->clipChanged = true;
2273
2274     ensureActive();
2275
2276     if (op == Qt::ReplaceClip) {
2277         op = Qt::IntersectClip;
2278         if (d->hasClipOperations()) {
2279             d->systemStateChanged();
2280             state()->canRestoreClip = false;
2281         }
2282     }
2283
2284 #ifndef QT_GL_NO_SCISSOR_TEST
2285     if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2286         const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2287         QRectF rect(points[0], points[2]);
2288
2289         if (state()->matrix.type() <= QTransform::TxScale
2290             || (state()->matrix.type() == QTransform::TxRotate
2291                 && qFuzzyIsNull(state()->matrix.m11())
2292                 && qFuzzyIsNull(state()->matrix.m22())))
2293         {
2294             state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2295             d->updateClipScissorTest();
2296             return;
2297         }
2298     }
2299 #endif
2300
2301     const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2302
2303     switch (op) {
2304     case Qt::NoClip:
2305         if (d->useSystemClip) {
2306             state()->clipTestEnabled = true;
2307             state()->currentClip = 1;
2308         } else {
2309             state()->clipTestEnabled = false;
2310         }
2311         state()->rectangleClip = QRect(0, 0, d->width, d->height);
2312         state()->canRestoreClip = false;
2313         d->updateClipScissorTest();
2314         break;
2315     case Qt::IntersectClip:
2316         state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2317         d->updateClipScissorTest();
2318         d->resetClipIfNeeded();
2319         ++d->maxClip;
2320         d->writeClip(path, d->maxClip);
2321         state()->currentClip = d->maxClip;
2322         state()->clipTestEnabled = true;
2323         break;
2324     default:
2325         break;
2326     }
2327 }
2328
2329 void QGL2PaintEngineExPrivate::regenerateClip()
2330 {
2331     systemStateChanged();
2332     replayClipOperations();
2333 }
2334
2335 void QGL2PaintEngineExPrivate::systemStateChanged()
2336 {
2337     Q_Q(QGL2PaintEngineEx);
2338
2339     q->state()->clipChanged = true;
2340
2341     if (systemClip.isEmpty()) {
2342         useSystemClip = false;
2343     } else {
2344         if (q->paintDevice()->devType() == QInternal::Widget && currentClipWidget) {
2345             QWidgetPrivate *widgetPrivate = qt_widget_private(currentClipWidget->window());
2346             useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2347         } else {
2348             useSystemClip = true;
2349         }
2350     }
2351
2352     q->state()->clipTestEnabled = false;
2353     q->state()->needsClipBufferClear = true;
2354
2355     q->state()->currentClip = 1;
2356     maxClip = 1;
2357
2358     q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2359     updateClipScissorTest();
2360
2361     if (systemClip.rectCount() == 1) {
2362         if (systemClip.boundingRect() == QRect(0, 0, width, height))
2363             useSystemClip = false;
2364 #ifndef QT_GL_NO_SCISSOR_TEST
2365         // scissoring takes care of the system clip
2366         return;
2367 #endif
2368     }
2369
2370     if (useSystemClip) {
2371         clearClip(0);
2372
2373         QPainterPath path;
2374         path.addRegion(systemClip);
2375
2376         q->state()->currentClip = 0;
2377         writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2378         q->state()->currentClip = 1;
2379         q->state()->clipTestEnabled = true;
2380     }
2381 }
2382
2383 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2384 {
2385     //     qDebug("QGL2PaintEngineEx::setState()");
2386
2387     Q_D(QGL2PaintEngineEx);
2388
2389     QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2390     QOpenGL2PaintEngineState *old_state = state();
2391
2392     QPaintEngineEx::setState(s);
2393
2394     if (s->isNew) {
2395         // Newly created state object.  The call to setState()
2396         // will either be followed by a call to begin(), or we are
2397         // setting the state as part of a save().
2398         s->isNew = false;
2399         return;
2400     }
2401
2402     // Setting the state as part of a restore().
2403
2404     if (old_state == s || old_state->renderHintsChanged)
2405         renderHintsChanged();
2406
2407     if (old_state == s || old_state->matrixChanged)
2408         d->matrixDirty = true;
2409
2410     if (old_state == s || old_state->compositionModeChanged)
2411         d->compositionModeDirty = true;
2412
2413     if (old_state == s || old_state->opacityChanged)
2414         d->opacityUniformDirty = true;
2415
2416     if (old_state == s || old_state->clipChanged) {
2417         if (old_state && old_state != s && old_state->canRestoreClip) {
2418             d->updateClipScissorTest();
2419             glDepthFunc(GL_LEQUAL);
2420         } else {
2421             d->regenerateClip();
2422         }
2423     }
2424 }
2425
2426 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2427 {
2428     if (orig)
2429         const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2430
2431     QOpenGL2PaintEngineState *s;
2432     if (!orig)
2433         s = new QOpenGL2PaintEngineState();
2434     else
2435         s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2436
2437     s->matrixChanged = false;
2438     s->compositionModeChanged = false;
2439     s->opacityChanged = false;
2440     s->renderHintsChanged = false;
2441     s->clipChanged = false;
2442
2443     return s;
2444 }
2445
2446 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2447     : QPainterState(other)
2448 {
2449     isNew = true;
2450     needsClipBufferClear = other.needsClipBufferClear;
2451     clipTestEnabled = other.clipTestEnabled;
2452     currentClip = other.currentClip;
2453     canRestoreClip = other.canRestoreClip;
2454     rectangleClip = other.rectangleClip;
2455 }
2456
2457 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2458 {
2459     isNew = true;
2460     needsClipBufferClear = true;
2461     clipTestEnabled = false;
2462     canRestoreClip = true;
2463 }
2464
2465 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2466 {
2467 }
2468
2469 QT_END_NAMESPACE