e0f1fe50a65aafa37be9a8232f4e287eff459ffc
[profile/ivi/qtbase.git] / src / gui / opengl / qopenglpaintengine.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*
43     When the active program changes, we need to update it's uniforms.
44     We could track state for each program and only update stale uniforms
45         - Could lead to lots of overhead if there's a lot of programs
46     We could update all the uniforms when the program changes
47         - Could end up updating lots of uniforms which don't need updating
48
49     Updating uniforms should be cheap, so the overhead of updating up-to-date
50     uniforms should be minimal. It's also less complex.
51
52     Things which _may_ cause a different program to be used:
53         - Change in brush/pen style
54         - Change in painter opacity
55         - Change in composition mode
56
57     Whenever we set a mode on the shader manager - it needs to tell us if it had
58     to switch to a different program.
59
60     The shader manager should only switch when we tell it to. E.g. if we set a new
61     brush style and then switch to transparent painter, we only want it to compile
62     and use the correct program when we really need it.
63 */
64
65 // #define QT_OPENGL_CACHE_AS_VBOS
66
67 #include "qopenglgradientcache_p.h"
68 #include "qopengltexturecache_p.h"
69 #include "qopenglpaintengine_p.h"
70
71 #include <string.h> //for memcpy
72 #include <qmath.h>
73
74 #include <private/qopengl_p.h>
75 #include <private/qopenglcontext_p.h>
76 #include <private/qopenglextensions_p.h>
77 #include <private/qmath_p.h>
78 #include <private/qpaintengineex_p.h>
79 #include <QPaintEngine>
80 #include <private/qpainter_p.h>
81 #include <private/qfontengine_p.h>
82 #include <private/qdatabuffer_p.h>
83 #include <private/qstatictext_p.h>
84 #include <private/qtriangulator_p.h>
85
86 #include "qopenglengineshadermanager_p.h"
87 #include "qopengl2pexvertexarray_p.h"
88 #include "qopengltextureglyphcache_p.h"
89
90 #include <QDebug>
91
92 // ####TODO Properly #ifdef this class to use #define symbols actually defined
93 // by OpenGL/ES includes
94 #ifndef GL_FRAMEBUFFER_SRGB
95 #define GL_FRAMEBUFFER_SRGB 0x8DB9
96 #endif
97
98 QT_BEGIN_NAMESPACE
99
100
101
102 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
103
104 ////////////////////////////////// Private Methods //////////////////////////////////////////
105
106 QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
107 {
108     delete shaderManager;
109
110     while (pathCaches.size()) {
111         QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
112         e->cleanup(e->engine, e->data);
113         e->data = 0;
114         e->engine = 0;
115     }
116
117     if (elementIndicesVBOId != 0) {
118         funcs.glDeleteBuffers(1, &elementIndicesVBOId);
119         elementIndicesVBOId = 0;
120     }
121 }
122
123 void QOpenGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
124 {
125 //    funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
126     if (id != GLuint(-1) && id == lastTextureUsed)
127         return;
128
129     lastTextureUsed = id;
130
131     if (smoothPixmapTransform) {
132         glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
133         glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
134     } else {
135         glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
136         glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
137     }
138     glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
139     glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
140 }
141
142
143 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
144 {
145     qreal alpha = c.alphaF() * opacity;
146     c.setAlphaF(alpha);
147     c.setRedF(c.redF() * alpha);
148     c.setGreenF(c.greenF() * alpha);
149     c.setBlueF(c.blueF() * alpha);
150     return c;
151 }
152
153
154 void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
155 {
156     if (qbrush_fast_equals(currentBrush, brush))
157         return;
158
159     const Qt::BrushStyle newStyle = qbrush_style(brush);
160     Q_ASSERT(newStyle != Qt::NoBrush);
161
162     currentBrush = brush;
163     if (!currentBrushPixmap.isNull())
164         currentBrushPixmap = QPixmap();
165     brushUniformsDirty = true; // All brushes have at least one uniform
166
167     if (newStyle > Qt::SolidPattern)
168         brushTextureDirty = true;
169
170     if (currentBrush.style() == Qt::TexturePattern
171         && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
172     {
173         shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
174     } else {
175         shaderManager->setSrcPixelType(newStyle);
176     }
177     shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
178 }
179
180
181 void QOpenGL2PaintEngineExPrivate::useSimpleShader()
182 {
183     shaderManager->useSimpleProgram();
184
185     if (matrixDirty)
186         updateMatrix();
187 }
188
189 void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
190 {
191     Q_Q(QOpenGL2PaintEngineEx);
192 //     qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
193     Qt::BrushStyle style = currentBrush.style();
194
195     if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
196         // Get the image data for the pattern
197         QImage texImage = qt_imageForBrush(style, false);
198
199         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
200         QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, texImage);
201         updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
202     }
203     else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
204         // Gradiant brush: All the gradiants use the same texture
205
206         const QGradient* g = currentBrush.gradient();
207
208         // We apply global opacity in the fragment shaders, so we always pass 1.0
209         // for opacity to the cache.
210         GLuint texId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
211
212         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
213         glBindTexture(GL_TEXTURE_2D, texId);
214
215         if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
216             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
217         else if (g->spread() == QGradient::ReflectSpread)
218             updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
219         else
220             updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
221     }
222     else if (style == Qt::TexturePattern) {
223         currentBrushPixmap = currentBrush.texture();
224
225         int max_texture_size = ctx->d_func()->maxTextureSize();
226         if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
227             currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
228
229         funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
230         QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, currentBrushPixmap);
231         updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
232         textureInvertedY = false;
233     }
234     brushTextureDirty = false;
235 }
236
237
238 void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
239 {
240 //     qDebug("QOpenGL2PaintEngineExPrivate::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(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::PatternColor), col);
260
261             QVector2D halfViewportSize(width*0.5, height*0.5);
262             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::LinearData), linearData);
280
281             QVector2D halfViewportSize(width*0.5, height*0.5);
282             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::Angle), angle);
291
292             QVector2D halfViewportSize(width*0.5, height*0.5);
293             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::Fmp), fmp);
304
305             GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
306             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
307             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
308                                                              GLfloat(1.0 / (2.0*fmp2_m_radius2)));
309             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
310                                                              GLfloat(g->focalRadius() * g->focalRadius()));
311             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::PatternColor), col);
325             }
326
327             QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
328             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
329
330             QVector2D halfViewportSize(width*0.5, height*0.5);
331             shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
332         }
333         else
334             qWarning("QOpenGL2PaintEngineEx: 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->paintFlipped()) {
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(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
355         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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 QOpenGL2PaintEngineExPrivate::updateMatrix()
363 {
364 //     qDebug("QOpenGL2PaintEngineExPrivate::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->paintFlipped()) {
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     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
425     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
426     funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
427
428     dasher.setInvScale(inverseScale);
429     stroker.setInvScale(inverseScale);
430 }
431
432
433 void QOpenGL2PaintEngineExPrivate::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() << "QOpenGL2PaintEngineExPrivate::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 QOpenGLRect &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 QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
499 {
500     // Setup for texture drawing
501     currentBrush = noBrush;
502     shaderManager->setSrcPixelType(pattern ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
503
504     if (snapToPixelGrid) {
505         snapToPixelGrid = false;
506         matrixDirty = true;
507     }
508
509     if (prepareForDraw(opaque))
510         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::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(QOpenGLEngineShaderManager::PatternColor), col);
515     }
516
517     GLfloat dx = 1.0 / textureSize.width();
518     GLfloat dy = 1.0 / textureSize.height();
519
520     QOpenGLRect 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 QOpenGL2PaintEngineEx::beginNativePainting()
529 {
530     Q_D(QOpenGL2PaintEngineEx);
531     ensureActive();
532     d->transferMode(BrushDrawingMode);
533
534     d->nativePaintingActive = true;
535
536     d->funcs.glUseProgram(0);
537
538     // Disable all the vertex attribute arrays:
539     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
540         d->funcs.glDisableVertexAttribArray(i);
541
542 #ifndef QT_OPENGL_ES_2
543     Q_ASSERT(QOpenGLContext::currentContext());
544     const QSurfaceFormat &fmt = d->device->context()->format();
545     if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
546         || fmt.profile() == QSurfaceFormat::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 #endif
571
572     d->lastTextureUsed = GLuint(-1);
573     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
574     d->resetGLState();
575
576     d->shaderManager->setDirty();
577
578     d->needsSync = true;
579 }
580
581 void QOpenGL2PaintEngineExPrivate::resetGLState()
582 {
583     glDisable(GL_BLEND);
584     funcs.glActiveTexture(GL_TEXTURE0);
585     glDisable(GL_STENCIL_TEST);
586     glDisable(GL_DEPTH_TEST);
587     glDisable(GL_SCISSOR_TEST);
588     glDepthMask(true);
589     glDepthFunc(GL_LESS);
590     funcs.glClearDepthf(1);
591     glStencilMask(0xff);
592     glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
593     glStencilFunc(GL_ALWAYS, 0, 0xff);
594     setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
595     setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
596     setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
597 #ifndef QT_OPENGL_ES_2
598     // gl_Color, corresponding to vertex attribute 3, may have been changed
599     float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
600     funcs.glVertexAttrib4fv(3, color);
601 #endif
602 }
603
604 void QOpenGL2PaintEngineEx::endNativePainting()
605 {
606     Q_D(QOpenGL2PaintEngineEx);
607     d->needsSync = true;
608     d->nativePaintingActive = false;
609 }
610
611 void QOpenGL2PaintEngineEx::invalidateState()
612 {
613     Q_D(QOpenGL2PaintEngineEx);
614     d->needsSync = true;
615 }
616
617 bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
618     Q_D(const QOpenGL2PaintEngineEx);
619     return d->nativePaintingActive;
620 }
621
622 void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
623 {
624     if (newMode == mode)
625         return;
626
627     if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
628         lastTextureUsed = GLuint(-1);
629     }
630
631     if (newMode == TextDrawingMode) {
632         shaderManager->setHasComplexGeometry(true);
633     } else {
634         shaderManager->setHasComplexGeometry(false);
635     }
636
637     if (newMode == ImageDrawingMode) {
638         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
639         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
640     }
641
642     if (newMode == ImageArrayDrawingMode) {
643         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
644         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
645         setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
646     }
647
648     // This needs to change when we implement high-quality anti-aliasing...
649     if (newMode != TextDrawingMode)
650         shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
651
652     mode = newMode;
653 }
654
655 struct QOpenGL2PEVectorPathCache
656 {
657 #ifdef QT_OPENGL_CACHE_AS_VBOS
658     GLuint vbo;
659     GLuint ibo;
660 #else
661     float *vertices;
662     void *indices;
663 #endif
664     int vertexCount;
665     int indexCount;
666     GLenum primitiveType;
667     qreal iscale;
668     QVertexIndexVector::Type indexType;
669 };
670
671 void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
672 {
673     QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
674 #ifdef QT_OPENGL_CACHE_AS_VBOS
675     Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
676     static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
677     if (c->ibo)
678         d->unusedIBOSToClean << c->ibo;
679 #else
680     Q_UNUSED(engine);
681     free(c->vertices);
682     free(c->indices);
683 #endif
684     delete c;
685 }
686
687 // Assumes everything is configured for the brush you want to use
688 void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
689 {
690     transferMode(BrushDrawingMode);
691
692     if (snapToPixelGrid) {
693         snapToPixelGrid = false;
694         matrixDirty = true;
695     }
696
697     // Might need to call updateMatrix to re-calculate inverseScale
698     if (matrixDirty)
699         updateMatrix();
700
701     const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
702
703     // Check to see if there's any hints
704     if (path.shape() == QVectorPath::RectangleHint) {
705         QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
706         prepareForDraw(currentBrush.isOpaque());
707         composite(rect);
708     } else if (path.isConvex()) {
709
710         if (path.isCacheable()) {
711             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
712             QOpenGL2PEVectorPathCache *cache;
713
714             bool updateCache = false;
715
716             if (data) {
717                 cache = (QOpenGL2PEVectorPathCache *) data->data;
718                 // Check if scale factor is exceeded for curved paths and generate curves if so...
719                 if (path.isCurved()) {
720                     qreal scaleFactor = cache->iscale / inverseScale;
721                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
722 #ifdef QT_OPENGL_CACHE_AS_VBOS
723                         glDeleteBuffers(1, &cache->vbo);
724                         cache->vbo = 0;
725                         Q_ASSERT(cache->ibo == 0);
726 #else
727                         free(cache->vertices);
728                         Q_ASSERT(cache->indices == 0);
729 #endif
730                         updateCache = true;
731                     }
732                 }
733             } else {
734                 cache = new QOpenGL2PEVectorPathCache;
735                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
736                 updateCache = true;
737             }
738
739             // Flatten the path at the current scale factor and fill it into the cache struct.
740             if (updateCache) {
741                 vertexCoordinateArray.clear();
742                 vertexCoordinateArray.addPath(path, inverseScale, false);
743                 int vertexCount = vertexCoordinateArray.vertexCount();
744                 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
745                 cache->vertexCount = vertexCount;
746                 cache->indexCount = 0;
747                 cache->primitiveType = GL_TRIANGLE_FAN;
748                 cache->iscale = inverseScale;
749 #ifdef QT_OPENGL_CACHE_AS_VBOS
750                 glGenBuffers(1, &cache->vbo);
751                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
752                 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
753                 cache->ibo = 0;
754 #else
755                 cache->vertices = (float *) malloc(floatSizeInBytes);
756                 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
757                 cache->indices = 0;
758 #endif
759             }
760
761             prepareForDraw(currentBrush.isOpaque());
762 #ifdef QT_OPENGL_CACHE_AS_VBOS
763             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
764             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
765 #else
766             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
767 #endif
768             glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
769
770         } else {
771       //        printf(" - Marking path as cachable...\n");
772             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
773             path.makeCacheable();
774             vertexCoordinateArray.clear();
775             vertexCoordinateArray.addPath(path, inverseScale, false);
776             prepareForDraw(currentBrush.isOpaque());
777             drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
778         }
779
780     } else {
781         bool useCache = path.isCacheable();
782         if (useCache) {
783             QRectF bbox = path.controlPointRect();
784             // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
785             useCache &= (bbox.left() > -0x8000 * inverseScale)
786                      && (bbox.right() < 0x8000 * inverseScale)
787                      && (bbox.top() > -0x8000 * inverseScale)
788                      && (bbox.bottom() < 0x8000 * inverseScale);
789         }
790
791         if (useCache) {
792             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
793             QOpenGL2PEVectorPathCache *cache;
794
795             bool updateCache = false;
796
797             if (data) {
798                 cache = (QOpenGL2PEVectorPathCache *) data->data;
799                 // Check if scale factor is exceeded for curved paths and generate curves if so...
800                 if (path.isCurved()) {
801                     qreal scaleFactor = cache->iscale / inverseScale;
802                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
803 #ifdef QT_OPENGL_CACHE_AS_VBOS
804                         glDeleteBuffers(1, &cache->vbo);
805                         glDeleteBuffers(1, &cache->ibo);
806 #else
807                         free(cache->vertices);
808                         free(cache->indices);
809 #endif
810                         updateCache = true;
811                     }
812                 }
813             } else {
814                 cache = new QOpenGL2PEVectorPathCache;
815                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
816                 updateCache = true;
817             }
818
819             // Flatten the path at the current scale factor and fill it into the cache struct.
820             if (updateCache) {
821                 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
822                 cache->vertexCount = polys.vertices.size() / 2;
823                 cache->indexCount = polys.indices.size();
824                 cache->primitiveType = GL_TRIANGLES;
825                 cache->iscale = inverseScale;
826                 cache->indexType = polys.indices.type();
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 (polys.indices.type() == QVertexIndexVector::UnsignedInt)
834                     funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
835                 else
836                     funcs.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                 funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
842 #else
843                 cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
844                 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
845                     cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
846                     memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
847                 } else {
848                     cache->indices = (quint16 *) malloc(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 (cache->indexType == QVertexIndexVector::UnsignedInt)
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 (cache->indexType == QVertexIndexVector::UnsignedInt)
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->context()->format().stencilBufferSize() == 0) {
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 (funcs.hasOpenGLExtension(QOpenGLExtensions::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 QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
940                                                           int count,
941                                                           int *stops,
942                                                           int stopCount,
943                                                           const QOpenGLRect &bounds,
944                                                           StencilFillMode mode)
945 {
946     Q_ASSERT(count || stops);
947
948 //     qDebug("QOpenGL2PaintEngineExPrivate::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         funcs.glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
990         // Dec. for back-facing "holes"
991         funcs.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 QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
1038 {
1039     if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1040         return;
1041
1042     Q_Q(QOpenGL2PaintEngineEx);
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     QOpenGLRect 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 QOpenGL2PaintEngineExPrivate::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     QOpenGLEngineShaderManager::OpacityMode opacityMode;
1094     if (mode == ImageArrayDrawingMode) {
1095         opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
1096     } else {
1097         opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
1098                                       : QOpenGLEngineShaderManager::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 = QOpenGLEngineShaderManager::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 == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1123         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1124         opacityUniformDirty = false;
1125     }
1126
1127     if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1128         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
1129                                                          pmvMatrix);
1130         matrixUniformDirty = false;
1131     }
1132
1133     return changed;
1134 }
1135
1136 void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& 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 QOpenGL2PaintEngineExPrivate::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 QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
1166     : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
1167 {
1168 }
1169
1170 QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
1171 {
1172 }
1173
1174 void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1175 {
1176     Q_D(QOpenGL2PaintEngineEx);
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 QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1189 {
1190     Q_D(QOpenGL2PaintEngineEx);
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 QOpenGL2PaintEngineExPrivate::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, QOpenGL2PaintEngineExPrivate::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 QOpenGL2PaintEngineEx::penChanged() { }
1288 void QOpenGL2PaintEngineEx::brushChanged() { }
1289 void QOpenGL2PaintEngineEx::brushOriginChanged() { }
1290
1291 void QOpenGL2PaintEngineEx::opacityChanged()
1292 {
1293 //    qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
1294     Q_D(QOpenGL2PaintEngineEx);
1295     state()->opacityChanged = true;
1296
1297     Q_ASSERT(d->shaderManager);
1298     d->brushUniformsDirty = true;
1299     d->opacityUniformDirty = true;
1300 }
1301
1302 void QOpenGL2PaintEngineEx::compositionModeChanged()
1303 {
1304 //     qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
1305     Q_D(QOpenGL2PaintEngineEx);
1306     state()->compositionModeChanged = true;
1307     d->compositionModeDirty = true;
1308 }
1309
1310 void QOpenGL2PaintEngineEx::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(QOpenGL2PaintEngineEx);
1323     d->lastTextureUsed = GLuint(-1);
1324     d->brushTextureDirty = true;
1325 //    qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
1326 }
1327
1328 void QOpenGL2PaintEngineEx::transformChanged()
1329 {
1330     Q_D(QOpenGL2PaintEngineEx);
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 QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1342 {
1343     Q_D(QOpenGL2PaintEngineEx);
1344     QOpenGLContext *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     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1361     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1362
1363     QOpenGLRect srcRect(src.left(), src.top(), src.right(), src.bottom());
1364
1365     bool isBitmap = pixmap.isQBitmap();
1366     bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1367
1368     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1369                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1370     d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1371 }
1372
1373 void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1374                         Qt::ImageConversionFlags)
1375 {
1376     Q_D(QOpenGL2PaintEngineEx);
1377     QOpenGLContext *ctx = d->ctx;
1378
1379     int max_texture_size = ctx->d_func()->maxTextureSize();
1380     if (image.width() > max_texture_size || image.height() > max_texture_size) {
1381         QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1382
1383         const qreal sx = scaled.width() / qreal(image.width());
1384         const qreal sy = scaled.height() / qreal(image.height());
1385
1386         drawImage(dest, scaled, scaleRect(src, sx, sy));
1387         return;
1388     }
1389
1390     ensureActive();
1391     d->transferMode(ImageDrawingMode);
1392
1393     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1394
1395     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
1396
1397     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1398                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1399     d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1400 }
1401
1402 void QOpenGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1403 {
1404     Q_D(QOpenGL2PaintEngineEx);
1405
1406     ensureActive();
1407
1408     QPainterState *s = state();
1409     float det = s->matrix.determinant();
1410
1411     // don't try to cache huge fonts or vastly transformed fonts
1412     QFontEngine *fontEngine = textItem->fontEngine();
1413     if (shouldDrawCachedGlyphs(fontEngine, s->matrix) && det >= 0.25f && det <= 4.f) {
1414         QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1415                                                 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1416                                                 : d->glyphCacheType;
1417         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1418             if (d->device->context()->format().alphaBufferSize() > 0 || s->matrix.type() > QTransform::TxTranslate
1419                 || (s->composition_mode != QPainter::CompositionMode_Source
1420                 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1421             {
1422                 glyphType = QFontEngineGlyphCache::Raster_A8;
1423             }
1424         }
1425
1426         d->drawCachedGlyphs(glyphType, textItem);
1427     } else {
1428         QPaintEngineEx::drawStaticTextItem(textItem);
1429     }
1430 }
1431
1432 bool QOpenGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1433 {
1434     Q_D(QOpenGL2PaintEngineEx);
1435     if (!d->shaderManager)
1436         return false;
1437
1438     ensureActive();
1439     d->transferMode(ImageDrawingMode);
1440
1441     d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1442     glBindTexture(GL_TEXTURE_2D, textureId);
1443
1444     QOpenGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1445
1446     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1447                            state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1448     d->drawTexture(dest, srcRect, size, false);
1449     return true;
1450 }
1451
1452 void QOpenGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1453 {
1454     Q_D(QOpenGL2PaintEngineEx);
1455
1456     ensureActive();
1457     QOpenGL2PaintEngineState *s = state();
1458
1459     const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1460
1461     QTransform::TransformationType txtype = s->matrix.type();
1462
1463     float det = s->matrix.determinant();
1464     bool drawCached = txtype < QTransform::TxProject;
1465
1466     // don't try to cache huge fonts or vastly transformed fonts
1467     if (!shouldDrawCachedGlyphs(ti.fontEngine, s->matrix) || det < 0.25f || det > 4.f)
1468         drawCached = false;
1469
1470     QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1471                                             ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1472                                             : d->glyphCacheType;
1473
1474
1475     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1476         if (d->device->context()->format().alphaBufferSize() > 0 || txtype > QTransform::TxTranslate
1477             || (state()->composition_mode != QPainter::CompositionMode_Source
1478             && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1479         {
1480             glyphType = QFontEngineGlyphCache::Raster_A8;
1481         }
1482     }
1483
1484     if (drawCached) {
1485         QVarLengthArray<QFixedPoint> positions;
1486         QVarLengthArray<glyph_t> glyphs;
1487         QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1488         ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1489
1490         {
1491             QStaticTextItem staticTextItem;
1492             staticTextItem.chars = const_cast<QChar *>(ti.chars);
1493             staticTextItem.setFontEngine(ti.fontEngine);
1494             staticTextItem.glyphs = glyphs.data();
1495             staticTextItem.numChars = ti.num_chars;
1496             staticTextItem.numGlyphs = glyphs.size();
1497             staticTextItem.glyphPositions = positions.data();
1498
1499             d->drawCachedGlyphs(glyphType, &staticTextItem);
1500         }
1501         return;
1502     }
1503
1504     QPaintEngineEx::drawTextItem(p, ti);
1505 }
1506
1507 namespace {
1508
1509     class QOpenGLStaticTextUserData: public QStaticTextUserData
1510     {
1511     public:
1512         QOpenGLStaticTextUserData()
1513             : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1514         {
1515         }
1516
1517         ~QOpenGLStaticTextUserData()
1518         {
1519         }
1520
1521         QSize cacheSize;
1522         QOpenGL2PEXVertexArray vertexCoordinateArray;
1523         QOpenGL2PEXVertexArray textureCoordinateArray;
1524         QFontEngineGlyphCache::Type glyphType;
1525         int cacheSerialNumber;
1526     };
1527
1528 }
1529
1530
1531 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1532
1533 void QOpenGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1534                                                 QStaticTextItem *staticTextItem)
1535 {
1536     Q_Q(QOpenGL2PaintEngineEx);
1537
1538     QOpenGL2PaintEngineState *s = q->state();
1539
1540     void *cacheKey = ctx->shareGroup();
1541     bool recreateVertexArrays = false;
1542     QFontEngine *fe = staticTextItem->fontEngine();
1543
1544     QOpenGLTextureGlyphCache *cache =
1545             (QOpenGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphType, QTransform());
1546     if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1547         cache = new QOpenGLTextureGlyphCache(glyphType, QTransform());
1548         fe->setGlyphCache(cacheKey, cache);
1549         recreateVertexArrays = true;
1550     }
1551
1552     if (staticTextItem->userDataNeedsUpdate) {
1553         recreateVertexArrays = true;
1554     } else if (staticTextItem->userData() == 0) {
1555         recreateVertexArrays = true;
1556     } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1557         recreateVertexArrays = true;
1558     } else {
1559         QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1560         if (userData->glyphType != glyphType) {
1561             recreateVertexArrays = true;
1562         } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1563             recreateVertexArrays = true;
1564         }
1565     }
1566
1567     // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1568     // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1569     // cache so this text is performed before we test if the cache size has changed.
1570     if (recreateVertexArrays) {
1571         cache->setPaintEnginePrivate(this);
1572         if (!cache->populate(fe, staticTextItem->numGlyphs,
1573                              staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1574             // No space for glyphs in cache. We need to reset it and try again.
1575             cache->clear();
1576             cache->populate(fe, staticTextItem->numGlyphs,
1577                             staticTextItem->glyphs, staticTextItem->glyphPositions);
1578         }
1579         cache->fillInPendingGlyphs();
1580     }
1581
1582     if (cache->width() == 0 || cache->height() == 0)
1583         return;
1584
1585     transferMode(TextDrawingMode);
1586
1587     int margin = fe->glyphMargin(glyphType);
1588
1589     GLfloat dx = 1.0 / cache->width();
1590     GLfloat dy = 1.0 / cache->height();
1591
1592     // Use global arrays by default
1593     QOpenGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1594     QOpenGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1595
1596     if (staticTextItem->useBackendOptimizations) {
1597         QOpenGLStaticTextUserData *userData = 0;
1598
1599         if (staticTextItem->userData() == 0
1600             || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1601
1602             userData = new QOpenGLStaticTextUserData();
1603             staticTextItem->setUserData(userData);
1604
1605         } else {
1606             userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1607         }
1608
1609         userData->glyphType = glyphType;
1610         userData->cacheSerialNumber = cache->serialNumber();
1611
1612         // Use cache if backend optimizations is turned on
1613         vertexCoordinates = &userData->vertexCoordinateArray;
1614         textureCoordinates = &userData->textureCoordinateArray;
1615
1616         QSize size(cache->width(), cache->height());
1617         if (userData->cacheSize != size) {
1618             recreateVertexArrays = true;
1619             userData->cacheSize = size;
1620         }
1621     }
1622
1623     if (recreateVertexArrays) {
1624         vertexCoordinates->clear();
1625         textureCoordinates->clear();
1626
1627         bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1628         for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1629             QFixed subPixelPosition;
1630             if (supportsSubPixelPositions)
1631                 subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1632
1633             QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1634
1635             const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1636             if (c.isNull())
1637                 continue;
1638
1639             int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1640             int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1641
1642             vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1643             textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1644         }
1645
1646         staticTextItem->userDataNeedsUpdate = false;
1647     }
1648
1649     int numGlyphs = vertexCoordinates->vertexCount() / 4;
1650     if (numGlyphs == 0)
1651         return;
1652
1653     if (elementIndices.size() < numGlyphs*6) {
1654         Q_ASSERT(elementIndices.size() % 6 == 0);
1655         int j = elementIndices.size() / 6 * 4;
1656         while (j < numGlyphs*4) {
1657             elementIndices.append(j + 0);
1658             elementIndices.append(j + 0);
1659             elementIndices.append(j + 1);
1660             elementIndices.append(j + 2);
1661             elementIndices.append(j + 3);
1662             elementIndices.append(j + 3);
1663
1664             j += 4;
1665         }
1666
1667 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1668         if (elementIndicesVBOId == 0)
1669             glGenBuffers(1, &elementIndicesVBOId);
1670
1671         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1672         glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1673                      elementIndices.constData(), GL_STATIC_DRAW);
1674 #endif
1675     } else {
1676 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1677         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1678 #endif
1679     }
1680
1681     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1682     setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1683
1684     if (!snapToPixelGrid) {
1685         snapToPixelGrid = true;
1686         matrixDirty = true;
1687     }
1688
1689     QBrush pensBrush = q->state()->pen.brush();
1690     setBrush(pensBrush);
1691
1692     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1693
1694         // Subpixel antialiasing without gamma correction
1695
1696         QPainter::CompositionMode compMode = q->state()->composition_mode;
1697         Q_ASSERT(compMode == QPainter::CompositionMode_Source
1698             || compMode == QPainter::CompositionMode_SourceOver);
1699
1700         shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass1);
1701
1702         if (pensBrush.style() == Qt::SolidPattern) {
1703             // Solid patterns can get away with only one pass.
1704             QColor c = pensBrush.color();
1705             qreal oldOpacity = q->state()->opacity;
1706             if (compMode == QPainter::CompositionMode_Source) {
1707                 c = qt_premultiplyColor(c, q->state()->opacity);
1708                 q->state()->opacity = 1;
1709                 opacityUniformDirty = true;
1710             }
1711
1712             compositionModeDirty = false; // I can handle this myself, thank you very much
1713             prepareForDraw(false); // Text always causes src pixels to be transparent
1714
1715             // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1716             if (compMode == QPainter::CompositionMode_Source) {
1717                 q->state()->opacity = oldOpacity;
1718                 opacityUniformDirty = true;
1719             }
1720
1721             glEnable(GL_BLEND);
1722             glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1723             funcs.glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1724         } else {
1725             // Other brush styles need two passes.
1726
1727             qreal oldOpacity = q->state()->opacity;
1728             if (compMode == QPainter::CompositionMode_Source) {
1729                 q->state()->opacity = 1;
1730                 opacityUniformDirty = true;
1731                 pensBrush = Qt::white;
1732                 setBrush(pensBrush);
1733             }
1734
1735             compositionModeDirty = false; // I can handle this myself, thank you very much
1736             prepareForDraw(false); // Text always causes src pixels to be transparent
1737             glEnable(GL_BLEND);
1738             glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1739
1740             funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1741             glBindTexture(GL_TEXTURE_2D, cache->texture());
1742             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1743
1744 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1745             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1746 #else
1747             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1748 #endif
1749
1750             shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass2);
1751
1752             if (compMode == QPainter::CompositionMode_Source) {
1753                 q->state()->opacity = oldOpacity;
1754                 opacityUniformDirty = true;
1755                 pensBrush = q->state()->pen.brush();
1756                 setBrush(pensBrush);
1757             }
1758
1759             compositionModeDirty = false;
1760             prepareForDraw(false); // Text always causes src pixels to be transparent
1761             glEnable(GL_BLEND);
1762             glBlendFunc(GL_ONE, GL_ONE);
1763         }
1764         compositionModeDirty = true;
1765     } else {
1766         // Greyscale/mono glyphs
1767
1768         shaderManager->setMaskType(QOpenGLEngineShaderManager::PixelMask);
1769         prepareForDraw(false); // Text always causes src pixels to be transparent
1770     }
1771
1772     QOpenGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QOpenGLTextureGlyphCache::Linear:QOpenGLTextureGlyphCache::Nearest;
1773     if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1774
1775         funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1776         if (lastMaskTextureUsed != cache->texture()) {
1777             glBindTexture(GL_TEXTURE_2D, cache->texture());
1778             lastMaskTextureUsed = cache->texture();
1779         }
1780
1781         if (cache->filterMode() != filterMode) {
1782             if (filterMode == QOpenGLTextureGlyphCache::Linear) {
1783                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1784                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1785             } else {
1786                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1787                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1788             }
1789             cache->setFilterMode(filterMode);
1790         }
1791     }
1792
1793     bool srgbFrameBufferEnabled = false;
1794     if (funcs.hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer)) {
1795         if (false)
1796         {
1797             glEnable(GL_FRAMEBUFFER_SRGB);
1798             srgbFrameBufferEnabled = true;
1799         }
1800     }
1801
1802 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1803     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1804     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1805 #else
1806     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1807 #endif
1808
1809     if (srgbFrameBufferEnabled)
1810         glDisable(GL_FRAMEBUFFER_SRGB);
1811
1812 }
1813
1814 void QOpenGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1815                                             QPainter::PixmapFragmentHints hints)
1816 {
1817     Q_D(QOpenGL2PaintEngineEx);
1818     // Use fallback for extended composition modes.
1819     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1820         QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1821         return;
1822     }
1823
1824     ensureActive();
1825     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1826     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1827         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1828         d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1829     } else {
1830         d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1831     }
1832 }
1833
1834
1835 void QOpenGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1836                                                    int fragmentCount, const QPixmap &pixmap,
1837                                                    QPainter::PixmapFragmentHints hints)
1838 {
1839     GLfloat dx = 1.0f / pixmap.size().width();
1840     GLfloat dy = 1.0f / pixmap.size().height();
1841
1842     vertexCoordinateArray.clear();
1843     textureCoordinateArray.clear();
1844     opacityArray.reset();
1845
1846     if (snapToPixelGrid) {
1847         snapToPixelGrid = false;
1848         matrixDirty = true;
1849     }
1850
1851     bool allOpaque = true;
1852
1853     for (int i = 0; i < fragmentCount; ++i) {
1854         qreal s = 0;
1855         qreal c = 1;
1856         if (fragments[i].rotation != 0) {
1857             s = qFastSin(fragments[i].rotation * Q_PI / 180);
1858             c = qFastCos(fragments[i].rotation * Q_PI / 180);
1859         }
1860
1861         qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1862         qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1863         QOpenGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1864         QOpenGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1865
1866         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1867         vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1868         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1869         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1870         vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1871         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1872
1873         QOpenGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1874                     (fragments[i].sourceLeft + fragments[i].width) * dx,
1875                     (fragments[i].sourceTop + fragments[i].height) * dy);
1876
1877         textureCoordinateArray.addVertex(src.right, src.bottom);
1878         textureCoordinateArray.addVertex(src.right, src.top);
1879         textureCoordinateArray.addVertex(src.left, src.top);
1880         textureCoordinateArray.addVertex(src.left, src.top);
1881         textureCoordinateArray.addVertex(src.left, src.bottom);
1882         textureCoordinateArray.addVertex(src.right, src.bottom);
1883
1884         qreal opacity = fragments[i].opacity * q->state()->opacity;
1885         opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1886         allOpaque &= (opacity >= 0.99f);
1887     }
1888
1889     funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1890     GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1891     transferMode(ImageArrayDrawingMode);
1892
1893     bool isBitmap = pixmap.isQBitmap();
1894     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1895
1896     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1897                            q->state()->renderHints & QPainter::SmoothPixmapTransform, id);
1898
1899     // Setup for texture drawing
1900     currentBrush = noBrush;
1901     shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc
1902                                             : QOpenGLEngineShaderManager::ImageSrc);
1903     if (prepareForDraw(isOpaque))
1904         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1905
1906     if (isBitmap) {
1907         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1908         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
1909     }
1910
1911     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1912 }
1913
1914 bool QOpenGL2PaintEngineEx::begin(QPaintDevice *pdev)
1915 {
1916     Q_D(QOpenGL2PaintEngineEx);
1917
1918     Q_ASSERT(pdev->devType() == QInternal::OpenGL);
1919     d->device = static_cast<QOpenGLPaintDevice*>(pdev);
1920
1921     if (!d->device)
1922         return false;
1923
1924     if (d->device->context() != QOpenGLContext::currentContext()) {
1925         qWarning("QPainter::begin(): QOpenGLPaintDevice's context needs to be current");
1926         return false;
1927     }
1928
1929     d->ctx = QOpenGLContext::currentContext();
1930     d->ctx->d_func()->active_engine = this;
1931
1932     d->funcs.initializeOpenGLFunctions();
1933
1934     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1935         d->vertexAttributeArraysEnabledState[i] = false;
1936
1937     const QSize sz = d->device->size();
1938     d->width = sz.width();
1939     d->height = sz.height();
1940     d->mode = BrushDrawingMode;
1941     d->brushTextureDirty = true;
1942     d->brushUniformsDirty = true;
1943     d->matrixUniformDirty = true;
1944     d->matrixDirty = true;
1945     d->compositionModeDirty = true;
1946     d->opacityUniformDirty = true;
1947     d->needsSync = true;
1948     d->useSystemClip = !systemClip().isEmpty();
1949     d->currentBrush = QBrush();
1950
1951     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1952     d->stencilClean = true;
1953
1954     d->shaderManager = new QOpenGLEngineShaderManager(d->ctx);
1955
1956     glDisable(GL_STENCIL_TEST);
1957     glDisable(GL_DEPTH_TEST);
1958     glDisable(GL_SCISSOR_TEST);
1959
1960 #if !defined(QT_OPENGL_ES_2)
1961     glDisable(GL_MULTISAMPLE);
1962 #endif
1963
1964     d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
1965
1966 #if !defined(QT_OPENGL_ES_2)
1967         d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
1968 #endif
1969
1970 #if defined(QT_OPENGL_ES_2)
1971     // OpenGL ES can't switch MSAA off, so if the gl paint device is
1972     // multisampled, it's always multisampled.
1973     d->multisamplingAlwaysEnabled = d->device->context()->format().samples() > 1;
1974 #else
1975     d->multisamplingAlwaysEnabled = false;
1976 #endif
1977
1978     return true;
1979 }
1980
1981 bool QOpenGL2PaintEngineEx::end()
1982 {
1983     Q_D(QOpenGL2PaintEngineEx);
1984
1985     QOpenGLContext *ctx = d->ctx;
1986     d->funcs.glUseProgram(0);
1987     d->transferMode(BrushDrawingMode);
1988
1989     ctx->d_func()->active_engine = 0;
1990
1991     d->resetGLState();
1992
1993     delete d->shaderManager;
1994     d->shaderManager = 0;
1995     d->currentBrush = QBrush();
1996
1997 #ifdef QT_OPENGL_CACHE_AS_VBOS
1998     if (!d->unusedVBOSToClean.isEmpty()) {
1999         glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2000         d->unusedVBOSToClean.clear();
2001     }
2002     if (!d->unusedIBOSToClean.isEmpty()) {
2003         glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2004         d->unusedIBOSToClean.clear();
2005     }
2006 #endif
2007
2008     return false;
2009 }
2010
2011 void QOpenGL2PaintEngineEx::ensureActive()
2012 {
2013     Q_D(QOpenGL2PaintEngineEx);
2014     QOpenGLContext *ctx = d->ctx;
2015
2016     if (isActive() && ctx->d_func()->active_engine != this) {
2017         ctx->d_func()->active_engine = this;
2018         d->needsSync = true;
2019     }
2020
2021     if (d->needsSync) {
2022         d->device->ensureActiveTarget();
2023
2024         d->transferMode(BrushDrawingMode);
2025         glViewport(0, 0, d->width, d->height);
2026         d->needsSync = false;
2027         d->lastMaskTextureUsed = 0;
2028         d->shaderManager->setDirty();
2029         d->syncGlState();
2030         for (int i = 0; i < 3; ++i)
2031             d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2032         setState(state());
2033     }
2034 }
2035
2036 void QOpenGL2PaintEngineExPrivate::updateClipScissorTest()
2037 {
2038     Q_Q(QOpenGL2PaintEngineEx);
2039     if (q->state()->clipTestEnabled) {
2040         glEnable(GL_STENCIL_TEST);
2041         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2042     } else {
2043         glDisable(GL_STENCIL_TEST);
2044         glStencilFunc(GL_ALWAYS, 0, 0xff);
2045     }
2046
2047 #ifdef QT_GL_NO_SCISSOR_TEST
2048     currentScissorBounds = QRect(0, 0, width, height);
2049 #else
2050     QRect bounds = q->state()->rectangleClip;
2051     if (!q->state()->clipEnabled) {
2052         if (useSystemClip)
2053             bounds = systemClip.boundingRect();
2054         else
2055             bounds = QRect(0, 0, width, height);
2056     } else {
2057         if (useSystemClip)
2058             bounds = bounds.intersected(systemClip.boundingRect());
2059         else
2060             bounds = bounds.intersected(QRect(0, 0, width, height));
2061     }
2062
2063     currentScissorBounds = bounds;
2064
2065     if (bounds == QRect(0, 0, width, height)) {
2066         glDisable(GL_SCISSOR_TEST);
2067     } else {
2068         glEnable(GL_SCISSOR_TEST);
2069         setScissor(bounds);
2070     }
2071 #endif
2072 }
2073
2074 void QOpenGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2075 {
2076     const int left = rect.left();
2077     const int width = rect.width();
2078     int bottom = height - (rect.top() + rect.height());
2079     if (device->paintFlipped()) {
2080         bottom = rect.top();
2081     }
2082     const int height = rect.height();
2083
2084     glScissor(left, bottom, width, height);
2085 }
2086
2087 void QOpenGL2PaintEngineEx::clipEnabledChanged()
2088 {
2089     Q_D(QOpenGL2PaintEngineEx);
2090
2091     state()->clipChanged = true;
2092
2093     if (painter()->hasClipping())
2094         d->regenerateClip();
2095     else
2096         d->systemStateChanged();
2097 }
2098
2099 void QOpenGL2PaintEngineExPrivate::clearClip(uint value)
2100 {
2101     dirtyStencilRegion -= currentScissorBounds;
2102
2103     glStencilMask(0xff);
2104     glClearStencil(value);
2105     glClear(GL_STENCIL_BUFFER_BIT);
2106     glStencilMask(0x0);
2107
2108     q->state()->needsClipBufferClear = false;
2109 }
2110
2111 void QOpenGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2112 {
2113     transferMode(BrushDrawingMode);
2114
2115     if (snapToPixelGrid) {
2116         snapToPixelGrid = false;
2117         matrixDirty = true;
2118     }
2119
2120     if (matrixDirty)
2121         updateMatrix();
2122
2123     stencilClean = false;
2124
2125     const bool singlePass = !path.hasWindingFill()
2126         && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2127             || q->state()->needsClipBufferClear);
2128     const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2129
2130     if (q->state()->needsClipBufferClear)
2131         clearClip(1);
2132
2133     if (path.isEmpty()) {
2134         glEnable(GL_STENCIL_TEST);
2135         glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2136         return;
2137     }
2138
2139     if (q->state()->clipTestEnabled)
2140         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2141     else
2142         glStencilFunc(GL_ALWAYS, 0, 0xff);
2143
2144     vertexCoordinateArray.clear();
2145     vertexCoordinateArray.addPath(path, inverseScale, false);
2146
2147     if (!singlePass)
2148         fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2149
2150     glColorMask(false, false, false, false);
2151     glEnable(GL_STENCIL_TEST);
2152     useSimpleShader();
2153
2154     if (singlePass) {
2155         // Under these conditions we can set the new stencil value in a single
2156         // pass, by using the current value and the "new value" as the toggles
2157
2158         glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2159         glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2160         glStencilMask(value ^ referenceClipValue);
2161
2162         drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2163     } else {
2164         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2165         glStencilMask(0xff);
2166
2167         if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2168             // Pass when any clip bit is set, set high bit
2169             glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2170             composite(vertexCoordinateArray.boundingRect());
2171         }
2172
2173         // Pass when high bit is set, replace stencil value with new clip value
2174         glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2175
2176         composite(vertexCoordinateArray.boundingRect());
2177     }
2178
2179     glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2180     glStencilMask(0);
2181
2182     glColorMask(true, true, true, true);
2183 }
2184
2185 void QOpenGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2186 {
2187 //     qDebug("QOpenGL2PaintEngineEx::clip()");
2188     Q_D(QOpenGL2PaintEngineEx);
2189
2190     state()->clipChanged = true;
2191
2192     ensureActive();
2193
2194     if (op == Qt::ReplaceClip) {
2195         op = Qt::IntersectClip;
2196         if (d->hasClipOperations()) {
2197             d->systemStateChanged();
2198             state()->canRestoreClip = false;
2199         }
2200     }
2201
2202 #ifndef QT_GL_NO_SCISSOR_TEST
2203     if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2204         const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2205         QRectF rect(points[0], points[2]);
2206
2207         if (state()->matrix.type() <= QTransform::TxScale
2208             || (state()->matrix.type() == QTransform::TxRotate
2209                 && qFuzzyIsNull(state()->matrix.m11())
2210                 && qFuzzyIsNull(state()->matrix.m22())))
2211         {
2212             state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2213             d->updateClipScissorTest();
2214             return;
2215         }
2216     }
2217 #endif
2218
2219     const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2220
2221     switch (op) {
2222     case Qt::NoClip:
2223         if (d->useSystemClip) {
2224             state()->clipTestEnabled = true;
2225             state()->currentClip = 1;
2226         } else {
2227             state()->clipTestEnabled = false;
2228         }
2229         state()->rectangleClip = QRect(0, 0, d->width, d->height);
2230         state()->canRestoreClip = false;
2231         d->updateClipScissorTest();
2232         break;
2233     case Qt::IntersectClip:
2234         state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2235         d->updateClipScissorTest();
2236         d->resetClipIfNeeded();
2237         ++d->maxClip;
2238         d->writeClip(path, d->maxClip);
2239         state()->currentClip = d->maxClip;
2240         state()->clipTestEnabled = true;
2241         break;
2242     default:
2243         break;
2244     }
2245 }
2246
2247 void QOpenGL2PaintEngineExPrivate::regenerateClip()
2248 {
2249     systemStateChanged();
2250     replayClipOperations();
2251 }
2252
2253 void QOpenGL2PaintEngineExPrivate::systemStateChanged()
2254 {
2255     Q_Q(QOpenGL2PaintEngineEx);
2256
2257     q->state()->clipChanged = true;
2258
2259     if (systemClip.isEmpty()) {
2260         useSystemClip = false;
2261     } else {
2262         if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2263             //QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2264             //useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2265             useSystemClip = true;
2266         } else {
2267             useSystemClip = true;
2268         }
2269     }
2270
2271     q->state()->clipTestEnabled = false;
2272     q->state()->needsClipBufferClear = true;
2273
2274     q->state()->currentClip = 1;
2275     maxClip = 1;
2276
2277     q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2278     updateClipScissorTest();
2279
2280     if (systemClip.rectCount() == 1) {
2281         if (systemClip.boundingRect() == QRect(0, 0, width, height))
2282             useSystemClip = false;
2283 #ifndef QT_GL_NO_SCISSOR_TEST
2284         // scissoring takes care of the system clip
2285         return;
2286 #endif
2287     }
2288
2289     if (useSystemClip) {
2290         clearClip(0);
2291
2292         QPainterPath path;
2293         path.addRegion(systemClip);
2294
2295         q->state()->currentClip = 0;
2296         writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2297         q->state()->currentClip = 1;
2298         q->state()->clipTestEnabled = true;
2299     }
2300 }
2301
2302 void QOpenGL2PaintEngineEx::setState(QPainterState *new_state)
2303 {
2304     //     qDebug("QOpenGL2PaintEngineEx::setState()");
2305
2306     Q_D(QOpenGL2PaintEngineEx);
2307
2308     QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2309     QOpenGL2PaintEngineState *old_state = state();
2310
2311     QPaintEngineEx::setState(s);
2312
2313     if (s->isNew) {
2314         // Newly created state object.  The call to setState()
2315         // will either be followed by a call to begin(), or we are
2316         // setting the state as part of a save().
2317         s->isNew = false;
2318         return;
2319     }
2320
2321     // Setting the state as part of a restore().
2322
2323     if (old_state == s || old_state->renderHintsChanged)
2324         renderHintsChanged();
2325
2326     if (old_state == s || old_state->matrixChanged)
2327         d->matrixDirty = true;
2328
2329     if (old_state == s || old_state->compositionModeChanged)
2330         d->compositionModeDirty = true;
2331
2332     if (old_state == s || old_state->opacityChanged)
2333         d->opacityUniformDirty = true;
2334
2335     if (old_state == s || old_state->clipChanged) {
2336         if (old_state && old_state != s && old_state->canRestoreClip) {
2337             d->updateClipScissorTest();
2338             glDepthFunc(GL_LEQUAL);
2339         } else {
2340             d->regenerateClip();
2341         }
2342     }
2343 }
2344
2345 QPainterState *QOpenGL2PaintEngineEx::createState(QPainterState *orig) const
2346 {
2347     if (orig)
2348         const_cast<QOpenGL2PaintEngineEx *>(this)->ensureActive();
2349
2350     QOpenGL2PaintEngineState *s;
2351     if (!orig)
2352         s = new QOpenGL2PaintEngineState();
2353     else
2354         s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2355
2356     s->matrixChanged = false;
2357     s->compositionModeChanged = false;
2358     s->opacityChanged = false;
2359     s->renderHintsChanged = false;
2360     s->clipChanged = false;
2361
2362     return s;
2363 }
2364
2365 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2366     : QPainterState(other)
2367 {
2368     isNew = true;
2369     needsClipBufferClear = other.needsClipBufferClear;
2370     clipTestEnabled = other.clipTestEnabled;
2371     currentClip = other.currentClip;
2372     canRestoreClip = other.canRestoreClip;
2373     rectangleClip = other.rectangleClip;
2374 }
2375
2376 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2377 {
2378     isNew = true;
2379     needsClipBufferClear = true;
2380     clipTestEnabled = false;
2381     canRestoreClip = true;
2382 }
2383
2384 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2385 {
2386 }
2387
2388 void QOpenGL2PaintEngineExPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
2389 {
2390     Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
2391
2392     if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
2393         funcs.glDisableVertexAttribArray(arrayIndex);
2394
2395     if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
2396         funcs.glEnableVertexAttribArray(arrayIndex);
2397
2398     vertexAttributeArraysEnabledState[arrayIndex] = enabled;
2399 }
2400
2401 void QOpenGL2PaintEngineExPrivate::syncGlState()
2402 {
2403     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
2404         if (vertexAttributeArraysEnabledState[i])
2405             funcs.glEnableVertexAttribArray(i);
2406         else
2407             funcs.glDisableVertexAttribArray(i);
2408     }
2409 }
2410
2411
2412 QT_END_NAMESPACE