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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
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/qpixmapdata_gl_p.h>
80 #include <private/qdatabuffer_p.h>
81 #include <private/qstatictext_p.h>
82 #include <private/qtriangulator_p.h>
84 #include "qglengineshadermanager_p.h"
85 #include "qgl2pexvertexarray_p.h"
86 #include "qtriangulatingstroker_p.h"
87 #include "qtextureglyphcache_gl_p.h"
94 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
98 extern bool qt_applefontsmoothing_enabled;
101 #if !defined(QT_MAX_CACHED_GLYPH_SIZE)
102 # define QT_MAX_CACHED_GLYPH_SIZE 64
105 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
107 ////////////////////////////////// Private Methods //////////////////////////////////////////
109 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
111 delete shaderManager;
113 while (pathCaches.size()) {
114 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
115 e->cleanup(e->engine, e->data);
120 if (elementIndicesVBOId != 0) {
121 glDeleteBuffers(1, &elementIndicesVBOId);
122 elementIndicesVBOId = 0;
126 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
128 // glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
129 if (id != GLuint(-1) && id == lastTextureUsed)
132 lastTextureUsed = id;
134 if (smoothPixmapTransform) {
135 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
136 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
138 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
139 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
141 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
142 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
146 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
148 qreal alpha = c.alphaF() * opacity;
150 c.setRedF(c.redF() * alpha);
151 c.setGreenF(c.greenF() * alpha);
152 c.setBlueF(c.blueF() * alpha);
157 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
159 if (qbrush_fast_equals(currentBrush, brush))
162 const Qt::BrushStyle newStyle = qbrush_style(brush);
163 Q_ASSERT(newStyle != Qt::NoBrush);
165 currentBrush = brush;
166 if (!currentBrushPixmap.isNull())
167 currentBrushPixmap = QPixmap();
168 brushUniformsDirty = true; // All brushes have at least one uniform
170 if (newStyle > Qt::SolidPattern)
171 brushTextureDirty = true;
173 if (currentBrush.style() == Qt::TexturePattern
174 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
176 shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
178 shaderManager->setSrcPixelType(newStyle);
180 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
184 void QGL2PaintEngineExPrivate::useSimpleShader()
186 shaderManager->useSimpleProgram();
192 void QGL2PaintEngineExPrivate::updateBrushTexture()
194 Q_Q(QGL2PaintEngineEx);
195 // qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
196 Qt::BrushStyle style = currentBrush.style();
198 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
199 // Get the image data for the pattern
200 QImage texImage = qt_imageForBrush(style, false);
202 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
203 ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
204 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
206 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
207 // Gradiant brush: All the gradiants use the same texture
209 const QGradient* g = currentBrush.gradient();
211 // We apply global opacity in the fragment shaders, so we always pass 1.0
212 // for opacity to the cache.
213 GLuint texId = QGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
215 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
216 glBindTexture(GL_TEXTURE_2D, texId);
218 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
219 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
220 else if (g->spread() == QGradient::ReflectSpread)
221 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, q->state()->renderHints & QPainter::SmoothPixmapTransform);
223 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
225 else if (style == Qt::TexturePattern) {
226 currentBrushPixmap = currentBrush.texture();
228 int max_texture_size = ctx->d_func()->maxTextureSize();
229 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
230 currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
232 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
233 QGLTexture *tex = ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
234 QGLContext::InternalBindOption |
235 QGLContext::CanFlipNativePixmapBindOption);
236 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
237 textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
239 brushTextureDirty = false;
243 void QGL2PaintEngineExPrivate::updateBrushUniforms()
245 // qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
246 Qt::BrushStyle style = currentBrush.style();
248 if (style == Qt::NoBrush)
251 QTransform brushQTransform = currentBrush.transform();
253 if (style == Qt::SolidPattern) {
254 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
255 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::FragmentColor), col);
258 // All other brushes have a transform and thus need the translation point:
259 QPointF translationPoint;
261 if (style <= Qt::DiagCrossPattern) {
262 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
264 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
266 QVector2D halfViewportSize(width*0.5, height*0.5);
267 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
269 else if (style == Qt::LinearGradientPattern) {
270 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
272 QPointF realStart = g->start();
273 QPointF realFinal = g->finalStop();
274 translationPoint = realStart;
276 QPointF l = realFinal - realStart;
278 QVector3D linearData(
281 1.0f / (l.x() * l.x() + l.y() * l.y())
284 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::LinearData), linearData);
286 QVector2D halfViewportSize(width*0.5, height*0.5);
287 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
289 else if (style == Qt::ConicalGradientPattern) {
290 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
291 translationPoint = g->center();
293 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
295 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Angle), angle);
297 QVector2D halfViewportSize(width*0.5, height*0.5);
298 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
300 else if (style == Qt::RadialGradientPattern) {
301 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
302 QPointF realCenter = g->center();
303 QPointF realFocal = g->focalPoint();
304 qreal realRadius = g->centerRadius() - g->focalRadius();
305 translationPoint = realFocal;
307 QPointF fmp = realCenter - realFocal;
308 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp), fmp);
310 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
311 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
312 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Inverse2Fmp2MRadius2),
313 GLfloat(1.0 / (2.0*fmp2_m_radius2)));
314 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::SqrFr),
315 GLfloat(g->focalRadius() * g->focalRadius()));
316 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BRadius),
317 GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
319 g->centerRadius() - g->focalRadius());
321 QVector2D halfViewportSize(width*0.5, height*0.5);
322 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
324 else if (style == Qt::TexturePattern) {
325 const QPixmap& texPixmap = currentBrush.texture();
327 if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
328 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
329 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
332 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
333 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
335 QVector2D halfViewportSize(width*0.5, height*0.5);
336 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
339 qWarning("QGL2PaintEngineEx: Unimplemented fill style");
341 const QPointF &brushOrigin = q->state()->brushOrigin;
342 QTransform matrix = q->state()->matrix;
343 matrix.translate(brushOrigin.x(), brushOrigin.y());
345 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
348 if (device->isFlipped()) {
352 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
353 QTransform inv_matrix;
354 if (style == Qt::TexturePattern && textureInvertedY == -1)
355 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
357 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
359 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTransform), inv_matrix);
360 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
362 brushUniformsDirty = false;
366 // This assumes the shader manager has already setup the correct shader program
367 void QGL2PaintEngineExPrivate::updateMatrix()
369 // qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
371 const QTransform& transform = q->state()->matrix;
373 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
374 // * GL's viewport is 2x2, Qt's is width x height
375 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
376 // * GL has [0,0] in the center, Qt has it in the top-left
378 // This results in the Projection matrix below, which is multiplied by the painter's
379 // transformation matrix, as shown below:
381 // Projection Matrix Painter Transform
382 // ------------------------------------------------ ------------------------
383 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
384 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
385 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
386 // ------------------------------------------------ ------------------------
388 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
390 const GLfloat wfactor = 2.0f / width;
391 GLfloat hfactor = -2.0f / height;
393 GLfloat dx = transform.dx();
394 GLfloat dy = transform.dy();
396 if (device->isFlipped()) {
401 // Non-integer translates can have strange effects for some rendering operations such as
402 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
403 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
404 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
405 dx = ceilf(dx - 0.5f);
406 dy = ceilf(dy - 0.5f);
408 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
409 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
410 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
411 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
412 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
413 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
414 pmvMatrix[0][2] = transform.m13();
415 pmvMatrix[1][2] = transform.m23();
416 pmvMatrix[2][2] = transform.m33();
418 // 1/10000 == 0.0001, so we have good enough res to cover curves
419 // that span the entire widget...
420 inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
421 qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
425 matrixUniformDirty = true;
427 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
428 // need to do this once for every matrix change and persists across all shader programs.
429 glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
430 glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
431 glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
433 dasher.setInvScale(inverseScale);
434 stroker.setInvScale(inverseScale);
438 void QGL2PaintEngineExPrivate::updateCompositionMode()
440 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
441 // composition modes look odd.
442 // qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
443 switch(q->state()->composition_mode) {
444 case QPainter::CompositionMode_SourceOver:
445 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
447 case QPainter::CompositionMode_DestinationOver:
448 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
450 case QPainter::CompositionMode_Clear:
451 glBlendFunc(GL_ZERO, GL_ZERO);
453 case QPainter::CompositionMode_Source:
454 glBlendFunc(GL_ONE, GL_ZERO);
456 case QPainter::CompositionMode_Destination:
457 glBlendFunc(GL_ZERO, GL_ONE);
459 case QPainter::CompositionMode_SourceIn:
460 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
462 case QPainter::CompositionMode_DestinationIn:
463 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
465 case QPainter::CompositionMode_SourceOut:
466 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
468 case QPainter::CompositionMode_DestinationOut:
469 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
471 case QPainter::CompositionMode_SourceAtop:
472 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
474 case QPainter::CompositionMode_DestinationAtop:
475 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
477 case QPainter::CompositionMode_Xor:
478 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
480 case QPainter::CompositionMode_Plus:
481 glBlendFunc(GL_ONE, GL_ONE);
484 qWarning("Unsupported composition mode");
488 compositionModeDirty = false;
491 static inline void setCoords(GLfloat *coords, const QGLRect &rect)
493 coords[0] = rect.left;
494 coords[1] = rect.top;
495 coords[2] = rect.right;
496 coords[3] = rect.top;
497 coords[4] = rect.right;
498 coords[5] = rect.bottom;
499 coords[6] = rect.left;
500 coords[7] = rect.bottom;
503 void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
505 // Setup for texture drawing
506 currentBrush = noBrush;
507 shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
509 if (snapToPixelGrid) {
510 snapToPixelGrid = false;
514 if (prepareForDraw(opaque))
515 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
518 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
519 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
522 GLfloat dx = 1.0 / textureSize.width();
523 GLfloat dy = 1.0 / textureSize.height();
525 QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
527 setCoords(staticVertexCoordinateArray, dest);
528 setCoords(staticTextureCoordinateArray, srcTextureRect);
530 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
533 void QGL2PaintEngineEx::beginNativePainting()
535 Q_D(QGL2PaintEngineEx);
537 d->transferMode(BrushDrawingMode);
539 d->nativePaintingActive = true;
541 QGLContext *ctx = d->ctx;
544 // Disable all the vertex attribute arrays:
545 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
546 glDisableVertexAttribArray(i);
548 #ifndef QT_OPENGL_ES_2
549 const QGLFormat &fmt = d->device->format();
550 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
551 || fmt.profile() == QGLFormat::CompatibilityProfile)
553 // be nice to people who mix OpenGL 1.x code with QPainter commands
554 // by setting modelview and projection matrices to mirror the GL 1
556 const QTransform& mtx = state()->matrix;
558 float mv_matrix[4][4] =
560 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
561 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
563 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
566 const QSize sz = d->device->size();
568 glMatrixMode(GL_PROJECTION);
570 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
572 glMatrixMode(GL_MODELVIEW);
573 glLoadMatrixf(&mv_matrix[0][0]);
579 d->lastTextureUsed = GLuint(-1);
580 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
583 d->shaderManager->setDirty();
588 void QGL2PaintEngineExPrivate::resetGLState()
591 glActiveTexture(GL_TEXTURE0);
592 glDisable(GL_STENCIL_TEST);
593 glDisable(GL_DEPTH_TEST);
594 glDisable(GL_SCISSOR_TEST);
596 glDepthFunc(GL_LESS);
599 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
600 glStencilFunc(GL_ALWAYS, 0, 0xff);
601 ctx->d_func()->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
602 ctx->d_func()->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
603 ctx->d_func()->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
604 #ifndef QT_OPENGL_ES_2
605 // gl_Color, corresponding to vertex attribute 3, may have been changed
606 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
607 glVertexAttrib4fv(3, color);
611 void QGL2PaintEngineEx::endNativePainting()
613 Q_D(QGL2PaintEngineEx);
615 d->nativePaintingActive = false;
618 void QGL2PaintEngineEx::invalidateState()
620 Q_D(QGL2PaintEngineEx);
624 bool QGL2PaintEngineEx::isNativePaintingActive() const {
625 Q_D(const QGL2PaintEngineEx);
626 return d->nativePaintingActive;
629 void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
634 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
635 lastTextureUsed = GLuint(-1);
638 if (newMode == TextDrawingMode) {
639 shaderManager->setHasComplexGeometry(true);
641 shaderManager->setHasComplexGeometry(false);
644 if (newMode == ImageDrawingMode) {
645 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
646 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
649 if (newMode == ImageArrayDrawingMode) {
650 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
651 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
652 setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
655 // This needs to change when we implement high-quality anti-aliasing...
656 if (newMode != TextDrawingMode)
657 shaderManager->setMaskType(QGLEngineShaderManager::NoMask);
662 struct QGL2PEVectorPathCache
664 #ifdef QT_OPENGL_CACHE_AS_VBOS
673 GLenum primitiveType;
677 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
679 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
680 #ifdef QT_OPENGL_CACHE_AS_VBOS
681 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
682 static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
684 d->unusedIBOSToClean << c->ibo;
693 // Assumes everything is configured for the brush you want to use
694 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
696 transferMode(BrushDrawingMode);
698 if (snapToPixelGrid) {
699 snapToPixelGrid = false;
703 // Might need to call updateMatrix to re-calculate inverseScale
707 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
709 // Check to see if there's any hints
710 if (path.shape() == QVectorPath::RectangleHint) {
711 QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
712 prepareForDraw(currentBrush.isOpaque());
714 } else if (path.isConvex()) {
716 if (path.isCacheable()) {
717 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
718 QGL2PEVectorPathCache *cache;
720 bool updateCache = false;
723 cache = (QGL2PEVectorPathCache *) data->data;
724 // Check if scale factor is exceeded for curved paths and generate curves if so...
725 if (path.isCurved()) {
726 qreal scaleFactor = cache->iscale / inverseScale;
727 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
728 #ifdef QT_OPENGL_CACHE_AS_VBOS
729 glDeleteBuffers(1, &cache->vbo);
731 Q_ASSERT(cache->ibo == 0);
733 qFree(cache->vertices);
734 Q_ASSERT(cache->indices == 0);
740 cache = new QGL2PEVectorPathCache;
741 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
745 // Flatten the path at the current scale factor and fill it into the cache struct.
747 vertexCoordinateArray.clear();
748 vertexCoordinateArray.addPath(path, inverseScale, false);
749 int vertexCount = vertexCoordinateArray.vertexCount();
750 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
751 cache->vertexCount = vertexCount;
752 cache->indexCount = 0;
753 cache->primitiveType = GL_TRIANGLE_FAN;
754 cache->iscale = inverseScale;
755 #ifdef QT_OPENGL_CACHE_AS_VBOS
756 glGenBuffers(1, &cache->vbo);
757 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
758 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
761 cache->vertices = (float *) qMalloc(floatSizeInBytes);
762 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
767 prepareForDraw(currentBrush.isOpaque());
768 #ifdef QT_OPENGL_CACHE_AS_VBOS
769 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
770 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
772 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
774 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
777 // printf(" - Marking path as cachable...\n");
778 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
779 path.makeCacheable();
780 vertexCoordinateArray.clear();
781 vertexCoordinateArray.addPath(path, inverseScale, false);
782 prepareForDraw(currentBrush.isOpaque());
783 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
787 bool useCache = path.isCacheable();
789 QRectF bbox = path.controlPointRect();
790 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
791 useCache &= (bbox.left() > -0x8000 * inverseScale)
792 && (bbox.right() < 0x8000 * inverseScale)
793 && (bbox.top() > -0x8000 * inverseScale)
794 && (bbox.bottom() < 0x8000 * inverseScale);
798 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
799 QGL2PEVectorPathCache *cache;
801 bool updateCache = false;
804 cache = (QGL2PEVectorPathCache *) data->data;
805 // Check if scale factor is exceeded for curved paths and generate curves if so...
806 if (path.isCurved()) {
807 qreal scaleFactor = cache->iscale / inverseScale;
808 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
809 #ifdef QT_OPENGL_CACHE_AS_VBOS
810 glDeleteBuffers(1, &cache->vbo);
811 glDeleteBuffers(1, &cache->ibo);
813 qFree(cache->vertices);
814 qFree(cache->indices);
820 cache = new QGL2PEVectorPathCache;
821 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
825 // Flatten the path at the current scale factor and fill it into the cache struct.
827 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
828 cache->vertexCount = polys.vertices.size() / 2;
829 cache->indexCount = polys.indices.size();
830 cache->primitiveType = GL_TRIANGLES;
831 cache->iscale = inverseScale;
832 #ifdef QT_OPENGL_CACHE_AS_VBOS
833 glGenBuffers(1, &cache->vbo);
834 glGenBuffers(1, &cache->ibo);
835 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
836 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
838 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
839 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
841 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
843 QVarLengthArray<float> vertices(polys.vertices.size());
844 for (int i = 0; i < polys.vertices.size(); ++i)
845 vertices[i] = float(inverseScale * polys.vertices.at(i));
846 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
848 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
849 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint) {
850 cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
851 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
853 cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
854 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
856 for (int i = 0; i < polys.vertices.size(); ++i)
857 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
861 prepareForDraw(currentBrush.isOpaque());
862 #ifdef QT_OPENGL_CACHE_AS_VBOS
863 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
864 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
865 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
866 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
867 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
869 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
870 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
871 glBindBuffer(GL_ARRAY_BUFFER, 0);
873 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
874 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
875 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
877 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
881 // printf(" - Marking path as cachable...\n");
882 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
883 path.makeCacheable();
885 if (!device->format().stencil()) {
886 // If there is no stencil buffer, triangulate the path instead.
888 QRectF bbox = path.controlPointRect();
889 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
890 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
891 && (bbox.right() < 0x8000 * inverseScale)
892 && (bbox.top() > -0x8000 * inverseScale)
893 && (bbox.bottom() < 0x8000 * inverseScale);
895 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
897 QVarLengthArray<float> vertices(polys.vertices.size());
898 for (int i = 0; i < polys.vertices.size(); ++i)
899 vertices[i] = float(inverseScale * polys.vertices.at(i));
901 prepareForDraw(currentBrush.isOpaque());
902 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
903 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
904 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
906 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
908 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
909 qWarning("Painter path exceeds +/-32767 pixels.");
914 // The path is too complicated & needs the stencil technique
915 vertexCoordinateArray.clear();
916 vertexCoordinateArray.addPath(path, inverseScale, false);
918 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
921 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
923 if (q->state()->clipTestEnabled) {
924 // Pass when high bit is set, replace stencil value with current clip
925 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
926 } else if (path.hasWindingFill()) {
927 // Pass when any bit is set, replace stencil value with 0
928 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
930 // Pass when high bit is set, replace stencil value with 0
931 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
933 prepareForDraw(currentBrush.isOpaque());
935 // Stencil the brush onto the dest buffer
936 composite(vertexCoordinateArray.boundingRect());
938 updateClipScissorTest();
944 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
948 const QGLRect &bounds,
949 StencilFillMode mode)
951 Q_ASSERT(count || stops);
953 // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
954 glStencilMask(0xff); // Enable stencil writes
956 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
957 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
958 glClearStencil(0); // Clear to zero
959 for (int i = 0; i < clearRegion.size(); ++i) {
960 #ifndef QT_GL_NO_SCISSOR_TEST
961 setScissor(clearRegion.at(i));
963 glClear(GL_STENCIL_BUFFER_BIT);
966 dirtyStencilRegion -= currentScissorBounds;
968 #ifndef QT_GL_NO_SCISSOR_TEST
969 updateClipScissorTest();
973 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
975 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
977 if (mode == WindingFillMode) {
978 Q_ASSERT(stops && !count);
979 if (q->state()->clipTestEnabled) {
980 // Flatten clip values higher than current clip, and set high bit to match current clip
981 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
982 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
985 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
986 } else if (!stencilClean) {
987 // Clear stencil buffer within bounding rect
988 glStencilFunc(GL_ALWAYS, 0, 0xff);
989 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
993 // Inc. for front-facing triangle
994 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
995 // Dec. for back-facing "holes"
996 glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
997 glStencilMask(~GL_STENCIL_HIGH_BIT);
998 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1000 if (q->state()->clipTestEnabled) {
1001 // Clear high bit of stencil outside of path
1002 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1003 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1004 glStencilMask(GL_STENCIL_HIGH_BIT);
1007 } else if (mode == OddEvenFillMode) {
1008 glStencilMask(GL_STENCIL_HIGH_BIT);
1009 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1010 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1012 } else { // TriStripStrokeFillMode
1013 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1014 glStencilMask(GL_STENCIL_HIGH_BIT);
1016 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1017 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1018 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1021 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1022 if (q->state()->clipTestEnabled) {
1023 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1024 ~GL_STENCIL_HIGH_BIT);
1026 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1028 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1029 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1033 // Enable color writes & disable stencil writes
1034 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1038 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1039 restore the stencil buffer to a pristine state. The current clip region
1040 is set to 1, and the rest to 0.
1042 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1044 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1047 Q_Q(QGL2PaintEngineEx);
1050 glEnable(GL_STENCIL_TEST);
1051 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1053 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1054 QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1056 // Set high bit on clip region
1057 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1058 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1059 glStencilMask(GL_STENCIL_HIGH_BIT);
1062 // Reset clipping to 1 and everything else to zero
1063 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1064 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1065 glStencilMask(0xff);
1068 q->state()->currentClip = 1;
1069 q->state()->canRestoreClip = false;
1074 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1077 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1079 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1080 updateBrushTexture();
1082 if (compositionModeDirty)
1083 updateCompositionMode();
1088 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1089 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1090 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1091 && srcPixelsAreOpaque && !stateHasOpacity))
1093 glDisable(GL_BLEND);
1098 QGLEngineShaderManager::OpacityMode opacityMode;
1099 if (mode == ImageArrayDrawingMode) {
1100 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1102 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1103 : QGLEngineShaderManager::NoOpacity;
1104 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1106 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1107 (currentBrush.style() <= Qt::DiagCrossPattern);
1109 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1110 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1113 shaderManager->setOpacityMode(opacityMode);
1115 bool changed = shaderManager->useCorrectShaderProg();
1116 // If the shader program needs changing, we change it and mark all uniforms as dirty
1118 // The shader program has changed so mark all uniforms as dirty:
1119 brushUniformsDirty = true;
1120 opacityUniformDirty = true;
1121 matrixUniformDirty = true;
1124 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1125 updateBrushUniforms();
1127 if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1128 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1129 opacityUniformDirty = false;
1132 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1133 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1135 matrixUniformDirty = false;
1141 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1143 setCoords(staticVertexCoordinateArray, boundingRect);
1144 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1145 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1148 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1149 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1152 // Now setup the pointer to the vertex array:
1153 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1155 int previousStop = 0;
1156 for (int i=0; i<stopCount; ++i) {
1157 int stop = stops[i];
1159 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1160 for (int i=previousStop; i<stop; ++i)
1161 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1163 glDrawArrays(primitive, previousStop, stop - previousStop);
1164 previousStop = stop;
1168 /////////////////////////////////// Public Methods //////////////////////////////////////////
1170 QGL2PaintEngineEx::QGL2PaintEngineEx()
1171 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1175 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1179 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1181 Q_D(QGL2PaintEngineEx);
1183 if (qbrush_style(brush) == Qt::NoBrush)
1190 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1193 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1195 Q_D(QGL2PaintEngineEx);
1197 const QBrush &penBrush = qpen_brush(pen);
1198 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1201 QOpenGL2PaintEngineState *s = state();
1202 if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1203 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1204 QPaintEngineEx::stroke(path, pen);
1209 d->setBrush(penBrush);
1210 d->stroke(path, pen);
1213 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1215 const QOpenGL2PaintEngineState *s = q->state();
1216 if (snapToPixelGrid) {
1217 snapToPixelGrid = false;
1221 const Qt::PenStyle penStyle = qpen_style(pen);
1222 const QBrush &penBrush = qpen_brush(pen);
1223 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1225 transferMode(BrushDrawingMode);
1227 // updateMatrix() is responsible for setting the inverse scale on
1228 // the strokers, so we need to call it here and not wait for
1229 // prepareForDraw() down below.
1232 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1233 ? q->state()->rectangleClip
1234 : QRectF(0, 0, width, height));
1236 if (penStyle == Qt::SolidLine) {
1237 stroker.process(path, pen, clip);
1239 } else { // Some sort of dash
1240 dasher.process(path, pen, clip);
1242 QVectorPath dashStroke(dasher.points(),
1243 dasher.elementCount(),
1244 dasher.elementTypes());
1245 stroker.process(dashStroke, pen, clip);
1248 if (!stroker.vertexCount())
1252 prepareForDraw(opaque);
1253 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1254 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1256 // QBrush b(Qt::green);
1258 // d->prepareForDraw(true);
1259 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1262 qreal width = qpen_widthf(pen) / 2;
1265 qreal extra = pen.joinStyle() == Qt::MiterJoin
1266 ? qMax(pen.miterLimit() * width, width)
1269 if (pen.isCosmetic())
1270 extra = extra * inverseScale;
1272 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1274 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1275 0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1277 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1279 // Pass when any bit is set, replace stencil value with 0
1280 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1281 prepareForDraw(false);
1283 // Stencil the brush onto the dest buffer
1288 updateClipScissorTest();
1292 void QGL2PaintEngineEx::penChanged() { }
1293 void QGL2PaintEngineEx::brushChanged() { }
1294 void QGL2PaintEngineEx::brushOriginChanged() { }
1296 void QGL2PaintEngineEx::opacityChanged()
1298 // qDebug("QGL2PaintEngineEx::opacityChanged()");
1299 Q_D(QGL2PaintEngineEx);
1300 state()->opacityChanged = true;
1302 Q_ASSERT(d->shaderManager);
1303 d->brushUniformsDirty = true;
1304 d->opacityUniformDirty = true;
1307 void QGL2PaintEngineEx::compositionModeChanged()
1309 // qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1310 Q_D(QGL2PaintEngineEx);
1311 state()->compositionModeChanged = true;
1312 d->compositionModeDirty = true;
1315 void QGL2PaintEngineEx::renderHintsChanged()
1317 state()->renderHintsChanged = true;
1319 #if !defined(QT_OPENGL_ES_2)
1320 if ((state()->renderHints & QPainter::Antialiasing)
1321 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1322 glEnable(GL_MULTISAMPLE);
1324 glDisable(GL_MULTISAMPLE);
1327 Q_D(QGL2PaintEngineEx);
1328 d->lastTextureUsed = GLuint(-1);
1329 d->brushTextureDirty = true;
1330 // qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1333 void QGL2PaintEngineEx::transformChanged()
1335 Q_D(QGL2PaintEngineEx);
1336 d->matrixDirty = true;
1337 state()->matrixChanged = true;
1341 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1343 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1346 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1348 Q_D(QGL2PaintEngineEx);
1349 QGLContext *ctx = d->ctx;
1351 int max_texture_size = ctx->d_func()->maxTextureSize();
1352 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1353 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1355 const qreal sx = scaled.width() / qreal(pixmap.width());
1356 const qreal sy = scaled.height() / qreal(pixmap.height());
1358 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1363 d->transferMode(ImageDrawingMode);
1365 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1366 #ifdef QGL_USE_TEXTURE_POOL
1367 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1370 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1371 QGLTexture *texture =
1372 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1374 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1375 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1376 QGLRect srcRect(src.left(), top, src.right(), bottom);
1378 bool isBitmap = pixmap.isQBitmap();
1379 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1381 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1382 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1383 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1385 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1386 // pixmap was temporarily cached as a QImage texture by pooling system
1387 // and should be destroyed immediately
1388 QGLTextureCache::instance()->remove(ctx, texture->id);
1392 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1393 Qt::ImageConversionFlags)
1395 Q_D(QGL2PaintEngineEx);
1396 QGLContext *ctx = d->ctx;
1398 int max_texture_size = ctx->d_func()->maxTextureSize();
1399 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1400 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1402 const qreal sx = scaled.width() / qreal(image.width());
1403 const qreal sy = scaled.height() / qreal(image.height());
1405 drawImage(dest, scaled, scaleRect(src, sx, sy));
1410 d->transferMode(ImageDrawingMode);
1412 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1414 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1415 #ifdef QGL_USE_TEXTURE_POOL
1416 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1419 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1420 GLuint id = texture->id;
1422 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1423 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1424 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1426 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1427 // image was temporarily cached by texture pooling system
1428 // and should be destroyed immediately
1429 QGLTextureCache::instance()->remove(ctx, texture->id);
1433 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1435 Q_D(QGL2PaintEngineEx);
1439 QFontEngineGlyphCache::Type glyphType = textItem->fontEngine()->glyphFormat >= 0
1440 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1441 : d->glyphCacheType;
1442 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1443 if (d->device->alphaRequested() || state()->matrix.type() > QTransform::TxTranslate
1444 || (state()->composition_mode != QPainter::CompositionMode_Source
1445 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1447 glyphType = QFontEngineGlyphCache::Raster_A8;
1451 d->drawCachedGlyphs(glyphType, textItem);
1454 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1456 Q_D(QGL2PaintEngineEx);
1457 if (!d->shaderManager)
1461 d->transferMode(ImageDrawingMode);
1463 #ifndef QT_OPENGL_ES_2
1464 QGLContext *ctx = d->ctx;
1466 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1467 glBindTexture(GL_TEXTURE_2D, textureId);
1469 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1471 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1472 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1473 d->drawTexture(dest, srcRect, size, false);
1477 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1479 Q_D(QGL2PaintEngineEx);
1482 QOpenGL2PaintEngineState *s = state();
1484 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1486 QTransform::TransformationType txtype = s->matrix.type();
1488 float det = s->matrix.determinant();
1489 bool drawCached = txtype < QTransform::TxProject;
1491 // don't try to cache huge fonts or vastly transformed fonts
1492 const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1493 if (pixelSize * pixelSize * qAbs(det) >= QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE ||
1494 det < 0.25f || det > 4.f)
1497 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1498 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1499 : d->glyphCacheType;
1502 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1503 if (d->device->alphaRequested() || txtype > QTransform::TxTranslate
1504 || (state()->composition_mode != QPainter::CompositionMode_Source
1505 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1507 glyphType = QFontEngineGlyphCache::Raster_A8;
1512 QVarLengthArray<QFixedPoint> positions;
1513 QVarLengthArray<glyph_t> glyphs;
1514 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1515 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1518 QStaticTextItem staticTextItem;
1519 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1520 staticTextItem.setFontEngine(ti.fontEngine);
1521 staticTextItem.glyphs = glyphs.data();
1522 staticTextItem.numChars = ti.num_chars;
1523 staticTextItem.numGlyphs = glyphs.size();
1524 staticTextItem.glyphPositions = positions.data();
1526 d->drawCachedGlyphs(glyphType, &staticTextItem);
1531 QPaintEngineEx::drawTextItem(p, ti);
1536 class QOpenGLStaticTextUserData: public QStaticTextUserData
1539 QOpenGLStaticTextUserData()
1540 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1544 ~QOpenGLStaticTextUserData()
1549 QGL2PEXVertexArray vertexCoordinateArray;
1550 QGL2PEXVertexArray textureCoordinateArray;
1551 QFontEngineGlyphCache::Type glyphType;
1552 int cacheSerialNumber;
1557 #if defined(Q_WS_WIN)
1558 static bool fontSmoothingApproximately(qreal target)
1560 extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1561 return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1565 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1567 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1568 QStaticTextItem *staticTextItem)
1570 Q_Q(QGL2PaintEngineEx);
1572 QOpenGL2PaintEngineState *s = q->state();
1574 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1575 bool recreateVertexArrays = false;
1577 QGLTextureGlyphCache *cache =
1578 (QGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1579 if (!cache || cache->cacheType() != glyphType || cache->context() == 0) {
1580 cache = new QGLTextureGlyphCache(ctx, glyphType, QTransform());
1581 staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1582 cache->insert(ctx, cache);
1583 recreateVertexArrays = true;
1586 if (staticTextItem->userDataNeedsUpdate) {
1587 recreateVertexArrays = true;
1588 } else if (staticTextItem->userData() == 0) {
1589 recreateVertexArrays = true;
1590 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1591 recreateVertexArrays = true;
1593 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1594 if (userData->glyphType != glyphType) {
1595 recreateVertexArrays = true;
1596 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1597 recreateVertexArrays = true;
1601 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1602 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1603 // cache so this text is performed before we test if the cache size has changed.
1604 if (recreateVertexArrays) {
1605 cache->setPaintEnginePrivate(this);
1606 if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1607 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1608 // No space for glyphs in cache. We need to reset it and try again.
1610 cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1611 staticTextItem->glyphs, staticTextItem->glyphPositions);
1613 cache->fillInPendingGlyphs();
1616 if (cache->width() == 0 || cache->height() == 0)
1619 transferMode(TextDrawingMode);
1621 int margin = cache->glyphMargin();
1623 GLfloat dx = 1.0 / cache->width();
1624 GLfloat dy = 1.0 / cache->height();
1626 // Use global arrays by default
1627 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1628 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1630 if (staticTextItem->useBackendOptimizations) {
1631 QOpenGLStaticTextUserData *userData = 0;
1633 if (staticTextItem->userData() == 0
1634 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1636 userData = new QOpenGLStaticTextUserData();
1637 staticTextItem->setUserData(userData);
1640 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1643 userData->glyphType = glyphType;
1644 userData->cacheSerialNumber = cache->serialNumber();
1646 // Use cache if backend optimizations is turned on
1647 vertexCoordinates = &userData->vertexCoordinateArray;
1648 textureCoordinates = &userData->textureCoordinateArray;
1650 QSize size(cache->width(), cache->height());
1651 if (userData->cacheSize != size) {
1652 recreateVertexArrays = true;
1653 userData->cacheSize = size;
1657 if (recreateVertexArrays) {
1658 vertexCoordinates->clear();
1659 textureCoordinates->clear();
1661 bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1662 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1663 QFixed subPixelPosition;
1664 if (supportsSubPixelPositions)
1665 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1667 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1669 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1673 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1674 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1676 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1677 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1680 staticTextItem->userDataNeedsUpdate = false;
1683 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1685 if (elementIndices.size() < numGlyphs*6) {
1686 Q_ASSERT(elementIndices.size() % 6 == 0);
1687 int j = elementIndices.size() / 6 * 4;
1688 while (j < numGlyphs*4) {
1689 elementIndices.append(j + 0);
1690 elementIndices.append(j + 0);
1691 elementIndices.append(j + 1);
1692 elementIndices.append(j + 2);
1693 elementIndices.append(j + 3);
1694 elementIndices.append(j + 3);
1699 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1700 if (elementIndicesVBOId == 0)
1701 glGenBuffers(1, &elementIndicesVBOId);
1703 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1704 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1705 elementIndices.constData(), GL_STATIC_DRAW);
1708 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1709 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1713 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1714 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1716 if (!snapToPixelGrid) {
1717 snapToPixelGrid = true;
1721 QBrush pensBrush = q->state()->pen.brush();
1722 setBrush(pensBrush);
1724 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1726 // Subpixel antialiasing without gamma correction
1728 QPainter::CompositionMode compMode = q->state()->composition_mode;
1729 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1730 || compMode == QPainter::CompositionMode_SourceOver);
1732 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1734 if (pensBrush.style() == Qt::SolidPattern) {
1735 // Solid patterns can get away with only one pass.
1736 QColor c = pensBrush.color();
1737 qreal oldOpacity = q->state()->opacity;
1738 if (compMode == QPainter::CompositionMode_Source) {
1739 c = qt_premultiplyColor(c, q->state()->opacity);
1740 q->state()->opacity = 1;
1741 opacityUniformDirty = true;
1744 compositionModeDirty = false; // I can handle this myself, thank you very much
1745 prepareForDraw(false); // Text always causes src pixels to be transparent
1747 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1748 if (compMode == QPainter::CompositionMode_Source) {
1749 q->state()->opacity = oldOpacity;
1750 opacityUniformDirty = true;
1754 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1755 glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1757 // Other brush styles need two passes.
1759 qreal oldOpacity = q->state()->opacity;
1760 if (compMode == QPainter::CompositionMode_Source) {
1761 q->state()->opacity = 1;
1762 opacityUniformDirty = true;
1763 pensBrush = Qt::white;
1764 setBrush(pensBrush);
1767 compositionModeDirty = false; // I can handle this myself, thank you very much
1768 prepareForDraw(false); // Text always causes src pixels to be transparent
1770 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1772 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1773 glBindTexture(GL_TEXTURE_2D, cache->texture());
1774 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1776 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1777 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1779 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1782 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1784 if (compMode == QPainter::CompositionMode_Source) {
1785 q->state()->opacity = oldOpacity;
1786 opacityUniformDirty = true;
1787 pensBrush = q->state()->pen.brush();
1788 setBrush(pensBrush);
1791 compositionModeDirty = false;
1792 prepareForDraw(false); // Text always causes src pixels to be transparent
1794 glBlendFunc(GL_ONE, GL_ONE);
1796 compositionModeDirty = true;
1798 // Greyscale/mono glyphs
1800 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1801 prepareForDraw(false); // Text always causes src pixels to be transparent
1804 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1805 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1807 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1808 if (lastMaskTextureUsed != cache->texture()) {
1809 glBindTexture(GL_TEXTURE_2D, cache->texture());
1810 lastMaskTextureUsed = cache->texture();
1813 if (cache->filterMode() != filterMode) {
1814 if (filterMode == QGLTextureGlyphCache::Linear) {
1815 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1816 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1818 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1819 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1821 cache->setFilterMode(filterMode);
1825 bool srgbFrameBufferEnabled = false;
1826 if (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer) {
1827 #if defined(Q_WS_MAC)
1828 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1829 #elif defined(Q_WS_WIN)
1830 if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1835 glEnable(FRAMEBUFFER_SRGB_EXT);
1836 srgbFrameBufferEnabled = true;
1840 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1841 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1842 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1844 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1847 if (srgbFrameBufferEnabled)
1848 glDisable(FRAMEBUFFER_SRGB_EXT);
1852 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1853 QPainter::PixmapFragmentHints hints)
1855 Q_D(QGL2PaintEngineEx);
1856 // Use fallback for extended composition modes.
1857 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1858 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1863 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1864 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1865 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1866 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1868 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1873 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1874 int fragmentCount, const QPixmap &pixmap,
1875 QPainter::PixmapFragmentHints hints)
1877 GLfloat dx = 1.0f / pixmap.size().width();
1878 GLfloat dy = 1.0f / pixmap.size().height();
1880 vertexCoordinateArray.clear();
1881 textureCoordinateArray.clear();
1882 opacityArray.reset();
1884 if (snapToPixelGrid) {
1885 snapToPixelGrid = false;
1889 bool allOpaque = true;
1891 for (int i = 0; i < fragmentCount; ++i) {
1894 if (fragments[i].rotation != 0) {
1895 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1896 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1899 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1900 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1901 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1902 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1904 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1905 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1906 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1907 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1908 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1909 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1911 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1912 (fragments[i].sourceLeft + fragments[i].width) * dx,
1913 (fragments[i].sourceTop + fragments[i].height) * dy);
1915 textureCoordinateArray.addVertex(src.right, src.bottom);
1916 textureCoordinateArray.addVertex(src.right, src.top);
1917 textureCoordinateArray.addVertex(src.left, src.top);
1918 textureCoordinateArray.addVertex(src.left, src.top);
1919 textureCoordinateArray.addVertex(src.left, src.bottom);
1920 textureCoordinateArray.addVertex(src.right, src.bottom);
1922 qreal opacity = fragments[i].opacity * q->state()->opacity;
1923 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1924 allOpaque &= (opacity >= 0.99f);
1927 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1928 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1929 QGLContext::InternalBindOption
1930 | QGLContext::CanFlipNativePixmapBindOption);
1932 if (texture->options & QGLContext::InvertedYBindOption) {
1933 // Flip texture y-coordinate.
1934 QGLPoint *data = textureCoordinateArray.data();
1935 for (int i = 0; i < 6 * fragmentCount; ++i)
1936 data[i].y = 1 - data[i].y;
1939 transferMode(ImageArrayDrawingMode);
1941 bool isBitmap = pixmap.isQBitmap();
1942 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1944 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1945 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1947 // Setup for texture drawing
1948 currentBrush = noBrush;
1949 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1950 : QGLEngineShaderManager::ImageSrc);
1951 if (prepareForDraw(isOpaque))
1952 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1955 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1956 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1959 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1962 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1964 Q_D(QGL2PaintEngineEx);
1966 // qDebug("QGL2PaintEngineEx::begin()");
1967 if (pdev->devType() == QInternal::OpenGL)
1968 d->device = static_cast<QGLPaintDevice*>(pdev);
1970 d->device = QGLPaintDevice::getDevice(pdev);
1975 d->ctx = d->device->context();
1976 d->ctx->d_ptr->active_engine = this;
1978 const QSize sz = d->device->size();
1979 d->width = sz.width();
1980 d->height = sz.height();
1981 d->mode = BrushDrawingMode;
1982 d->brushTextureDirty = true;
1983 d->brushUniformsDirty = true;
1984 d->matrixUniformDirty = true;
1985 d->matrixDirty = true;
1986 d->compositionModeDirty = true;
1987 d->opacityUniformDirty = true;
1988 d->needsSync = true;
1989 d->useSystemClip = !systemClip().isEmpty();
1990 d->currentBrush = QBrush();
1992 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1993 d->stencilClean = true;
1995 // Calling begin paint should make the correct context current. So, any
1996 // code which calls into GL or otherwise needs a current context *must*
1997 // go after beginPaint:
1998 d->device->beginPaint();
2000 #if !defined(QT_OPENGL_ES_2)
2001 bool success = qt_resolve_version_2_0_functions(d->ctx)
2002 && qt_resolve_buffer_extensions(d->ctx);
2007 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2009 glDisable(GL_STENCIL_TEST);
2010 glDisable(GL_DEPTH_TEST);
2011 glDisable(GL_SCISSOR_TEST);
2013 #if !defined(QT_OPENGL_ES_2)
2014 glDisable(GL_MULTISAMPLE);
2017 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2019 #if !defined(QT_OPENGL_ES_2)
2020 #if defined(Q_WS_WIN)
2021 if (qt_cleartype_enabled
2022 && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2024 #if defined(Q_WS_MAC)
2025 if (qt_applefontsmoothing_enabled)
2027 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2030 #if defined(QT_OPENGL_ES_2)
2031 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2032 // multisampled, it's always multisampled.
2033 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2035 d->multisamplingAlwaysEnabled = false;
2041 bool QGL2PaintEngineEx::end()
2043 Q_D(QGL2PaintEngineEx);
2044 QGLContext *ctx = d->ctx;
2047 d->transferMode(BrushDrawingMode);
2048 d->device->endPaint();
2050 #if defined(Q_WS_X11)
2051 // On some (probably all) drivers, deleting an X pixmap which has been bound to a texture
2052 // before calling glFinish/swapBuffers renders garbage. Presumably this is because X deletes
2053 // the pixmap behind the driver's back before it's had a chance to use it. To fix this, we
2054 // reference all QPixmaps which have been bound to stop them being deleted and only deref
2055 // them here, after swapBuffers, where they can be safely deleted.
2056 ctx->d_func()->boundPixmaps.clear();
2058 d->ctx->d_ptr->active_engine = 0;
2062 delete d->shaderManager;
2063 d->shaderManager = 0;
2064 d->currentBrush = QBrush();
2066 #ifdef QT_OPENGL_CACHE_AS_VBOS
2067 if (!d->unusedVBOSToClean.isEmpty()) {
2068 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2069 d->unusedVBOSToClean.clear();
2071 if (!d->unusedIBOSToClean.isEmpty()) {
2072 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2073 d->unusedIBOSToClean.clear();
2080 void QGL2PaintEngineEx::ensureActive()
2082 Q_D(QGL2PaintEngineEx);
2083 QGLContext *ctx = d->ctx;
2085 if (isActive() && ctx->d_ptr->active_engine != this) {
2086 ctx->d_ptr->active_engine = this;
2087 d->needsSync = true;
2090 d->device->ensureActiveTarget();
2093 d->transferMode(BrushDrawingMode);
2094 glViewport(0, 0, d->width, d->height);
2095 d->needsSync = false;
2096 d->lastMaskTextureUsed = 0;
2097 d->shaderManager->setDirty();
2098 d->ctx->d_func()->syncGlState();
2099 for (int i = 0; i < 3; ++i)
2100 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2105 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2107 Q_Q(QGL2PaintEngineEx);
2108 if (q->state()->clipTestEnabled) {
2109 glEnable(GL_STENCIL_TEST);
2110 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2112 glDisable(GL_STENCIL_TEST);
2113 glStencilFunc(GL_ALWAYS, 0, 0xff);
2116 #ifdef QT_GL_NO_SCISSOR_TEST
2117 currentScissorBounds = QRect(0, 0, width, height);
2119 QRect bounds = q->state()->rectangleClip;
2120 if (!q->state()->clipEnabled) {
2122 bounds = systemClip.boundingRect();
2124 bounds = QRect(0, 0, width, height);
2127 bounds = bounds.intersected(systemClip.boundingRect());
2129 bounds = bounds.intersected(QRect(0, 0, width, height));
2132 currentScissorBounds = bounds;
2134 if (bounds == QRect(0, 0, width, height)) {
2135 glDisable(GL_SCISSOR_TEST);
2137 glEnable(GL_SCISSOR_TEST);
2143 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2145 const int left = rect.left();
2146 const int width = rect.width();
2147 int bottom = height - (rect.top() + rect.height());
2148 if (device->isFlipped()) {
2149 bottom = rect.top();
2151 const int height = rect.height();
2153 glScissor(left, bottom, width, height);
2156 void QGL2PaintEngineEx::clipEnabledChanged()
2158 Q_D(QGL2PaintEngineEx);
2160 state()->clipChanged = true;
2162 if (painter()->hasClipping())
2163 d->regenerateClip();
2165 d->systemStateChanged();
2168 void QGL2PaintEngineExPrivate::clearClip(uint value)
2170 dirtyStencilRegion -= currentScissorBounds;
2172 glStencilMask(0xff);
2173 glClearStencil(value);
2174 glClear(GL_STENCIL_BUFFER_BIT);
2177 q->state()->needsClipBufferClear = false;
2180 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2182 transferMode(BrushDrawingMode);
2184 if (snapToPixelGrid) {
2185 snapToPixelGrid = false;
2192 stencilClean = false;
2194 const bool singlePass = !path.hasWindingFill()
2195 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2196 || q->state()->needsClipBufferClear);
2197 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2199 if (q->state()->needsClipBufferClear)
2202 if (path.isEmpty()) {
2203 glEnable(GL_STENCIL_TEST);
2204 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2208 if (q->state()->clipTestEnabled)
2209 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2211 glStencilFunc(GL_ALWAYS, 0, 0xff);
2213 vertexCoordinateArray.clear();
2214 vertexCoordinateArray.addPath(path, inverseScale, false);
2217 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2219 glColorMask(false, false, false, false);
2220 glEnable(GL_STENCIL_TEST);
2224 // Under these conditions we can set the new stencil value in a single
2225 // pass, by using the current value and the "new value" as the toggles
2227 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2228 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2229 glStencilMask(value ^ referenceClipValue);
2231 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2233 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2234 glStencilMask(0xff);
2236 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2237 // Pass when any clip bit is set, set high bit
2238 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2239 composite(vertexCoordinateArray.boundingRect());
2242 // Pass when high bit is set, replace stencil value with new clip value
2243 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2245 composite(vertexCoordinateArray.boundingRect());
2248 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2251 glColorMask(true, true, true, true);
2254 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2256 // qDebug("QGL2PaintEngineEx::clip()");
2257 Q_D(QGL2PaintEngineEx);
2259 state()->clipChanged = true;
2263 if (op == Qt::ReplaceClip) {
2264 op = Qt::IntersectClip;
2265 if (d->hasClipOperations()) {
2266 d->systemStateChanged();
2267 state()->canRestoreClip = false;
2271 #ifndef QT_GL_NO_SCISSOR_TEST
2272 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2273 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2274 QRectF rect(points[0], points[2]);
2276 if (state()->matrix.type() <= QTransform::TxScale
2277 || (state()->matrix.type() == QTransform::TxRotate
2278 && qFuzzyIsNull(state()->matrix.m11())
2279 && qFuzzyIsNull(state()->matrix.m22())))
2281 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2282 d->updateClipScissorTest();
2288 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2292 if (d->useSystemClip) {
2293 state()->clipTestEnabled = true;
2294 state()->currentClip = 1;
2296 state()->clipTestEnabled = false;
2298 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2299 state()->canRestoreClip = false;
2300 d->updateClipScissorTest();
2302 case Qt::IntersectClip:
2303 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2304 d->updateClipScissorTest();
2305 d->resetClipIfNeeded();
2307 d->writeClip(path, d->maxClip);
2308 state()->currentClip = d->maxClip;
2309 state()->clipTestEnabled = true;
2311 case Qt::UniteClip: {
2312 d->resetClipIfNeeded();
2314 if (state()->rectangleClip.isValid()) {
2316 path.addRect(state()->rectangleClip);
2318 // flush the existing clip rectangle to the depth buffer
2319 d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(path)), d->maxClip);
2322 state()->clipTestEnabled = false;
2323 #ifndef QT_GL_NO_SCISSOR_TEST
2324 QRect oldRectangleClip = state()->rectangleClip;
2326 state()->rectangleClip = state()->rectangleClip.united(pathRect);
2327 d->updateClipScissorTest();
2329 QRegion extendRegion = QRegion(state()->rectangleClip) - oldRectangleClip;
2331 if (!extendRegion.isEmpty()) {
2332 QPainterPath extendPath;
2333 extendPath.addRegion(extendRegion);
2335 // first clear the depth buffer in the extended region
2336 d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(extendPath)), 0);
2339 // now write the clip path
2340 d->writeClip(path, d->maxClip);
2341 state()->canRestoreClip = false;
2342 state()->currentClip = d->maxClip;
2343 state()->clipTestEnabled = true;
2351 void QGL2PaintEngineExPrivate::regenerateClip()
2353 systemStateChanged();
2354 replayClipOperations();
2357 void QGL2PaintEngineExPrivate::systemStateChanged()
2359 Q_Q(QGL2PaintEngineEx);
2361 q->state()->clipChanged = true;
2363 if (systemClip.isEmpty()) {
2364 useSystemClip = false;
2366 if (q->paintDevice()->devType() == QInternal::Widget && currentClipWidget) {
2367 QWidgetPrivate *widgetPrivate = qt_widget_private(currentClipWidget->window());
2368 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2370 useSystemClip = true;
2374 q->state()->clipTestEnabled = false;
2375 q->state()->needsClipBufferClear = true;
2377 q->state()->currentClip = 1;
2380 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2381 updateClipScissorTest();
2383 if (systemClip.rectCount() == 1) {
2384 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2385 useSystemClip = false;
2386 #ifndef QT_GL_NO_SCISSOR_TEST
2387 // scissoring takes care of the system clip
2392 if (useSystemClip) {
2396 path.addRegion(systemClip);
2398 q->state()->currentClip = 0;
2399 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2400 q->state()->currentClip = 1;
2401 q->state()->clipTestEnabled = true;
2405 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2407 // qDebug("QGL2PaintEngineEx::setState()");
2409 Q_D(QGL2PaintEngineEx);
2411 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2412 QOpenGL2PaintEngineState *old_state = state();
2414 QPaintEngineEx::setState(s);
2417 // Newly created state object. The call to setState()
2418 // will either be followed by a call to begin(), or we are
2419 // setting the state as part of a save().
2424 // Setting the state as part of a restore().
2426 if (old_state == s || old_state->renderHintsChanged)
2427 renderHintsChanged();
2429 if (old_state == s || old_state->matrixChanged)
2430 d->matrixDirty = true;
2432 if (old_state == s || old_state->compositionModeChanged)
2433 d->compositionModeDirty = true;
2435 if (old_state == s || old_state->opacityChanged)
2436 d->opacityUniformDirty = true;
2438 if (old_state == s || old_state->clipChanged) {
2439 if (old_state && old_state != s && old_state->canRestoreClip) {
2440 d->updateClipScissorTest();
2441 glDepthFunc(GL_LEQUAL);
2443 d->regenerateClip();
2448 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2451 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2453 QOpenGL2PaintEngineState *s;
2455 s = new QOpenGL2PaintEngineState();
2457 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2459 s->matrixChanged = false;
2460 s->compositionModeChanged = false;
2461 s->opacityChanged = false;
2462 s->renderHintsChanged = false;
2463 s->clipChanged = false;
2468 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2469 : QPainterState(other)
2472 needsClipBufferClear = other.needsClipBufferClear;
2473 clipTestEnabled = other.clipTestEnabled;
2474 currentClip = other.currentClip;
2475 canRestoreClip = other.canRestoreClip;
2476 rectangleClip = other.rectangleClip;
2479 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2482 needsClipBufferClear = true;
2483 clipTestEnabled = false;
2484 canRestoreClip = true;
2487 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()