1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtOpenGL module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
43 When the active program changes, we need to update it's uniforms.
44 We could track state for each program and only update stale uniforms
45 - Could lead to lots of overhead if there's a lot of programs
46 We could update all the uniforms when the program changes
47 - Could end up updating lots of uniforms which don't need updating
49 Updating uniforms should be cheap, so the overhead of updating up-to-date
50 uniforms should be minimal. It's also less complex.
52 Things which _may_ cause a different program to be used:
53 - Change in brush/pen style
54 - Change in painter opacity
55 - Change in composition mode
57 Whenever we set a mode on the shader manager - it needs to tell us if it had
58 to switch to a different program.
60 The shader manager should only switch when we tell it to. E.g. if we set a new
61 brush style and then switch to transparent painter, we only want it to compile
62 and use the correct program when we really need it.
65 // #define QT_OPENGL_CACHE_AS_VBOS
67 #include "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 <QtGui/private/qtriangulator_p.h>
83 #include "qglengineshadermanager_p.h"
84 #include "qgl2pexvertexarray_p.h"
85 #include "qtextureglyphcache_gl_p.h"
89 // ####TODO Properly #ifdef this class to use #define symbols actually defined
90 // by OpenGL/ES includes
91 #ifndef GL_FRAMEBUFFER_SRGB
92 #define GL_FRAMEBUFFER_SRGB 0x8DB9
99 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
101 ////////////////////////////////// Private Methods //////////////////////////////////////////
103 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
105 delete shaderManager;
107 while (pathCaches.size()) {
108 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
109 e->cleanup(e->engine, e->data);
114 if (elementIndicesVBOId != 0) {
115 glDeleteBuffers(1, &elementIndicesVBOId);
116 elementIndicesVBOId = 0;
120 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
122 // glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
123 if (id != GLuint(-1) && id == lastTextureUsed)
126 lastTextureUsed = id;
128 if (smoothPixmapTransform) {
129 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
130 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
132 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
133 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
135 glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
136 glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
140 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
142 qreal alpha = c.alphaF() * opacity;
144 c.setRedF(c.redF() * alpha);
145 c.setGreenF(c.greenF() * alpha);
146 c.setBlueF(c.blueF() * alpha);
151 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
153 if (qbrush_fast_equals(currentBrush, brush))
156 const Qt::BrushStyle newStyle = qbrush_style(brush);
157 Q_ASSERT(newStyle != Qt::NoBrush);
159 currentBrush = brush;
160 if (!currentBrushPixmap.isNull())
161 currentBrushPixmap = QPixmap();
162 brushUniformsDirty = true; // All brushes have at least one uniform
164 if (newStyle > Qt::SolidPattern)
165 brushTextureDirty = true;
167 if (currentBrush.style() == Qt::TexturePattern
168 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
170 shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
172 shaderManager->setSrcPixelType(newStyle);
174 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
178 void QGL2PaintEngineExPrivate::useSimpleShader()
180 shaderManager->useSimpleProgram();
186 // ####TODO Properly #ifdef this class to use #define symbols actually defined
187 // by OpenGL/ES includes
188 #ifndef GL_MIRRORED_REPEAT_IBM
189 #define GL_MIRRORED_REPEAT_IBM 0x8370
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;
675 QVertexIndexVector::Type indexType;
678 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
680 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
681 #ifdef QT_OPENGL_CACHE_AS_VBOS
682 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
683 static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
685 d->unusedIBOSToClean << c->ibo;
694 // Assumes everything is configured for the brush you want to use
695 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
697 transferMode(BrushDrawingMode);
699 if (snapToPixelGrid) {
700 snapToPixelGrid = false;
704 // Might need to call updateMatrix to re-calculate inverseScale
708 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
710 // Check to see if there's any hints
711 if (path.shape() == QVectorPath::RectangleHint) {
712 QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
713 prepareForDraw(currentBrush.isOpaque());
715 } else if (path.isConvex()) {
717 if (path.isCacheable()) {
718 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
719 QGL2PEVectorPathCache *cache;
721 bool updateCache = false;
724 cache = (QGL2PEVectorPathCache *) data->data;
725 // Check if scale factor is exceeded for curved paths and generate curves if so...
726 if (path.isCurved()) {
727 qreal scaleFactor = cache->iscale / inverseScale;
728 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
729 #ifdef QT_OPENGL_CACHE_AS_VBOS
730 glDeleteBuffers(1, &cache->vbo);
732 Q_ASSERT(cache->ibo == 0);
734 free(cache->vertices);
735 Q_ASSERT(cache->indices == 0);
741 cache = new QGL2PEVectorPathCache;
742 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
746 // Flatten the path at the current scale factor and fill it into the cache struct.
748 vertexCoordinateArray.clear();
749 vertexCoordinateArray.addPath(path, inverseScale, false);
750 int vertexCount = vertexCoordinateArray.vertexCount();
751 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
752 cache->vertexCount = vertexCount;
753 cache->indexCount = 0;
754 cache->primitiveType = GL_TRIANGLE_FAN;
755 cache->iscale = inverseScale;
756 #ifdef QT_OPENGL_CACHE_AS_VBOS
757 glGenBuffers(1, &cache->vbo);
758 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
759 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
762 cache->vertices = (float *) malloc(floatSizeInBytes);
763 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
768 prepareForDraw(currentBrush.isOpaque());
769 #ifdef QT_OPENGL_CACHE_AS_VBOS
770 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
771 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
773 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
775 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
778 // printf(" - Marking path as cachable...\n");
779 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
780 path.makeCacheable();
781 vertexCoordinateArray.clear();
782 vertexCoordinateArray.addPath(path, inverseScale, false);
783 prepareForDraw(currentBrush.isOpaque());
784 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
788 bool useCache = path.isCacheable();
790 QRectF bbox = path.controlPointRect();
791 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
792 useCache &= (bbox.left() > -0x8000 * inverseScale)
793 && (bbox.right() < 0x8000 * inverseScale)
794 && (bbox.top() > -0x8000 * inverseScale)
795 && (bbox.bottom() < 0x8000 * inverseScale);
799 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
800 QGL2PEVectorPathCache *cache;
802 bool updateCache = false;
805 cache = (QGL2PEVectorPathCache *) data->data;
806 // Check if scale factor is exceeded for curved paths and generate curves if so...
807 if (path.isCurved()) {
808 qreal scaleFactor = cache->iscale / inverseScale;
809 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
810 #ifdef QT_OPENGL_CACHE_AS_VBOS
811 glDeleteBuffers(1, &cache->vbo);
812 glDeleteBuffers(1, &cache->ibo);
814 free(cache->vertices);
815 free(cache->indices);
821 cache = new QGL2PEVectorPathCache;
822 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
826 // Flatten the path at the current scale factor and fill it into the cache struct.
828 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
829 cache->vertexCount = polys.vertices.size() / 2;
830 cache->indexCount = polys.indices.size();
831 cache->primitiveType = GL_TRIANGLES;
832 cache->iscale = inverseScale;
833 cache->indexType = polys.indices.type();
834 #ifdef QT_OPENGL_CACHE_AS_VBOS
835 glGenBuffers(1, &cache->vbo);
836 glGenBuffers(1, &cache->ibo);
837 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
838 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
840 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
841 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
843 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
845 QVarLengthArray<float> vertices(polys.vertices.size());
846 for (int i = 0; i < polys.vertices.size(); ++i)
847 vertices[i] = float(inverseScale * polys.vertices.at(i));
848 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
850 cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
851 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
852 cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
853 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
855 cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
856 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
858 for (int i = 0; i < polys.vertices.size(); ++i)
859 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
863 prepareForDraw(currentBrush.isOpaque());
864 #ifdef QT_OPENGL_CACHE_AS_VBOS
865 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
866 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
867 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
868 if (cache->indexType == QVertexIndexVector::UnsignedInt)
869 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
871 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
872 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
873 glBindBuffer(GL_ARRAY_BUFFER, 0);
875 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
876 if (cache->indexType == QVertexIndexVector::UnsignedInt)
877 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
879 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
883 // printf(" - Marking path as cachable...\n");
884 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
885 path.makeCacheable();
887 if (!device->format().stencil()) {
888 // If there is no stencil buffer, triangulate the path instead.
890 QRectF bbox = path.controlPointRect();
891 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
892 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
893 && (bbox.right() < 0x8000 * inverseScale)
894 && (bbox.top() > -0x8000 * inverseScale)
895 && (bbox.bottom() < 0x8000 * inverseScale);
897 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
899 QVarLengthArray<float> vertices(polys.vertices.size());
900 for (int i = 0; i < polys.vertices.size(); ++i)
901 vertices[i] = float(inverseScale * polys.vertices.at(i));
903 prepareForDraw(currentBrush.isOpaque());
904 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
905 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
906 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
908 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
910 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
911 qWarning("Painter path exceeds +/-32767 pixels.");
916 // The path is too complicated & needs the stencil technique
917 vertexCoordinateArray.clear();
918 vertexCoordinateArray.addPath(path, inverseScale, false);
920 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
923 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
925 if (q->state()->clipTestEnabled) {
926 // Pass when high bit is set, replace stencil value with current clip
927 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
928 } else if (path.hasWindingFill()) {
929 // Pass when any bit is set, replace stencil value with 0
930 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
932 // Pass when high bit is set, replace stencil value with 0
933 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
935 prepareForDraw(currentBrush.isOpaque());
937 // Stencil the brush onto the dest buffer
938 composite(vertexCoordinateArray.boundingRect());
940 updateClipScissorTest();
946 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
950 const QGLRect &bounds,
951 StencilFillMode mode)
953 Q_ASSERT(count || stops);
955 // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
956 glStencilMask(0xff); // Enable stencil writes
958 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
959 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
960 glClearStencil(0); // Clear to zero
961 for (int i = 0; i < clearRegion.size(); ++i) {
962 #ifndef QT_GL_NO_SCISSOR_TEST
963 setScissor(clearRegion.at(i));
965 glClear(GL_STENCIL_BUFFER_BIT);
968 dirtyStencilRegion -= currentScissorBounds;
970 #ifndef QT_GL_NO_SCISSOR_TEST
971 updateClipScissorTest();
975 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
977 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
979 if (mode == WindingFillMode) {
980 Q_ASSERT(stops && !count);
981 if (q->state()->clipTestEnabled) {
982 // Flatten clip values higher than current clip, and set high bit to match current clip
983 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
984 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
987 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
988 } else if (!stencilClean) {
989 // Clear stencil buffer within bounding rect
990 glStencilFunc(GL_ALWAYS, 0, 0xff);
991 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
995 // Inc. for front-facing triangle
996 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
997 // Dec. for back-facing "holes"
998 glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
999 glStencilMask(~GL_STENCIL_HIGH_BIT);
1000 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1002 if (q->state()->clipTestEnabled) {
1003 // Clear high bit of stencil outside of path
1004 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1005 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1006 glStencilMask(GL_STENCIL_HIGH_BIT);
1009 } else if (mode == OddEvenFillMode) {
1010 glStencilMask(GL_STENCIL_HIGH_BIT);
1011 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1012 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1014 } else { // TriStripStrokeFillMode
1015 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1016 glStencilMask(GL_STENCIL_HIGH_BIT);
1018 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1019 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1020 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1023 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1024 if (q->state()->clipTestEnabled) {
1025 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1026 ~GL_STENCIL_HIGH_BIT);
1028 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1030 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1031 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1035 // Enable color writes & disable stencil writes
1036 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1040 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1041 restore the stencil buffer to a pristine state. The current clip region
1042 is set to 1, and the rest to 0.
1044 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1046 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1049 Q_Q(QGL2PaintEngineEx);
1052 glEnable(GL_STENCIL_TEST);
1053 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1055 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1056 QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1058 // Set high bit on clip region
1059 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1060 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1061 glStencilMask(GL_STENCIL_HIGH_BIT);
1064 // Reset clipping to 1 and everything else to zero
1065 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1066 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1067 glStencilMask(0xff);
1070 q->state()->currentClip = 1;
1071 q->state()->canRestoreClip = false;
1076 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1079 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1081 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1082 updateBrushTexture();
1084 if (compositionModeDirty)
1085 updateCompositionMode();
1090 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1091 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1092 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1093 && srcPixelsAreOpaque && !stateHasOpacity))
1095 glDisable(GL_BLEND);
1100 QGLEngineShaderManager::OpacityMode opacityMode;
1101 if (mode == ImageArrayDrawingMode) {
1102 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1104 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1105 : QGLEngineShaderManager::NoOpacity;
1106 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1108 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1109 (currentBrush.style() <= Qt::DiagCrossPattern);
1111 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1112 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1115 shaderManager->setOpacityMode(opacityMode);
1117 bool changed = shaderManager->useCorrectShaderProg();
1118 // If the shader program needs changing, we change it and mark all uniforms as dirty
1120 // The shader program has changed so mark all uniforms as dirty:
1121 brushUniformsDirty = true;
1122 opacityUniformDirty = true;
1123 matrixUniformDirty = true;
1126 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1127 updateBrushUniforms();
1129 if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1130 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1131 opacityUniformDirty = false;
1134 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1135 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1137 matrixUniformDirty = false;
1143 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1145 setCoords(staticVertexCoordinateArray, boundingRect);
1146 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1147 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1150 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1151 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1154 // Now setup the pointer to the vertex array:
1155 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1157 int previousStop = 0;
1158 for (int i=0; i<stopCount; ++i) {
1159 int stop = stops[i];
1161 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1162 for (int i=previousStop; i<stop; ++i)
1163 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1165 glDrawArrays(primitive, previousStop, stop - previousStop);
1166 previousStop = stop;
1170 /////////////////////////////////// Public Methods //////////////////////////////////////////
1172 QGL2PaintEngineEx::QGL2PaintEngineEx()
1173 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1177 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1181 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1183 Q_D(QGL2PaintEngineEx);
1185 if (qbrush_style(brush) == Qt::NoBrush)
1192 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1195 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1197 Q_D(QGL2PaintEngineEx);
1199 const QBrush &penBrush = qpen_brush(pen);
1200 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1203 QOpenGL2PaintEngineState *s = state();
1204 if (qt_pen_is_cosmetic(pen, s->renderHints) && !qt_scaleForTransform(s->transform(), 0)) {
1205 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1206 QPaintEngineEx::stroke(path, pen);
1211 d->setBrush(penBrush);
1212 d->stroke(path, pen);
1215 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1217 const QOpenGL2PaintEngineState *s = q->state();
1218 if (snapToPixelGrid) {
1219 snapToPixelGrid = false;
1223 const Qt::PenStyle penStyle = qpen_style(pen);
1224 const QBrush &penBrush = qpen_brush(pen);
1225 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1227 transferMode(BrushDrawingMode);
1229 // updateMatrix() is responsible for setting the inverse scale on
1230 // the strokers, so we need to call it here and not wait for
1231 // prepareForDraw() down below.
1234 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1235 ? q->state()->rectangleClip
1236 : QRectF(0, 0, width, height));
1238 if (penStyle == Qt::SolidLine) {
1239 stroker.process(path, pen, clip, s->renderHints);
1241 } else { // Some sort of dash
1242 dasher.process(path, pen, clip, s->renderHints);
1244 QVectorPath dashStroke(dasher.points(),
1245 dasher.elementCount(),
1246 dasher.elementTypes());
1247 stroker.process(dashStroke, pen, clip, s->renderHints);
1250 if (!stroker.vertexCount())
1254 prepareForDraw(opaque);
1255 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1256 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1258 // QBrush b(Qt::green);
1260 // d->prepareForDraw(true);
1261 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1264 qreal width = qpen_widthf(pen) / 2;
1267 qreal extra = pen.joinStyle() == Qt::MiterJoin
1268 ? qMax(pen.miterLimit() * width, width)
1271 if (qt_pen_is_cosmetic(pen, s->renderHints))
1272 extra = extra * inverseScale;
1274 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1276 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1277 0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1279 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1281 // Pass when any bit is set, replace stencil value with 0
1282 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1283 prepareForDraw(false);
1285 // Stencil the brush onto the dest buffer
1290 updateClipScissorTest();
1294 void QGL2PaintEngineEx::penChanged() { }
1295 void QGL2PaintEngineEx::brushChanged() { }
1296 void QGL2PaintEngineEx::brushOriginChanged() { }
1298 void QGL2PaintEngineEx::opacityChanged()
1300 // qDebug("QGL2PaintEngineEx::opacityChanged()");
1301 Q_D(QGL2PaintEngineEx);
1302 state()->opacityChanged = true;
1304 Q_ASSERT(d->shaderManager);
1305 d->brushUniformsDirty = true;
1306 d->opacityUniformDirty = true;
1309 void QGL2PaintEngineEx::compositionModeChanged()
1311 // qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1312 Q_D(QGL2PaintEngineEx);
1313 state()->compositionModeChanged = true;
1314 d->compositionModeDirty = true;
1317 void QGL2PaintEngineEx::renderHintsChanged()
1319 state()->renderHintsChanged = true;
1321 #if !defined(QT_OPENGL_ES_2)
1322 if ((state()->renderHints & QPainter::Antialiasing)
1323 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1324 glEnable(GL_MULTISAMPLE);
1326 glDisable(GL_MULTISAMPLE);
1329 Q_D(QGL2PaintEngineEx);
1330 d->lastTextureUsed = GLuint(-1);
1331 d->brushTextureDirty = true;
1332 // qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1335 void QGL2PaintEngineEx::transformChanged()
1337 Q_D(QGL2PaintEngineEx);
1338 d->matrixDirty = true;
1339 state()->matrixChanged = true;
1343 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1345 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1348 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1350 Q_D(QGL2PaintEngineEx);
1351 QGLContext *ctx = d->ctx;
1353 int max_texture_size = ctx->d_func()->maxTextureSize();
1354 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1355 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1357 const qreal sx = scaled.width() / qreal(pixmap.width());
1358 const qreal sy = scaled.height() / qreal(pixmap.height());
1360 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1365 d->transferMode(ImageDrawingMode);
1367 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1368 #ifdef QGL_USE_TEXTURE_POOL
1369 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1372 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1373 QGLTexture *texture =
1374 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1376 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1377 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1378 QGLRect srcRect(src.left(), top, src.right(), bottom);
1380 bool isBitmap = pixmap.isQBitmap();
1381 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1383 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1384 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1385 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1387 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1388 // pixmap was temporarily cached as a QImage texture by pooling system
1389 // and should be destroyed immediately
1390 QGLTextureCache::instance()->remove(ctx, texture->id);
1394 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1395 Qt::ImageConversionFlags)
1397 Q_D(QGL2PaintEngineEx);
1398 QGLContext *ctx = d->ctx;
1400 int max_texture_size = ctx->d_func()->maxTextureSize();
1401 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1402 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1404 const qreal sx = scaled.width() / qreal(image.width());
1405 const qreal sy = scaled.height() / qreal(image.height());
1407 drawImage(dest, scaled, scaleRect(src, sx, sy));
1412 d->transferMode(ImageDrawingMode);
1414 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1416 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1417 #ifdef QGL_USE_TEXTURE_POOL
1418 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1421 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1422 GLuint id = texture->id;
1424 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1425 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1426 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1428 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1429 // image was temporarily cached by texture pooling system
1430 // and should be destroyed immediately
1431 QGLTextureCache::instance()->remove(ctx, texture->id);
1435 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1437 Q_D(QGL2PaintEngineEx);
1441 QPainterState *s = state();
1442 float det = s->matrix.determinant();
1444 // don't try to cache huge fonts or vastly transformed fonts
1445 QFontEngine *fontEngine = textItem->fontEngine();
1446 if (shouldDrawCachedGlyphs(fontEngine, s->matrix) && det >= 0.25f && det <= 4.f) {
1447 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1448 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1449 : d->glyphCacheType;
1450 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1451 if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1452 || d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1453 || (s->composition_mode != QPainter::CompositionMode_Source
1454 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1456 glyphType = QFontEngineGlyphCache::Raster_A8;
1460 d->drawCachedGlyphs(glyphType, textItem);
1462 QPaintEngineEx::drawStaticTextItem(textItem);
1466 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1468 Q_D(QGL2PaintEngineEx);
1469 if (!d->shaderManager)
1473 d->transferMode(ImageDrawingMode);
1475 #ifndef QT_OPENGL_ES_2
1476 QGLContext *ctx = d->ctx;
1478 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1479 glBindTexture(GL_TEXTURE_2D, textureId);
1481 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1483 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1484 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1485 d->drawTexture(dest, srcRect, size, false);
1489 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1491 Q_D(QGL2PaintEngineEx);
1494 QOpenGL2PaintEngineState *s = state();
1496 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1498 QTransform::TransformationType txtype = s->matrix.type();
1500 float det = s->matrix.determinant();
1501 bool drawCached = txtype < QTransform::TxProject;
1503 // don't try to cache huge fonts or vastly transformed fonts
1504 if (!shouldDrawCachedGlyphs(ti.fontEngine, s->matrix) || 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 (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1514 || d->device->alphaRequested() || txtype > QTransform::TxTranslate
1515 || (state()->composition_mode != QPainter::CompositionMode_Source
1516 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1518 glyphType = QFontEngineGlyphCache::Raster_A8;
1523 QVarLengthArray<QFixedPoint> positions;
1524 QVarLengthArray<glyph_t> glyphs;
1525 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1526 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1529 QStaticTextItem staticTextItem;
1530 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1531 staticTextItem.setFontEngine(ti.fontEngine);
1532 staticTextItem.glyphs = glyphs.data();
1533 staticTextItem.numChars = ti.num_chars;
1534 staticTextItem.numGlyphs = glyphs.size();
1535 staticTextItem.glyphPositions = positions.data();
1537 d->drawCachedGlyphs(glyphType, &staticTextItem);
1542 QPaintEngineEx::drawTextItem(p, ti);
1547 class QOpenGLStaticTextUserData: public QStaticTextUserData
1550 QOpenGLStaticTextUserData()
1551 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1555 ~QOpenGLStaticTextUserData()
1560 QGL2PEXVertexArray vertexCoordinateArray;
1561 QGL2PEXVertexArray textureCoordinateArray;
1562 QFontEngineGlyphCache::Type glyphType;
1563 int cacheSerialNumber;
1569 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1571 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1572 QStaticTextItem *staticTextItem)
1574 Q_Q(QGL2PaintEngineEx);
1576 QOpenGL2PaintEngineState *s = q->state();
1578 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1579 bool recreateVertexArrays = false;
1581 QFontEngine *fe = staticTextItem->fontEngine();
1582 QGLTextureGlyphCache *cache =
1583 (QGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphType, QTransform());
1584 if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1585 cache = new QGLTextureGlyphCache(glyphType, QTransform());
1586 fe->setGlyphCache(cacheKey, cache);
1587 recreateVertexArrays = true;
1590 if (staticTextItem->userDataNeedsUpdate) {
1591 recreateVertexArrays = true;
1592 } else if (staticTextItem->userData() == 0) {
1593 recreateVertexArrays = true;
1594 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1595 recreateVertexArrays = true;
1597 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1598 if (userData->glyphType != glyphType) {
1599 recreateVertexArrays = true;
1600 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1601 recreateVertexArrays = true;
1605 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1606 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1607 // cache so this text is performed before we test if the cache size has changed.
1608 if (recreateVertexArrays) {
1609 cache->setPaintEnginePrivate(this);
1610 if (!cache->populate(fe, staticTextItem->numGlyphs,
1611 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1612 // No space for glyphs in cache. We need to reset it and try again.
1614 cache->populate(fe, staticTextItem->numGlyphs,
1615 staticTextItem->glyphs, staticTextItem->glyphPositions);
1617 cache->fillInPendingGlyphs();
1620 if (cache->width() == 0 || cache->height() == 0)
1623 transferMode(TextDrawingMode);
1625 int margin = fe->glyphMargin(glyphType);
1627 GLfloat dx = 1.0 / cache->width();
1628 GLfloat dy = 1.0 / cache->height();
1630 // Use global arrays by default
1631 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1632 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1634 if (staticTextItem->useBackendOptimizations) {
1635 QOpenGLStaticTextUserData *userData = 0;
1637 if (staticTextItem->userData() == 0
1638 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1640 userData = new QOpenGLStaticTextUserData();
1641 staticTextItem->setUserData(userData);
1644 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1647 userData->glyphType = glyphType;
1648 userData->cacheSerialNumber = cache->serialNumber();
1650 // Use cache if backend optimizations is turned on
1651 vertexCoordinates = &userData->vertexCoordinateArray;
1652 textureCoordinates = &userData->textureCoordinateArray;
1654 QSize size(cache->width(), cache->height());
1655 if (userData->cacheSize != size) {
1656 recreateVertexArrays = true;
1657 userData->cacheSize = size;
1661 if (recreateVertexArrays) {
1662 vertexCoordinates->clear();
1663 textureCoordinates->clear();
1665 bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1666 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1667 QFixed subPixelPosition;
1668 if (supportsSubPixelPositions)
1669 subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1671 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1673 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1677 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1678 int y = qRound(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1680 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1681 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1684 staticTextItem->userDataNeedsUpdate = false;
1687 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1691 if (elementIndices.size() < numGlyphs*6) {
1692 Q_ASSERT(elementIndices.size() % 6 == 0);
1693 int j = elementIndices.size() / 6 * 4;
1694 while (j < numGlyphs*4) {
1695 elementIndices.append(j + 0);
1696 elementIndices.append(j + 0);
1697 elementIndices.append(j + 1);
1698 elementIndices.append(j + 2);
1699 elementIndices.append(j + 3);
1700 elementIndices.append(j + 3);
1705 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1706 if (elementIndicesVBOId == 0)
1707 glGenBuffers(1, &elementIndicesVBOId);
1709 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1710 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1711 elementIndices.constData(), GL_STATIC_DRAW);
1714 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1715 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1719 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1720 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1722 if (!snapToPixelGrid) {
1723 snapToPixelGrid = true;
1727 QBrush pensBrush = q->state()->pen.brush();
1728 setBrush(pensBrush);
1730 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1732 // Subpixel antialiasing without gamma correction
1734 QPainter::CompositionMode compMode = q->state()->composition_mode;
1735 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1736 || compMode == QPainter::CompositionMode_SourceOver);
1738 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1740 if (pensBrush.style() == Qt::SolidPattern) {
1741 // Solid patterns can get away with only one pass.
1742 QColor c = pensBrush.color();
1743 qreal oldOpacity = q->state()->opacity;
1744 if (compMode == QPainter::CompositionMode_Source) {
1745 c = qt_premultiplyColor(c, q->state()->opacity);
1746 q->state()->opacity = 1;
1747 opacityUniformDirty = true;
1750 compositionModeDirty = false; // I can handle this myself, thank you very much
1751 prepareForDraw(false); // Text always causes src pixels to be transparent
1753 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1754 if (compMode == QPainter::CompositionMode_Source) {
1755 q->state()->opacity = oldOpacity;
1756 opacityUniformDirty = true;
1760 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1761 glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1763 // Other brush styles need two passes.
1765 qreal oldOpacity = q->state()->opacity;
1766 if (compMode == QPainter::CompositionMode_Source) {
1767 q->state()->opacity = 1;
1768 opacityUniformDirty = true;
1769 pensBrush = Qt::white;
1770 setBrush(pensBrush);
1773 compositionModeDirty = false; // I can handle this myself, thank you very much
1774 prepareForDraw(false); // Text always causes src pixels to be transparent
1776 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1778 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1779 glBindTexture(GL_TEXTURE_2D, cache->texture());
1780 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1782 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1783 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1785 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1788 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1790 if (compMode == QPainter::CompositionMode_Source) {
1791 q->state()->opacity = oldOpacity;
1792 opacityUniformDirty = true;
1793 pensBrush = q->state()->pen.brush();
1794 setBrush(pensBrush);
1797 compositionModeDirty = false;
1798 prepareForDraw(false); // Text always causes src pixels to be transparent
1800 glBlendFunc(GL_ONE, GL_ONE);
1802 compositionModeDirty = true;
1804 // Greyscale/mono glyphs
1806 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1807 prepareForDraw(false); // Text always causes src pixels to be transparent
1810 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1811 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1813 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1814 if (lastMaskTextureUsed != cache->texture()) {
1815 glBindTexture(GL_TEXTURE_2D, cache->texture());
1816 lastMaskTextureUsed = cache->texture();
1819 if (cache->filterMode() != filterMode) {
1820 if (filterMode == QGLTextureGlyphCache::Linear) {
1821 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1822 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1824 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1825 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1827 cache->setFilterMode(filterMode);
1831 bool srgbFrameBufferEnabled = false;
1833 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1834 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1835 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1837 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1840 if (srgbFrameBufferEnabled)
1841 glDisable(GL_FRAMEBUFFER_SRGB);
1845 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1846 QPainter::PixmapFragmentHints hints)
1848 Q_D(QGL2PaintEngineEx);
1849 // Use fallback for extended composition modes.
1850 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1851 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1856 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1857 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1858 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1859 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1861 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1866 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1867 int fragmentCount, const QPixmap &pixmap,
1868 QPainter::PixmapFragmentHints hints)
1870 GLfloat dx = 1.0f / pixmap.size().width();
1871 GLfloat dy = 1.0f / pixmap.size().height();
1873 vertexCoordinateArray.clear();
1874 textureCoordinateArray.clear();
1875 opacityArray.reset();
1877 if (snapToPixelGrid) {
1878 snapToPixelGrid = false;
1882 bool allOpaque = true;
1884 for (int i = 0; i < fragmentCount; ++i) {
1887 if (fragments[i].rotation != 0) {
1888 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1889 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1892 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1893 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1894 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1895 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1897 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1898 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1899 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1900 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1901 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1902 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1904 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1905 (fragments[i].sourceLeft + fragments[i].width) * dx,
1906 (fragments[i].sourceTop + fragments[i].height) * dy);
1908 textureCoordinateArray.addVertex(src.right, src.bottom);
1909 textureCoordinateArray.addVertex(src.right, src.top);
1910 textureCoordinateArray.addVertex(src.left, src.top);
1911 textureCoordinateArray.addVertex(src.left, src.top);
1912 textureCoordinateArray.addVertex(src.left, src.bottom);
1913 textureCoordinateArray.addVertex(src.right, src.bottom);
1915 qreal opacity = fragments[i].opacity * q->state()->opacity;
1916 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1917 allOpaque &= (opacity >= 0.99f);
1920 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1921 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1922 QGLContext::InternalBindOption
1923 | QGLContext::CanFlipNativePixmapBindOption);
1925 if (texture->options & QGLContext::InvertedYBindOption) {
1926 // Flip texture y-coordinate.
1927 QGLPoint *data = textureCoordinateArray.data();
1928 for (int i = 0; i < 6 * fragmentCount; ++i)
1929 data[i].y = 1 - data[i].y;
1932 transferMode(ImageArrayDrawingMode);
1934 bool isBitmap = pixmap.isQBitmap();
1935 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1937 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1938 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1940 // Setup for texture drawing
1941 currentBrush = noBrush;
1942 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1943 : QGLEngineShaderManager::ImageSrc);
1944 if (prepareForDraw(isOpaque))
1945 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1948 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1949 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1952 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1955 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1957 Q_D(QGL2PaintEngineEx);
1959 // qDebug("QGL2PaintEngineEx::begin()");
1960 if (pdev->devType() == QInternal::OpenGL)
1961 d->device = static_cast<QGLPaintDevice*>(pdev);
1963 d->device = QGLPaintDevice::getDevice(pdev);
1968 d->ctx = d->device->context();
1969 d->ctx->d_ptr->active_engine = this;
1971 const QSize sz = d->device->size();
1972 d->width = sz.width();
1973 d->height = sz.height();
1974 d->mode = BrushDrawingMode;
1975 d->brushTextureDirty = true;
1976 d->brushUniformsDirty = true;
1977 d->matrixUniformDirty = true;
1978 d->matrixDirty = true;
1979 d->compositionModeDirty = true;
1980 d->opacityUniformDirty = true;
1981 d->needsSync = true;
1982 d->useSystemClip = !systemClip().isEmpty();
1983 d->currentBrush = QBrush();
1985 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1986 d->stencilClean = true;
1988 // Calling begin paint should make the correct context current. So, any
1989 // code which calls into GL or otherwise needs a current context *must*
1990 // go after beginPaint:
1991 d->device->beginPaint();
1993 #if !defined(QT_OPENGL_ES_2)
1994 bool success = qt_resolve_version_2_0_functions(d->ctx)
1995 && qt_resolve_buffer_extensions(d->ctx)
1996 && (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1997 || qt_resolve_framebufferobject_extensions(d->ctx));
2002 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2004 glDisable(GL_STENCIL_TEST);
2005 glDisable(GL_DEPTH_TEST);
2006 glDisable(GL_SCISSOR_TEST);
2008 #if !defined(QT_OPENGL_ES_2)
2009 glDisable(GL_MULTISAMPLE);
2012 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2014 #if !defined(QT_OPENGL_ES_2)
2015 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2018 #if defined(QT_OPENGL_ES_2)
2019 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2020 // multisampled, it's always multisampled.
2021 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2023 d->multisamplingAlwaysEnabled = false;
2029 bool QGL2PaintEngineEx::end()
2031 Q_D(QGL2PaintEngineEx);
2033 QGLContext *ctx = d->ctx;
2035 d->transferMode(BrushDrawingMode);
2036 d->device->endPaint();
2038 ctx->d_ptr->active_engine = 0;
2042 delete d->shaderManager;
2043 d->shaderManager = 0;
2044 d->currentBrush = QBrush();
2046 #ifdef QT_OPENGL_CACHE_AS_VBOS
2047 if (!d->unusedVBOSToClean.isEmpty()) {
2048 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2049 d->unusedVBOSToClean.clear();
2051 if (!d->unusedIBOSToClean.isEmpty()) {
2052 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2053 d->unusedIBOSToClean.clear();
2060 void QGL2PaintEngineEx::ensureActive()
2062 Q_D(QGL2PaintEngineEx);
2063 QGLContext *ctx = d->ctx;
2065 if (isActive() && ctx->d_ptr->active_engine != this) {
2066 ctx->d_ptr->active_engine = this;
2067 d->needsSync = true;
2070 d->device->ensureActiveTarget();
2073 d->transferMode(BrushDrawingMode);
2074 glViewport(0, 0, d->width, d->height);
2075 d->needsSync = false;
2076 d->lastMaskTextureUsed = 0;
2077 d->shaderManager->setDirty();
2078 d->ctx->d_func()->syncGlState();
2079 for (int i = 0; i < 3; ++i)
2080 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2085 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2087 Q_Q(QGL2PaintEngineEx);
2088 if (q->state()->clipTestEnabled) {
2089 glEnable(GL_STENCIL_TEST);
2090 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2092 glDisable(GL_STENCIL_TEST);
2093 glStencilFunc(GL_ALWAYS, 0, 0xff);
2096 #ifdef QT_GL_NO_SCISSOR_TEST
2097 currentScissorBounds = QRect(0, 0, width, height);
2099 QRect bounds = q->state()->rectangleClip;
2100 if (!q->state()->clipEnabled) {
2102 bounds = systemClip.boundingRect();
2104 bounds = QRect(0, 0, width, height);
2107 bounds = bounds.intersected(systemClip.boundingRect());
2109 bounds = bounds.intersected(QRect(0, 0, width, height));
2112 currentScissorBounds = bounds;
2114 if (bounds == QRect(0, 0, width, height)) {
2115 glDisable(GL_SCISSOR_TEST);
2117 glEnable(GL_SCISSOR_TEST);
2123 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2125 const int left = rect.left();
2126 const int width = rect.width();
2127 int bottom = height - (rect.top() + rect.height());
2128 if (device->isFlipped()) {
2129 bottom = rect.top();
2131 const int height = rect.height();
2133 glScissor(left, bottom, width, height);
2136 void QGL2PaintEngineEx::clipEnabledChanged()
2138 Q_D(QGL2PaintEngineEx);
2140 state()->clipChanged = true;
2142 if (painter()->hasClipping())
2143 d->regenerateClip();
2145 d->systemStateChanged();
2148 void QGL2PaintEngineExPrivate::clearClip(uint value)
2150 dirtyStencilRegion -= currentScissorBounds;
2152 glStencilMask(0xff);
2153 glClearStencil(value);
2154 glClear(GL_STENCIL_BUFFER_BIT);
2157 q->state()->needsClipBufferClear = false;
2160 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2162 transferMode(BrushDrawingMode);
2164 if (snapToPixelGrid) {
2165 snapToPixelGrid = false;
2172 stencilClean = false;
2174 const bool singlePass = !path.hasWindingFill()
2175 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2176 || q->state()->needsClipBufferClear);
2177 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2179 if (q->state()->needsClipBufferClear)
2182 if (path.isEmpty()) {
2183 glEnable(GL_STENCIL_TEST);
2184 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2188 if (q->state()->clipTestEnabled)
2189 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2191 glStencilFunc(GL_ALWAYS, 0, 0xff);
2193 vertexCoordinateArray.clear();
2194 vertexCoordinateArray.addPath(path, inverseScale, false);
2197 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2199 glColorMask(false, false, false, false);
2200 glEnable(GL_STENCIL_TEST);
2204 // Under these conditions we can set the new stencil value in a single
2205 // pass, by using the current value and the "new value" as the toggles
2207 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2208 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2209 glStencilMask(value ^ referenceClipValue);
2211 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2213 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2214 glStencilMask(0xff);
2216 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2217 // Pass when any clip bit is set, set high bit
2218 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2219 composite(vertexCoordinateArray.boundingRect());
2222 // Pass when high bit is set, replace stencil value with new clip value
2223 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2225 composite(vertexCoordinateArray.boundingRect());
2228 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2231 glColorMask(true, true, true, true);
2234 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2236 // qDebug("QGL2PaintEngineEx::clip()");
2237 Q_D(QGL2PaintEngineEx);
2239 state()->clipChanged = true;
2243 if (op == Qt::ReplaceClip) {
2244 op = Qt::IntersectClip;
2245 if (d->hasClipOperations()) {
2246 d->systemStateChanged();
2247 state()->canRestoreClip = false;
2251 #ifndef QT_GL_NO_SCISSOR_TEST
2252 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2253 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2254 QRectF rect(points[0], points[2]);
2256 if (state()->matrix.type() <= QTransform::TxScale
2257 || (state()->matrix.type() == QTransform::TxRotate
2258 && qFuzzyIsNull(state()->matrix.m11())
2259 && qFuzzyIsNull(state()->matrix.m22())))
2261 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2262 d->updateClipScissorTest();
2268 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2272 if (d->useSystemClip) {
2273 state()->clipTestEnabled = true;
2274 state()->currentClip = 1;
2276 state()->clipTestEnabled = false;
2278 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2279 state()->canRestoreClip = false;
2280 d->updateClipScissorTest();
2282 case Qt::IntersectClip:
2283 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2284 d->updateClipScissorTest();
2285 d->resetClipIfNeeded();
2287 d->writeClip(path, d->maxClip);
2288 state()->currentClip = d->maxClip;
2289 state()->clipTestEnabled = true;
2296 void QGL2PaintEngineExPrivate::regenerateClip()
2298 systemStateChanged();
2299 replayClipOperations();
2302 void QGL2PaintEngineExPrivate::systemStateChanged()
2304 Q_Q(QGL2PaintEngineEx);
2306 q->state()->clipChanged = true;
2308 if (systemClip.isEmpty()) {
2309 useSystemClip = false;
2311 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2312 QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2313 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2315 useSystemClip = true;
2319 q->state()->clipTestEnabled = false;
2320 q->state()->needsClipBufferClear = true;
2322 q->state()->currentClip = 1;
2325 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2326 updateClipScissorTest();
2328 if (systemClip.rectCount() == 1) {
2329 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2330 useSystemClip = false;
2331 #ifndef QT_GL_NO_SCISSOR_TEST
2332 // scissoring takes care of the system clip
2337 if (useSystemClip) {
2341 path.addRegion(systemClip);
2343 q->state()->currentClip = 0;
2344 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2345 q->state()->currentClip = 1;
2346 q->state()->clipTestEnabled = true;
2350 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2352 // qDebug("QGL2PaintEngineEx::setState()");
2354 Q_D(QGL2PaintEngineEx);
2356 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2357 QOpenGL2PaintEngineState *old_state = state();
2359 QPaintEngineEx::setState(s);
2362 // Newly created state object. The call to setState()
2363 // will either be followed by a call to begin(), or we are
2364 // setting the state as part of a save().
2369 // Setting the state as part of a restore().
2371 if (old_state == s || old_state->renderHintsChanged)
2372 renderHintsChanged();
2374 if (old_state == s || old_state->matrixChanged)
2375 d->matrixDirty = true;
2377 if (old_state == s || old_state->compositionModeChanged)
2378 d->compositionModeDirty = true;
2380 if (old_state == s || old_state->opacityChanged)
2381 d->opacityUniformDirty = true;
2383 if (old_state == s || old_state->clipChanged) {
2384 if (old_state && old_state != s && old_state->canRestoreClip) {
2385 d->updateClipScissorTest();
2386 glDepthFunc(GL_LEQUAL);
2388 d->regenerateClip();
2393 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2396 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2398 QOpenGL2PaintEngineState *s;
2400 s = new QOpenGL2PaintEngineState();
2402 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2404 s->matrixChanged = false;
2405 s->compositionModeChanged = false;
2406 s->opacityChanged = false;
2407 s->renderHintsChanged = false;
2408 s->clipChanged = false;
2413 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2414 : QPainterState(other)
2417 needsClipBufferClear = other.needsClipBufferClear;
2418 clipTestEnabled = other.clipTestEnabled;
2419 currentClip = other.currentClip;
2420 canRestoreClip = other.canRestoreClip;
2421 rectangleClip = other.rectangleClip;
2424 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2427 needsClipBufferClear = true;
2428 clipTestEnabled = false;
2429 canRestoreClip = true;
2432 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()