1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtGui module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
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
49 Updating uniforms should be cheap, so the overhead of updating up-to-date
50 uniforms should be minimal. It's also less complex.
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
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.
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.
65 // #define QT_OPENGL_CACHE_AS_VBOS
67 #include "qopenglgradientcache_p.h"
68 #include "qopengltexturecache_p.h"
69 #include "qopenglpaintengine_p.h"
71 #include <string.h> //for memcpy
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>
86 #include "qopenglengineshadermanager_p.h"
87 #include "qopengl2pexvertexarray_p.h"
88 #include "qopengltextureglyphcache_p.h"
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
102 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
104 ////////////////////////////////// Private Methods //////////////////////////////////////////
106 QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
108 delete shaderManager;
110 while (pathCaches.size()) {
111 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
112 e->cleanup(e->engine, e->data);
117 if (elementIndicesVBOId != 0) {
118 funcs.glDeleteBuffers(1, &elementIndicesVBOId);
119 elementIndicesVBOId = 0;
123 void QOpenGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
125 // funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
126 if (id != GLuint(-1) && id == lastTextureUsed)
129 lastTextureUsed = id;
131 if (smoothPixmapTransform) {
132 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
133 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
135 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
136 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138 glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
139 glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
143 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
145 qreal alpha = c.alphaF() * opacity;
147 c.setRedF(c.redF() * alpha);
148 c.setGreenF(c.greenF() * alpha);
149 c.setBlueF(c.blueF() * alpha);
154 void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
156 if (qbrush_fast_equals(currentBrush, brush))
159 const Qt::BrushStyle newStyle = qbrush_style(brush);
160 Q_ASSERT(newStyle != Qt::NoBrush);
162 currentBrush = brush;
163 if (!currentBrushPixmap.isNull())
164 currentBrushPixmap = QPixmap();
165 brushUniformsDirty = true; // All brushes have at least one uniform
167 if (newStyle > Qt::SolidPattern)
168 brushTextureDirty = true;
170 if (currentBrush.style() == Qt::TexturePattern
171 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
173 shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
175 shaderManager->setSrcPixelType(newStyle);
177 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
181 void QOpenGL2PaintEngineExPrivate::useSimpleShader()
183 shaderManager->useSimpleProgram();
189 void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
191 Q_Q(QOpenGL2PaintEngineEx);
192 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
193 Qt::BrushStyle style = currentBrush.style();
195 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
196 // Get the image data for the pattern
197 QImage texImage = qt_imageForBrush(style, false);
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);
203 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
204 // Gradiant brush: All the gradiants use the same texture
206 const QGradient* g = currentBrush.gradient();
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);
212 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
213 glBindTexture(GL_TEXTURE_2D, texId);
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);
220 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
222 else if (style == Qt::TexturePattern) {
223 currentBrushPixmap = currentBrush.texture();
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);
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;
234 brushTextureDirty = false;
238 void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
240 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
241 Qt::BrushStyle style = currentBrush.style();
243 if (style == Qt::NoBrush)
246 QTransform brushQTransform = currentBrush.transform();
248 if (style == Qt::SolidPattern) {
249 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
250 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
253 // All other brushes have a transform and thus need the translation point:
254 QPointF translationPoint;
256 if (style <= Qt::DiagCrossPattern) {
257 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
259 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
261 QVector2D halfViewportSize(width*0.5, height*0.5);
262 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
264 else if (style == Qt::LinearGradientPattern) {
265 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
267 QPointF realStart = g->start();
268 QPointF realFinal = g->finalStop();
269 translationPoint = realStart;
271 QPointF l = realFinal - realStart;
273 QVector3D linearData(
276 1.0f / (l.x() * l.x() + l.y() * l.y())
279 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);
281 QVector2D halfViewportSize(width*0.5, height*0.5);
282 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
284 else if (style == Qt::ConicalGradientPattern) {
285 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
286 translationPoint = g->center();
288 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
290 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);
292 QVector2D halfViewportSize(width*0.5, height*0.5);
293 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
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;
302 QPointF fmp = realCenter - realFocal;
303 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);
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()),
314 g->centerRadius() - g->focalRadius());
316 QVector2D halfViewportSize(width*0.5, height*0.5);
317 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
319 else if (style == Qt::TexturePattern) {
320 const QPixmap& texPixmap = currentBrush.texture();
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);
327 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
328 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
330 QVector2D halfViewportSize(width*0.5, height*0.5);
331 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
334 qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");
336 const QPointF &brushOrigin = q->state()->brushOrigin;
337 QTransform matrix = q->state()->matrix;
338 matrix.translate(brushOrigin.x(), brushOrigin.y());
340 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
343 if (device->paintFlipped()) {
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;
352 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
354 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
355 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
357 brushUniformsDirty = false;
361 // This assumes the shader manager has already setup the correct shader program
362 void QOpenGL2PaintEngineExPrivate::updateMatrix()
364 // qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");
366 const QTransform& transform = q->state()->matrix;
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
373 // This results in the Projection matrix below, which is multiplied by the painter's
374 // transformation matrix, as shown below:
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 // ------------------------------------------------ ------------------------
383 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
385 const GLfloat wfactor = 2.0f / width;
386 GLfloat hfactor = -2.0f / height;
388 GLfloat dx = transform.dx();
389 GLfloat dy = transform.dy();
391 if (device->paintFlipped()) {
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);
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();
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())) ),
420 matrixUniformDirty = true;
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]);
428 dasher.setInvScale(inverseScale);
429 stroker.setInvScale(inverseScale);
433 void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
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);
442 case QPainter::CompositionMode_DestinationOver:
443 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
445 case QPainter::CompositionMode_Clear:
446 glBlendFunc(GL_ZERO, GL_ZERO);
448 case QPainter::CompositionMode_Source:
449 glBlendFunc(GL_ONE, GL_ZERO);
451 case QPainter::CompositionMode_Destination:
452 glBlendFunc(GL_ZERO, GL_ONE);
454 case QPainter::CompositionMode_SourceIn:
455 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
457 case QPainter::CompositionMode_DestinationIn:
458 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
460 case QPainter::CompositionMode_SourceOut:
461 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
463 case QPainter::CompositionMode_DestinationOut:
464 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
466 case QPainter::CompositionMode_SourceAtop:
467 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
469 case QPainter::CompositionMode_DestinationAtop:
470 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
472 case QPainter::CompositionMode_Xor:
473 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
475 case QPainter::CompositionMode_Plus:
476 glBlendFunc(GL_ONE, GL_ONE);
479 qWarning("Unsupported composition mode");
483 compositionModeDirty = false;
486 static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
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;
498 void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
500 // Setup for texture drawing
501 currentBrush = noBrush;
502 shaderManager->setSrcPixelType(pattern ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
504 if (snapToPixelGrid) {
505 snapToPixelGrid = false;
509 if (prepareForDraw(opaque))
510 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
513 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
514 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
517 GLfloat dx = 1.0 / textureSize.width();
518 GLfloat dy = 1.0 / textureSize.height();
520 QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
522 setCoords(staticVertexCoordinateArray, dest);
523 setCoords(staticTextureCoordinateArray, srcTextureRect);
525 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
528 void QOpenGL2PaintEngineEx::beginNativePainting()
530 Q_D(QOpenGL2PaintEngineEx);
532 d->transferMode(BrushDrawingMode);
534 d->nativePaintingActive = true;
536 d->funcs.glUseProgram(0);
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);
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)
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
551 const QTransform& mtx = state()->matrix;
553 float mv_matrix[4][4] =
555 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
556 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
558 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
561 const QSize sz = d->device->size();
563 glMatrixMode(GL_PROJECTION);
565 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
567 glMatrixMode(GL_MODELVIEW);
568 glLoadMatrixf(&mv_matrix[0][0]);
572 d->lastTextureUsed = GLuint(-1);
573 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
576 d->shaderManager->setDirty();
581 void QOpenGL2PaintEngineExPrivate::resetGLState()
584 funcs.glActiveTexture(GL_TEXTURE0);
585 glDisable(GL_STENCIL_TEST);
586 glDisable(GL_DEPTH_TEST);
587 glDisable(GL_SCISSOR_TEST);
589 glDepthFunc(GL_LESS);
590 funcs.glClearDepthf(1);
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);
604 void QOpenGL2PaintEngineEx::endNativePainting()
606 Q_D(QOpenGL2PaintEngineEx);
608 d->nativePaintingActive = false;
611 void QOpenGL2PaintEngineEx::invalidateState()
613 Q_D(QOpenGL2PaintEngineEx);
617 bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
618 Q_D(const QOpenGL2PaintEngineEx);
619 return d->nativePaintingActive;
622 void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
627 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
628 lastTextureUsed = GLuint(-1);
631 if (newMode == TextDrawingMode) {
632 shaderManager->setHasComplexGeometry(true);
634 shaderManager->setHasComplexGeometry(false);
637 if (newMode == ImageDrawingMode) {
638 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
639 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
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());
648 // This needs to change when we implement high-quality anti-aliasing...
649 if (newMode != TextDrawingMode)
650 shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
655 struct QOpenGL2PEVectorPathCache
657 #ifdef QT_OPENGL_CACHE_AS_VBOS
666 GLenum primitiveType;
668 QVertexIndexVector::Type indexType;
671 void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
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;
678 d->unusedIBOSToClean << c->ibo;
687 // Assumes everything is configured for the brush you want to use
688 void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
690 transferMode(BrushDrawingMode);
692 if (snapToPixelGrid) {
693 snapToPixelGrid = false;
697 // Might need to call updateMatrix to re-calculate inverseScale
701 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
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());
708 } else if (path.isConvex()) {
710 if (path.isCacheable()) {
711 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
712 QOpenGL2PEVectorPathCache *cache;
714 bool updateCache = false;
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);
725 Q_ASSERT(cache->ibo == 0);
727 free(cache->vertices);
728 Q_ASSERT(cache->indices == 0);
734 cache = new QOpenGL2PEVectorPathCache;
735 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
739 // Flatten the path at the current scale factor and fill it into the cache struct.
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);
755 cache->vertices = (float *) malloc(floatSizeInBytes);
756 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
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);
766 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
768 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
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);
781 bool useCache = path.isCacheable();
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);
792 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
793 QOpenGL2PEVectorPathCache *cache;
795 bool updateCache = false;
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);
807 free(cache->vertices);
808 free(cache->indices);
814 cache = new QOpenGL2PEVectorPathCache;
815 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
819 // Flatten the path at the current scale factor and fill it into the cache struct.
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);
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);
836 funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
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);
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());
848 cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
849 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
851 for (int i = 0; i < polys.vertices.size(); ++i)
852 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
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);
864 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
865 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
866 glBindBuffer(GL_ARRAY_BUFFER, 0);
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);
872 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
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();
880 if (device->context()->format().stencilBufferSize() == 0) {
881 // If there is no stencil buffer, triangulate the path instead.
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);
890 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
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));
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());
901 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
903 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
904 qWarning("Painter path exceeds +/-32767 pixels.");
909 // The path is too complicated & needs the stencil technique
910 vertexCoordinateArray.clear();
911 vertexCoordinateArray.addPath(path, inverseScale, false);
913 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
916 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
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);
925 // Pass when high bit is set, replace stencil value with 0
926 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
928 prepareForDraw(currentBrush.isOpaque());
930 // Stencil the brush onto the dest buffer
931 composite(vertexCoordinateArray.boundingRect());
933 updateClipScissorTest();
939 void QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
943 const QOpenGLRect &bounds,
944 StencilFillMode mode)
946 Q_ASSERT(count || stops);
948 // qDebug("QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
949 glStencilMask(0xff); // Enable stencil writes
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));
958 glClear(GL_STENCIL_BUFFER_BIT);
961 dirtyStencilRegion -= currentScissorBounds;
963 #ifndef QT_GL_NO_SCISSOR_TEST
964 updateClipScissorTest();
968 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
970 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
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);
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);
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);
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);
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);
1007 } else { // TriStripStrokeFillMode
1008 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1009 glStencilMask(GL_STENCIL_HIGH_BIT);
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);
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);
1021 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1023 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1024 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1028 // Enable color writes & disable stencil writes
1029 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
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.
1037 void QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
1039 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1042 Q_Q(QOpenGL2PaintEngineEx);
1045 glEnable(GL_STENCIL_TEST);
1046 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1048 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1049 QOpenGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
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);
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);
1063 q->state()->currentClip = 1;
1064 q->state()->canRestoreClip = false;
1069 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1072 bool QOpenGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1074 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1075 updateBrushTexture();
1077 if (compositionModeDirty)
1078 updateCompositionMode();
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))
1088 glDisable(GL_BLEND);
1093 QOpenGLEngineShaderManager::OpacityMode opacityMode;
1094 if (mode == ImageArrayDrawingMode) {
1095 opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
1097 opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
1098 : QOpenGLEngineShaderManager::NoOpacity;
1099 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1101 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1102 (currentBrush.style() <= Qt::DiagCrossPattern);
1104 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1105 opacityMode = QOpenGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1108 shaderManager->setOpacityMode(opacityMode);
1110 bool changed = shaderManager->useCorrectShaderProg();
1111 // If the shader program needs changing, we change it and mark all uniforms as dirty
1113 // The shader program has changed so mark all uniforms as dirty:
1114 brushUniformsDirty = true;
1115 opacityUniformDirty = true;
1116 matrixUniformDirty = true;
1119 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1120 updateBrushUniforms();
1122 if (opacityMode == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1123 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1124 opacityUniformDirty = false;
1127 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1128 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
1130 matrixUniformDirty = false;
1136 void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& boundingRect)
1138 setCoords(staticVertexCoordinateArray, boundingRect);
1139 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1140 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1143 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1144 void QOpenGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1147 // Now setup the pointer to the vertex array:
1148 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1150 int previousStop = 0;
1151 for (int i=0; i<stopCount; ++i) {
1152 int stop = stops[i];
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);
1158 glDrawArrays(primitive, previousStop, stop - previousStop);
1159 previousStop = stop;
1163 /////////////////////////////////// Public Methods //////////////////////////////////////////
1165 QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
1166 : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
1170 QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
1174 void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1176 Q_D(QOpenGL2PaintEngineEx);
1178 if (qbrush_style(brush) == Qt::NoBrush)
1185 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1188 void QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1190 Q_D(QOpenGL2PaintEngineEx);
1192 const QBrush &penBrush = qpen_brush(pen);
1193 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1196 QOpenGL2PaintEngineState *s = state();
1197 if (qt_pen_is_cosmetic(pen, state()->renderHints) && !qt_scaleForTransform(s->transform(), 0)) {
1198 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1199 QPaintEngineEx::stroke(path, pen);
1204 d->setBrush(penBrush);
1205 d->stroke(path, pen);
1208 void QOpenGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1210 const QOpenGL2PaintEngineState *s = q->state();
1211 if (snapToPixelGrid) {
1212 snapToPixelGrid = false;
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;
1220 transferMode(BrushDrawingMode);
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.
1227 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1228 ? q->state()->rectangleClip
1229 : QRectF(0, 0, width, height));
1231 if (penStyle == Qt::SolidLine) {
1232 stroker.process(path, pen, clip, s->renderHints);
1234 } else { // Some sort of dash
1235 dasher.process(path, pen, clip, s->renderHints);
1237 QVectorPath dashStroke(dasher.points(),
1238 dasher.elementCount(),
1239 dasher.elementTypes(),
1241 stroker.process(dashStroke, pen, clip, s->renderHints);
1244 if (!stroker.vertexCount())
1248 prepareForDraw(opaque);
1249 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1250 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1252 // QBrush b(Qt::green);
1254 // d->prepareForDraw(true);
1255 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1258 qreal width = qpen_widthf(pen) / 2;
1261 qreal extra = pen.joinStyle() == Qt::MiterJoin
1262 ? qMax(pen.miterLimit() * width, width)
1265 if (qt_pen_is_cosmetic(pen, q->state()->renderHints))
1266 extra = extra * inverseScale;
1268 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1270 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1271 0, 0, bounds, QOpenGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1273 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1275 // Pass when any bit is set, replace stencil value with 0
1276 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1277 prepareForDraw(false);
1279 // Stencil the brush onto the dest buffer
1284 updateClipScissorTest();
1288 void QOpenGL2PaintEngineEx::penChanged() { }
1289 void QOpenGL2PaintEngineEx::brushChanged() { }
1290 void QOpenGL2PaintEngineEx::brushOriginChanged() { }
1292 void QOpenGL2PaintEngineEx::opacityChanged()
1294 // qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
1295 Q_D(QOpenGL2PaintEngineEx);
1296 state()->opacityChanged = true;
1298 Q_ASSERT(d->shaderManager);
1299 d->brushUniformsDirty = true;
1300 d->opacityUniformDirty = true;
1303 void QOpenGL2PaintEngineEx::compositionModeChanged()
1305 // qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
1306 Q_D(QOpenGL2PaintEngineEx);
1307 state()->compositionModeChanged = true;
1308 d->compositionModeDirty = true;
1311 void QOpenGL2PaintEngineEx::renderHintsChanged()
1313 state()->renderHintsChanged = true;
1315 #if !defined(QT_OPENGL_ES_2)
1316 if ((state()->renderHints & QPainter::Antialiasing)
1317 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1318 glEnable(GL_MULTISAMPLE);
1320 glDisable(GL_MULTISAMPLE);
1323 Q_D(QOpenGL2PaintEngineEx);
1324 d->lastTextureUsed = GLuint(-1);
1325 d->brushTextureDirty = true;
1326 // qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
1329 void QOpenGL2PaintEngineEx::transformChanged()
1331 Q_D(QOpenGL2PaintEngineEx);
1332 d->matrixDirty = true;
1333 state()->matrixChanged = true;
1337 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1339 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1342 void QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1344 Q_D(QOpenGL2PaintEngineEx);
1345 QOpenGLContext *ctx = d->ctx;
1347 int max_texture_size = ctx->d_func()->maxTextureSize();
1348 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1349 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1351 const qreal sx = scaled.width() / qreal(pixmap.width());
1352 const qreal sy = scaled.height() / qreal(pixmap.height());
1354 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1359 d->transferMode(ImageDrawingMode);
1361 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1362 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1364 QOpenGLRect srcRect(src.left(), src.top(), src.right(), src.bottom());
1366 bool isBitmap = pixmap.isQBitmap();
1367 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1369 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1370 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1371 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1374 void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1375 Qt::ImageConversionFlags)
1377 Q_D(QOpenGL2PaintEngineEx);
1378 QOpenGLContext *ctx = d->ctx;
1380 int max_texture_size = ctx->d_func()->maxTextureSize();
1381 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1382 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1384 const qreal sx = scaled.width() / qreal(image.width());
1385 const qreal sy = scaled.height() / qreal(image.height());
1387 drawImage(dest, scaled, scaleRect(src, sx, sy));
1392 d->transferMode(ImageDrawingMode);
1394 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1396 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
1398 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1399 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1400 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1403 void QOpenGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1405 Q_D(QOpenGL2PaintEngineEx);
1409 QPainterState *s = state();
1410 float det = s->matrix.determinant();
1412 // don't try to cache huge fonts or vastly transformed fonts
1413 QFontEngine *fontEngine = textItem->fontEngine();
1414 if (shouldDrawCachedGlyphs(fontEngine, s->matrix) && det >= 0.25f && det <= 4.f) {
1415 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1416 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1417 : d->glyphCacheType;
1418 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1419 if (d->device->context()->format().alphaBufferSize() > 0 || s->matrix.type() > QTransform::TxTranslate
1420 || (s->composition_mode != QPainter::CompositionMode_Source
1421 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1423 glyphType = QFontEngineGlyphCache::Raster_A8;
1427 d->drawCachedGlyphs(glyphType, textItem);
1429 QPaintEngineEx::drawStaticTextItem(textItem);
1433 bool QOpenGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1435 Q_D(QOpenGL2PaintEngineEx);
1436 if (!d->shaderManager)
1440 d->transferMode(ImageDrawingMode);
1442 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1443 glBindTexture(GL_TEXTURE_2D, textureId);
1445 QOpenGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1447 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1448 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1449 d->drawTexture(dest, srcRect, size, false);
1453 void QOpenGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1455 Q_D(QOpenGL2PaintEngineEx);
1458 QOpenGL2PaintEngineState *s = state();
1460 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1462 QTransform::TransformationType txtype = s->matrix.type();
1464 float det = s->matrix.determinant();
1465 bool drawCached = txtype < QTransform::TxProject;
1467 // don't try to cache huge fonts or vastly transformed fonts
1468 if (!shouldDrawCachedGlyphs(ti.fontEngine, s->matrix) || det < 0.25f || det > 4.f)
1471 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1472 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1473 : d->glyphCacheType;
1476 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1477 if (d->device->context()->format().alphaBufferSize() > 0 || txtype > QTransform::TxTranslate
1478 || (state()->composition_mode != QPainter::CompositionMode_Source
1479 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1481 glyphType = QFontEngineGlyphCache::Raster_A8;
1486 QVarLengthArray<QFixedPoint> positions;
1487 QVarLengthArray<glyph_t> glyphs;
1488 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1489 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1492 QStaticTextItem staticTextItem;
1493 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1494 staticTextItem.setFontEngine(ti.fontEngine);
1495 staticTextItem.glyphs = glyphs.data();
1496 staticTextItem.numChars = ti.num_chars;
1497 staticTextItem.numGlyphs = glyphs.size();
1498 staticTextItem.glyphPositions = positions.data();
1500 d->drawCachedGlyphs(glyphType, &staticTextItem);
1505 QPaintEngineEx::drawTextItem(p, ti);
1510 class QOpenGLStaticTextUserData: public QStaticTextUserData
1513 QOpenGLStaticTextUserData()
1514 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1518 ~QOpenGLStaticTextUserData()
1523 QOpenGL2PEXVertexArray vertexCoordinateArray;
1524 QOpenGL2PEXVertexArray textureCoordinateArray;
1525 QFontEngineGlyphCache::Type glyphType;
1526 int cacheSerialNumber;
1532 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1534 void QOpenGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1535 QStaticTextItem *staticTextItem)
1537 Q_Q(QOpenGL2PaintEngineEx);
1539 QOpenGL2PaintEngineState *s = q->state();
1541 void *cacheKey = ctx->shareGroup();
1542 bool recreateVertexArrays = false;
1543 QFontEngine *fe = staticTextItem->fontEngine();
1545 QOpenGLTextureGlyphCache *cache =
1546 (QOpenGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphType, QTransform());
1547 if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1548 cache = new QOpenGLTextureGlyphCache(glyphType, QTransform());
1549 fe->setGlyphCache(cacheKey, cache);
1550 recreateVertexArrays = true;
1553 if (staticTextItem->userDataNeedsUpdate) {
1554 recreateVertexArrays = true;
1555 } else if (staticTextItem->userData() == 0) {
1556 recreateVertexArrays = true;
1557 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1558 recreateVertexArrays = true;
1560 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1561 if (userData->glyphType != glyphType) {
1562 recreateVertexArrays = true;
1563 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1564 recreateVertexArrays = true;
1568 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1569 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1570 // cache so this text is performed before we test if the cache size has changed.
1571 if (recreateVertexArrays) {
1572 cache->setPaintEnginePrivate(this);
1573 if (!cache->populate(fe, staticTextItem->numGlyphs,
1574 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1575 // No space for glyphs in cache. We need to reset it and try again.
1577 cache->populate(fe, staticTextItem->numGlyphs,
1578 staticTextItem->glyphs, staticTextItem->glyphPositions);
1580 cache->fillInPendingGlyphs();
1583 if (cache->width() == 0 || cache->height() == 0)
1586 transferMode(TextDrawingMode);
1588 int margin = fe->glyphMargin(glyphType);
1590 GLfloat dx = 1.0 / cache->width();
1591 GLfloat dy = 1.0 / cache->height();
1593 // Use global arrays by default
1594 QOpenGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1595 QOpenGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1597 if (staticTextItem->useBackendOptimizations) {
1598 QOpenGLStaticTextUserData *userData = 0;
1600 if (staticTextItem->userData() == 0
1601 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1603 userData = new QOpenGLStaticTextUserData();
1604 staticTextItem->setUserData(userData);
1607 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1610 userData->glyphType = glyphType;
1611 userData->cacheSerialNumber = cache->serialNumber();
1613 // Use cache if backend optimizations is turned on
1614 vertexCoordinates = &userData->vertexCoordinateArray;
1615 textureCoordinates = &userData->textureCoordinateArray;
1617 QSize size(cache->width(), cache->height());
1618 if (userData->cacheSize != size) {
1619 recreateVertexArrays = true;
1620 userData->cacheSize = size;
1624 if (recreateVertexArrays) {
1625 vertexCoordinates->clear();
1626 textureCoordinates->clear();
1628 bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1629 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1630 QFixed subPixelPosition;
1631 if (supportsSubPixelPositions)
1632 subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1634 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1636 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1640 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1641 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1643 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1644 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1647 staticTextItem->userDataNeedsUpdate = false;
1650 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1654 if (elementIndices.size() < numGlyphs*6) {
1655 Q_ASSERT(elementIndices.size() % 6 == 0);
1656 int j = elementIndices.size() / 6 * 4;
1657 while (j < numGlyphs*4) {
1658 elementIndices.append(j + 0);
1659 elementIndices.append(j + 0);
1660 elementIndices.append(j + 1);
1661 elementIndices.append(j + 2);
1662 elementIndices.append(j + 3);
1663 elementIndices.append(j + 3);
1668 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1669 if (elementIndicesVBOId == 0)
1670 glGenBuffers(1, &elementIndicesVBOId);
1672 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1673 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1674 elementIndices.constData(), GL_STATIC_DRAW);
1677 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1678 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1682 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1683 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1685 if (!snapToPixelGrid) {
1686 snapToPixelGrid = true;
1690 QBrush pensBrush = q->state()->pen.brush();
1691 setBrush(pensBrush);
1693 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1695 // Subpixel antialiasing without gamma correction
1697 QPainter::CompositionMode compMode = q->state()->composition_mode;
1698 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1699 || compMode == QPainter::CompositionMode_SourceOver);
1701 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass1);
1703 if (pensBrush.style() == Qt::SolidPattern) {
1704 // Solid patterns can get away with only one pass.
1705 QColor c = pensBrush.color();
1706 qreal oldOpacity = q->state()->opacity;
1707 if (compMode == QPainter::CompositionMode_Source) {
1708 c = qt_premultiplyColor(c, q->state()->opacity);
1709 q->state()->opacity = 1;
1710 opacityUniformDirty = true;
1713 compositionModeDirty = false; // I can handle this myself, thank you very much
1714 prepareForDraw(false); // Text always causes src pixels to be transparent
1716 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1717 if (compMode == QPainter::CompositionMode_Source) {
1718 q->state()->opacity = oldOpacity;
1719 opacityUniformDirty = true;
1723 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1724 funcs.glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1726 // Other brush styles need two passes.
1728 qreal oldOpacity = q->state()->opacity;
1729 if (compMode == QPainter::CompositionMode_Source) {
1730 q->state()->opacity = 1;
1731 opacityUniformDirty = true;
1732 pensBrush = Qt::white;
1733 setBrush(pensBrush);
1736 compositionModeDirty = false; // I can handle this myself, thank you very much
1737 prepareForDraw(false); // Text always causes src pixels to be transparent
1739 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1741 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1742 glBindTexture(GL_TEXTURE_2D, cache->texture());
1743 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1745 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1746 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1748 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1751 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass2);
1753 if (compMode == QPainter::CompositionMode_Source) {
1754 q->state()->opacity = oldOpacity;
1755 opacityUniformDirty = true;
1756 pensBrush = q->state()->pen.brush();
1757 setBrush(pensBrush);
1760 compositionModeDirty = false;
1761 prepareForDraw(false); // Text always causes src pixels to be transparent
1763 glBlendFunc(GL_ONE, GL_ONE);
1765 compositionModeDirty = true;
1767 // Greyscale/mono glyphs
1769 shaderManager->setMaskType(QOpenGLEngineShaderManager::PixelMask);
1770 prepareForDraw(false); // Text always causes src pixels to be transparent
1773 QOpenGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QOpenGLTextureGlyphCache::Linear:QOpenGLTextureGlyphCache::Nearest;
1774 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1776 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1777 if (lastMaskTextureUsed != cache->texture()) {
1778 glBindTexture(GL_TEXTURE_2D, cache->texture());
1779 lastMaskTextureUsed = cache->texture();
1782 if (cache->filterMode() != filterMode) {
1783 if (filterMode == QOpenGLTextureGlyphCache::Linear) {
1784 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1785 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1787 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1788 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1790 cache->setFilterMode(filterMode);
1794 bool srgbFrameBufferEnabled = false;
1795 if (funcs.hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer)) {
1798 glEnable(GL_FRAMEBUFFER_SRGB);
1799 srgbFrameBufferEnabled = true;
1803 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1804 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1805 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1807 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1810 if (srgbFrameBufferEnabled)
1811 glDisable(GL_FRAMEBUFFER_SRGB);
1815 void QOpenGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1816 QPainter::PixmapFragmentHints hints)
1818 Q_D(QOpenGL2PaintEngineEx);
1819 // Use fallback for extended composition modes.
1820 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1821 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1826 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1827 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1828 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1829 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1831 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1836 void QOpenGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1837 int fragmentCount, const QPixmap &pixmap,
1838 QPainter::PixmapFragmentHints hints)
1840 GLfloat dx = 1.0f / pixmap.size().width();
1841 GLfloat dy = 1.0f / pixmap.size().height();
1843 vertexCoordinateArray.clear();
1844 textureCoordinateArray.clear();
1845 opacityArray.reset();
1847 if (snapToPixelGrid) {
1848 snapToPixelGrid = false;
1852 bool allOpaque = true;
1854 for (int i = 0; i < fragmentCount; ++i) {
1857 if (fragments[i].rotation != 0) {
1858 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1859 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1862 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1863 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1864 QOpenGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1865 QOpenGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1867 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1868 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1869 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1870 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1871 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1872 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1874 QOpenGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1875 (fragments[i].sourceLeft + fragments[i].width) * dx,
1876 (fragments[i].sourceTop + fragments[i].height) * dy);
1878 textureCoordinateArray.addVertex(src.right, src.bottom);
1879 textureCoordinateArray.addVertex(src.right, src.top);
1880 textureCoordinateArray.addVertex(src.left, src.top);
1881 textureCoordinateArray.addVertex(src.left, src.top);
1882 textureCoordinateArray.addVertex(src.left, src.bottom);
1883 textureCoordinateArray.addVertex(src.right, src.bottom);
1885 qreal opacity = fragments[i].opacity * q->state()->opacity;
1886 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1887 allOpaque &= (opacity >= 0.99f);
1890 funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1891 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1892 transferMode(ImageArrayDrawingMode);
1894 bool isBitmap = pixmap.isQBitmap();
1895 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1897 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1898 q->state()->renderHints & QPainter::SmoothPixmapTransform, id);
1900 // Setup for texture drawing
1901 currentBrush = noBrush;
1902 shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc
1903 : QOpenGLEngineShaderManager::ImageSrc);
1904 if (prepareForDraw(isOpaque))
1905 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1908 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1909 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
1912 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1915 bool QOpenGL2PaintEngineEx::begin(QPaintDevice *pdev)
1917 Q_D(QOpenGL2PaintEngineEx);
1919 Q_ASSERT(pdev->devType() == QInternal::OpenGL);
1920 d->device = static_cast<QOpenGLPaintDevice*>(pdev);
1925 if (d->device->context() != QOpenGLContext::currentContext()) {
1926 qWarning("QPainter::begin(): QOpenGLPaintDevice's context needs to be current");
1930 d->ctx = QOpenGLContext::currentContext();
1931 d->ctx->d_func()->active_engine = this;
1933 d->funcs.initializeOpenGLFunctions();
1935 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1936 d->vertexAttributeArraysEnabledState[i] = false;
1938 const QSize sz = d->device->size();
1939 d->width = sz.width();
1940 d->height = sz.height();
1941 d->mode = BrushDrawingMode;
1942 d->brushTextureDirty = true;
1943 d->brushUniformsDirty = true;
1944 d->matrixUniformDirty = true;
1945 d->matrixDirty = true;
1946 d->compositionModeDirty = true;
1947 d->opacityUniformDirty = true;
1948 d->needsSync = true;
1949 d->useSystemClip = !systemClip().isEmpty();
1950 d->currentBrush = QBrush();
1952 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1953 d->stencilClean = true;
1955 d->shaderManager = new QOpenGLEngineShaderManager(d->ctx);
1957 glDisable(GL_STENCIL_TEST);
1958 glDisable(GL_DEPTH_TEST);
1959 glDisable(GL_SCISSOR_TEST);
1961 #if !defined(QT_OPENGL_ES_2)
1962 glDisable(GL_MULTISAMPLE);
1965 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
1967 #if !defined(QT_OPENGL_ES_2)
1968 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
1971 #if defined(QT_OPENGL_ES_2)
1972 // OpenGL ES can't switch MSAA off, so if the gl paint device is
1973 // multisampled, it's always multisampled.
1974 d->multisamplingAlwaysEnabled = d->device->context()->format().samples() > 1;
1976 d->multisamplingAlwaysEnabled = false;
1982 bool QOpenGL2PaintEngineEx::end()
1984 Q_D(QOpenGL2PaintEngineEx);
1986 QOpenGLContext *ctx = d->ctx;
1987 d->funcs.glUseProgram(0);
1988 d->transferMode(BrushDrawingMode);
1990 ctx->d_func()->active_engine = 0;
1994 delete d->shaderManager;
1995 d->shaderManager = 0;
1996 d->currentBrush = QBrush();
1998 #ifdef QT_OPENGL_CACHE_AS_VBOS
1999 if (!d->unusedVBOSToClean.isEmpty()) {
2000 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2001 d->unusedVBOSToClean.clear();
2003 if (!d->unusedIBOSToClean.isEmpty()) {
2004 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2005 d->unusedIBOSToClean.clear();
2012 void QOpenGL2PaintEngineEx::ensureActive()
2014 Q_D(QOpenGL2PaintEngineEx);
2015 QOpenGLContext *ctx = d->ctx;
2017 if (isActive() && ctx->d_func()->active_engine != this) {
2018 ctx->d_func()->active_engine = this;
2019 d->needsSync = true;
2023 d->device->ensureActiveTarget();
2025 d->transferMode(BrushDrawingMode);
2026 glViewport(0, 0, d->width, d->height);
2027 d->needsSync = false;
2028 d->lastMaskTextureUsed = 0;
2029 d->shaderManager->setDirty();
2031 for (int i = 0; i < 3; ++i)
2032 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2037 void QOpenGL2PaintEngineExPrivate::updateClipScissorTest()
2039 Q_Q(QOpenGL2PaintEngineEx);
2040 if (q->state()->clipTestEnabled) {
2041 glEnable(GL_STENCIL_TEST);
2042 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2044 glDisable(GL_STENCIL_TEST);
2045 glStencilFunc(GL_ALWAYS, 0, 0xff);
2048 #ifdef QT_GL_NO_SCISSOR_TEST
2049 currentScissorBounds = QRect(0, 0, width, height);
2051 QRect bounds = q->state()->rectangleClip;
2052 if (!q->state()->clipEnabled) {
2054 bounds = systemClip.boundingRect();
2056 bounds = QRect(0, 0, width, height);
2059 bounds = bounds.intersected(systemClip.boundingRect());
2061 bounds = bounds.intersected(QRect(0, 0, width, height));
2064 currentScissorBounds = bounds;
2066 if (bounds == QRect(0, 0, width, height)) {
2067 glDisable(GL_SCISSOR_TEST);
2069 glEnable(GL_SCISSOR_TEST);
2075 void QOpenGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2077 const int left = rect.left();
2078 const int width = rect.width();
2079 int bottom = height - (rect.top() + rect.height());
2080 if (device->paintFlipped()) {
2081 bottom = rect.top();
2083 const int height = rect.height();
2085 glScissor(left, bottom, width, height);
2088 void QOpenGL2PaintEngineEx::clipEnabledChanged()
2090 Q_D(QOpenGL2PaintEngineEx);
2092 state()->clipChanged = true;
2094 if (painter()->hasClipping())
2095 d->regenerateClip();
2097 d->systemStateChanged();
2100 void QOpenGL2PaintEngineExPrivate::clearClip(uint value)
2102 dirtyStencilRegion -= currentScissorBounds;
2104 glStencilMask(0xff);
2105 glClearStencil(value);
2106 glClear(GL_STENCIL_BUFFER_BIT);
2109 q->state()->needsClipBufferClear = false;
2112 void QOpenGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2114 transferMode(BrushDrawingMode);
2116 if (snapToPixelGrid) {
2117 snapToPixelGrid = false;
2124 stencilClean = false;
2126 const bool singlePass = !path.hasWindingFill()
2127 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2128 || q->state()->needsClipBufferClear);
2129 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2131 if (q->state()->needsClipBufferClear)
2134 if (path.isEmpty()) {
2135 glEnable(GL_STENCIL_TEST);
2136 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2140 if (q->state()->clipTestEnabled)
2141 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2143 glStencilFunc(GL_ALWAYS, 0, 0xff);
2145 vertexCoordinateArray.clear();
2146 vertexCoordinateArray.addPath(path, inverseScale, false);
2149 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2151 glColorMask(false, false, false, false);
2152 glEnable(GL_STENCIL_TEST);
2156 // Under these conditions we can set the new stencil value in a single
2157 // pass, by using the current value and the "new value" as the toggles
2159 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2160 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2161 glStencilMask(value ^ referenceClipValue);
2163 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2165 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2166 glStencilMask(0xff);
2168 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2169 // Pass when any clip bit is set, set high bit
2170 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2171 composite(vertexCoordinateArray.boundingRect());
2174 // Pass when high bit is set, replace stencil value with new clip value
2175 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2177 composite(vertexCoordinateArray.boundingRect());
2180 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2183 glColorMask(true, true, true, true);
2186 void QOpenGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2188 // qDebug("QOpenGL2PaintEngineEx::clip()");
2189 Q_D(QOpenGL2PaintEngineEx);
2191 state()->clipChanged = true;
2195 if (op == Qt::ReplaceClip) {
2196 op = Qt::IntersectClip;
2197 if (d->hasClipOperations()) {
2198 d->systemStateChanged();
2199 state()->canRestoreClip = false;
2203 #ifndef QT_GL_NO_SCISSOR_TEST
2204 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2205 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2206 QRectF rect(points[0], points[2]);
2208 if (state()->matrix.type() <= QTransform::TxScale
2209 || (state()->matrix.type() == QTransform::TxRotate
2210 && qFuzzyIsNull(state()->matrix.m11())
2211 && qFuzzyIsNull(state()->matrix.m22())))
2213 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2214 d->updateClipScissorTest();
2220 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2224 if (d->useSystemClip) {
2225 state()->clipTestEnabled = true;
2226 state()->currentClip = 1;
2228 state()->clipTestEnabled = false;
2230 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2231 state()->canRestoreClip = false;
2232 d->updateClipScissorTest();
2234 case Qt::IntersectClip:
2235 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2236 d->updateClipScissorTest();
2237 d->resetClipIfNeeded();
2239 d->writeClip(path, d->maxClip);
2240 state()->currentClip = d->maxClip;
2241 state()->clipTestEnabled = true;
2248 void QOpenGL2PaintEngineExPrivate::regenerateClip()
2250 systemStateChanged();
2251 replayClipOperations();
2254 void QOpenGL2PaintEngineExPrivate::systemStateChanged()
2256 Q_Q(QOpenGL2PaintEngineEx);
2258 q->state()->clipChanged = true;
2260 if (systemClip.isEmpty()) {
2261 useSystemClip = false;
2263 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2264 //QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2265 //useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2266 useSystemClip = true;
2268 useSystemClip = true;
2272 q->state()->clipTestEnabled = false;
2273 q->state()->needsClipBufferClear = true;
2275 q->state()->currentClip = 1;
2278 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2279 updateClipScissorTest();
2281 if (systemClip.rectCount() == 1) {
2282 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2283 useSystemClip = false;
2284 #ifndef QT_GL_NO_SCISSOR_TEST
2285 // scissoring takes care of the system clip
2290 if (useSystemClip) {
2294 path.addRegion(systemClip);
2296 q->state()->currentClip = 0;
2297 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2298 q->state()->currentClip = 1;
2299 q->state()->clipTestEnabled = true;
2303 void QOpenGL2PaintEngineEx::setState(QPainterState *new_state)
2305 // qDebug("QOpenGL2PaintEngineEx::setState()");
2307 Q_D(QOpenGL2PaintEngineEx);
2309 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2310 QOpenGL2PaintEngineState *old_state = state();
2312 QPaintEngineEx::setState(s);
2315 // Newly created state object. The call to setState()
2316 // will either be followed by a call to begin(), or we are
2317 // setting the state as part of a save().
2322 // Setting the state as part of a restore().
2324 if (old_state == s || old_state->renderHintsChanged)
2325 renderHintsChanged();
2327 if (old_state == s || old_state->matrixChanged)
2328 d->matrixDirty = true;
2330 if (old_state == s || old_state->compositionModeChanged)
2331 d->compositionModeDirty = true;
2333 if (old_state == s || old_state->opacityChanged)
2334 d->opacityUniformDirty = true;
2336 if (old_state == s || old_state->clipChanged) {
2337 if (old_state && old_state != s && old_state->canRestoreClip) {
2338 d->updateClipScissorTest();
2339 glDepthFunc(GL_LEQUAL);
2341 d->regenerateClip();
2346 QPainterState *QOpenGL2PaintEngineEx::createState(QPainterState *orig) const
2349 const_cast<QOpenGL2PaintEngineEx *>(this)->ensureActive();
2351 QOpenGL2PaintEngineState *s;
2353 s = new QOpenGL2PaintEngineState();
2355 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2357 s->matrixChanged = false;
2358 s->compositionModeChanged = false;
2359 s->opacityChanged = false;
2360 s->renderHintsChanged = false;
2361 s->clipChanged = false;
2366 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2367 : QPainterState(other)
2370 needsClipBufferClear = other.needsClipBufferClear;
2371 clipTestEnabled = other.clipTestEnabled;
2372 currentClip = other.currentClip;
2373 canRestoreClip = other.canRestoreClip;
2374 rectangleClip = other.rectangleClip;
2377 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2380 needsClipBufferClear = true;
2381 clipTestEnabled = false;
2382 canRestoreClip = true;
2385 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2389 void QOpenGL2PaintEngineExPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
2391 Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
2393 if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
2394 funcs.glDisableVertexAttribArray(arrayIndex);
2396 if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
2397 funcs.glEnableVertexAttribArray(arrayIndex);
2399 vertexAttributeArraysEnabledState[arrayIndex] = enabled;
2402 void QOpenGL2PaintEngineExPrivate::syncGlState()
2404 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
2405 if (vertexAttributeArraysEnabledState[i])
2406 funcs.glEnableVertexAttribArray(i);
2408 funcs.glDisableVertexAttribArray(i);