Update spec to build Qt 5.0
[profile/ivi/qtbase.git] / src / opengl / gl2paintengineex / qpaintengineex_opengl2.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtOpenGL module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*
43     When the active program changes, we need to update it's uniforms.
44     We could track state for each program and only update stale uniforms
45         - Could lead to lots of overhead if there's a lot of programs
46     We could update all the uniforms when the program changes
47         - Could end up updating lots of uniforms which don't need updating
48
49     Updating uniforms should be cheap, so the overhead of updating up-to-date
50     uniforms should be minimal. It's also less complex.
51
52     Things which _may_ cause a different program to be used:
53         - Change in brush/pen style
54         - Change in painter opacity
55         - Change in composition mode
56
57     Whenever we set a mode on the shader manager - it needs to tell us if it had
58     to switch to a different program.
59
60     The shader manager should only switch when we tell it to. E.g. if we set a new
61     brush style and then switch to transparent painter, we only want it to compile
62     and use the correct program when we really need it.
63 */
64
65 // #define QT_OPENGL_CACHE_AS_VBOS
66
67 #include "qglgradientcache_p.h"
68 #include "qpaintengineex_opengl2_p.h"
69
70 #include <string.h> //for memcpy
71 #include <qmath.h>
72
73 #include <private/qgl_p.h>
74 #include <private/qmath_p.h>
75 #include <private/qpaintengineex_p.h>
76 #include <QPaintEngine>
77 #include <private/qpainter_p.h>
78 #include <private/qfontengine_p.h>
79 #include <private/qdatabuffer_p.h>
80 #include <private/qstatictext_p.h>
81 #include <QtGui/private/qtriangulator_p.h>
82
83 #include "qglengineshadermanager_p.h"
84 #include "qgl2pexvertexarray_p.h"
85 #include "qtextureglyphcache_gl_p.h"
86
87 #include <QDebug>
88
89 // ####TODO Properly #ifdef this class to use #define symbols actually defined
90 // by OpenGL/ES includes
91 #ifndef GL_FRAMEBUFFER_SRGB
92 #define GL_FRAMEBUFFER_SRGB 0x8DB9
93 #endif
94
95 QT_BEGIN_NAMESPACE
96
97
98
99 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
100
101 ////////////////////////////////// Private Methods //////////////////////////////////////////
102
103 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
104 {
105     delete shaderManager;
106
107     while (pathCaches.size()) {
108         QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
109         e->cleanup(e->engine, e->data);
110         e->data = 0;
111         e->engine = 0;
112     }
113
114     if (elementIndicesVBOId != 0) {
115         glDeleteBuffers(1, &elementIndicesVBOId);
116         elementIndicesVBOId = 0;
117     }
118 }
119
120 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
121 {
122 //    glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
123     if (id != GLuint(-1) && id == lastTextureUsed)
124         return;
125
126     lastTextureUsed = id;
127
128     if (smoothPixmapTransform) {
129         glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
130         glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
131     } else {
132         glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
133         glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
134     }
135     glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
136     glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
137 }
138
139
140 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
141 {
142     qreal alpha = c.alphaF() * opacity;
143     c.setAlphaF(alpha);
144     c.setRedF(c.redF() * alpha);
145     c.setGreenF(c.greenF() * alpha);
146     c.setBlueF(c.blueF() * alpha);
147     return c;
148 }
149
150
151 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
152 {
153     if (qbrush_fast_equals(currentBrush, brush))
154         return;
155
156     const Qt::BrushStyle newStyle = qbrush_style(brush);
157     Q_ASSERT(newStyle != Qt::NoBrush);
158
159     currentBrush = brush;
160     if (!currentBrushPixmap.isNull())
161         currentBrushPixmap = QPixmap();
162     brushUniformsDirty = true; // All brushes have at least one uniform
163
164     if (newStyle > Qt::SolidPattern)
165         brushTextureDirty = true;
166
167     if (currentBrush.style() == Qt::TexturePattern
168         && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
169     {
170         shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
171     } else {
172         shaderManager->setSrcPixelType(newStyle);
173     }
174     shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
175 }
176
177
178 void QGL2PaintEngineExPrivate::useSimpleShader()
179 {
180     shaderManager->useSimpleProgram();
181
182     if (matrixDirty)
183         updateMatrix();
184 }
185
186 // ####TODO Properly #ifdef this class to use #define symbols actually defined
187 // by OpenGL/ES includes
188 #ifndef GL_MIRRORED_REPEAT_IBM
189 #define GL_MIRRORED_REPEAT_IBM 0x8370
190 #endif
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     QVertexIndexVector::Type indexType;
676 };
677
678 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
679 {
680     QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
681 #ifdef QT_OPENGL_CACHE_AS_VBOS
682     Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
683     static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
684     if (c->ibo)
685         d->unusedIBOSToClean << c->ibo;
686 #else
687     Q_UNUSED(engine);
688     free(c->vertices);
689     free(c->indices);
690 #endif
691     delete c;
692 }
693
694 // Assumes everything is configured for the brush you want to use
695 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
696 {
697     transferMode(BrushDrawingMode);
698
699     if (snapToPixelGrid) {
700         snapToPixelGrid = false;
701         matrixDirty = true;
702     }
703
704     // Might need to call updateMatrix to re-calculate inverseScale
705     if (matrixDirty)
706         updateMatrix();
707
708     const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
709
710     // Check to see if there's any hints
711     if (path.shape() == QVectorPath::RectangleHint) {
712         QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
713         prepareForDraw(currentBrush.isOpaque());
714         composite(rect);
715     } else if (path.isConvex()) {
716
717         if (path.isCacheable()) {
718             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
719             QGL2PEVectorPathCache *cache;
720
721             bool updateCache = false;
722
723             if (data) {
724                 cache = (QGL2PEVectorPathCache *) data->data;
725                 // Check if scale factor is exceeded for curved paths and generate curves if so...
726                 if (path.isCurved()) {
727                     qreal scaleFactor = cache->iscale / inverseScale;
728                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
729 #ifdef QT_OPENGL_CACHE_AS_VBOS
730                         glDeleteBuffers(1, &cache->vbo);
731                         cache->vbo = 0;
732                         Q_ASSERT(cache->ibo == 0);
733 #else
734                         free(cache->vertices);
735                         Q_ASSERT(cache->indices == 0);
736 #endif
737                         updateCache = true;
738                     }
739                 }
740             } else {
741                 cache = new QGL2PEVectorPathCache;
742                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
743                 updateCache = true;
744             }
745
746             // Flatten the path at the current scale factor and fill it into the cache struct.
747             if (updateCache) {
748                 vertexCoordinateArray.clear();
749                 vertexCoordinateArray.addPath(path, inverseScale, false);
750                 int vertexCount = vertexCoordinateArray.vertexCount();
751                 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
752                 cache->vertexCount = vertexCount;
753                 cache->indexCount = 0;
754                 cache->primitiveType = GL_TRIANGLE_FAN;
755                 cache->iscale = inverseScale;
756 #ifdef QT_OPENGL_CACHE_AS_VBOS
757                 glGenBuffers(1, &cache->vbo);
758                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
759                 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
760                 cache->ibo = 0;
761 #else
762                 cache->vertices = (float *) malloc(floatSizeInBytes);
763                 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
764                 cache->indices = 0;
765 #endif
766             }
767
768             prepareForDraw(currentBrush.isOpaque());
769 #ifdef QT_OPENGL_CACHE_AS_VBOS
770             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
771             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
772 #else
773             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
774 #endif
775             glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
776
777         } else {
778       //        printf(" - Marking path as cachable...\n");
779             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
780             path.makeCacheable();
781             vertexCoordinateArray.clear();
782             vertexCoordinateArray.addPath(path, inverseScale, false);
783             prepareForDraw(currentBrush.isOpaque());
784             drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
785         }
786
787     } else {
788         bool useCache = path.isCacheable();
789         if (useCache) {
790             QRectF bbox = path.controlPointRect();
791             // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
792             useCache &= (bbox.left() > -0x8000 * inverseScale)
793                      && (bbox.right() < 0x8000 * inverseScale)
794                      && (bbox.top() > -0x8000 * inverseScale)
795                      && (bbox.bottom() < 0x8000 * inverseScale);
796         }
797
798         if (useCache) {
799             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
800             QGL2PEVectorPathCache *cache;
801
802             bool updateCache = false;
803
804             if (data) {
805                 cache = (QGL2PEVectorPathCache *) data->data;
806                 // Check if scale factor is exceeded for curved paths and generate curves if so...
807                 if (path.isCurved()) {
808                     qreal scaleFactor = cache->iscale / inverseScale;
809                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
810 #ifdef QT_OPENGL_CACHE_AS_VBOS
811                         glDeleteBuffers(1, &cache->vbo);
812                         glDeleteBuffers(1, &cache->ibo);
813 #else
814                         free(cache->vertices);
815                         free(cache->indices);
816 #endif
817                         updateCache = true;
818                     }
819                 }
820             } else {
821                 cache = new QGL2PEVectorPathCache;
822                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
823                 updateCache = true;
824             }
825
826             // Flatten the path at the current scale factor and fill it into the cache struct.
827             if (updateCache) {
828                 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
829                 cache->vertexCount = polys.vertices.size() / 2;
830                 cache->indexCount = polys.indices.size();
831                 cache->primitiveType = GL_TRIANGLES;
832                 cache->iscale = inverseScale;
833                 cache->indexType = polys.indices.type();
834 #ifdef QT_OPENGL_CACHE_AS_VBOS
835                 glGenBuffers(1, &cache->vbo);
836                 glGenBuffers(1, &cache->ibo);
837                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
838                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
839
840                 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
841                     glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
842                 else
843                     glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
844
845                 QVarLengthArray<float> vertices(polys.vertices.size());
846                 for (int i = 0; i < polys.vertices.size(); ++i)
847                     vertices[i] = float(inverseScale * polys.vertices.at(i));
848                 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
849 #else
850                 cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
851                 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
852                     cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
853                     memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
854                 } else {
855                     cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
856                     memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
857                 }
858                 for (int i = 0; i < polys.vertices.size(); ++i)
859                     cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
860 #endif
861             }
862
863             prepareForDraw(currentBrush.isOpaque());
864 #ifdef QT_OPENGL_CACHE_AS_VBOS
865             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
866             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
867             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
868             if (cache->indexType == QVertexIndexVector::UnsignedInt)
869                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
870             else
871                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
872             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
873             glBindBuffer(GL_ARRAY_BUFFER, 0);
874 #else
875             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
876             if (cache->indexType == QVertexIndexVector::UnsignedInt)
877                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
878             else
879                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
880 #endif
881
882         } else {
883       //        printf(" - Marking path as cachable...\n");
884             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
885             path.makeCacheable();
886
887             if (!device->format().stencil()) {
888                 // If there is no stencil buffer, triangulate the path instead.
889
890                 QRectF bbox = path.controlPointRect();
891                 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
892                 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
893                                   && (bbox.right() < 0x8000 * inverseScale)
894                                   && (bbox.top() > -0x8000 * inverseScale)
895                                   && (bbox.bottom() < 0x8000 * inverseScale);
896                 if (withinLimits) {
897                     QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
898
899                     QVarLengthArray<float> vertices(polys.vertices.size());
900                     for (int i = 0; i < polys.vertices.size(); ++i)
901                         vertices[i] = float(inverseScale * polys.vertices.at(i));
902
903                     prepareForDraw(currentBrush.isOpaque());
904                     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
905                     if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
906                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
907                     else
908                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
909                 } else {
910                     // We can't handle big, concave painter paths with OpenGL without stencil buffer.
911                     qWarning("Painter path exceeds +/-32767 pixels.");
912                 }
913                 return;
914             }
915
916             // The path is too complicated & needs the stencil technique
917             vertexCoordinateArray.clear();
918             vertexCoordinateArray.addPath(path, inverseScale, false);
919
920             fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
921
922             glStencilMask(0xff);
923             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
924
925             if (q->state()->clipTestEnabled) {
926                 // Pass when high bit is set, replace stencil value with current clip
927                 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
928             } else if (path.hasWindingFill()) {
929                 // Pass when any bit is set, replace stencil value with 0
930                 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
931             } else {
932                 // Pass when high bit is set, replace stencil value with 0
933                 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
934             }
935             prepareForDraw(currentBrush.isOpaque());
936
937             // Stencil the brush onto the dest buffer
938             composite(vertexCoordinateArray.boundingRect());
939             glStencilMask(0);
940             updateClipScissorTest();
941         }
942     }
943 }
944
945
946 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
947                                                           int count,
948                                                           int *stops,
949                                                           int stopCount,
950                                                           const QGLRect &bounds,
951                                                           StencilFillMode mode)
952 {
953     Q_ASSERT(count || stops);
954
955 //     qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
956     glStencilMask(0xff); // Enable stencil writes
957
958     if (dirtyStencilRegion.intersects(currentScissorBounds)) {
959         QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
960         glClearStencil(0); // Clear to zero
961         for (int i = 0; i < clearRegion.size(); ++i) {
962 #ifndef QT_GL_NO_SCISSOR_TEST
963             setScissor(clearRegion.at(i));
964 #endif
965             glClear(GL_STENCIL_BUFFER_BIT);
966         }
967
968         dirtyStencilRegion -= currentScissorBounds;
969
970 #ifndef QT_GL_NO_SCISSOR_TEST
971         updateClipScissorTest();
972 #endif
973     }
974
975     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
976     useSimpleShader();
977     glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
978
979     if (mode == WindingFillMode) {
980         Q_ASSERT(stops && !count);
981         if (q->state()->clipTestEnabled) {
982             // Flatten clip values higher than current clip, and set high bit to match current clip
983             glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
984             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
985             composite(bounds);
986
987             glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
988         } else if (!stencilClean) {
989             // Clear stencil buffer within bounding rect
990             glStencilFunc(GL_ALWAYS, 0, 0xff);
991             glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
992             composite(bounds);
993         }
994
995         // Inc. for front-facing triangle
996         glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
997         // Dec. for back-facing "holes"
998         glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
999         glStencilMask(~GL_STENCIL_HIGH_BIT);
1000         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1001
1002         if (q->state()->clipTestEnabled) {
1003             // Clear high bit of stencil outside of path
1004             glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1005             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1006             glStencilMask(GL_STENCIL_HIGH_BIT);
1007             composite(bounds);
1008         }
1009     } else if (mode == OddEvenFillMode) {
1010         glStencilMask(GL_STENCIL_HIGH_BIT);
1011         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1012         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1013
1014     } else { // TriStripStrokeFillMode
1015         Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1016         glStencilMask(GL_STENCIL_HIGH_BIT);
1017 #if 0
1018         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1019         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1020         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1021 #else
1022
1023         glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1024         if (q->state()->clipTestEnabled) {
1025             glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1026                           ~GL_STENCIL_HIGH_BIT);
1027         } else {
1028             glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1029         }
1030         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1031         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1032 #endif
1033     }
1034
1035     // Enable color writes & disable stencil writes
1036     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1037 }
1038
1039 /*
1040     If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1041     restore the stencil buffer to a pristine state.  The current clip region
1042     is set to 1, and the rest to 0.
1043 */
1044 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1045 {
1046     if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1047         return;
1048
1049     Q_Q(QGL2PaintEngineEx);
1050
1051     useSimpleShader();
1052     glEnable(GL_STENCIL_TEST);
1053     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1054
1055     QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1056     QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1057
1058     // Set high bit on clip region
1059     glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1060     glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1061     glStencilMask(GL_STENCIL_HIGH_BIT);
1062     composite(rect);
1063
1064     // Reset clipping to 1 and everything else to zero
1065     glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1066     glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1067     glStencilMask(0xff);
1068     composite(rect);
1069
1070     q->state()->currentClip = 1;
1071     q->state()->canRestoreClip = false;
1072
1073     maxClip = 1;
1074
1075     glStencilMask(0x0);
1076     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1077 }
1078
1079 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1080 {
1081     if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1082         updateBrushTexture();
1083
1084     if (compositionModeDirty)
1085         updateCompositionMode();
1086
1087     if (matrixDirty)
1088         updateMatrix();
1089
1090     const bool stateHasOpacity = q->state()->opacity < 0.99f;
1091     if (q->state()->composition_mode == QPainter::CompositionMode_Source
1092         || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1093             && srcPixelsAreOpaque && !stateHasOpacity))
1094     {
1095         glDisable(GL_BLEND);
1096     } else {
1097         glEnable(GL_BLEND);
1098     }
1099
1100     QGLEngineShaderManager::OpacityMode opacityMode;
1101     if (mode == ImageArrayDrawingMode) {
1102         opacityMode = QGLEngineShaderManager::AttributeOpacity;
1103     } else {
1104         opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1105                                       : QGLEngineShaderManager::NoOpacity;
1106         if (stateHasOpacity && (mode != ImageDrawingMode)) {
1107             // Using a brush
1108             bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1109                                   (currentBrush.style() <= Qt::DiagCrossPattern);
1110
1111             if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1112                 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1113         }
1114     }
1115     shaderManager->setOpacityMode(opacityMode);
1116
1117     bool changed = shaderManager->useCorrectShaderProg();
1118     // If the shader program needs changing, we change it and mark all uniforms as dirty
1119     if (changed) {
1120         // The shader program has changed so mark all uniforms as dirty:
1121         brushUniformsDirty = true;
1122         opacityUniformDirty = true;
1123         matrixUniformDirty = true;
1124     }
1125
1126     if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1127         updateBrushUniforms();
1128
1129     if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1130         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1131         opacityUniformDirty = false;
1132     }
1133
1134     if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1135         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1136                                                          pmvMatrix);
1137         matrixUniformDirty = false;
1138     }
1139
1140     return changed;
1141 }
1142
1143 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1144 {
1145     setCoords(staticVertexCoordinateArray, boundingRect);
1146     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1147     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1148 }
1149
1150 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1151 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1152                                                 GLenum primitive)
1153 {
1154     // Now setup the pointer to the vertex array:
1155     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1156
1157     int previousStop = 0;
1158     for (int i=0; i<stopCount; ++i) {
1159         int stop = stops[i];
1160 /*
1161         qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1162         for (int i=previousStop; i<stop; ++i)
1163             qDebug("   %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1164 */
1165         glDrawArrays(primitive, previousStop, stop - previousStop);
1166         previousStop = stop;
1167     }
1168 }
1169
1170 /////////////////////////////////// Public Methods //////////////////////////////////////////
1171
1172 QGL2PaintEngineEx::QGL2PaintEngineEx()
1173     : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1174 {
1175 }
1176
1177 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1178 {
1179 }
1180
1181 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1182 {
1183     Q_D(QGL2PaintEngineEx);
1184
1185     if (qbrush_style(brush) == Qt::NoBrush)
1186         return;
1187     ensureActive();
1188     d->setBrush(brush);
1189     d->fill(path);
1190 }
1191
1192 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1193
1194
1195 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1196 {
1197     Q_D(QGL2PaintEngineEx);
1198
1199     const QBrush &penBrush = qpen_brush(pen);
1200     if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1201         return;
1202
1203     QOpenGL2PaintEngineState *s = state();
1204     if (qt_pen_is_cosmetic(pen, s->renderHints) && !qt_scaleForTransform(s->transform(), 0)) {
1205         // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1206         QPaintEngineEx::stroke(path, pen);
1207         return;
1208     }
1209
1210     ensureActive();
1211     d->setBrush(penBrush);
1212     d->stroke(path, pen);
1213 }
1214
1215 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1216 {
1217     const QOpenGL2PaintEngineState *s = q->state();
1218     if (snapToPixelGrid) {
1219         snapToPixelGrid = false;
1220         matrixDirty = true;
1221     }
1222
1223     const Qt::PenStyle penStyle = qpen_style(pen);
1224     const QBrush &penBrush = qpen_brush(pen);
1225     const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1226
1227     transferMode(BrushDrawingMode);
1228
1229     // updateMatrix() is responsible for setting the inverse scale on
1230     // the strokers, so we need to call it here and not wait for
1231     // prepareForDraw() down below.
1232     updateMatrix();
1233
1234     QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1235                                                         ? q->state()->rectangleClip
1236                                                         : QRectF(0, 0, width, height));
1237
1238     if (penStyle == Qt::SolidLine) {
1239         stroker.process(path, pen, clip, s->renderHints);
1240
1241     } else { // Some sort of dash
1242         dasher.process(path, pen, clip, s->renderHints);
1243
1244         QVectorPath dashStroke(dasher.points(),
1245                                dasher.elementCount(),
1246                                dasher.elementTypes());
1247         stroker.process(dashStroke, pen, clip, s->renderHints);
1248     }
1249
1250     if (!stroker.vertexCount())
1251         return;
1252
1253     if (opaque) {
1254         prepareForDraw(opaque);
1255         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1256         glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1257
1258 //         QBrush b(Qt::green);
1259 //         d->setBrush(&b);
1260 //         d->prepareForDraw(true);
1261 //         glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1262
1263     } else {
1264         qreal width = qpen_widthf(pen) / 2;
1265         if (width == 0)
1266             width = 0.5;
1267         qreal extra = pen.joinStyle() == Qt::MiterJoin
1268                       ? qMax(pen.miterLimit() * width, width)
1269                       : width;
1270
1271         if (qt_pen_is_cosmetic(pen, s->renderHints))
1272             extra = extra * inverseScale;
1273
1274         QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1275
1276         fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1277                                       0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1278
1279         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1280
1281         // Pass when any bit is set, replace stencil value with 0
1282         glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1283         prepareForDraw(false);
1284
1285         // Stencil the brush onto the dest buffer
1286         composite(bounds);
1287
1288         glStencilMask(0);
1289
1290         updateClipScissorTest();
1291     }
1292 }
1293
1294 void QGL2PaintEngineEx::penChanged() { }
1295 void QGL2PaintEngineEx::brushChanged() { }
1296 void QGL2PaintEngineEx::brushOriginChanged() { }
1297
1298 void QGL2PaintEngineEx::opacityChanged()
1299 {
1300 //    qDebug("QGL2PaintEngineEx::opacityChanged()");
1301     Q_D(QGL2PaintEngineEx);
1302     state()->opacityChanged = true;
1303
1304     Q_ASSERT(d->shaderManager);
1305     d->brushUniformsDirty = true;
1306     d->opacityUniformDirty = true;
1307 }
1308
1309 void QGL2PaintEngineEx::compositionModeChanged()
1310 {
1311 //     qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1312     Q_D(QGL2PaintEngineEx);
1313     state()->compositionModeChanged = true;
1314     d->compositionModeDirty = true;
1315 }
1316
1317 void QGL2PaintEngineEx::renderHintsChanged()
1318 {
1319     state()->renderHintsChanged = true;
1320
1321 #if !defined(QT_OPENGL_ES_2)
1322     if ((state()->renderHints & QPainter::Antialiasing)
1323         || (state()->renderHints & QPainter::HighQualityAntialiasing))
1324         glEnable(GL_MULTISAMPLE);
1325     else
1326         glDisable(GL_MULTISAMPLE);
1327 #endif
1328
1329     Q_D(QGL2PaintEngineEx);
1330     d->lastTextureUsed = GLuint(-1);
1331     d->brushTextureDirty = true;
1332 //    qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1333 }
1334
1335 void QGL2PaintEngineEx::transformChanged()
1336 {
1337     Q_D(QGL2PaintEngineEx);
1338     d->matrixDirty = true;
1339     state()->matrixChanged = true;
1340 }
1341
1342
1343 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1344 {
1345     return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1346 }
1347
1348 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1349 {
1350     Q_D(QGL2PaintEngineEx);
1351     QGLContext *ctx = d->ctx;
1352
1353     int max_texture_size = ctx->d_func()->maxTextureSize();
1354     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1355         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1356
1357         const qreal sx = scaled.width() / qreal(pixmap.width());
1358         const qreal sy = scaled.height() / qreal(pixmap.height());
1359
1360         drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1361         return;
1362     }
1363
1364     ensureActive();
1365     d->transferMode(ImageDrawingMode);
1366
1367     QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1368 #ifdef QGL_USE_TEXTURE_POOL
1369     bindOptions |= QGLContext::TemporarilyCachedBindOption;
1370 #endif
1371
1372     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1373     QGLTexture *texture =
1374         ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1375
1376     GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1377     GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1378     QGLRect srcRect(src.left(), top, src.right(), bottom);
1379
1380     bool isBitmap = pixmap.isQBitmap();
1381     bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1382
1383     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1384                            state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1385     d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1386
1387     if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1388         // pixmap was temporarily cached as a QImage texture by pooling system
1389         // and should be destroyed immediately
1390         QGLTextureCache::instance()->remove(ctx, texture->id);
1391     }
1392 }
1393
1394 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1395                         Qt::ImageConversionFlags)
1396 {
1397     Q_D(QGL2PaintEngineEx);
1398     QGLContext *ctx = d->ctx;
1399
1400     int max_texture_size = ctx->d_func()->maxTextureSize();
1401     if (image.width() > max_texture_size || image.height() > max_texture_size) {
1402         QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1403
1404         const qreal sx = scaled.width() / qreal(image.width());
1405         const qreal sy = scaled.height() / qreal(image.height());
1406
1407         drawImage(dest, scaled, scaleRect(src, sx, sy));
1408         return;
1409     }
1410
1411     ensureActive();
1412     d->transferMode(ImageDrawingMode);
1413
1414     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1415
1416     QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1417 #ifdef QGL_USE_TEXTURE_POOL
1418     bindOptions |= QGLContext::TemporarilyCachedBindOption;
1419 #endif
1420
1421     QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1422     GLuint id = texture->id;
1423
1424     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1425                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1426     d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1427
1428     if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1429         // image was temporarily cached by texture pooling system
1430         // and should be destroyed immediately
1431         QGLTextureCache::instance()->remove(ctx, texture->id);
1432     }
1433 }
1434
1435 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1436 {
1437     Q_D(QGL2PaintEngineEx);
1438
1439     ensureActive();
1440
1441     QPainterState *s = state();
1442     float det = s->matrix.determinant();
1443
1444     // don't try to cache huge fonts or vastly transformed fonts
1445     QFontEngine *fontEngine = textItem->fontEngine();
1446     if (shouldDrawCachedGlyphs(fontEngine, s->matrix) && 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 (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1452                 || d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1453                 || (s->composition_mode != QPainter::CompositionMode_Source
1454                 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1455             {
1456                 glyphType = QFontEngineGlyphCache::Raster_A8;
1457             }
1458         }
1459
1460         d->drawCachedGlyphs(glyphType, textItem);
1461     } else {
1462         QPaintEngineEx::drawStaticTextItem(textItem);
1463     }
1464 }
1465
1466 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1467 {
1468     Q_D(QGL2PaintEngineEx);
1469     if (!d->shaderManager)
1470         return false;
1471
1472     ensureActive();
1473     d->transferMode(ImageDrawingMode);
1474
1475 #ifndef QT_OPENGL_ES_2
1476     QGLContext *ctx = d->ctx;
1477 #endif
1478     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1479     glBindTexture(GL_TEXTURE_2D, textureId);
1480
1481     QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1482
1483     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1484                            state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1485     d->drawTexture(dest, srcRect, size, false);
1486     return true;
1487 }
1488
1489 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1490 {
1491     Q_D(QGL2PaintEngineEx);
1492
1493     ensureActive();
1494     QOpenGL2PaintEngineState *s = state();
1495
1496     const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1497
1498     QTransform::TransformationType txtype = s->matrix.type();
1499
1500     float det = s->matrix.determinant();
1501     bool drawCached = txtype < QTransform::TxProject;
1502
1503     // don't try to cache huge fonts or vastly transformed fonts
1504     if (!shouldDrawCachedGlyphs(ti.fontEngine, s->matrix) || det < 0.25f || det > 4.f)
1505         drawCached = false;
1506
1507     QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1508                                             ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1509                                             : d->glyphCacheType;
1510
1511
1512     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1513         if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1514             || 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
1569 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1570
1571 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1572                                                 QStaticTextItem *staticTextItem)
1573 {
1574     Q_Q(QGL2PaintEngineEx);
1575
1576     QOpenGL2PaintEngineState *s = q->state();
1577
1578     void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1579     bool recreateVertexArrays = false;
1580
1581     QFontEngine *fe = staticTextItem->fontEngine();
1582     QGLTextureGlyphCache *cache =
1583             (QGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphType, QTransform());
1584     if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1585         cache = new QGLTextureGlyphCache(glyphType, QTransform());
1586         fe->setGlyphCache(cacheKey, cache);
1587         recreateVertexArrays = true;
1588     }
1589
1590     if (staticTextItem->userDataNeedsUpdate) {
1591         recreateVertexArrays = true;
1592     } else if (staticTextItem->userData() == 0) {
1593         recreateVertexArrays = true;
1594     } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1595         recreateVertexArrays = true;
1596     } else {
1597         QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1598         if (userData->glyphType != glyphType) {
1599             recreateVertexArrays = true;
1600         } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1601             recreateVertexArrays = true;
1602         }
1603     }
1604
1605     // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1606     // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1607     // cache so this text is performed before we test if the cache size has changed.
1608     if (recreateVertexArrays) {
1609         cache->setPaintEnginePrivate(this);
1610         if (!cache->populate(fe, staticTextItem->numGlyphs,
1611                              staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1612             // No space for glyphs in cache. We need to reset it and try again.
1613             cache->clear();
1614             cache->populate(fe, staticTextItem->numGlyphs,
1615                             staticTextItem->glyphs, staticTextItem->glyphPositions);
1616         }
1617         cache->fillInPendingGlyphs();
1618     }
1619
1620     if (cache->width() == 0 || cache->height() == 0)
1621         return;
1622
1623     transferMode(TextDrawingMode);
1624
1625     int margin = fe->glyphMargin(glyphType);
1626
1627     GLfloat dx = 1.0 / cache->width();
1628     GLfloat dy = 1.0 / cache->height();
1629
1630     // Use global arrays by default
1631     QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1632     QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1633
1634     if (staticTextItem->useBackendOptimizations) {
1635         QOpenGLStaticTextUserData *userData = 0;
1636
1637         if (staticTextItem->userData() == 0
1638             || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1639
1640             userData = new QOpenGLStaticTextUserData();
1641             staticTextItem->setUserData(userData);
1642
1643         } else {
1644             userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1645         }
1646
1647         userData->glyphType = glyphType;
1648         userData->cacheSerialNumber = cache->serialNumber();
1649
1650         // Use cache if backend optimizations is turned on
1651         vertexCoordinates = &userData->vertexCoordinateArray;
1652         textureCoordinates = &userData->textureCoordinateArray;
1653
1654         QSize size(cache->width(), cache->height());
1655         if (userData->cacheSize != size) {
1656             recreateVertexArrays = true;
1657             userData->cacheSize = size;
1658         }
1659     }
1660
1661     if (recreateVertexArrays) {
1662         vertexCoordinates->clear();
1663         textureCoordinates->clear();
1664
1665         bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1666         for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1667             QFixed subPixelPosition;
1668             if (supportsSubPixelPositions)
1669                 subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1670
1671             QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1672
1673             const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1674             if (c.isNull())
1675                 continue;
1676
1677             int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1678             int y = qRound(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1679
1680             vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1681             textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1682         }
1683
1684         staticTextItem->userDataNeedsUpdate = false;
1685     }
1686
1687     int numGlyphs = vertexCoordinates->vertexCount() / 4;
1688     if (numGlyphs == 0)
1689         return;
1690
1691     if (elementIndices.size() < numGlyphs*6) {
1692         Q_ASSERT(elementIndices.size() % 6 == 0);
1693         int j = elementIndices.size() / 6 * 4;
1694         while (j < numGlyphs*4) {
1695             elementIndices.append(j + 0);
1696             elementIndices.append(j + 0);
1697             elementIndices.append(j + 1);
1698             elementIndices.append(j + 2);
1699             elementIndices.append(j + 3);
1700             elementIndices.append(j + 3);
1701
1702             j += 4;
1703         }
1704
1705 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1706         if (elementIndicesVBOId == 0)
1707             glGenBuffers(1, &elementIndicesVBOId);
1708
1709         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1710         glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1711                      elementIndices.constData(), GL_STATIC_DRAW);
1712 #endif
1713     } else {
1714 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1715         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1716 #endif
1717     }
1718
1719     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1720     setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1721
1722     if (!snapToPixelGrid) {
1723         snapToPixelGrid = true;
1724         matrixDirty = true;
1725     }
1726
1727     QBrush pensBrush = q->state()->pen.brush();
1728     setBrush(pensBrush);
1729
1730     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1731
1732         // Subpixel antialiasing without gamma correction
1733
1734         QPainter::CompositionMode compMode = q->state()->composition_mode;
1735         Q_ASSERT(compMode == QPainter::CompositionMode_Source
1736             || compMode == QPainter::CompositionMode_SourceOver);
1737
1738         shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1739
1740         if (pensBrush.style() == Qt::SolidPattern) {
1741             // Solid patterns can get away with only one pass.
1742             QColor c = pensBrush.color();
1743             qreal oldOpacity = q->state()->opacity;
1744             if (compMode == QPainter::CompositionMode_Source) {
1745                 c = qt_premultiplyColor(c, q->state()->opacity);
1746                 q->state()->opacity = 1;
1747                 opacityUniformDirty = true;
1748             }
1749
1750             compositionModeDirty = false; // I can handle this myself, thank you very much
1751             prepareForDraw(false); // Text always causes src pixels to be transparent
1752
1753             // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1754             if (compMode == QPainter::CompositionMode_Source) {
1755                 q->state()->opacity = oldOpacity;
1756                 opacityUniformDirty = true;
1757             }
1758
1759             glEnable(GL_BLEND);
1760             glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1761             glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1762         } else {
1763             // Other brush styles need two passes.
1764
1765             qreal oldOpacity = q->state()->opacity;
1766             if (compMode == QPainter::CompositionMode_Source) {
1767                 q->state()->opacity = 1;
1768                 opacityUniformDirty = true;
1769                 pensBrush = Qt::white;
1770                 setBrush(pensBrush);
1771             }
1772
1773             compositionModeDirty = false; // I can handle this myself, thank you very much
1774             prepareForDraw(false); // Text always causes src pixels to be transparent
1775             glEnable(GL_BLEND);
1776             glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1777
1778             glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1779             glBindTexture(GL_TEXTURE_2D, cache->texture());
1780             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1781
1782 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1783             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1784 #else
1785             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1786 #endif
1787
1788             shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1789
1790             if (compMode == QPainter::CompositionMode_Source) {
1791                 q->state()->opacity = oldOpacity;
1792                 opacityUniformDirty = true;
1793                 pensBrush = q->state()->pen.brush();
1794                 setBrush(pensBrush);
1795             }
1796
1797             compositionModeDirty = false;
1798             prepareForDraw(false); // Text always causes src pixels to be transparent
1799             glEnable(GL_BLEND);
1800             glBlendFunc(GL_ONE, GL_ONE);
1801         }
1802         compositionModeDirty = true;
1803     } else {
1804         // Greyscale/mono glyphs
1805
1806         shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1807         prepareForDraw(false); // Text always causes src pixels to be transparent
1808     }
1809
1810     QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1811     if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1812
1813         glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1814         if (lastMaskTextureUsed != cache->texture()) {
1815             glBindTexture(GL_TEXTURE_2D, cache->texture());
1816             lastMaskTextureUsed = cache->texture();
1817         }
1818
1819         if (cache->filterMode() != filterMode) {
1820             if (filterMode == QGLTextureGlyphCache::Linear) {
1821                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1822                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1823             } else {
1824                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1825                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1826             }
1827             cache->setFilterMode(filterMode);
1828         }
1829     }
1830
1831     bool srgbFrameBufferEnabled = false;
1832
1833 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1834     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1835     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1836 #else
1837     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1838 #endif
1839
1840     if (srgbFrameBufferEnabled)
1841         glDisable(GL_FRAMEBUFFER_SRGB);
1842
1843 }
1844
1845 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1846                                             QPainter::PixmapFragmentHints hints)
1847 {
1848     Q_D(QGL2PaintEngineEx);
1849     // Use fallback for extended composition modes.
1850     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1851         QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1852         return;
1853     }
1854
1855     ensureActive();
1856     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1857     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1858         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1859         d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1860     } else {
1861         d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1862     }
1863 }
1864
1865
1866 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1867                                                    int fragmentCount, const QPixmap &pixmap,
1868                                                    QPainter::PixmapFragmentHints hints)
1869 {
1870     GLfloat dx = 1.0f / pixmap.size().width();
1871     GLfloat dy = 1.0f / pixmap.size().height();
1872
1873     vertexCoordinateArray.clear();
1874     textureCoordinateArray.clear();
1875     opacityArray.reset();
1876
1877     if (snapToPixelGrid) {
1878         snapToPixelGrid = false;
1879         matrixDirty = true;
1880     }
1881
1882     bool allOpaque = true;
1883
1884     for (int i = 0; i < fragmentCount; ++i) {
1885         qreal s = 0;
1886         qreal c = 1;
1887         if (fragments[i].rotation != 0) {
1888             s = qFastSin(fragments[i].rotation * Q_PI / 180);
1889             c = qFastCos(fragments[i].rotation * Q_PI / 180);
1890         }
1891
1892         qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1893         qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1894         QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1895         QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1896
1897         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1898         vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1899         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1900         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1901         vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1902         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1903
1904         QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1905                     (fragments[i].sourceLeft + fragments[i].width) * dx,
1906                     (fragments[i].sourceTop + fragments[i].height) * dy);
1907
1908         textureCoordinateArray.addVertex(src.right, src.bottom);
1909         textureCoordinateArray.addVertex(src.right, src.top);
1910         textureCoordinateArray.addVertex(src.left, src.top);
1911         textureCoordinateArray.addVertex(src.left, src.top);
1912         textureCoordinateArray.addVertex(src.left, src.bottom);
1913         textureCoordinateArray.addVertex(src.right, src.bottom);
1914
1915         qreal opacity = fragments[i].opacity * q->state()->opacity;
1916         opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1917         allOpaque &= (opacity >= 0.99f);
1918     }
1919
1920     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1921     QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1922                                                      QGLContext::InternalBindOption
1923                                                      | QGLContext::CanFlipNativePixmapBindOption);
1924
1925     if (texture->options & QGLContext::InvertedYBindOption) {
1926         // Flip texture y-coordinate.
1927         QGLPoint *data = textureCoordinateArray.data();
1928         for (int i = 0; i < 6 * fragmentCount; ++i)
1929             data[i].y = 1 - data[i].y;
1930     }
1931
1932     transferMode(ImageArrayDrawingMode);
1933
1934     bool isBitmap = pixmap.isQBitmap();
1935     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1936
1937     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1938                            q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1939
1940     // Setup for texture drawing
1941     currentBrush = noBrush;
1942     shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1943                                             : QGLEngineShaderManager::ImageSrc);
1944     if (prepareForDraw(isOpaque))
1945         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1946
1947     if (isBitmap) {
1948         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1949         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1950     }
1951
1952     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1953 }
1954
1955 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1956 {
1957     Q_D(QGL2PaintEngineEx);
1958
1959 //     qDebug("QGL2PaintEngineEx::begin()");
1960     if (pdev->devType() == QInternal::OpenGL)
1961         d->device = static_cast<QGLPaintDevice*>(pdev);
1962     else
1963         d->device = QGLPaintDevice::getDevice(pdev);
1964
1965     if (!d->device)
1966         return false;
1967
1968     d->ctx = d->device->context();
1969     d->ctx->d_ptr->active_engine = this;
1970
1971     const QSize sz = d->device->size();
1972     d->width = sz.width();
1973     d->height = sz.height();
1974     d->mode = BrushDrawingMode;
1975     d->brushTextureDirty = true;
1976     d->brushUniformsDirty = true;
1977     d->matrixUniformDirty = true;
1978     d->matrixDirty = true;
1979     d->compositionModeDirty = true;
1980     d->opacityUniformDirty = true;
1981     d->needsSync = true;
1982     d->useSystemClip = !systemClip().isEmpty();
1983     d->currentBrush = QBrush();
1984
1985     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1986     d->stencilClean = true;
1987
1988     // Calling begin paint should make the correct context current. So, any
1989     // code which calls into GL or otherwise needs a current context *must*
1990     // go after beginPaint:
1991     d->device->beginPaint();
1992
1993 #if !defined(QT_OPENGL_ES_2)
1994     bool success = qt_resolve_version_2_0_functions(d->ctx)
1995                    && qt_resolve_buffer_extensions(d->ctx)
1996                    && (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1997                        || qt_resolve_framebufferobject_extensions(d->ctx));
1998     Q_ASSERT(success);
1999     Q_UNUSED(success);
2000 #endif
2001
2002     d->shaderManager = new QGLEngineShaderManager(d->ctx);
2003
2004     glDisable(GL_STENCIL_TEST);
2005     glDisable(GL_DEPTH_TEST);
2006     glDisable(GL_SCISSOR_TEST);
2007
2008 #if !defined(QT_OPENGL_ES_2)
2009     glDisable(GL_MULTISAMPLE);
2010 #endif
2011
2012     d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2013
2014 #if !defined(QT_OPENGL_ES_2)
2015         d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2016 #endif
2017
2018 #if defined(QT_OPENGL_ES_2)
2019     // OpenGL ES can't switch MSAA off, so if the gl paint device is
2020     // multisampled, it's always multisampled.
2021     d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2022 #else
2023     d->multisamplingAlwaysEnabled = false;
2024 #endif
2025
2026     return true;
2027 }
2028
2029 bool QGL2PaintEngineEx::end()
2030 {
2031     Q_D(QGL2PaintEngineEx);
2032
2033     QGLContext *ctx = d->ctx;
2034     glUseProgram(0);
2035     d->transferMode(BrushDrawingMode);
2036     d->device->endPaint();
2037
2038     ctx->d_ptr->active_engine = 0;
2039
2040     d->resetGLState();
2041
2042     delete d->shaderManager;
2043     d->shaderManager = 0;
2044     d->currentBrush = QBrush();
2045
2046 #ifdef QT_OPENGL_CACHE_AS_VBOS
2047     if (!d->unusedVBOSToClean.isEmpty()) {
2048         glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2049         d->unusedVBOSToClean.clear();
2050     }
2051     if (!d->unusedIBOSToClean.isEmpty()) {
2052         glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2053         d->unusedIBOSToClean.clear();
2054     }
2055 #endif
2056
2057     return false;
2058 }
2059
2060 void QGL2PaintEngineEx::ensureActive()
2061 {
2062     Q_D(QGL2PaintEngineEx);
2063     QGLContext *ctx = d->ctx;
2064
2065     if (isActive() && ctx->d_ptr->active_engine != this) {
2066         ctx->d_ptr->active_engine = this;
2067         d->needsSync = true;
2068     }
2069
2070     d->device->ensureActiveTarget();
2071
2072     if (d->needsSync) {
2073         d->transferMode(BrushDrawingMode);
2074         glViewport(0, 0, d->width, d->height);
2075         d->needsSync = false;
2076         d->lastMaskTextureUsed = 0;
2077         d->shaderManager->setDirty();
2078         d->ctx->d_func()->syncGlState();
2079         for (int i = 0; i < 3; ++i)
2080             d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2081         setState(state());
2082     }
2083 }
2084
2085 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2086 {
2087     Q_Q(QGL2PaintEngineEx);
2088     if (q->state()->clipTestEnabled) {
2089         glEnable(GL_STENCIL_TEST);
2090         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2091     } else {
2092         glDisable(GL_STENCIL_TEST);
2093         glStencilFunc(GL_ALWAYS, 0, 0xff);
2094     }
2095
2096 #ifdef QT_GL_NO_SCISSOR_TEST
2097     currentScissorBounds = QRect(0, 0, width, height);
2098 #else
2099     QRect bounds = q->state()->rectangleClip;
2100     if (!q->state()->clipEnabled) {
2101         if (useSystemClip)
2102             bounds = systemClip.boundingRect();
2103         else
2104             bounds = QRect(0, 0, width, height);
2105     } else {
2106         if (useSystemClip)
2107             bounds = bounds.intersected(systemClip.boundingRect());
2108         else
2109             bounds = bounds.intersected(QRect(0, 0, width, height));
2110     }
2111
2112     currentScissorBounds = bounds;
2113
2114     if (bounds == QRect(0, 0, width, height)) {
2115         glDisable(GL_SCISSOR_TEST);
2116     } else {
2117         glEnable(GL_SCISSOR_TEST);
2118         setScissor(bounds);
2119     }
2120 #endif
2121 }
2122
2123 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2124 {
2125     const int left = rect.left();
2126     const int width = rect.width();
2127     int bottom = height - (rect.top() + rect.height());
2128     if (device->isFlipped()) {
2129         bottom = rect.top();
2130     }
2131     const int height = rect.height();
2132
2133     glScissor(left, bottom, width, height);
2134 }
2135
2136 void QGL2PaintEngineEx::clipEnabledChanged()
2137 {
2138     Q_D(QGL2PaintEngineEx);
2139
2140     state()->clipChanged = true;
2141
2142     if (painter()->hasClipping())
2143         d->regenerateClip();
2144     else
2145         d->systemStateChanged();
2146 }
2147
2148 void QGL2PaintEngineExPrivate::clearClip(uint value)
2149 {
2150     dirtyStencilRegion -= currentScissorBounds;
2151
2152     glStencilMask(0xff);
2153     glClearStencil(value);
2154     glClear(GL_STENCIL_BUFFER_BIT);
2155     glStencilMask(0x0);
2156
2157     q->state()->needsClipBufferClear = false;
2158 }
2159
2160 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2161 {
2162     transferMode(BrushDrawingMode);
2163
2164     if (snapToPixelGrid) {
2165         snapToPixelGrid = false;
2166         matrixDirty = true;
2167     }
2168
2169     if (matrixDirty)
2170         updateMatrix();
2171
2172     stencilClean = false;
2173
2174     const bool singlePass = !path.hasWindingFill()
2175         && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2176             || q->state()->needsClipBufferClear);
2177     const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2178
2179     if (q->state()->needsClipBufferClear)
2180         clearClip(1);
2181
2182     if (path.isEmpty()) {
2183         glEnable(GL_STENCIL_TEST);
2184         glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2185         return;
2186     }
2187
2188     if (q->state()->clipTestEnabled)
2189         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2190     else
2191         glStencilFunc(GL_ALWAYS, 0, 0xff);
2192
2193     vertexCoordinateArray.clear();
2194     vertexCoordinateArray.addPath(path, inverseScale, false);
2195
2196     if (!singlePass)
2197         fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2198
2199     glColorMask(false, false, false, false);
2200     glEnable(GL_STENCIL_TEST);
2201     useSimpleShader();
2202
2203     if (singlePass) {
2204         // Under these conditions we can set the new stencil value in a single
2205         // pass, by using the current value and the "new value" as the toggles
2206
2207         glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2208         glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2209         glStencilMask(value ^ referenceClipValue);
2210
2211         drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2212     } else {
2213         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2214         glStencilMask(0xff);
2215
2216         if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2217             // Pass when any clip bit is set, set high bit
2218             glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2219             composite(vertexCoordinateArray.boundingRect());
2220         }
2221
2222         // Pass when high bit is set, replace stencil value with new clip value
2223         glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2224
2225         composite(vertexCoordinateArray.boundingRect());
2226     }
2227
2228     glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2229     glStencilMask(0);
2230
2231     glColorMask(true, true, true, true);
2232 }
2233
2234 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2235 {
2236 //     qDebug("QGL2PaintEngineEx::clip()");
2237     Q_D(QGL2PaintEngineEx);
2238
2239     state()->clipChanged = true;
2240
2241     ensureActive();
2242
2243     if (op == Qt::ReplaceClip) {
2244         op = Qt::IntersectClip;
2245         if (d->hasClipOperations()) {
2246             d->systemStateChanged();
2247             state()->canRestoreClip = false;
2248         }
2249     }
2250
2251 #ifndef QT_GL_NO_SCISSOR_TEST
2252     if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2253         const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2254         QRectF rect(points[0], points[2]);
2255
2256         if (state()->matrix.type() <= QTransform::TxScale
2257             || (state()->matrix.type() == QTransform::TxRotate
2258                 && qFuzzyIsNull(state()->matrix.m11())
2259                 && qFuzzyIsNull(state()->matrix.m22())))
2260         {
2261             state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2262             d->updateClipScissorTest();
2263             return;
2264         }
2265     }
2266 #endif
2267
2268     const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2269
2270     switch (op) {
2271     case Qt::NoClip:
2272         if (d->useSystemClip) {
2273             state()->clipTestEnabled = true;
2274             state()->currentClip = 1;
2275         } else {
2276             state()->clipTestEnabled = false;
2277         }
2278         state()->rectangleClip = QRect(0, 0, d->width, d->height);
2279         state()->canRestoreClip = false;
2280         d->updateClipScissorTest();
2281         break;
2282     case Qt::IntersectClip:
2283         state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2284         d->updateClipScissorTest();
2285         d->resetClipIfNeeded();
2286         ++d->maxClip;
2287         d->writeClip(path, d->maxClip);
2288         state()->currentClip = d->maxClip;
2289         state()->clipTestEnabled = true;
2290         break;
2291     default:
2292         break;
2293     }
2294 }
2295
2296 void QGL2PaintEngineExPrivate::regenerateClip()
2297 {
2298     systemStateChanged();
2299     replayClipOperations();
2300 }
2301
2302 void QGL2PaintEngineExPrivate::systemStateChanged()
2303 {
2304     Q_Q(QGL2PaintEngineEx);
2305
2306     q->state()->clipChanged = true;
2307
2308     if (systemClip.isEmpty()) {
2309         useSystemClip = false;
2310     } else {
2311         if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2312             QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2313             useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2314         } else {
2315             useSystemClip = true;
2316         }
2317     }
2318
2319     q->state()->clipTestEnabled = false;
2320     q->state()->needsClipBufferClear = true;
2321
2322     q->state()->currentClip = 1;
2323     maxClip = 1;
2324
2325     q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2326     updateClipScissorTest();
2327
2328     if (systemClip.rectCount() == 1) {
2329         if (systemClip.boundingRect() == QRect(0, 0, width, height))
2330             useSystemClip = false;
2331 #ifndef QT_GL_NO_SCISSOR_TEST
2332         // scissoring takes care of the system clip
2333         return;
2334 #endif
2335     }
2336
2337     if (useSystemClip) {
2338         clearClip(0);
2339
2340         QPainterPath path;
2341         path.addRegion(systemClip);
2342
2343         q->state()->currentClip = 0;
2344         writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2345         q->state()->currentClip = 1;
2346         q->state()->clipTestEnabled = true;
2347     }
2348 }
2349
2350 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2351 {
2352     //     qDebug("QGL2PaintEngineEx::setState()");
2353
2354     Q_D(QGL2PaintEngineEx);
2355
2356     QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2357     QOpenGL2PaintEngineState *old_state = state();
2358
2359     QPaintEngineEx::setState(s);
2360
2361     if (s->isNew) {
2362         // Newly created state object.  The call to setState()
2363         // will either be followed by a call to begin(), or we are
2364         // setting the state as part of a save().
2365         s->isNew = false;
2366         return;
2367     }
2368
2369     // Setting the state as part of a restore().
2370
2371     if (old_state == s || old_state->renderHintsChanged)
2372         renderHintsChanged();
2373
2374     if (old_state == s || old_state->matrixChanged)
2375         d->matrixDirty = true;
2376
2377     if (old_state == s || old_state->compositionModeChanged)
2378         d->compositionModeDirty = true;
2379
2380     if (old_state == s || old_state->opacityChanged)
2381         d->opacityUniformDirty = true;
2382
2383     if (old_state == s || old_state->clipChanged) {
2384         if (old_state && old_state != s && old_state->canRestoreClip) {
2385             d->updateClipScissorTest();
2386             glDepthFunc(GL_LEQUAL);
2387         } else {
2388             d->regenerateClip();
2389         }
2390     }
2391 }
2392
2393 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2394 {
2395     if (orig)
2396         const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2397
2398     QOpenGL2PaintEngineState *s;
2399     if (!orig)
2400         s = new QOpenGL2PaintEngineState();
2401     else
2402         s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2403
2404     s->matrixChanged = false;
2405     s->compositionModeChanged = false;
2406     s->opacityChanged = false;
2407     s->renderHintsChanged = false;
2408     s->clipChanged = false;
2409
2410     return s;
2411 }
2412
2413 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2414     : QPainterState(other)
2415 {
2416     isNew = true;
2417     needsClipBufferClear = other.needsClipBufferClear;
2418     clipTestEnabled = other.clipTestEnabled;
2419     currentClip = other.currentClip;
2420     canRestoreClip = other.canRestoreClip;
2421     rectangleClip = other.rectangleClip;
2422 }
2423
2424 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2425 {
2426     isNew = true;
2427     needsClipBufferClear = true;
2428     clipTestEnabled = false;
2429     canRestoreClip = true;
2430 }
2431
2432 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2433 {
2434 }
2435
2436 QT_END_NAMESPACE