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