1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtOpenGL module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
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 "qglgradientcache_p.h"
68 #include "qpaintengineex_opengl2_p.h"
70 #include <string.h> //for memcpy
73 #include <private/qgl_p.h>
74 #include <private/qmath_p.h>
75 #include <private/qpaintengineex_p.h>
76 #include <QPaintEngine>
77 #include <private/qpainter_p.h>
78 #include <private/qfontengine_p.h>
79 #include <private/qdatabuffer_p.h>
80 #include <private/qstatictext_p.h>
81 #include <private/qtriangulator_p.h>
83 #include "qglengineshadermanager_p.h"
84 #include "qgl2pexvertexarray_p.h"
85 #include "qtriangulatingstroker_p.h"
86 #include "qtextureglyphcache_gl_p.h"
93 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
97 extern bool qt_applefontsmoothing_enabled;
100 #if !defined(QT_MAX_CACHED_GLYPH_SIZE)
101 # define QT_MAX_CACHED_GLYPH_SIZE 64
104 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
106 ////////////////////////////////// Private Methods //////////////////////////////////////////
108 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
110 delete shaderManager;
112 while (pathCaches.size()) {
113 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
114 e->cleanup(e->engine, e->data);
119 if (elementIndicesVBOId != 0) {
120 glDeleteBuffers(1, &elementIndicesVBOId);
121 elementIndicesVBOId = 0;
125 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
127 // glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
128 if (id != GLuint(-1) && id == lastTextureUsed)
131 lastTextureUsed = id;
133 if (smoothPixmapTransform) {
134 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
135 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
137 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
138 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
140 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
141 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
145 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
147 qreal alpha = c.alphaF() * opacity;
149 c.setRedF(c.redF() * alpha);
150 c.setGreenF(c.greenF() * alpha);
151 c.setBlueF(c.blueF() * alpha);
156 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
158 if (qbrush_fast_equals(currentBrush, brush))
161 const Qt::BrushStyle newStyle = qbrush_style(brush);
162 Q_ASSERT(newStyle != Qt::NoBrush);
164 currentBrush = brush;
165 if (!currentBrushPixmap.isNull())
166 currentBrushPixmap = QPixmap();
167 brushUniformsDirty = true; // All brushes have at least one uniform
169 if (newStyle > Qt::SolidPattern)
170 brushTextureDirty = true;
172 if (currentBrush.style() == Qt::TexturePattern
173 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
175 shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
177 shaderManager->setSrcPixelType(newStyle);
179 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
183 void QGL2PaintEngineExPrivate::useSimpleShader()
185 shaderManager->useSimpleProgram();
191 void QGL2PaintEngineExPrivate::updateBrushTexture()
193 Q_Q(QGL2PaintEngineEx);
194 // qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
195 Qt::BrushStyle style = currentBrush.style();
197 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
198 // Get the image data for the pattern
199 QImage texImage = qt_imageForBrush(style, false);
201 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
202 ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
203 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
205 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
206 // Gradiant brush: All the gradiants use the same texture
208 const QGradient* g = currentBrush.gradient();
210 // We apply global opacity in the fragment shaders, so we always pass 1.0
211 // for opacity to the cache.
212 GLuint texId = QGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
214 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
215 glBindTexture(GL_TEXTURE_2D, texId);
217 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
218 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
219 else if (g->spread() == QGradient::ReflectSpread)
220 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, q->state()->renderHints & QPainter::SmoothPixmapTransform);
222 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
224 else if (style == Qt::TexturePattern) {
225 currentBrushPixmap = currentBrush.texture();
227 int max_texture_size = ctx->d_func()->maxTextureSize();
228 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
229 currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
231 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
232 QGLTexture *tex = ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
233 QGLContext::InternalBindOption |
234 QGLContext::CanFlipNativePixmapBindOption);
235 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
236 textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
238 brushTextureDirty = false;
242 void QGL2PaintEngineExPrivate::updateBrushUniforms()
244 // qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
245 Qt::BrushStyle style = currentBrush.style();
247 if (style == Qt::NoBrush)
250 QTransform brushQTransform = currentBrush.transform();
252 if (style == Qt::SolidPattern) {
253 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
254 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::FragmentColor), col);
257 // All other brushes have a transform and thus need the translation point:
258 QPointF translationPoint;
260 if (style <= Qt::DiagCrossPattern) {
261 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
263 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
265 QVector2D halfViewportSize(width*0.5, height*0.5);
266 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
268 else if (style == Qt::LinearGradientPattern) {
269 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
271 QPointF realStart = g->start();
272 QPointF realFinal = g->finalStop();
273 translationPoint = realStart;
275 QPointF l = realFinal - realStart;
277 QVector3D linearData(
280 1.0f / (l.x() * l.x() + l.y() * l.y())
283 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::LinearData), linearData);
285 QVector2D halfViewportSize(width*0.5, height*0.5);
286 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
288 else if (style == Qt::ConicalGradientPattern) {
289 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
290 translationPoint = g->center();
292 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
294 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Angle), angle);
296 QVector2D halfViewportSize(width*0.5, height*0.5);
297 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
299 else if (style == Qt::RadialGradientPattern) {
300 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
301 QPointF realCenter = g->center();
302 QPointF realFocal = g->focalPoint();
303 qreal realRadius = g->centerRadius() - g->focalRadius();
304 translationPoint = realFocal;
306 QPointF fmp = realCenter - realFocal;
307 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp), fmp);
309 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
310 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
311 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Inverse2Fmp2MRadius2),
312 GLfloat(1.0 / (2.0*fmp2_m_radius2)));
313 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::SqrFr),
314 GLfloat(g->focalRadius() * g->focalRadius()));
315 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BRadius),
316 GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
318 g->centerRadius() - g->focalRadius());
320 QVector2D halfViewportSize(width*0.5, height*0.5);
321 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
323 else if (style == Qt::TexturePattern) {
324 const QPixmap& texPixmap = currentBrush.texture();
326 if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
327 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
328 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
331 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
332 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
334 QVector2D halfViewportSize(width*0.5, height*0.5);
335 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
338 qWarning("QGL2PaintEngineEx: Unimplemented fill style");
340 const QPointF &brushOrigin = q->state()->brushOrigin;
341 QTransform matrix = q->state()->matrix;
342 matrix.translate(brushOrigin.x(), brushOrigin.y());
344 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
347 if (device->isFlipped()) {
351 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
352 QTransform inv_matrix;
353 if (style == Qt::TexturePattern && textureInvertedY == -1)
354 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
356 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
358 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTransform), inv_matrix);
359 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
361 brushUniformsDirty = false;
365 // This assumes the shader manager has already setup the correct shader program
366 void QGL2PaintEngineExPrivate::updateMatrix()
368 // qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
370 const QTransform& transform = q->state()->matrix;
372 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
373 // * GL's viewport is 2x2, Qt's is width x height
374 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
375 // * GL has [0,0] in the center, Qt has it in the top-left
377 // This results in the Projection matrix below, which is multiplied by the painter's
378 // transformation matrix, as shown below:
380 // Projection Matrix Painter Transform
381 // ------------------------------------------------ ------------------------
382 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
383 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
384 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
385 // ------------------------------------------------ ------------------------
387 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
389 const GLfloat wfactor = 2.0f / width;
390 GLfloat hfactor = -2.0f / height;
392 GLfloat dx = transform.dx();
393 GLfloat dy = transform.dy();
395 if (device->isFlipped()) {
400 // Non-integer translates can have strange effects for some rendering operations such as
401 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
402 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
403 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
404 dx = ceilf(dx - 0.5f);
405 dy = ceilf(dy - 0.5f);
407 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
408 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
409 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
410 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
411 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
412 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
413 pmvMatrix[0][2] = transform.m13();
414 pmvMatrix[1][2] = transform.m23();
415 pmvMatrix[2][2] = transform.m33();
417 // 1/10000 == 0.0001, so we have good enough res to cover curves
418 // that span the entire widget...
419 inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
420 qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
424 matrixUniformDirty = true;
426 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
427 // need to do this once for every matrix change and persists across all shader programs.
428 glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
429 glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
430 glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
432 dasher.setInvScale(inverseScale);
433 stroker.setInvScale(inverseScale);
437 void QGL2PaintEngineExPrivate::updateCompositionMode()
439 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
440 // composition modes look odd.
441 // qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
442 switch(q->state()->composition_mode) {
443 case QPainter::CompositionMode_SourceOver:
444 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
446 case QPainter::CompositionMode_DestinationOver:
447 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
449 case QPainter::CompositionMode_Clear:
450 glBlendFunc(GL_ZERO, GL_ZERO);
452 case QPainter::CompositionMode_Source:
453 glBlendFunc(GL_ONE, GL_ZERO);
455 case QPainter::CompositionMode_Destination:
456 glBlendFunc(GL_ZERO, GL_ONE);
458 case QPainter::CompositionMode_SourceIn:
459 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
461 case QPainter::CompositionMode_DestinationIn:
462 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
464 case QPainter::CompositionMode_SourceOut:
465 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
467 case QPainter::CompositionMode_DestinationOut:
468 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
470 case QPainter::CompositionMode_SourceAtop:
471 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
473 case QPainter::CompositionMode_DestinationAtop:
474 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
476 case QPainter::CompositionMode_Xor:
477 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
479 case QPainter::CompositionMode_Plus:
480 glBlendFunc(GL_ONE, GL_ONE);
483 qWarning("Unsupported composition mode");
487 compositionModeDirty = false;
490 static inline void setCoords(GLfloat *coords, const QGLRect &rect)
492 coords[0] = rect.left;
493 coords[1] = rect.top;
494 coords[2] = rect.right;
495 coords[3] = rect.top;
496 coords[4] = rect.right;
497 coords[5] = rect.bottom;
498 coords[6] = rect.left;
499 coords[7] = rect.bottom;
502 void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
504 // Setup for texture drawing
505 currentBrush = noBrush;
506 shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
508 if (snapToPixelGrid) {
509 snapToPixelGrid = false;
513 if (prepareForDraw(opaque))
514 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
517 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
518 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
521 GLfloat dx = 1.0 / textureSize.width();
522 GLfloat dy = 1.0 / textureSize.height();
524 QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
526 setCoords(staticVertexCoordinateArray, dest);
527 setCoords(staticTextureCoordinateArray, srcTextureRect);
529 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
532 void QGL2PaintEngineEx::beginNativePainting()
534 Q_D(QGL2PaintEngineEx);
536 d->transferMode(BrushDrawingMode);
538 d->nativePaintingActive = true;
540 QGLContext *ctx = d->ctx;
543 // Disable all the vertex attribute arrays:
544 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
545 glDisableVertexAttribArray(i);
547 #ifndef QT_OPENGL_ES_2
548 const QGLFormat &fmt = d->device->format();
549 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
550 || fmt.profile() == QGLFormat::CompatibilityProfile)
552 // be nice to people who mix OpenGL 1.x code with QPainter commands
553 // by setting modelview and projection matrices to mirror the GL 1
555 const QTransform& mtx = state()->matrix;
557 float mv_matrix[4][4] =
559 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
560 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
562 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
565 const QSize sz = d->device->size();
567 glMatrixMode(GL_PROJECTION);
569 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
571 glMatrixMode(GL_MODELVIEW);
572 glLoadMatrixf(&mv_matrix[0][0]);
578 d->lastTextureUsed = GLuint(-1);
579 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
582 d->shaderManager->setDirty();
587 void QGL2PaintEngineExPrivate::resetGLState()
590 glActiveTexture(GL_TEXTURE0);
591 glDisable(GL_STENCIL_TEST);
592 glDisable(GL_DEPTH_TEST);
593 glDisable(GL_SCISSOR_TEST);
595 glDepthFunc(GL_LESS);
598 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
599 glStencilFunc(GL_ALWAYS, 0, 0xff);
600 ctx->d_func()->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
601 ctx->d_func()->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
602 ctx->d_func()->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
603 #ifndef QT_OPENGL_ES_2
604 // gl_Color, corresponding to vertex attribute 3, may have been changed
605 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
606 glVertexAttrib4fv(3, color);
610 void QGL2PaintEngineEx::endNativePainting()
612 Q_D(QGL2PaintEngineEx);
614 d->nativePaintingActive = false;
617 void QGL2PaintEngineEx::invalidateState()
619 Q_D(QGL2PaintEngineEx);
623 bool QGL2PaintEngineEx::isNativePaintingActive() const {
624 Q_D(const QGL2PaintEngineEx);
625 return d->nativePaintingActive;
628 void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
633 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
634 lastTextureUsed = GLuint(-1);
637 if (newMode == TextDrawingMode) {
638 shaderManager->setHasComplexGeometry(true);
640 shaderManager->setHasComplexGeometry(false);
643 if (newMode == ImageDrawingMode) {
644 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
645 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
648 if (newMode == ImageArrayDrawingMode) {
649 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
650 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
651 setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
654 // This needs to change when we implement high-quality anti-aliasing...
655 if (newMode != TextDrawingMode)
656 shaderManager->setMaskType(QGLEngineShaderManager::NoMask);
661 struct QGL2PEVectorPathCache
663 #ifdef QT_OPENGL_CACHE_AS_VBOS
672 GLenum primitiveType;
676 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
678 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
679 #ifdef QT_OPENGL_CACHE_AS_VBOS
680 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
681 static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
683 d->unusedIBOSToClean << c->ibo;
692 // Assumes everything is configured for the brush you want to use
693 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
695 transferMode(BrushDrawingMode);
697 if (snapToPixelGrid) {
698 snapToPixelGrid = false;
702 // Might need to call updateMatrix to re-calculate inverseScale
706 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
708 // Check to see if there's any hints
709 if (path.shape() == QVectorPath::RectangleHint) {
710 QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
711 prepareForDraw(currentBrush.isOpaque());
713 } else if (path.isConvex()) {
715 if (path.isCacheable()) {
716 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
717 QGL2PEVectorPathCache *cache;
719 bool updateCache = false;
722 cache = (QGL2PEVectorPathCache *) data->data;
723 // Check if scale factor is exceeded for curved paths and generate curves if so...
724 if (path.isCurved()) {
725 qreal scaleFactor = cache->iscale / inverseScale;
726 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
727 #ifdef QT_OPENGL_CACHE_AS_VBOS
728 glDeleteBuffers(1, &cache->vbo);
730 Q_ASSERT(cache->ibo == 0);
732 qFree(cache->vertices);
733 Q_ASSERT(cache->indices == 0);
739 cache = new QGL2PEVectorPathCache;
740 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
744 // Flatten the path at the current scale factor and fill it into the cache struct.
746 vertexCoordinateArray.clear();
747 vertexCoordinateArray.addPath(path, inverseScale, false);
748 int vertexCount = vertexCoordinateArray.vertexCount();
749 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
750 cache->vertexCount = vertexCount;
751 cache->indexCount = 0;
752 cache->primitiveType = GL_TRIANGLE_FAN;
753 cache->iscale = inverseScale;
754 #ifdef QT_OPENGL_CACHE_AS_VBOS
755 glGenBuffers(1, &cache->vbo);
756 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
757 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
760 cache->vertices = (float *) qMalloc(floatSizeInBytes);
761 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
766 prepareForDraw(currentBrush.isOpaque());
767 #ifdef QT_OPENGL_CACHE_AS_VBOS
768 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
769 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
771 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
773 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
776 // printf(" - Marking path as cachable...\n");
777 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
778 path.makeCacheable();
779 vertexCoordinateArray.clear();
780 vertexCoordinateArray.addPath(path, inverseScale, false);
781 prepareForDraw(currentBrush.isOpaque());
782 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
786 bool useCache = path.isCacheable();
788 QRectF bbox = path.controlPointRect();
789 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
790 useCache &= (bbox.left() > -0x8000 * inverseScale)
791 && (bbox.right() < 0x8000 * inverseScale)
792 && (bbox.top() > -0x8000 * inverseScale)
793 && (bbox.bottom() < 0x8000 * inverseScale);
797 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
798 QGL2PEVectorPathCache *cache;
800 bool updateCache = false;
803 cache = (QGL2PEVectorPathCache *) data->data;
804 // Check if scale factor is exceeded for curved paths and generate curves if so...
805 if (path.isCurved()) {
806 qreal scaleFactor = cache->iscale / inverseScale;
807 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
808 #ifdef QT_OPENGL_CACHE_AS_VBOS
809 glDeleteBuffers(1, &cache->vbo);
810 glDeleteBuffers(1, &cache->ibo);
812 qFree(cache->vertices);
813 qFree(cache->indices);
819 cache = new QGL2PEVectorPathCache;
820 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
824 // Flatten the path at the current scale factor and fill it into the cache struct.
826 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
827 cache->vertexCount = polys.vertices.size() / 2;
828 cache->indexCount = polys.indices.size();
829 cache->primitiveType = GL_TRIANGLES;
830 cache->iscale = inverseScale;
831 #ifdef QT_OPENGL_CACHE_AS_VBOS
832 glGenBuffers(1, &cache->vbo);
833 glGenBuffers(1, &cache->ibo);
834 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
835 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
837 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
838 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
840 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
842 QVarLengthArray<float> vertices(polys.vertices.size());
843 for (int i = 0; i < polys.vertices.size(); ++i)
844 vertices[i] = float(inverseScale * polys.vertices.at(i));
845 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
847 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
848 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint) {
849 cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
850 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
852 cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
853 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
855 for (int i = 0; i < polys.vertices.size(); ++i)
856 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
860 prepareForDraw(currentBrush.isOpaque());
861 #ifdef QT_OPENGL_CACHE_AS_VBOS
862 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
863 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
864 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
865 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
866 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
868 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
869 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
870 glBindBuffer(GL_ARRAY_BUFFER, 0);
872 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
873 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
874 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
876 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
880 // printf(" - Marking path as cachable...\n");
881 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
882 path.makeCacheable();
884 if (!device->format().stencil()) {
885 // If there is no stencil buffer, triangulate the path instead.
887 QRectF bbox = path.controlPointRect();
888 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
889 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
890 && (bbox.right() < 0x8000 * inverseScale)
891 && (bbox.top() > -0x8000 * inverseScale)
892 && (bbox.bottom() < 0x8000 * inverseScale);
894 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
896 QVarLengthArray<float> vertices(polys.vertices.size());
897 for (int i = 0; i < polys.vertices.size(); ++i)
898 vertices[i] = float(inverseScale * polys.vertices.at(i));
900 prepareForDraw(currentBrush.isOpaque());
901 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
902 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
903 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
905 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
907 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
908 qWarning("Painter path exceeds +/-32767 pixels.");
913 // The path is too complicated & needs the stencil technique
914 vertexCoordinateArray.clear();
915 vertexCoordinateArray.addPath(path, inverseScale, false);
917 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
920 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
922 if (q->state()->clipTestEnabled) {
923 // Pass when high bit is set, replace stencil value with current clip
924 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
925 } else if (path.hasWindingFill()) {
926 // Pass when any bit is set, replace stencil value with 0
927 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
929 // Pass when high bit is set, replace stencil value with 0
930 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
932 prepareForDraw(currentBrush.isOpaque());
934 // Stencil the brush onto the dest buffer
935 composite(vertexCoordinateArray.boundingRect());
937 updateClipScissorTest();
943 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
947 const QGLRect &bounds,
948 StencilFillMode mode)
950 Q_ASSERT(count || stops);
952 // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
953 glStencilMask(0xff); // Enable stencil writes
955 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
956 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
957 glClearStencil(0); // Clear to zero
958 for (int i = 0; i < clearRegion.size(); ++i) {
959 #ifndef QT_GL_NO_SCISSOR_TEST
960 setScissor(clearRegion.at(i));
962 glClear(GL_STENCIL_BUFFER_BIT);
965 dirtyStencilRegion -= currentScissorBounds;
967 #ifndef QT_GL_NO_SCISSOR_TEST
968 updateClipScissorTest();
972 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
974 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
976 if (mode == WindingFillMode) {
977 Q_ASSERT(stops && !count);
978 if (q->state()->clipTestEnabled) {
979 // Flatten clip values higher than current clip, and set high bit to match current clip
980 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
981 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
984 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
985 } else if (!stencilClean) {
986 // Clear stencil buffer within bounding rect
987 glStencilFunc(GL_ALWAYS, 0, 0xff);
988 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
992 // Inc. for front-facing triangle
993 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
994 // Dec. for back-facing "holes"
995 glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
996 glStencilMask(~GL_STENCIL_HIGH_BIT);
997 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
999 if (q->state()->clipTestEnabled) {
1000 // Clear high bit of stencil outside of path
1001 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1002 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1003 glStencilMask(GL_STENCIL_HIGH_BIT);
1006 } else if (mode == OddEvenFillMode) {
1007 glStencilMask(GL_STENCIL_HIGH_BIT);
1008 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1009 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1011 } else { // TriStripStrokeFillMode
1012 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1013 glStencilMask(GL_STENCIL_HIGH_BIT);
1015 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1016 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1017 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1020 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1021 if (q->state()->clipTestEnabled) {
1022 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1023 ~GL_STENCIL_HIGH_BIT);
1025 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1027 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1028 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1032 // Enable color writes & disable stencil writes
1033 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1037 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1038 restore the stencil buffer to a pristine state. The current clip region
1039 is set to 1, and the rest to 0.
1041 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1043 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1046 Q_Q(QGL2PaintEngineEx);
1049 glEnable(GL_STENCIL_TEST);
1050 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1052 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1053 QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1055 // Set high bit on clip region
1056 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1057 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1058 glStencilMask(GL_STENCIL_HIGH_BIT);
1061 // Reset clipping to 1 and everything else to zero
1062 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1063 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1064 glStencilMask(0xff);
1067 q->state()->currentClip = 1;
1068 q->state()->canRestoreClip = false;
1073 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1076 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1078 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1079 updateBrushTexture();
1081 if (compositionModeDirty)
1082 updateCompositionMode();
1087 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1088 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1089 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1090 && srcPixelsAreOpaque && !stateHasOpacity))
1092 glDisable(GL_BLEND);
1097 QGLEngineShaderManager::OpacityMode opacityMode;
1098 if (mode == ImageArrayDrawingMode) {
1099 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1101 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1102 : QGLEngineShaderManager::NoOpacity;
1103 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1105 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1106 (currentBrush.style() <= Qt::DiagCrossPattern);
1108 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1109 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1112 shaderManager->setOpacityMode(opacityMode);
1114 bool changed = shaderManager->useCorrectShaderProg();
1115 // If the shader program needs changing, we change it and mark all uniforms as dirty
1117 // The shader program has changed so mark all uniforms as dirty:
1118 brushUniformsDirty = true;
1119 opacityUniformDirty = true;
1120 matrixUniformDirty = true;
1123 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1124 updateBrushUniforms();
1126 if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1127 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1128 opacityUniformDirty = false;
1131 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1132 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1134 matrixUniformDirty = false;
1140 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1142 setCoords(staticVertexCoordinateArray, boundingRect);
1143 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1144 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1147 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1148 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1151 // Now setup the pointer to the vertex array:
1152 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1154 int previousStop = 0;
1155 for (int i=0; i<stopCount; ++i) {
1156 int stop = stops[i];
1158 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1159 for (int i=previousStop; i<stop; ++i)
1160 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1162 glDrawArrays(primitive, previousStop, stop - previousStop);
1163 previousStop = stop;
1167 /////////////////////////////////// Public Methods //////////////////////////////////////////
1169 QGL2PaintEngineEx::QGL2PaintEngineEx()
1170 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1174 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1178 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1180 Q_D(QGL2PaintEngineEx);
1182 if (qbrush_style(brush) == Qt::NoBrush)
1189 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1192 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1194 Q_D(QGL2PaintEngineEx);
1196 const QBrush &penBrush = qpen_brush(pen);
1197 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1200 QOpenGL2PaintEngineState *s = state();
1201 if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1202 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1203 QPaintEngineEx::stroke(path, pen);
1208 d->setBrush(penBrush);
1209 d->stroke(path, pen);
1212 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1214 const QOpenGL2PaintEngineState *s = q->state();
1215 if (snapToPixelGrid) {
1216 snapToPixelGrid = false;
1220 const Qt::PenStyle penStyle = qpen_style(pen);
1221 const QBrush &penBrush = qpen_brush(pen);
1222 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1224 transferMode(BrushDrawingMode);
1226 // updateMatrix() is responsible for setting the inverse scale on
1227 // the strokers, so we need to call it here and not wait for
1228 // prepareForDraw() down below.
1231 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1232 ? q->state()->rectangleClip
1233 : QRectF(0, 0, width, height));
1235 if (penStyle == Qt::SolidLine) {
1236 stroker.process(path, pen, clip);
1238 } else { // Some sort of dash
1239 dasher.process(path, pen, clip);
1241 QVectorPath dashStroke(dasher.points(),
1242 dasher.elementCount(),
1243 dasher.elementTypes());
1244 stroker.process(dashStroke, pen, clip);
1247 if (!stroker.vertexCount())
1251 prepareForDraw(opaque);
1252 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1253 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1255 // QBrush b(Qt::green);
1257 // d->prepareForDraw(true);
1258 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1261 qreal width = qpen_widthf(pen) / 2;
1264 qreal extra = pen.joinStyle() == Qt::MiterJoin
1265 ? qMax(pen.miterLimit() * width, width)
1268 if (pen.isCosmetic())
1269 extra = extra * inverseScale;
1271 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1273 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1274 0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1276 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1278 // Pass when any bit is set, replace stencil value with 0
1279 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1280 prepareForDraw(false);
1282 // Stencil the brush onto the dest buffer
1287 updateClipScissorTest();
1291 void QGL2PaintEngineEx::penChanged() { }
1292 void QGL2PaintEngineEx::brushChanged() { }
1293 void QGL2PaintEngineEx::brushOriginChanged() { }
1295 void QGL2PaintEngineEx::opacityChanged()
1297 // qDebug("QGL2PaintEngineEx::opacityChanged()");
1298 Q_D(QGL2PaintEngineEx);
1299 state()->opacityChanged = true;
1301 Q_ASSERT(d->shaderManager);
1302 d->brushUniformsDirty = true;
1303 d->opacityUniformDirty = true;
1306 void QGL2PaintEngineEx::compositionModeChanged()
1308 // qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1309 Q_D(QGL2PaintEngineEx);
1310 state()->compositionModeChanged = true;
1311 d->compositionModeDirty = true;
1314 void QGL2PaintEngineEx::renderHintsChanged()
1316 state()->renderHintsChanged = true;
1318 #if !defined(QT_OPENGL_ES_2)
1319 if ((state()->renderHints & QPainter::Antialiasing)
1320 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1321 glEnable(GL_MULTISAMPLE);
1323 glDisable(GL_MULTISAMPLE);
1326 Q_D(QGL2PaintEngineEx);
1327 d->lastTextureUsed = GLuint(-1);
1328 d->brushTextureDirty = true;
1329 // qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1332 void QGL2PaintEngineEx::transformChanged()
1334 Q_D(QGL2PaintEngineEx);
1335 d->matrixDirty = true;
1336 state()->matrixChanged = true;
1340 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1342 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1345 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1347 Q_D(QGL2PaintEngineEx);
1348 QGLContext *ctx = d->ctx;
1350 int max_texture_size = ctx->d_func()->maxTextureSize();
1351 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1352 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1354 const qreal sx = scaled.width() / qreal(pixmap.width());
1355 const qreal sy = scaled.height() / qreal(pixmap.height());
1357 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1362 d->transferMode(ImageDrawingMode);
1364 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1365 #ifdef QGL_USE_TEXTURE_POOL
1366 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1369 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1370 QGLTexture *texture =
1371 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1373 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1374 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1375 QGLRect srcRect(src.left(), top, src.right(), bottom);
1377 bool isBitmap = pixmap.isQBitmap();
1378 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1380 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1381 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1382 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1384 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1385 // pixmap was temporarily cached as a QImage texture by pooling system
1386 // and should be destroyed immediately
1387 QGLTextureCache::instance()->remove(ctx, texture->id);
1391 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1392 Qt::ImageConversionFlags)
1394 Q_D(QGL2PaintEngineEx);
1395 QGLContext *ctx = d->ctx;
1397 int max_texture_size = ctx->d_func()->maxTextureSize();
1398 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1399 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1401 const qreal sx = scaled.width() / qreal(image.width());
1402 const qreal sy = scaled.height() / qreal(image.height());
1404 drawImage(dest, scaled, scaleRect(src, sx, sy));
1409 d->transferMode(ImageDrawingMode);
1411 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1413 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1414 #ifdef QGL_USE_TEXTURE_POOL
1415 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1418 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1419 GLuint id = texture->id;
1421 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1422 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1423 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1425 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1426 // image was temporarily cached by texture pooling system
1427 // and should be destroyed immediately
1428 QGLTextureCache::instance()->remove(ctx, texture->id);
1432 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1434 Q_D(QGL2PaintEngineEx);
1438 QPainterState *s = state();
1439 float det = s->matrix.determinant();
1441 // don't try to cache huge fonts or vastly transformed fonts
1442 QFontEngine *fontEngine = textItem->fontEngine();
1443 const qreal pixelSize = fontEngine->fontDef.pixelSize;
1444 if (pixelSize * pixelSize * qAbs(det) < QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE ||
1445 det < 0.25f || det > 4.f) {
1446 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1447 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1448 : d->glyphCacheType;
1449 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1450 if (d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1451 || (s->composition_mode != QPainter::CompositionMode_Source
1452 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1454 glyphType = QFontEngineGlyphCache::Raster_A8;
1458 d->drawCachedGlyphs(glyphType, textItem);
1460 QPaintEngineEx::drawStaticTextItem(textItem);
1464 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1466 Q_D(QGL2PaintEngineEx);
1467 if (!d->shaderManager)
1471 d->transferMode(ImageDrawingMode);
1473 #ifndef QT_OPENGL_ES_2
1474 QGLContext *ctx = d->ctx;
1476 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1477 glBindTexture(GL_TEXTURE_2D, textureId);
1479 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1481 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1482 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1483 d->drawTexture(dest, srcRect, size, false);
1487 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1489 Q_D(QGL2PaintEngineEx);
1492 QOpenGL2PaintEngineState *s = state();
1494 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1496 QTransform::TransformationType txtype = s->matrix.type();
1498 float det = s->matrix.determinant();
1499 bool drawCached = txtype < QTransform::TxProject;
1501 // don't try to cache huge fonts or vastly transformed fonts
1502 const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1503 if (pixelSize * pixelSize * qAbs(det) >= QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE ||
1504 det < 0.25f || det > 4.f)
1507 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1508 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1509 : d->glyphCacheType;
1512 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1513 if (d->device->alphaRequested() || txtype > QTransform::TxTranslate
1514 || (state()->composition_mode != QPainter::CompositionMode_Source
1515 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1517 glyphType = QFontEngineGlyphCache::Raster_A8;
1522 QVarLengthArray<QFixedPoint> positions;
1523 QVarLengthArray<glyph_t> glyphs;
1524 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1525 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1528 QStaticTextItem staticTextItem;
1529 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1530 staticTextItem.setFontEngine(ti.fontEngine);
1531 staticTextItem.glyphs = glyphs.data();
1532 staticTextItem.numChars = ti.num_chars;
1533 staticTextItem.numGlyphs = glyphs.size();
1534 staticTextItem.glyphPositions = positions.data();
1536 d->drawCachedGlyphs(glyphType, &staticTextItem);
1541 QPaintEngineEx::drawTextItem(p, ti);
1546 class QOpenGLStaticTextUserData: public QStaticTextUserData
1549 QOpenGLStaticTextUserData()
1550 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1554 ~QOpenGLStaticTextUserData()
1559 QGL2PEXVertexArray vertexCoordinateArray;
1560 QGL2PEXVertexArray textureCoordinateArray;
1561 QFontEngineGlyphCache::Type glyphType;
1562 int cacheSerialNumber;
1567 #if defined(Q_WS_WIN)
1568 static bool fontSmoothingApproximately(qreal target)
1570 extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1571 return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1575 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1577 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1578 QStaticTextItem *staticTextItem)
1580 Q_Q(QGL2PaintEngineEx);
1582 QOpenGL2PaintEngineState *s = q->state();
1584 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1585 bool recreateVertexArrays = false;
1587 QGLTextureGlyphCache *cache =
1588 (QGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1589 if (!cache || cache->cacheType() != glyphType || cache->context() == 0) {
1590 cache = new QGLTextureGlyphCache(ctx, glyphType, QTransform());
1591 staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1592 cache->insert(ctx, cache);
1593 recreateVertexArrays = true;
1596 if (staticTextItem->userDataNeedsUpdate) {
1597 recreateVertexArrays = true;
1598 } else if (staticTextItem->userData() == 0) {
1599 recreateVertexArrays = true;
1600 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1601 recreateVertexArrays = true;
1603 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1604 if (userData->glyphType != glyphType) {
1605 recreateVertexArrays = true;
1606 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1607 recreateVertexArrays = true;
1611 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1612 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1613 // cache so this text is performed before we test if the cache size has changed.
1614 if (recreateVertexArrays) {
1615 cache->setPaintEnginePrivate(this);
1616 if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1617 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1618 // No space for glyphs in cache. We need to reset it and try again.
1620 cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1621 staticTextItem->glyphs, staticTextItem->glyphPositions);
1623 cache->fillInPendingGlyphs();
1626 if (cache->width() == 0 || cache->height() == 0)
1629 transferMode(TextDrawingMode);
1631 int margin = cache->glyphMargin();
1633 GLfloat dx = 1.0 / cache->width();
1634 GLfloat dy = 1.0 / cache->height();
1636 // Use global arrays by default
1637 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1638 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1640 if (staticTextItem->useBackendOptimizations) {
1641 QOpenGLStaticTextUserData *userData = 0;
1643 if (staticTextItem->userData() == 0
1644 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1646 userData = new QOpenGLStaticTextUserData();
1647 staticTextItem->setUserData(userData);
1650 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1653 userData->glyphType = glyphType;
1654 userData->cacheSerialNumber = cache->serialNumber();
1656 // Use cache if backend optimizations is turned on
1657 vertexCoordinates = &userData->vertexCoordinateArray;
1658 textureCoordinates = &userData->textureCoordinateArray;
1660 QSize size(cache->width(), cache->height());
1661 if (userData->cacheSize != size) {
1662 recreateVertexArrays = true;
1663 userData->cacheSize = size;
1667 if (recreateVertexArrays) {
1668 vertexCoordinates->clear();
1669 textureCoordinates->clear();
1671 bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1672 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1673 QFixed subPixelPosition;
1674 if (supportsSubPixelPositions)
1675 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1677 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1679 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1683 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1684 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1686 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1687 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1690 staticTextItem->userDataNeedsUpdate = false;
1693 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1695 if (elementIndices.size() < numGlyphs*6) {
1696 Q_ASSERT(elementIndices.size() % 6 == 0);
1697 int j = elementIndices.size() / 6 * 4;
1698 while (j < numGlyphs*4) {
1699 elementIndices.append(j + 0);
1700 elementIndices.append(j + 0);
1701 elementIndices.append(j + 1);
1702 elementIndices.append(j + 2);
1703 elementIndices.append(j + 3);
1704 elementIndices.append(j + 3);
1709 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1710 if (elementIndicesVBOId == 0)
1711 glGenBuffers(1, &elementIndicesVBOId);
1713 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1714 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1715 elementIndices.constData(), GL_STATIC_DRAW);
1718 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1719 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1723 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1724 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1726 if (!snapToPixelGrid) {
1727 snapToPixelGrid = true;
1731 QBrush pensBrush = q->state()->pen.brush();
1732 setBrush(pensBrush);
1734 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1736 // Subpixel antialiasing without gamma correction
1738 QPainter::CompositionMode compMode = q->state()->composition_mode;
1739 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1740 || compMode == QPainter::CompositionMode_SourceOver);
1742 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1744 if (pensBrush.style() == Qt::SolidPattern) {
1745 // Solid patterns can get away with only one pass.
1746 QColor c = pensBrush.color();
1747 qreal oldOpacity = q->state()->opacity;
1748 if (compMode == QPainter::CompositionMode_Source) {
1749 c = qt_premultiplyColor(c, q->state()->opacity);
1750 q->state()->opacity = 1;
1751 opacityUniformDirty = true;
1754 compositionModeDirty = false; // I can handle this myself, thank you very much
1755 prepareForDraw(false); // Text always causes src pixels to be transparent
1757 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1758 if (compMode == QPainter::CompositionMode_Source) {
1759 q->state()->opacity = oldOpacity;
1760 opacityUniformDirty = true;
1764 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1765 glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1767 // Other brush styles need two passes.
1769 qreal oldOpacity = q->state()->opacity;
1770 if (compMode == QPainter::CompositionMode_Source) {
1771 q->state()->opacity = 1;
1772 opacityUniformDirty = true;
1773 pensBrush = Qt::white;
1774 setBrush(pensBrush);
1777 compositionModeDirty = false; // I can handle this myself, thank you very much
1778 prepareForDraw(false); // Text always causes src pixels to be transparent
1780 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1782 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1783 glBindTexture(GL_TEXTURE_2D, cache->texture());
1784 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1786 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1787 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1789 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1792 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1794 if (compMode == QPainter::CompositionMode_Source) {
1795 q->state()->opacity = oldOpacity;
1796 opacityUniformDirty = true;
1797 pensBrush = q->state()->pen.brush();
1798 setBrush(pensBrush);
1801 compositionModeDirty = false;
1802 prepareForDraw(false); // Text always causes src pixels to be transparent
1804 glBlendFunc(GL_ONE, GL_ONE);
1806 compositionModeDirty = true;
1808 // Greyscale/mono glyphs
1810 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1811 prepareForDraw(false); // Text always causes src pixels to be transparent
1814 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1815 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1817 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1818 if (lastMaskTextureUsed != cache->texture()) {
1819 glBindTexture(GL_TEXTURE_2D, cache->texture());
1820 lastMaskTextureUsed = cache->texture();
1823 if (cache->filterMode() != filterMode) {
1824 if (filterMode == QGLTextureGlyphCache::Linear) {
1825 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1826 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1828 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1829 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1831 cache->setFilterMode(filterMode);
1835 bool srgbFrameBufferEnabled = false;
1836 if (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer) {
1837 #if defined(Q_WS_MAC)
1838 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1839 #elif defined(Q_WS_WIN)
1840 if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1845 glEnable(FRAMEBUFFER_SRGB_EXT);
1846 srgbFrameBufferEnabled = true;
1850 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1851 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1852 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1854 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1857 if (srgbFrameBufferEnabled)
1858 glDisable(FRAMEBUFFER_SRGB_EXT);
1862 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1863 QPainter::PixmapFragmentHints hints)
1865 Q_D(QGL2PaintEngineEx);
1866 // Use fallback for extended composition modes.
1867 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1868 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1873 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1874 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1875 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1876 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1878 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1883 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1884 int fragmentCount, const QPixmap &pixmap,
1885 QPainter::PixmapFragmentHints hints)
1887 GLfloat dx = 1.0f / pixmap.size().width();
1888 GLfloat dy = 1.0f / pixmap.size().height();
1890 vertexCoordinateArray.clear();
1891 textureCoordinateArray.clear();
1892 opacityArray.reset();
1894 if (snapToPixelGrid) {
1895 snapToPixelGrid = false;
1899 bool allOpaque = true;
1901 for (int i = 0; i < fragmentCount; ++i) {
1904 if (fragments[i].rotation != 0) {
1905 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1906 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1909 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1910 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1911 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1912 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1914 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1915 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1916 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1917 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1918 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1919 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1921 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1922 (fragments[i].sourceLeft + fragments[i].width) * dx,
1923 (fragments[i].sourceTop + fragments[i].height) * dy);
1925 textureCoordinateArray.addVertex(src.right, src.bottom);
1926 textureCoordinateArray.addVertex(src.right, src.top);
1927 textureCoordinateArray.addVertex(src.left, src.top);
1928 textureCoordinateArray.addVertex(src.left, src.top);
1929 textureCoordinateArray.addVertex(src.left, src.bottom);
1930 textureCoordinateArray.addVertex(src.right, src.bottom);
1932 qreal opacity = fragments[i].opacity * q->state()->opacity;
1933 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1934 allOpaque &= (opacity >= 0.99f);
1937 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1938 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1939 QGLContext::InternalBindOption
1940 | QGLContext::CanFlipNativePixmapBindOption);
1942 if (texture->options & QGLContext::InvertedYBindOption) {
1943 // Flip texture y-coordinate.
1944 QGLPoint *data = textureCoordinateArray.data();
1945 for (int i = 0; i < 6 * fragmentCount; ++i)
1946 data[i].y = 1 - data[i].y;
1949 transferMode(ImageArrayDrawingMode);
1951 bool isBitmap = pixmap.isQBitmap();
1952 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1954 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1955 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1957 // Setup for texture drawing
1958 currentBrush = noBrush;
1959 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1960 : QGLEngineShaderManager::ImageSrc);
1961 if (prepareForDraw(isOpaque))
1962 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1965 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1966 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1969 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1972 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1974 Q_D(QGL2PaintEngineEx);
1976 // qDebug("QGL2PaintEngineEx::begin()");
1977 if (pdev->devType() == QInternal::OpenGL)
1978 d->device = static_cast<QGLPaintDevice*>(pdev);
1980 d->device = QGLPaintDevice::getDevice(pdev);
1985 d->ctx = d->device->context();
1986 d->ctx->d_ptr->active_engine = this;
1988 const QSize sz = d->device->size();
1989 d->width = sz.width();
1990 d->height = sz.height();
1991 d->mode = BrushDrawingMode;
1992 d->brushTextureDirty = true;
1993 d->brushUniformsDirty = true;
1994 d->matrixUniformDirty = true;
1995 d->matrixDirty = true;
1996 d->compositionModeDirty = true;
1997 d->opacityUniformDirty = true;
1998 d->needsSync = true;
1999 d->useSystemClip = !systemClip().isEmpty();
2000 d->currentBrush = QBrush();
2002 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
2003 d->stencilClean = true;
2005 // Calling begin paint should make the correct context current. So, any
2006 // code which calls into GL or otherwise needs a current context *must*
2007 // go after beginPaint:
2008 d->device->beginPaint();
2010 #if !defined(QT_OPENGL_ES_2)
2011 bool success = qt_resolve_version_2_0_functions(d->ctx)
2012 && qt_resolve_buffer_extensions(d->ctx);
2017 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2019 glDisable(GL_STENCIL_TEST);
2020 glDisable(GL_DEPTH_TEST);
2021 glDisable(GL_SCISSOR_TEST);
2023 #if !defined(QT_OPENGL_ES_2)
2024 glDisable(GL_MULTISAMPLE);
2027 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2029 #if !defined(QT_OPENGL_ES_2)
2030 #if defined(Q_WS_WIN)
2031 if (qt_cleartype_enabled
2032 && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2034 #if defined(Q_WS_MAC)
2035 if (qt_applefontsmoothing_enabled)
2037 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2040 #if defined(QT_OPENGL_ES_2)
2041 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2042 // multisampled, it's always multisampled.
2043 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2045 d->multisamplingAlwaysEnabled = false;
2051 bool QGL2PaintEngineEx::end()
2053 Q_D(QGL2PaintEngineEx);
2054 QGLContext *ctx = d->ctx;
2057 d->transferMode(BrushDrawingMode);
2058 d->device->endPaint();
2060 #if defined(Q_WS_X11)
2061 // On some (probably all) drivers, deleting an X pixmap which has been bound to a texture
2062 // before calling glFinish/swapBuffers renders garbage. Presumably this is because X deletes
2063 // the pixmap behind the driver's back before it's had a chance to use it. To fix this, we
2064 // reference all QPixmaps which have been bound to stop them being deleted and only deref
2065 // them here, after swapBuffers, where they can be safely deleted.
2066 ctx->d_func()->boundPixmaps.clear();
2068 d->ctx->d_ptr->active_engine = 0;
2072 delete d->shaderManager;
2073 d->shaderManager = 0;
2074 d->currentBrush = QBrush();
2076 #ifdef QT_OPENGL_CACHE_AS_VBOS
2077 if (!d->unusedVBOSToClean.isEmpty()) {
2078 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2079 d->unusedVBOSToClean.clear();
2081 if (!d->unusedIBOSToClean.isEmpty()) {
2082 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2083 d->unusedIBOSToClean.clear();
2090 void QGL2PaintEngineEx::ensureActive()
2092 Q_D(QGL2PaintEngineEx);
2093 QGLContext *ctx = d->ctx;
2095 if (isActive() && ctx->d_ptr->active_engine != this) {
2096 ctx->d_ptr->active_engine = this;
2097 d->needsSync = true;
2100 d->device->ensureActiveTarget();
2103 d->transferMode(BrushDrawingMode);
2104 glViewport(0, 0, d->width, d->height);
2105 d->needsSync = false;
2106 d->lastMaskTextureUsed = 0;
2107 d->shaderManager->setDirty();
2108 d->ctx->d_func()->syncGlState();
2109 for (int i = 0; i < 3; ++i)
2110 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2115 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2117 Q_Q(QGL2PaintEngineEx);
2118 if (q->state()->clipTestEnabled) {
2119 glEnable(GL_STENCIL_TEST);
2120 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2122 glDisable(GL_STENCIL_TEST);
2123 glStencilFunc(GL_ALWAYS, 0, 0xff);
2126 #ifdef QT_GL_NO_SCISSOR_TEST
2127 currentScissorBounds = QRect(0, 0, width, height);
2129 QRect bounds = q->state()->rectangleClip;
2130 if (!q->state()->clipEnabled) {
2132 bounds = systemClip.boundingRect();
2134 bounds = QRect(0, 0, width, height);
2137 bounds = bounds.intersected(systemClip.boundingRect());
2139 bounds = bounds.intersected(QRect(0, 0, width, height));
2142 currentScissorBounds = bounds;
2144 if (bounds == QRect(0, 0, width, height)) {
2145 glDisable(GL_SCISSOR_TEST);
2147 glEnable(GL_SCISSOR_TEST);
2153 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2155 const int left = rect.left();
2156 const int width = rect.width();
2157 int bottom = height - (rect.top() + rect.height());
2158 if (device->isFlipped()) {
2159 bottom = rect.top();
2161 const int height = rect.height();
2163 glScissor(left, bottom, width, height);
2166 void QGL2PaintEngineEx::clipEnabledChanged()
2168 Q_D(QGL2PaintEngineEx);
2170 state()->clipChanged = true;
2172 if (painter()->hasClipping())
2173 d->regenerateClip();
2175 d->systemStateChanged();
2178 void QGL2PaintEngineExPrivate::clearClip(uint value)
2180 dirtyStencilRegion -= currentScissorBounds;
2182 glStencilMask(0xff);
2183 glClearStencil(value);
2184 glClear(GL_STENCIL_BUFFER_BIT);
2187 q->state()->needsClipBufferClear = false;
2190 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2192 transferMode(BrushDrawingMode);
2194 if (snapToPixelGrid) {
2195 snapToPixelGrid = false;
2202 stencilClean = false;
2204 const bool singlePass = !path.hasWindingFill()
2205 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2206 || q->state()->needsClipBufferClear);
2207 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2209 if (q->state()->needsClipBufferClear)
2212 if (path.isEmpty()) {
2213 glEnable(GL_STENCIL_TEST);
2214 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2218 if (q->state()->clipTestEnabled)
2219 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2221 glStencilFunc(GL_ALWAYS, 0, 0xff);
2223 vertexCoordinateArray.clear();
2224 vertexCoordinateArray.addPath(path, inverseScale, false);
2227 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2229 glColorMask(false, false, false, false);
2230 glEnable(GL_STENCIL_TEST);
2234 // Under these conditions we can set the new stencil value in a single
2235 // pass, by using the current value and the "new value" as the toggles
2237 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2238 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2239 glStencilMask(value ^ referenceClipValue);
2241 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2243 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2244 glStencilMask(0xff);
2246 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2247 // Pass when any clip bit is set, set high bit
2248 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2249 composite(vertexCoordinateArray.boundingRect());
2252 // Pass when high bit is set, replace stencil value with new clip value
2253 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2255 composite(vertexCoordinateArray.boundingRect());
2258 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2261 glColorMask(true, true, true, true);
2264 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2266 // qDebug("QGL2PaintEngineEx::clip()");
2267 Q_D(QGL2PaintEngineEx);
2269 state()->clipChanged = true;
2273 if (op == Qt::ReplaceClip) {
2274 op = Qt::IntersectClip;
2275 if (d->hasClipOperations()) {
2276 d->systemStateChanged();
2277 state()->canRestoreClip = false;
2281 #ifndef QT_GL_NO_SCISSOR_TEST
2282 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2283 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2284 QRectF rect(points[0], points[2]);
2286 if (state()->matrix.type() <= QTransform::TxScale
2287 || (state()->matrix.type() == QTransform::TxRotate
2288 && qFuzzyIsNull(state()->matrix.m11())
2289 && qFuzzyIsNull(state()->matrix.m22())))
2291 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2292 d->updateClipScissorTest();
2298 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2302 if (d->useSystemClip) {
2303 state()->clipTestEnabled = true;
2304 state()->currentClip = 1;
2306 state()->clipTestEnabled = false;
2308 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2309 state()->canRestoreClip = false;
2310 d->updateClipScissorTest();
2312 case Qt::IntersectClip:
2313 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2314 d->updateClipScissorTest();
2315 d->resetClipIfNeeded();
2317 d->writeClip(path, d->maxClip);
2318 state()->currentClip = d->maxClip;
2319 state()->clipTestEnabled = true;
2321 case Qt::UniteClip: {
2322 d->resetClipIfNeeded();
2324 if (state()->rectangleClip.isValid()) {
2326 path.addRect(state()->rectangleClip);
2328 // flush the existing clip rectangle to the depth buffer
2329 d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(path)), d->maxClip);
2332 state()->clipTestEnabled = false;
2333 #ifndef QT_GL_NO_SCISSOR_TEST
2334 QRect oldRectangleClip = state()->rectangleClip;
2336 state()->rectangleClip = state()->rectangleClip.united(pathRect);
2337 d->updateClipScissorTest();
2339 QRegion extendRegion = QRegion(state()->rectangleClip) - oldRectangleClip;
2341 if (!extendRegion.isEmpty()) {
2342 QPainterPath extendPath;
2343 extendPath.addRegion(extendRegion);
2345 // first clear the depth buffer in the extended region
2346 d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(extendPath)), 0);
2349 // now write the clip path
2350 d->writeClip(path, d->maxClip);
2351 state()->canRestoreClip = false;
2352 state()->currentClip = d->maxClip;
2353 state()->clipTestEnabled = true;
2361 void QGL2PaintEngineExPrivate::regenerateClip()
2363 systemStateChanged();
2364 replayClipOperations();
2367 void QGL2PaintEngineExPrivate::systemStateChanged()
2369 Q_Q(QGL2PaintEngineEx);
2371 q->state()->clipChanged = true;
2373 if (systemClip.isEmpty()) {
2374 useSystemClip = false;
2376 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2377 QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2378 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2380 useSystemClip = true;
2384 q->state()->clipTestEnabled = false;
2385 q->state()->needsClipBufferClear = true;
2387 q->state()->currentClip = 1;
2390 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2391 updateClipScissorTest();
2393 if (systemClip.rectCount() == 1) {
2394 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2395 useSystemClip = false;
2396 #ifndef QT_GL_NO_SCISSOR_TEST
2397 // scissoring takes care of the system clip
2402 if (useSystemClip) {
2406 path.addRegion(systemClip);
2408 q->state()->currentClip = 0;
2409 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2410 q->state()->currentClip = 1;
2411 q->state()->clipTestEnabled = true;
2415 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2417 // qDebug("QGL2PaintEngineEx::setState()");
2419 Q_D(QGL2PaintEngineEx);
2421 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2422 QOpenGL2PaintEngineState *old_state = state();
2424 QPaintEngineEx::setState(s);
2427 // Newly created state object. The call to setState()
2428 // will either be followed by a call to begin(), or we are
2429 // setting the state as part of a save().
2434 // Setting the state as part of a restore().
2436 if (old_state == s || old_state->renderHintsChanged)
2437 renderHintsChanged();
2439 if (old_state == s || old_state->matrixChanged)
2440 d->matrixDirty = true;
2442 if (old_state == s || old_state->compositionModeChanged)
2443 d->compositionModeDirty = true;
2445 if (old_state == s || old_state->opacityChanged)
2446 d->opacityUniformDirty = true;
2448 if (old_state == s || old_state->clipChanged) {
2449 if (old_state && old_state != s && old_state->canRestoreClip) {
2450 d->updateClipScissorTest();
2451 glDepthFunc(GL_LEQUAL);
2453 d->regenerateClip();
2458 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2461 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2463 QOpenGL2PaintEngineState *s;
2465 s = new QOpenGL2PaintEngineState();
2467 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2469 s->matrixChanged = false;
2470 s->compositionModeChanged = false;
2471 s->opacityChanged = false;
2472 s->renderHintsChanged = false;
2473 s->clipChanged = false;
2478 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2479 : QPainterState(other)
2482 needsClipBufferClear = other.needsClipBufferClear;
2483 clipTestEnabled = other.clipTestEnabled;
2484 currentClip = other.currentClip;
2485 canRestoreClip = other.canRestoreClip;
2486 rectangleClip = other.rectangleClip;
2489 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2492 needsClipBufferClear = true;
2493 clipTestEnabled = false;
2494 canRestoreClip = true;
2497 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()