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