1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtOpenGL module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40/*
41 When the active program changes, we need to update it's uniforms.
42 We could track state for each program and only update stale uniforms
43 - Could lead to lots of overhead if there's a lot of programs
44 We could update all the uniforms when the program changes
45 - Could end up updating lots of uniforms which don't need updating
46
47 Updating uniforms should be cheap, so the overhead of updating up-to-date
48 uniforms should be minimal. It's also less complex.
49
50 Things which _may_ cause a different program to be used:
51 - Change in brush/pen style
52 - Change in painter opacity
53 - Change in composition mode
54
55 Whenever we set a mode on the shader manager - it needs to tell us if it had
56 to switch to a different program.
57
58 The shader manager should only switch when we tell it to. E.g. if we set a new
59 brush style and then switch to transparent painter, we only want it to compile
60 and use the correct program when we really need it.
61*/
62
63// #define QT_OPENGL_CACHE_AS_VBOS
64
65#include "qglgradientcache_p.h"
66#include "qpaintengineex_opengl2_p.h"
67
68#include <string.h> //for memcpy
69#include <qmath.h>
70
71#include <private/qgl_p.h>
72#include <private/qpaintengineex_p.h>
73#include <QPaintEngine>
74#include <private/qpainter_p.h>
75#include <private/qfontengine_p.h>
76#include <private/qdatabuffer_p.h>
77#include <private/qstatictext_p.h>
78#include <QtGui/private/qtriangulator_p.h>
79
80#include "qglengineshadermanager_p.h"
81#include "qgl2pexvertexarray_p.h"
82#include "qtextureglyphcache_gl_p.h"
83
84#include <QDebug>
85
86#ifndef QT_OPENGL_ES_2
87# include <qopenglfunctions_1_1.h>
88#endif
89
90QT_BEGIN_NAMESPACE
91
92
93
94Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
95
96////////////////////////////////// Private Methods //////////////////////////////////////////
97
98QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
99{
100 delete shaderManager;
101
102 while (pathCaches.size()) {
103 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
104 e->cleanup(e->engine, e->data);
105 e->data = 0;
106 e->engine = 0;
107 }
108
109 if (elementIndicesVBOId != 0) {
110 glDeleteBuffers(n: 1, buffers: &elementIndicesVBOId);
111 elementIndicesVBOId = 0;
112 }
113}
114
115void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
116{
117// glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
118 if (id != GLuint(-1) && id == lastTextureUsed)
119 return;
120
121 lastTextureUsed = id;
122
123 if (smoothPixmapTransform) {
124 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
125 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
126 } else {
127 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
128 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
129 }
130 glTexParameteri(target, GL_TEXTURE_WRAP_S, param: wrapMode);
131 glTexParameteri(target, GL_TEXTURE_WRAP_T, param: wrapMode);
132}
133
134
135inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
136{
137 qreal alpha = c.alphaF() * opacity;
138 c.setAlphaF(alpha);
139 c.setRedF(c.redF() * alpha);
140 c.setGreenF(c.greenF() * alpha);
141 c.setBlueF(c.blueF() * alpha);
142 return c;
143}
144
145
146void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
147{
148 if (qbrush_fast_equals(a: currentBrush, b: brush))
149 return;
150
151 const Qt::BrushStyle newStyle = qbrush_style(b: brush);
152 Q_ASSERT(newStyle != Qt::NoBrush);
153
154 currentBrush = brush;
155 if (!currentBrushPixmap.isNull())
156 currentBrushPixmap = QPixmap();
157 brushUniformsDirty = true; // All brushes have at least one uniform
158
159 if (newStyle > Qt::SolidPattern)
160 brushTextureDirty = true;
161
162 if (currentBrush.style() == Qt::TexturePattern
163 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
164 {
165 shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
166 } else {
167 shaderManager->setSrcPixelType(newStyle);
168 }
169 shaderManager->optimiseForBrushTransform(transformType: currentBrush.transform().type());
170}
171
172
173void QGL2PaintEngineExPrivate::useSimpleShader()
174{
175 shaderManager->useSimpleProgram();
176
177 if (matrixDirty)
178 updateMatrix();
179}
180
181// ####TODO Properly #ifdef this class to use #define symbols actually defined
182// by OpenGL/ES includes
183#ifndef GL_MIRRORED_REPEAT_IBM
184#define GL_MIRRORED_REPEAT_IBM 0x8370
185#endif
186
187void QGL2PaintEngineExPrivate::updateBrushTexture()
188{
189 Q_Q(QGL2PaintEngineEx);
190// qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
191 Qt::BrushStyle style = currentBrush.style();
192
193 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
194 // Get the image data for the pattern
195 QImage texImage = qt_imageForBrush(brushStyle: style, invert: false);
196
197 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
198 ctx->d_func()->bindTexture(image: texImage, GL_TEXTURE_2D, GL_RGBA, options: QGLContext::InternalBindOption);
199 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform);
200 }
201 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
202 // Gradiant brush: All the gradiants use the same texture
203
204 const QGradient* g = currentBrush.gradient();
205
206 // We apply global opacity in the fragment shaders, so we always pass 1.0
207 // for opacity to the cache.
208 GLuint texId = QGL2GradientCache::cacheForContext(context: ctx)->getBuffer(gradient: *g, opacity: 1.0);
209
210 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
211 glBindTexture(GL_TEXTURE_2D, texture: texId);
212
213 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
214 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform);
215 else if (g->spread() == QGradient::ReflectSpread)
216 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform);
217 else
218 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform);
219 }
220 else if (style == Qt::TexturePattern) {
221 currentBrushPixmap = currentBrush.texture();
222
223 int max_texture_size = ctx->d_func()->maxTextureSize();
224 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
225 currentBrushPixmap = currentBrushPixmap.scaled(w: max_texture_size, h: max_texture_size, aspectMode: Qt::KeepAspectRatio);
226
227 GLuint wrapMode = GL_REPEAT;
228 if (ctx->contextHandle()->isOpenGLES()) {
229 // OpenGL ES does not support GL_REPEAT wrap modes for NPOT textures. So instead,
230 // we emulate GL_REPEAT by only taking the fractional part of the texture coords
231 // in the qopenglslTextureBrushSrcFragmentShader program.
232 wrapMode = GL_CLAMP_TO_EDGE;
233 }
234
235 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
236 QGLTexture *tex = ctx->d_func()->bindTexture(pixmap: currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
237 options: QGLContext::InternalBindOption |
238 QGLContext::CanFlipNativePixmapBindOption);
239 updateTextureFilter(GL_TEXTURE_2D, wrapMode, smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform);
240 textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
241 }
242 brushTextureDirty = false;
243}
244
245
246void QGL2PaintEngineExPrivate::updateBrushUniforms()
247{
248// qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
249 Qt::BrushStyle style = currentBrush.style();
250
251 if (style == Qt::NoBrush)
252 return;
253
254 QTransform brushQTransform = currentBrush.transform();
255
256 if (style == Qt::SolidPattern) {
257 QColor col = qt_premultiplyColor(c: currentBrush.color(), opacity: (GLfloat)q->state()->opacity);
258 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::FragmentColor), color: col);
259 }
260 else {
261 // All other brushes have a transform and thus need the translation point:
262 QPointF translationPoint;
263
264 if (style <= Qt::DiagCrossPattern) {
265 QColor col = qt_premultiplyColor(c: currentBrush.color(), opacity: (GLfloat)q->state()->opacity);
266
267 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::PatternColor), color: col);
268
269 QVector2D halfViewportSize(width*0.5, height*0.5);
270 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::HalfViewportSize), value: halfViewportSize);
271 }
272 else if (style == Qt::LinearGradientPattern) {
273 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
274
275 QPointF realStart = g->start();
276 QPointF realFinal = g->finalStop();
277 translationPoint = realStart;
278
279 QPointF l = realFinal - realStart;
280
281 QVector3D linearData(
282 l.x(),
283 l.y(),
284 1.0f / (l.x() * l.x() + l.y() * l.y())
285 );
286
287 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::LinearData), value: linearData);
288
289 QVector2D halfViewportSize(width*0.5, height*0.5);
290 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::HalfViewportSize), value: halfViewportSize);
291 }
292 else if (style == Qt::ConicalGradientPattern) {
293 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
294 translationPoint = g->center();
295
296 GLfloat angle = -qDegreesToRadians(degrees: g->angle());
297
298 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::Angle), value: angle);
299
300 QVector2D halfViewportSize(width*0.5, height*0.5);
301 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::HalfViewportSize), value: halfViewportSize);
302 }
303 else if (style == Qt::RadialGradientPattern) {
304 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
305 QPointF realCenter = g->center();
306 QPointF realFocal = g->focalPoint();
307 qreal realRadius = g->centerRadius() - g->focalRadius();
308 translationPoint = realFocal;
309
310 QPointF fmp = realCenter - realFocal;
311 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::Fmp), point: fmp);
312
313 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
314 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::Fmp2MRadius2), value: fmp2_m_radius2);
315 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::Inverse2Fmp2MRadius2),
316 value: GLfloat(1.0 / (2.0*fmp2_m_radius2)));
317 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::SqrFr),
318 value: GLfloat(g->focalRadius() * g->focalRadius()));
319 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::BRadius),
320 x: GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
321 y: g->focalRadius(),
322 z: g->centerRadius() - g->focalRadius());
323
324 QVector2D halfViewportSize(width*0.5, height*0.5);
325 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::HalfViewportSize), value: halfViewportSize);
326 }
327 else if (style == Qt::TexturePattern) {
328 const QPixmap& texPixmap = currentBrush.texture();
329
330 if (qHasPixmapTexture(brush: currentBrush) && currentBrush.texture().isQBitmap()) {
331 QColor col = qt_premultiplyColor(c: currentBrush.color(), opacity: (GLfloat)q->state()->opacity);
332 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::PatternColor), color: col);
333 }
334
335 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
336 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::InvertedTextureSize), size: invertedTextureSize);
337
338 QVector2D halfViewportSize(width*0.5, height*0.5);
339 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::HalfViewportSize), value: halfViewportSize);
340 }
341 else
342 qWarning(msg: "QGL2PaintEngineEx: Unimplemented fill style");
343
344 const QPointF &brushOrigin = q->state()->brushOrigin;
345 QTransform matrix = q->state()->matrix;
346 matrix.translate(dx: brushOrigin.x(), dy: brushOrigin.y());
347
348 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
349 qreal m22 = -1;
350 qreal dy = height;
351 if (device->isFlipped()) {
352 m22 = 1;
353 dy = 0;
354 }
355 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
356 QTransform inv_matrix;
357 if (style == Qt::TexturePattern && textureInvertedY == -1)
358 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
359 else
360 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
361
362 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::BrushTransform), value: inv_matrix);
363 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
364 }
365 brushUniformsDirty = false;
366}
367
368
369// This assumes the shader manager has already setup the correct shader program
370void QGL2PaintEngineExPrivate::updateMatrix()
371{
372// qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
373
374 const QTransform& transform = q->state()->matrix;
375
376 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
377 // * GL's viewport is 2x2, Qt's is width x height
378 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
379 // * GL has [0,0] in the center, Qt has it in the top-left
380 //
381 // This results in the Projection matrix below, which is multiplied by the painter's
382 // transformation matrix, as shown below:
383 //
384 // Projection Matrix Painter Transform
385 // ------------------------------------------------ ------------------------
386 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
387 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
388 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
389 // ------------------------------------------------ ------------------------
390 //
391 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
392
393 const GLfloat wfactor = 2.0f / width;
394 GLfloat hfactor = -2.0f / height;
395
396 GLfloat dx = transform.dx();
397 GLfloat dy = transform.dy();
398
399 if (device->isFlipped()) {
400 hfactor *= -1;
401 dy -= height;
402 }
403
404 // Non-integer translates can have strange effects for some rendering operations such as
405 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
406 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
407 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
408 dx = std::ceil(x: dx - 0.5f);
409 dy = std::ceil(x: dy - 0.5f);
410 }
411 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
412 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
413 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
414 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
415 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
416 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
417 pmvMatrix[0][2] = transform.m13();
418 pmvMatrix[1][2] = transform.m23();
419 pmvMatrix[2][2] = transform.m33();
420
421 // 1/10000 == 0.0001, so we have good enough res to cover curves
422 // that span the entire widget...
423 inverseScale = qMax(a: 1 / qMax( a: qMax(a: qAbs(t: transform.m11()), b: qAbs(t: transform.m22())),
424 b: qMax(a: qAbs(t: transform.m12()), b: qAbs(t: transform.m21())) ),
425 b: qreal(0.0001));
426
427 matrixDirty = false;
428 matrixUniformDirty = true;
429
430 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
431 // need to do this once for every matrix change and persists across all shader programs.
432 glVertexAttrib3fv(indx: QT_PMV_MATRIX_1_ATTR, values: pmvMatrix[0]);
433 glVertexAttrib3fv(indx: QT_PMV_MATRIX_2_ATTR, values: pmvMatrix[1]);
434 glVertexAttrib3fv(indx: QT_PMV_MATRIX_3_ATTR, values: pmvMatrix[2]);
435
436 dasher.setInvScale(inverseScale);
437 stroker.setInvScale(inverseScale);
438}
439
440
441void QGL2PaintEngineExPrivate::updateCompositionMode()
442{
443 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
444 // composition modes look odd.
445// qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
446 switch(q->state()->composition_mode) {
447 case QPainter::CompositionMode_SourceOver:
448 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
449 break;
450 case QPainter::CompositionMode_DestinationOver:
451 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
452 break;
453 case QPainter::CompositionMode_Clear:
454 glBlendFunc(GL_ZERO, GL_ZERO);
455 break;
456 case QPainter::CompositionMode_Source:
457 glBlendFunc(GL_ONE, GL_ZERO);
458 break;
459 case QPainter::CompositionMode_Destination:
460 glBlendFunc(GL_ZERO, GL_ONE);
461 break;
462 case QPainter::CompositionMode_SourceIn:
463 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
464 break;
465 case QPainter::CompositionMode_DestinationIn:
466 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
467 break;
468 case QPainter::CompositionMode_SourceOut:
469 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
470 break;
471 case QPainter::CompositionMode_DestinationOut:
472 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
473 break;
474 case QPainter::CompositionMode_SourceAtop:
475 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
476 break;
477 case QPainter::CompositionMode_DestinationAtop:
478 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
479 break;
480 case QPainter::CompositionMode_Xor:
481 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
482 break;
483 case QPainter::CompositionMode_Plus:
484 glBlendFunc(GL_ONE, GL_ONE);
485 break;
486 default:
487 qWarning(msg: "Unsupported composition mode");
488 break;
489 }
490
491 compositionModeDirty = false;
492}
493
494static inline void setCoords(GLfloat *coords, const QGLRect &rect)
495{
496 coords[0] = rect.left;
497 coords[1] = rect.top;
498 coords[2] = rect.right;
499 coords[3] = rect.top;
500 coords[4] = rect.right;
501 coords[5] = rect.bottom;
502 coords[6] = rect.left;
503 coords[7] = rect.bottom;
504}
505
506void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
507{
508 // Setup for texture drawing
509 currentBrush = noBrush;
510 shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
511
512 if (snapToPixelGrid) {
513 snapToPixelGrid = false;
514 matrixDirty = true;
515 }
516
517 if (prepareForDraw(srcPixelsAreOpaque: opaque))
518 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
519
520 if (pattern) {
521 QColor col = qt_premultiplyColor(c: q->state()->pen.color(), opacity: (GLfloat)q->state()->opacity);
522 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::PatternColor), color: col);
523 }
524
525 GLfloat dx = 1.0 / textureSize.width();
526 GLfloat dy = 1.0 / textureSize.height();
527
528 QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
529
530 setCoords(coords: staticVertexCoordinateArray, rect: dest);
531 setCoords(coords: staticTextureCoordinateArray, rect: srcTextureRect);
532
533 glDrawArrays(GL_TRIANGLE_FAN, first: 0, count: 4);
534}
535
536void QGL2PaintEngineEx::beginNativePainting()
537{
538 Q_D(QGL2PaintEngineEx);
539 ensureActive();
540 d->transferMode(newMode: BrushDrawingMode);
541
542 d->nativePaintingActive = true;
543
544 d->glUseProgram(program: 0);
545
546 // Disable all the vertex attribute arrays:
547 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
548 d->glDisableVertexAttribArray(index: i);
549
550#ifndef QT_OPENGL_ES_2
551 if (!d->ctx->contextHandle()->isOpenGLES()) {
552 const QGLContext *ctx = d->ctx;
553 const QGLFormat &fmt = d->device->format();
554 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
555 || (fmt.majorVersion() == 3 && fmt.minorVersion() == 1 && ctx->contextHandle()->hasExtension(QByteArrayLiteral("GL_ARB_compatibility")))
556 || fmt.profile() == QGLFormat::CompatibilityProfile)
557 {
558 // be nice to people who mix OpenGL 1.x code with QPainter commands
559 // by setting modelview and projection matrices to mirror the GL 1
560 // paint engine
561 const QTransform& mtx = state()->matrix;
562
563 float mv_matrix[4][4] =
564 {
565 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
566 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
567 { 0, 0, 1, 0 },
568 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
569 };
570
571 const QSize sz = d->device->size();
572
573 QOpenGLFunctions_1_1 *gl1funcs = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_1_1>();
574 gl1funcs->initializeOpenGLFunctions();
575
576 gl1funcs->glMatrixMode(GL_PROJECTION);
577 gl1funcs->glLoadIdentity();
578 gl1funcs->glOrtho(left: 0, right: sz.width(), bottom: sz.height(), top: 0, zNear: -999999, zFar: 999999);
579
580 gl1funcs->glMatrixMode(GL_MODELVIEW);
581 gl1funcs->glLoadMatrixf(m: &mv_matrix[0][0]);
582 }
583 }
584#endif
585
586 d->lastTextureUsed = GLuint(-1);
587 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
588 d->resetGLState();
589
590 d->shaderManager->setDirty();
591
592 d->needsSync = true;
593}
594
595void QGL2PaintEngineExPrivate::resetGLState()
596{
597 glDisable(GL_BLEND);
598 glActiveTexture(GL_TEXTURE0);
599 glDisable(GL_STENCIL_TEST);
600 glDisable(GL_DEPTH_TEST);
601 glDisable(GL_SCISSOR_TEST);
602 glDepthMask(flag: true);
603 glDepthFunc(GL_LESS);
604 glClearDepthf(depth: 1);
605 glStencilMask(mask: 0xff);
606 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
607 glStencilFunc(GL_ALWAYS, ref: 0, mask: 0xff);
608 ctx->d_func()->setVertexAttribArrayEnabled(arrayIndex: QT_TEXTURE_COORDS_ATTR, enabled: false);
609 ctx->d_func()->setVertexAttribArrayEnabled(arrayIndex: QT_VERTEX_COORDS_ATTR, enabled: false);
610 ctx->d_func()->setVertexAttribArrayEnabled(arrayIndex: QT_OPACITY_ATTR, enabled: false);
611#ifndef QT_OPENGL_ES_2
612 if (!ctx->contextHandle()->isOpenGLES()) {
613 // gl_Color, corresponding to vertex attribute 3, may have been changed
614 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
615 glVertexAttrib4fv(indx: 3, values: color);
616 }
617#endif
618}
619
620bool QGL2PaintEngineExPrivate::resetOpenGLContextActiveEngine()
621{
622 QOpenGLContext *guiGlContext = ctx->contextHandle();
623 QOpenGLContextPrivate *guiGlContextPrivate =
624 guiGlContext ? QOpenGLContextPrivate::get(context: guiGlContext) : 0;
625
626 if (guiGlContextPrivate && guiGlContextPrivate->active_engine) {
627 ctx->d_func()->refreshCurrentFbo();
628 guiGlContextPrivate->active_engine = 0;
629 return true;
630 }
631
632 return false;
633}
634
635void QGL2PaintEngineEx::endNativePainting()
636{
637 Q_D(QGL2PaintEngineEx);
638 d->needsSync = true;
639 d->nativePaintingActive = false;
640}
641
642void QGL2PaintEngineEx::invalidateState()
643{
644 Q_D(QGL2PaintEngineEx);
645 d->needsSync = true;
646}
647
648bool QGL2PaintEngineEx::isNativePaintingActive() const {
649 Q_D(const QGL2PaintEngineEx);
650 return d->nativePaintingActive;
651}
652
653bool QGL2PaintEngineEx::shouldDrawCachedGlyphs(QFontEngine *fontEngine, const QTransform &t) const
654{
655 // The paint engine does not support projected cached glyph drawing
656 if (t.type() == QTransform::TxProject)
657 return false;
658
659 // The font engine might not support filling the glyph cache
660 // with the given transform applied, in which case we need to
661 // fall back to the QPainterPath code-path.
662 if (!fontEngine->supportsTransformation(transform: t)) {
663 // Except that drawing paths is slow, so for scales between
664 // 0.5 and 2.0 we leave the glyph cache untransformed and deal
665 // with the transform ourselves when painting, resulting in
666 // drawing 1x cached glyphs with a smooth-scale.
667 float det = t.determinant();
668 if (det >= 0.25f && det <= 4.f) {
669 // Assuming the baseclass still agrees
670 return QPaintEngineEx::shouldDrawCachedGlyphs(fontEngine, m: t);
671 }
672
673 return false; // Fall back to path-drawing
674 }
675
676 return QPaintEngineEx::shouldDrawCachedGlyphs(fontEngine, m: t);
677}
678
679void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
680{
681 if (newMode == mode)
682 return;
683
684 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
685 lastTextureUsed = GLuint(-1);
686 }
687
688 if (newMode == TextDrawingMode) {
689 shaderManager->setHasComplexGeometry(true);
690 } else {
691 shaderManager->setHasComplexGeometry(false);
692 }
693
694 if (newMode == ImageDrawingMode) {
695 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: staticVertexCoordinateArray);
696 setVertexAttributePointer(arrayIndex: QT_TEXTURE_COORDS_ATTR, pointer: staticTextureCoordinateArray);
697 }
698
699 if (newMode == ImageArrayDrawingMode) {
700 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: (GLfloat*)vertexCoordinateArray.data());
701 setVertexAttributePointer(arrayIndex: QT_TEXTURE_COORDS_ATTR, pointer: (GLfloat*)textureCoordinateArray.data());
702 setVertexAttributePointer(arrayIndex: QT_OPACITY_ATTR, pointer: (GLfloat*)opacityArray.data());
703 }
704
705 // This needs to change when we implement high-quality anti-aliasing...
706 if (newMode != TextDrawingMode)
707 shaderManager->setMaskType(QGLEngineShaderManager::NoMask);
708
709 mode = newMode;
710}
711
712struct QGL2PEVectorPathCache
713{
714#ifdef QT_OPENGL_CACHE_AS_VBOS
715 GLuint vbo;
716 GLuint ibo;
717#else
718 float *vertices;
719 void *indices;
720#endif
721 int vertexCount;
722 int indexCount;
723 GLenum primitiveType;
724 qreal iscale;
725 QVertexIndexVector::Type indexType;
726};
727
728void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
729{
730 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
731#ifdef QT_OPENGL_CACHE_AS_VBOS
732 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
733 static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
734 if (c->ibo)
735 d->unusedIBOSToClean << c->ibo;
736#else
737 Q_UNUSED(engine);
738 free(ptr: c->vertices);
739 free(ptr: c->indices);
740#endif
741 delete c;
742}
743
744// Assumes everything is configured for the brush you want to use
745void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
746{
747 transferMode(newMode: BrushDrawingMode);
748
749 if (snapToPixelGrid) {
750 snapToPixelGrid = false;
751 matrixDirty = true;
752 }
753
754 // Might need to call updateMatrix to re-calculate inverseScale
755 if (matrixDirty)
756 updateMatrix();
757
758 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
759
760 // Check to see if there's any hints
761 if (path.shape() == QVectorPath::RectangleHint) {
762 QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
763 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
764 composite(boundingRect: rect);
765 } else if (path.isConvex()) {
766
767 if (path.isCacheable()) {
768 QVectorPath::CacheEntry *data = path.lookupCacheData(engine: q);
769 QGL2PEVectorPathCache *cache;
770
771 bool updateCache = false;
772
773 if (data) {
774 cache = (QGL2PEVectorPathCache *) data->data;
775 // Check if scale factor is exceeded for curved paths and generate curves if so...
776 if (path.isCurved()) {
777 qreal scaleFactor = cache->iscale / inverseScale;
778 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
779#ifdef QT_OPENGL_CACHE_AS_VBOS
780 glDeleteBuffers(1, &cache->vbo);
781 cache->vbo = 0;
782 Q_ASSERT(cache->ibo == 0);
783#else
784 free(ptr: cache->vertices);
785 Q_ASSERT(cache->indices == 0);
786#endif
787 updateCache = true;
788 }
789 }
790 } else {
791 cache = new QGL2PEVectorPathCache;
792 data = const_cast<QVectorPath &>(path).addCacheData(engine: q, data: cache, cleanup: cleanupVectorPath);
793 updateCache = true;
794 }
795
796 // Flatten the path at the current scale factor and fill it into the cache struct.
797 if (updateCache) {
798 vertexCoordinateArray.clear();
799 vertexCoordinateArray.addPath(path, curveInverseScale: inverseScale, outline: false);
800 int vertexCount = vertexCoordinateArray.vertexCount();
801 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
802 cache->vertexCount = vertexCount;
803 cache->indexCount = 0;
804 cache->primitiveType = GL_TRIANGLE_FAN;
805 cache->iscale = inverseScale;
806#ifdef QT_OPENGL_CACHE_AS_VBOS
807 glGenBuffers(1, &cache->vbo);
808 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
809 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
810 cache->ibo = 0;
811#else
812 cache->vertices = (float *) malloc(size: floatSizeInBytes);
813 memcpy(dest: cache->vertices, src: vertexCoordinateArray.data(), n: floatSizeInBytes);
814 cache->indices = 0;
815#endif
816 }
817
818 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
819#ifdef QT_OPENGL_CACHE_AS_VBOS
820 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
821 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
822#else
823 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: cache->vertices);
824#endif
825 glDrawArrays(mode: cache->primitiveType, first: 0, count: cache->vertexCount);
826
827 } else {
828 // printf(" - Marking path as cachable...\n");
829 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
830 path.makeCacheable();
831 vertexCoordinateArray.clear();
832 vertexCoordinateArray.addPath(path, curveInverseScale: inverseScale, outline: false);
833 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
834 drawVertexArrays(vertexArray&: vertexCoordinateArray, GL_TRIANGLE_FAN);
835 }
836
837 } else {
838 bool useCache = path.isCacheable();
839 if (useCache) {
840 QRectF bbox = path.controlPointRect();
841 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
842 useCache &= (bbox.left() > -0x8000 * inverseScale)
843 && (bbox.right() < 0x8000 * inverseScale)
844 && (bbox.top() > -0x8000 * inverseScale)
845 && (bbox.bottom() < 0x8000 * inverseScale);
846 }
847
848 if (useCache) {
849 QVectorPath::CacheEntry *data = path.lookupCacheData(engine: q);
850 QGL2PEVectorPathCache *cache;
851
852 bool updateCache = false;
853
854 if (data) {
855 cache = (QGL2PEVectorPathCache *) data->data;
856 // Check if scale factor is exceeded for curved paths and generate curves if so...
857 if (path.isCurved()) {
858 qreal scaleFactor = cache->iscale / inverseScale;
859 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
860#ifdef QT_OPENGL_CACHE_AS_VBOS
861 glDeleteBuffers(1, &cache->vbo);
862 glDeleteBuffers(1, &cache->ibo);
863#else
864 free(ptr: cache->vertices);
865 free(ptr: cache->indices);
866#endif
867 updateCache = true;
868 }
869 }
870 } else {
871 cache = new QGL2PEVectorPathCache;
872 data = const_cast<QVectorPath &>(path).addCacheData(engine: q, data: cache, cleanup: cleanupVectorPath);
873 updateCache = true;
874 }
875
876 // Flatten the path at the current scale factor and fill it into the cache struct.
877 if (updateCache) {
878 QTriangleSet polys = qTriangulate(path, matrix: QTransform().scale(sx: 1 / inverseScale, sy: 1 / inverseScale));
879 cache->vertexCount = polys.vertices.size() / 2;
880 cache->indexCount = polys.indices.size();
881 cache->primitiveType = GL_TRIANGLES;
882 cache->iscale = inverseScale;
883 cache->indexType = polys.indices.type();
884#ifdef QT_OPENGL_CACHE_AS_VBOS
885 glGenBuffers(1, &cache->vbo);
886 glGenBuffers(1, &cache->ibo);
887 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
888 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
889
890 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
891 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
892 else
893 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
894
895 QVarLengthArray<float> vertices(polys.vertices.size());
896 for (int i = 0; i < polys.vertices.size(); ++i)
897 vertices[i] = float(inverseScale * polys.vertices.at(i));
898 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
899#else
900 cache->vertices = (float *) malloc(size: sizeof(float) * polys.vertices.size());
901 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
902 cache->indices = (quint32 *) malloc(size: sizeof(quint32) * polys.indices.size());
903 memcpy(dest: cache->indices, src: polys.indices.data(), n: sizeof(quint32) * polys.indices.size());
904 } else {
905 cache->indices = (quint16 *) malloc(size: sizeof(quint16) * polys.indices.size());
906 memcpy(dest: cache->indices, src: polys.indices.data(), n: sizeof(quint16) * polys.indices.size());
907 }
908 for (int i = 0; i < polys.vertices.size(); ++i)
909 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
910#endif
911 }
912
913 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
914#ifdef QT_OPENGL_CACHE_AS_VBOS
915 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
916 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
917 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
918 if (cache->indexType == QVertexIndexVector::UnsignedInt)
919 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
920 else
921 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
922 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
923 glBindBuffer(GL_ARRAY_BUFFER, 0);
924#else
925 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: cache->vertices);
926 if (cache->indexType == QVertexIndexVector::UnsignedInt)
927 glDrawElements(mode: cache->primitiveType, count: cache->indexCount, GL_UNSIGNED_INT, indices: (qint32 *)cache->indices);
928 else
929 glDrawElements(mode: cache->primitiveType, count: cache->indexCount, GL_UNSIGNED_SHORT, indices: (qint16 *)cache->indices);
930#endif
931
932 } else {
933 // printf(" - Marking path as cachable...\n");
934 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
935 path.makeCacheable();
936
937 if (!device->format().stencil()) {
938 // If there is no stencil buffer, triangulate the path instead.
939
940 QRectF bbox = path.controlPointRect();
941 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
942 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
943 && (bbox.right() < 0x8000 * inverseScale)
944 && (bbox.top() > -0x8000 * inverseScale)
945 && (bbox.bottom() < 0x8000 * inverseScale);
946 if (withinLimits) {
947 QTriangleSet polys = qTriangulate(path, matrix: QTransform().scale(sx: 1 / inverseScale, sy: 1 / inverseScale));
948
949 QVarLengthArray<float> vertices(polys.vertices.size());
950 for (int i = 0; i < polys.vertices.size(); ++i)
951 vertices[i] = float(inverseScale * polys.vertices.at(i));
952
953 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
954 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: vertices.constData());
955 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
956 glDrawElements(GL_TRIANGLES, count: polys.indices.size(), GL_UNSIGNED_INT, indices: polys.indices.data());
957 else
958 glDrawElements(GL_TRIANGLES, count: polys.indices.size(), GL_UNSIGNED_SHORT, indices: polys.indices.data());
959 } else {
960 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
961 qWarning(msg: "Painter path exceeds +/-32767 pixels.");
962 }
963 return;
964 }
965
966 // The path is too complicated & needs the stencil technique
967 vertexCoordinateArray.clear();
968 vertexCoordinateArray.addPath(path, curveInverseScale: inverseScale, outline: false);
969
970 fillStencilWithVertexArray(vertexArray&: vertexCoordinateArray, useWindingFill: path.hasWindingFill());
971
972 glStencilMask(mask: 0xff);
973 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
974
975 if (q->state()->clipTestEnabled) {
976 // Pass when high bit is set, replace stencil value with current clip
977 glStencilFunc(GL_NOTEQUAL, ref: q->state()->currentClip, GL_STENCIL_HIGH_BIT);
978 } else if (path.hasWindingFill()) {
979 // Pass when any bit is set, replace stencil value with 0
980 glStencilFunc(GL_NOTEQUAL, ref: 0, mask: 0xff);
981 } else {
982 // Pass when high bit is set, replace stencil value with 0
983 glStencilFunc(GL_NOTEQUAL, ref: 0, GL_STENCIL_HIGH_BIT);
984 }
985 prepareForDraw(srcPixelsAreOpaque: currentBrush.isOpaque());
986
987 // Stencil the brush onto the dest buffer
988 composite(boundingRect: vertexCoordinateArray.boundingRect());
989 glStencilMask(mask: 0);
990 updateClipScissorTest();
991 }
992 }
993}
994
995
996void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
997 int count,
998 int *stops,
999 int stopCount,
1000 const QGLRect &bounds,
1001 StencilFillMode mode)
1002{
1003 Q_ASSERT(count || stops);
1004
1005// qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
1006 glStencilMask(mask: 0xff); // Enable stencil writes
1007
1008 if (dirtyStencilRegion.intersects(r: currentScissorBounds)) {
1009 const QRegion clearRegion = dirtyStencilRegion.intersected(r: currentScissorBounds);
1010 glClearStencil(s: 0); // Clear to zero
1011 for (const QRect &rect : clearRegion) {
1012#ifndef QT_GL_NO_SCISSOR_TEST
1013 setScissor(rect);
1014#endif
1015 glClear(GL_STENCIL_BUFFER_BIT);
1016 }
1017
1018 dirtyStencilRegion -= currentScissorBounds;
1019
1020#ifndef QT_GL_NO_SCISSOR_TEST
1021 updateClipScissorTest();
1022#endif
1023 }
1024
1025 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
1026 useSimpleShader();
1027 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
1028
1029 if (mode == WindingFillMode) {
1030 Q_ASSERT(stops && !count);
1031 if (q->state()->clipTestEnabled) {
1032 // Flatten clip values higher than current clip, and set high bit to match current clip
1033 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, mask: ~GL_STENCIL_HIGH_BIT);
1034 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1035 composite(boundingRect: bounds);
1036
1037 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
1038 } else if (!stencilClean) {
1039 // Clear stencil buffer within bounding rect
1040 glStencilFunc(GL_ALWAYS, ref: 0, mask: 0xff);
1041 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
1042 composite(boundingRect: bounds);
1043 }
1044
1045 // Inc. for front-facing triangle
1046 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
1047 // Dec. for back-facing "holes"
1048 glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
1049 glStencilMask(mask: ~GL_STENCIL_HIGH_BIT);
1050 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1051
1052 if (q->state()->clipTestEnabled) {
1053 // Clear high bit of stencil outside of path
1054 glStencilFunc(GL_EQUAL, ref: q->state()->currentClip, mask: ~GL_STENCIL_HIGH_BIT);
1055 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1056 glStencilMask(GL_STENCIL_HIGH_BIT);
1057 composite(boundingRect: bounds);
1058 }
1059 } else if (mode == OddEvenFillMode) {
1060 glStencilMask(GL_STENCIL_HIGH_BIT);
1061 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1062 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1063
1064 } else { // TriStripStrokeFillMode
1065 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1066 glStencilMask(GL_STENCIL_HIGH_BIT);
1067#if 0
1068 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1069 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1070 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1071#else
1072
1073 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1074 if (q->state()->clipTestEnabled) {
1075 glStencilFunc(GL_LEQUAL, ref: q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1076 mask: ~GL_STENCIL_HIGH_BIT);
1077 } else {
1078 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, mask: 0xff);
1079 }
1080 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: data);
1081 glDrawArrays(GL_TRIANGLE_STRIP, first: 0, count);
1082#endif
1083 }
1084
1085 // Enable color writes & disable stencil writes
1086 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1087}
1088
1089/*
1090 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1091 restore the stencil buffer to a pristine state. The current clip region
1092 is set to 1, and the rest to 0.
1093*/
1094void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1095{
1096 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1097 return;
1098
1099 Q_Q(QGL2PaintEngineEx);
1100
1101 useSimpleShader();
1102 glEnable(GL_STENCIL_TEST);
1103 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1104
1105 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1106 QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1107
1108 // Set high bit on clip region
1109 glStencilFunc(GL_LEQUAL, ref: q->state()->currentClip, mask: 0xff);
1110 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1111 glStencilMask(GL_STENCIL_HIGH_BIT);
1112 composite(boundingRect: rect);
1113
1114 // Reset clipping to 1 and everything else to zero
1115 glStencilFunc(GL_NOTEQUAL, ref: 0x01, GL_STENCIL_HIGH_BIT);
1116 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1117 glStencilMask(mask: 0xff);
1118 composite(boundingRect: rect);
1119
1120 q->state()->currentClip = 1;
1121 q->state()->canRestoreClip = false;
1122
1123 maxClip = 1;
1124
1125 glStencilMask(mask: 0x0);
1126 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1127}
1128
1129bool QGL2PaintEngineExPrivate::prepareForCachedGlyphDraw(const QFontEngineGlyphCache &cache)
1130{
1131 Q_Q(QGL2PaintEngineEx);
1132
1133 Q_ASSERT(cache.transform().type() <= QTransform::TxScale);
1134
1135 QTransform &transform = q->state()->matrix;
1136 transform.scale(sx: 1.0 / cache.transform().m11(), sy: 1.0 / cache.transform().m22());
1137 bool ret = prepareForDraw(srcPixelsAreOpaque: false);
1138 transform.scale(sx: cache.transform().m11(), sy: cache.transform().m22());
1139
1140 return ret;
1141}
1142
1143bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1144{
1145 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1146 updateBrushTexture();
1147
1148 if (compositionModeDirty)
1149 updateCompositionMode();
1150
1151 if (matrixDirty)
1152 updateMatrix();
1153
1154 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1155 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1156 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1157 && srcPixelsAreOpaque && !stateHasOpacity))
1158 {
1159 glDisable(GL_BLEND);
1160 } else {
1161 glEnable(GL_BLEND);
1162 }
1163
1164 QGLEngineShaderManager::OpacityMode opacityMode;
1165 if (mode == ImageArrayDrawingMode) {
1166 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1167 } else {
1168 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1169 : QGLEngineShaderManager::NoOpacity;
1170 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1171 // Using a brush
1172 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1173 (currentBrush.style() <= Qt::DiagCrossPattern);
1174
1175 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1176 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1177 }
1178 }
1179 shaderManager->setOpacityMode(opacityMode);
1180
1181 bool changed = shaderManager->useCorrectShaderProg();
1182 // If the shader program needs changing, we change it and mark all uniforms as dirty
1183 if (changed) {
1184 // The shader program has changed so mark all uniforms as dirty:
1185 brushUniformsDirty = true;
1186 opacityUniformDirty = true;
1187 matrixUniformDirty = true;
1188 translateZUniformDirty = true;
1189 }
1190
1191 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1192 updateBrushUniforms();
1193
1194 if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1195 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::GlobalOpacity), value: (GLfloat)q->state()->opacity);
1196 opacityUniformDirty = false;
1197 }
1198
1199 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1200 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::Matrix),
1201 value: pmvMatrix);
1202 matrixUniformDirty = false;
1203 }
1204
1205 if (translateZUniformDirty && shaderManager->hasComplexGeometry()) {
1206 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::TranslateZ),
1207 value: translateZ);
1208 translateZUniformDirty = false;
1209 }
1210
1211 return changed;
1212}
1213
1214void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1215{
1216 setCoords(coords: staticVertexCoordinateArray, rect: boundingRect);
1217 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: staticVertexCoordinateArray);
1218 glDrawArrays(GL_TRIANGLE_FAN, first: 0, count: 4);
1219}
1220
1221// Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1222void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1223 GLenum primitive)
1224{
1225 // Now setup the pointer to the vertex array:
1226 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: data);
1227
1228 int previousStop = 0;
1229 for (int i=0; i<stopCount; ++i) {
1230 int stop = stops[i];
1231/*
1232 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1233 for (int i=previousStop; i<stop; ++i)
1234 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1235*/
1236 glDrawArrays(mode: primitive, first: previousStop, count: stop - previousStop);
1237 previousStop = stop;
1238 }
1239}
1240
1241/////////////////////////////////// Public Methods //////////////////////////////////////////
1242
1243QGL2PaintEngineEx::QGL2PaintEngineEx()
1244 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1245{
1246}
1247
1248QGL2PaintEngineEx::~QGL2PaintEngineEx()
1249{
1250}
1251
1252void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1253{
1254 Q_D(QGL2PaintEngineEx);
1255
1256 if (qbrush_style(b: brush) == Qt::NoBrush)
1257 return;
1258 ensureActive();
1259 d->setBrush(brush);
1260 d->fill(path);
1261}
1262
1263Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1264
1265
1266void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1267{
1268 Q_D(QGL2PaintEngineEx);
1269
1270 const QBrush &penBrush = qpen_brush(p: pen);
1271 if (qpen_style(p: pen) == Qt::NoPen || qbrush_style(b: penBrush) == Qt::NoBrush)
1272 return;
1273
1274 QGL2PaintEngineState *s = state();
1275 if (qt_pen_is_cosmetic(pen, hints: s->renderHints) && !qt_scaleForTransform(transform: s->transform(), scale: 0)) {
1276 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1277 QPaintEngineEx::stroke(path, pen);
1278 return;
1279 }
1280
1281 ensureActive();
1282 d->setBrush(penBrush);
1283 d->stroke(path, pen);
1284}
1285
1286void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1287{
1288 const QGL2PaintEngineState *s = q->state();
1289 if (snapToPixelGrid) {
1290 snapToPixelGrid = false;
1291 matrixDirty = true;
1292 }
1293
1294 const Qt::PenStyle penStyle = qpen_style(p: pen);
1295 const QBrush &penBrush = qpen_brush(p: pen);
1296 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1297
1298 transferMode(newMode: BrushDrawingMode);
1299
1300 // updateMatrix() is responsible for setting the inverse scale on
1301 // the strokers, so we need to call it here and not wait for
1302 // prepareForDraw() down below.
1303 updateMatrix();
1304
1305 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1306 ? q->state()->rectangleClip
1307 : QRectF(0, 0, width, height));
1308
1309 if (penStyle == Qt::SolidLine) {
1310 stroker.process(path, pen, clip, hints: s->renderHints);
1311
1312 } else { // Some sort of dash
1313 dasher.process(path, pen, clip, hints: s->renderHints);
1314
1315 QVectorPath dashStroke(dasher.points(),
1316 dasher.elementCount(),
1317 dasher.elementTypes());
1318 stroker.process(path: dashStroke, pen, clip, hints: s->renderHints);
1319 }
1320
1321 if (!stroker.vertexCount())
1322 return;
1323
1324 if (opaque) {
1325 prepareForDraw(srcPixelsAreOpaque: opaque);
1326 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: stroker.vertices());
1327 glDrawArrays(GL_TRIANGLE_STRIP, first: 0, count: stroker.vertexCount() / 2);
1328
1329// QBrush b(Qt::green);
1330// d->setBrush(&b);
1331// d->prepareForDraw(true);
1332// glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1333
1334 } else {
1335 qreal width = qpen_widthf(p: pen) / 2;
1336 if (width == 0)
1337 width = 0.5;
1338 qreal extra = pen.joinStyle() == Qt::MiterJoin
1339 ? qMax(a: pen.miterLimit() * width, b: width)
1340 : width;
1341
1342 if (qt_pen_is_cosmetic(pen, hints: s->renderHints))
1343 extra = extra * inverseScale;
1344
1345 QRectF bounds = path.controlPointRect().adjusted(xp1: -extra, yp1: -extra, xp2: extra, yp2: extra);
1346
1347 fillStencilWithVertexArray(data: stroker.vertices(), count: stroker.vertexCount() / 2,
1348 stops: 0, stopCount: 0, bounds, mode: QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1349
1350 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1351
1352 // Pass when any bit is set, replace stencil value with 0
1353 glStencilFunc(GL_NOTEQUAL, ref: 0, GL_STENCIL_HIGH_BIT);
1354 prepareForDraw(srcPixelsAreOpaque: false);
1355
1356 // Stencil the brush onto the dest buffer
1357 composite(boundingRect: bounds);
1358
1359 glStencilMask(mask: 0);
1360
1361 updateClipScissorTest();
1362 }
1363}
1364
1365void QGL2PaintEngineEx::penChanged() { }
1366void QGL2PaintEngineEx::brushChanged() { }
1367void QGL2PaintEngineEx::brushOriginChanged() { }
1368
1369void QGL2PaintEngineEx::opacityChanged()
1370{
1371// qDebug("QGL2PaintEngineEx::opacityChanged()");
1372 Q_D(QGL2PaintEngineEx);
1373 state()->opacityChanged = true;
1374
1375 Q_ASSERT(d->shaderManager);
1376 d->brushUniformsDirty = true;
1377 d->opacityUniformDirty = true;
1378}
1379
1380void QGL2PaintEngineEx::compositionModeChanged()
1381{
1382// qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1383 Q_D(QGL2PaintEngineEx);
1384 state()->compositionModeChanged = true;
1385 d->compositionModeDirty = true;
1386}
1387
1388void QGL2PaintEngineEx::renderHintsChanged()
1389{
1390 Q_D(QGL2PaintEngineEx);
1391 state()->renderHintsChanged = true;
1392
1393#if !defined(QT_OPENGL_ES_2)
1394QT_WARNING_PUSH
1395QT_WARNING_DISABLE_DEPRECATED
1396 if (!d->ctx->contextHandle()->isOpenGLES()) {
1397 if ((state()->renderHints & QPainter::Antialiasing)
1398#if QT_DEPRECATED_SINCE(5, 14)
1399 || (state()->renderHints & QPainter::HighQualityAntialiasing)
1400#endif
1401 )
1402 d->glEnable(GL_MULTISAMPLE);
1403 else
1404 d->glDisable(GL_MULTISAMPLE);
1405 }
1406QT_WARNING_POP
1407#endif
1408
1409 d->lastTextureUsed = GLuint(-1);
1410 d->brushTextureDirty = true;
1411// qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1412}
1413
1414void QGL2PaintEngineEx::transformChanged()
1415{
1416 Q_D(QGL2PaintEngineEx);
1417 d->matrixDirty = true;
1418 state()->matrixChanged = true;
1419}
1420
1421
1422static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1423{
1424 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1425}
1426
1427void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1428{
1429 Q_D(QGL2PaintEngineEx);
1430 QGLContext *ctx = d->ctx;
1431
1432 int max_texture_size = ctx->d_func()->maxTextureSize();
1433 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1434 QPixmap scaled = pixmap.scaled(w: max_texture_size, h: max_texture_size, aspectMode: Qt::KeepAspectRatio);
1435
1436 const qreal sx = scaled.width() / qreal(pixmap.width());
1437 const qreal sy = scaled.height() / qreal(pixmap.height());
1438
1439 drawPixmap(dest, pixmap: scaled, src: scaleRect(r: src, sx, sy));
1440 return;
1441 }
1442
1443 ensureActive();
1444 d->transferMode(newMode: ImageDrawingMode);
1445
1446 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1447#ifdef QGL_USE_TEXTURE_POOL
1448 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1449#endif
1450
1451 d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1452 QGLTexture *texture =
1453 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, options: bindOptions);
1454
1455 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1456 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1457 QGLRect srcRect(src.left(), top, src.right(), bottom);
1458
1459 bool isBitmap = pixmap.isQBitmap();
1460 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1461
1462 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1463 smoothPixmapTransform: state()->renderHints & QPainter::SmoothPixmapTransform, id: texture->id);
1464 d->drawTexture(dest, src: srcRect, textureSize: pixmap.size(), opaque: isOpaque, pattern: isBitmap);
1465
1466 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1467 // pixmap was temporarily cached as a QImage texture by pooling system
1468 // and should be destroyed immediately
1469 QGLTextureCache::instance()->remove(ctx, textureId: texture->id);
1470 }
1471}
1472
1473void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1474 Qt::ImageConversionFlags)
1475{
1476 Q_D(QGL2PaintEngineEx);
1477 QGLContext *ctx = d->ctx;
1478
1479 int max_texture_size = ctx->d_func()->maxTextureSize();
1480 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1481 QImage scaled = image.scaled(w: max_texture_size, h: max_texture_size, aspectMode: Qt::KeepAspectRatio);
1482
1483 const qreal sx = scaled.width() / qreal(image.width());
1484 const qreal sy = scaled.height() / qreal(image.height());
1485
1486 drawImage(dest, image: scaled, src: scaleRect(r: src, sx, sy));
1487 return;
1488 }
1489
1490 ensureActive();
1491 d->transferMode(newMode: ImageDrawingMode);
1492
1493 d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1494
1495 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1496#ifdef QGL_USE_TEXTURE_POOL
1497 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1498#endif
1499
1500 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, options: bindOptions);
1501 GLuint id = texture->id;
1502
1503 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1504 smoothPixmapTransform: state()->renderHints & QPainter::SmoothPixmapTransform, id);
1505 d->drawTexture(dest, src, textureSize: image.size(), opaque: !image.hasAlphaChannel());
1506
1507 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1508 // image was temporarily cached by texture pooling system
1509 // and should be destroyed immediately
1510 QGLTextureCache::instance()->remove(ctx, textureId: texture->id);
1511 }
1512}
1513
1514void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1515{
1516 Q_D(QGL2PaintEngineEx);
1517
1518 ensureActive();
1519
1520 QPainterState *s = state();
1521
1522 // don't try to cache huge fonts or vastly transformed fonts
1523 QFontEngine *fontEngine = textItem->fontEngine();
1524 if (shouldDrawCachedGlyphs(fontEngine, t: s->matrix)) {
1525
1526 QFontEngine::GlyphFormat glyphFormat = fontEngine->glyphFormat != QFontEngine::Format_None
1527 ? fontEngine->glyphFormat : d->glyphCacheFormat;
1528
1529 if (glyphFormat == QFontEngine::Format_A32) {
1530 if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1531 || d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1532 || (s->composition_mode != QPainter::CompositionMode_Source
1533 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1534 {
1535 glyphFormat = QFontEngine::Format_A8;
1536 }
1537 }
1538
1539 d->drawCachedGlyphs(glyphFormat, staticTextItem: textItem);
1540 } else {
1541 QPaintEngineEx::drawStaticTextItem(textItem);
1542 }
1543}
1544
1545bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1546{
1547 Q_D(QGL2PaintEngineEx);
1548 if (!d->shaderManager)
1549 return false;
1550
1551 ensureActive();
1552 d->transferMode(newMode: ImageDrawingMode);
1553
1554 d->glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1555 d->glBindTexture(GL_TEXTURE_2D, texture: textureId);
1556
1557 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1558
1559 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1560 smoothPixmapTransform: state()->renderHints & QPainter::SmoothPixmapTransform, id: textureId);
1561 d->drawTexture(dest, src: srcRect, textureSize: size, opaque: false);
1562 return true;
1563}
1564
1565void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1566{
1567 Q_D(QGL2PaintEngineEx);
1568
1569 ensureActive();
1570 QGL2PaintEngineState *s = state();
1571
1572 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1573
1574 QTransform::TransformationType txtype = s->matrix.type();
1575
1576 QFontEngine::GlyphFormat glyphFormat = ti.fontEngine->glyphFormat != QFontEngine::Format_None
1577 ? ti.fontEngine->glyphFormat : d->glyphCacheFormat;
1578
1579 if (glyphFormat == QFontEngine::Format_A32) {
1580 if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
1581 || d->device->alphaRequested() || txtype > QTransform::TxTranslate
1582 || (state()->composition_mode != QPainter::CompositionMode_Source
1583 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1584 {
1585 glyphFormat = QFontEngine::Format_A8;
1586 }
1587 }
1588
1589 if (shouldDrawCachedGlyphs(fontEngine: ti.fontEngine, t: s->matrix)) {
1590 QVarLengthArray<QFixedPoint> positions;
1591 QVarLengthArray<glyph_t> glyphs;
1592 QTransform matrix = QTransform::fromTranslate(dx: p.x(), dy: p.y());
1593 ti.fontEngine->getGlyphPositions(glyphs: ti.glyphs, matrix, flags: ti.flags, glyphs_out&: glyphs, positions);
1594
1595 {
1596 QStaticTextItem staticTextItem;
1597 staticTextItem.setFontEngine(ti.fontEngine);
1598 staticTextItem.glyphs = glyphs.data();
1599 staticTextItem.numGlyphs = glyphs.size();
1600 staticTextItem.glyphPositions = positions.data();
1601
1602 d->drawCachedGlyphs(glyphFormat, staticTextItem: &staticTextItem);
1603 }
1604 return;
1605 }
1606
1607 QPaintEngineEx::drawTextItem(p, textItem: ti);
1608}
1609
1610namespace {
1611
1612 class QOpenGLStaticTextUserData: public QStaticTextUserData
1613 {
1614 public:
1615 QOpenGLStaticTextUserData()
1616 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1617 {
1618 }
1619
1620 ~QOpenGLStaticTextUserData()
1621 {
1622 }
1623
1624 QSize cacheSize;
1625 QGL2PEXVertexArray vertexCoordinateArray;
1626 QGL2PEXVertexArray textureCoordinateArray;
1627 QFontEngine::GlyphFormat glyphFormat;
1628 int cacheSerialNumber;
1629 };
1630
1631}
1632
1633
1634// #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1635
1636void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngine::GlyphFormat glyphFormat,
1637 QStaticTextItem *staticTextItem)
1638{
1639 Q_Q(QGL2PaintEngineEx);
1640
1641 QGL2PaintEngineState *s = q->state();
1642
1643 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1644 bool recreateVertexArrays = false;
1645
1646 QTransform glyphCacheTransform;
1647 QFontEngine *fe = staticTextItem->fontEngine();
1648 if (fe->supportsTransformation(transform: s->matrix)) {
1649 // The font-engine supports rendering glyphs with the current transform, so we
1650 // build a glyph-cache with the scale pre-applied, so that the cache contains
1651 // glyphs with the appropriate resolution in the case of retina displays.
1652 glyphCacheTransform = s->matrix.type() < QTransform::TxRotate ?
1653 QTransform::fromScale(dx: qAbs(t: s->matrix.m11()), dy: qAbs(t: s->matrix.m22())) :
1654 QTransform::fromScale(
1655 dx: QVector2D(s->matrix.m11(), s->matrix.m12()).length(),
1656 dy: QVector2D(s->matrix.m21(), s->matrix.m22()).length());
1657 }
1658
1659 QGLTextureGlyphCache *cache =
1660 (QGLTextureGlyphCache *) fe->glyphCache(key: cacheKey, format: glyphFormat, transform: glyphCacheTransform);
1661 if (!cache || cache->glyphFormat() != glyphFormat || cache->contextGroup() == 0) {
1662 cache = new QGLTextureGlyphCache(glyphFormat, glyphCacheTransform);
1663 fe->setGlyphCache(key: cacheKey, data: cache);
1664 recreateVertexArrays = true;
1665 }
1666
1667 if (staticTextItem->userDataNeedsUpdate) {
1668 recreateVertexArrays = true;
1669 } else if (staticTextItem->userData() == 0) {
1670 recreateVertexArrays = true;
1671 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1672 recreateVertexArrays = true;
1673 } else {
1674 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1675 if (userData->glyphFormat != glyphFormat) {
1676 recreateVertexArrays = true;
1677 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1678 recreateVertexArrays = true;
1679 }
1680 }
1681
1682 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1683 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1684 // cache so this text is performed before we test if the cache size has changed.
1685 if (recreateVertexArrays) {
1686 cache->setPaintEnginePrivate(this);
1687 if (!cache->populate(fontEngine: fe, numGlyphs: staticTextItem->numGlyphs,
1688 glyphs: staticTextItem->glyphs, positions: staticTextItem->glyphPositions)) {
1689 // No space for glyphs in cache. We need to reset it and try again.
1690 cache->clear();
1691 cache->populate(fontEngine: fe, numGlyphs: staticTextItem->numGlyphs,
1692 glyphs: staticTextItem->glyphs, positions: staticTextItem->glyphPositions);
1693 }
1694 cache->fillInPendingGlyphs();
1695 }
1696
1697 if (cache->width() == 0 || cache->height() == 0)
1698 return;
1699
1700 transferMode(newMode: TextDrawingMode);
1701
1702 int margin = fe->glyphMargin(format: glyphFormat);
1703
1704 GLfloat dx = 1.0 / cache->width();
1705 GLfloat dy = 1.0 / cache->height();
1706
1707 // Use global arrays by default
1708 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1709 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1710
1711 if (staticTextItem->useBackendOptimizations) {
1712 QOpenGLStaticTextUserData *userData = 0;
1713
1714 if (staticTextItem->userData() == 0
1715 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1716
1717 userData = new QOpenGLStaticTextUserData();
1718 staticTextItem->setUserData(userData);
1719
1720 } else {
1721 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1722 }
1723
1724 userData->glyphFormat = glyphFormat;
1725 userData->cacheSerialNumber = cache->serialNumber();
1726
1727 // Use cache if backend optimizations is turned on
1728 vertexCoordinates = &userData->vertexCoordinateArray;
1729 textureCoordinates = &userData->textureCoordinateArray;
1730
1731 QSize size(cache->width(), cache->height());
1732 if (userData->cacheSize != size) {
1733 recreateVertexArrays = true;
1734 userData->cacheSize = size;
1735 }
1736 }
1737
1738 if (recreateVertexArrays) {
1739 vertexCoordinates->clear();
1740 textureCoordinates->clear();
1741
1742 bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1743 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1744 QFixed subPixelPosition;
1745 if (supportsSubPixelPositions)
1746 subPixelPosition = fe->subPixelPositionForX(x: staticTextItem->glyphPositions[i].x);
1747
1748 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1749
1750 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1751 if (c.isNull())
1752 continue;
1753
1754 int x = qFloor(v: staticTextItem->glyphPositions[i].x.toReal() * cache->transform().m11()) + c.baseLineX - margin;
1755 int y = qRound(d: staticTextItem->glyphPositions[i].y.toReal() * cache->transform().m22()) - c.baseLineY - margin;
1756
1757 vertexCoordinates->addQuad(rect: QRectF(x, y, c.w, c.h));
1758 textureCoordinates->addQuad(rect: QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1759 }
1760
1761 staticTextItem->userDataNeedsUpdate = false;
1762 }
1763
1764 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1765 if (numGlyphs == 0)
1766 return;
1767
1768 if (elementIndices.size() < numGlyphs*6) {
1769 Q_ASSERT(elementIndices.size() % 6 == 0);
1770 int j = elementIndices.size() / 6 * 4;
1771 while (j < numGlyphs*4) {
1772 elementIndices.append(t: j + 0);
1773 elementIndices.append(t: j + 0);
1774 elementIndices.append(t: j + 1);
1775 elementIndices.append(t: j + 2);
1776 elementIndices.append(t: j + 3);
1777 elementIndices.append(t: j + 3);
1778
1779 j += 4;
1780 }
1781
1782#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1783 if (elementIndicesVBOId == 0)
1784 glGenBuffers(1, &elementIndicesVBOId);
1785
1786 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1787 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1788 elementIndices.constData(), GL_STATIC_DRAW);
1789#endif
1790 } else {
1791#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1792 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1793#endif
1794 }
1795
1796 setVertexAttributePointer(arrayIndex: QT_VERTEX_COORDS_ATTR, pointer: (GLfloat*)vertexCoordinates->data());
1797 setVertexAttributePointer(arrayIndex: QT_TEXTURE_COORDS_ATTR, pointer: (GLfloat*)textureCoordinates->data());
1798
1799 if (!snapToPixelGrid) {
1800 snapToPixelGrid = true;
1801 matrixDirty = true;
1802 }
1803
1804 QBrush pensBrush = q->state()->pen.brush();
1805 setBrush(pensBrush);
1806
1807 if (glyphFormat == QFontEngine::Format_A32) {
1808
1809 // Subpixel antialiasing without gamma correction
1810
1811 QPainter::CompositionMode compMode = q->state()->composition_mode;
1812 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1813 || compMode == QPainter::CompositionMode_SourceOver);
1814
1815 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1816
1817 if (pensBrush.style() == Qt::SolidPattern) {
1818 // Solid patterns can get away with only one pass.
1819 QColor c = pensBrush.color();
1820 qreal oldOpacity = q->state()->opacity;
1821 if (compMode == QPainter::CompositionMode_Source) {
1822 c = qt_premultiplyColor(c, opacity: q->state()->opacity);
1823 q->state()->opacity = 1;
1824 opacityUniformDirty = true;
1825 }
1826
1827 compositionModeDirty = false; // I can handle this myself, thank you very much
1828 prepareForCachedGlyphDraw(cache: *cache);
1829
1830 // prepareForCachedGlyphDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1831 if (compMode == QPainter::CompositionMode_Source) {
1832 q->state()->opacity = oldOpacity;
1833 opacityUniformDirty = true;
1834 }
1835
1836 glEnable(GL_BLEND);
1837 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1838 glBlendColor(red: c.redF(), green: c.greenF(), blue: c.blueF(), alpha: c.alphaF());
1839 } else {
1840 // Other brush styles need two passes.
1841
1842 qreal oldOpacity = q->state()->opacity;
1843 if (compMode == QPainter::CompositionMode_Source) {
1844 q->state()->opacity = 1;
1845 opacityUniformDirty = true;
1846 pensBrush = Qt::white;
1847 setBrush(pensBrush);
1848 }
1849
1850 compositionModeDirty = false; // I can handle this myself, thank you very much
1851 prepareForCachedGlyphDraw(cache: *cache);
1852 glEnable(GL_BLEND);
1853 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1854
1855 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1856 glBindTexture(GL_TEXTURE_2D, texture: cache->texture());
1857 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, smoothPixmapTransform: false);
1858
1859#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1860 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1861#else
1862 glDrawElements(GL_TRIANGLE_STRIP, count: 6 * numGlyphs, GL_UNSIGNED_SHORT, indices: elementIndices.data());
1863#endif
1864
1865 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1866
1867 if (compMode == QPainter::CompositionMode_Source) {
1868 q->state()->opacity = oldOpacity;
1869 opacityUniformDirty = true;
1870 pensBrush = q->state()->pen.brush();
1871 setBrush(pensBrush);
1872 }
1873
1874 compositionModeDirty = false;
1875 prepareForCachedGlyphDraw(cache: *cache);
1876 glEnable(GL_BLEND);
1877 glBlendFunc(GL_ONE, GL_ONE);
1878 }
1879 compositionModeDirty = true;
1880 } else {
1881 // Grayscale/mono glyphs
1882
1883 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1884 prepareForCachedGlyphDraw(cache: *cache);
1885 }
1886
1887 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1888 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1889
1890 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1891 if (lastMaskTextureUsed != cache->texture()) {
1892 glBindTexture(GL_TEXTURE_2D, texture: cache->texture());
1893 lastMaskTextureUsed = cache->texture();
1894 }
1895
1896 if (cache->filterMode() != filterMode) {
1897 if (filterMode == QGLTextureGlyphCache::Linear) {
1898 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1899 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1900 } else {
1901 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1902 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1903 }
1904 cache->setFilterMode(filterMode);
1905 }
1906 }
1907
1908#if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1909 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1910 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1911#else
1912 glDrawElements(GL_TRIANGLE_STRIP, count: 6 * numGlyphs, GL_UNSIGNED_SHORT, indices: elementIndices.data());
1913#endif
1914}
1915
1916void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1917 QPainter::PixmapFragmentHints hints)
1918{
1919 Q_D(QGL2PaintEngineEx);
1920 // Use fallback for extended composition modes.
1921 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1922 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1923 return;
1924 }
1925
1926 ensureActive();
1927 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1928 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1929 QPixmap scaled = pixmap.scaled(w: max_texture_size, h: max_texture_size, aspectMode: Qt::KeepAspectRatio);
1930 d->drawPixmapFragments(fragments, fragmentCount, pixmap: scaled, hints);
1931 } else {
1932 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1933 }
1934}
1935
1936
1937void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1938 int fragmentCount, const QPixmap &pixmap,
1939 QPainter::PixmapFragmentHints hints)
1940{
1941 GLfloat dx = 1.0f / pixmap.size().width();
1942 GLfloat dy = 1.0f / pixmap.size().height();
1943
1944 vertexCoordinateArray.clear();
1945 textureCoordinateArray.clear();
1946 opacityArray.reset();
1947
1948 if (snapToPixelGrid) {
1949 snapToPixelGrid = false;
1950 matrixDirty = true;
1951 }
1952
1953 bool allOpaque = true;
1954
1955 for (int i = 0; i < fragmentCount; ++i) {
1956 qreal s = 0;
1957 qreal c = 1;
1958 if (fragments[i].rotation != 0) {
1959 s = qFastSin(x: qDegreesToRadians(degrees: fragments[i].rotation));
1960 c = qFastCos(x: qDegreesToRadians(degrees: fragments[i].rotation));
1961 }
1962
1963 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1964 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1965 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1966 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1967
1968 vertexCoordinateArray.addVertex(x: bottomRight.x + fragments[i].x, y: bottomRight.y + fragments[i].y);
1969 vertexCoordinateArray.addVertex(x: -bottomLeft.x + fragments[i].x, y: -bottomLeft.y + fragments[i].y);
1970 vertexCoordinateArray.addVertex(x: -bottomRight.x + fragments[i].x, y: -bottomRight.y + fragments[i].y);
1971 vertexCoordinateArray.addVertex(x: -bottomRight.x + fragments[i].x, y: -bottomRight.y + fragments[i].y);
1972 vertexCoordinateArray.addVertex(x: bottomLeft.x + fragments[i].x, y: bottomLeft.y + fragments[i].y);
1973 vertexCoordinateArray.addVertex(x: bottomRight.x + fragments[i].x, y: bottomRight.y + fragments[i].y);
1974
1975 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1976 (fragments[i].sourceLeft + fragments[i].width) * dx,
1977 (fragments[i].sourceTop + fragments[i].height) * dy);
1978
1979 textureCoordinateArray.addVertex(x: src.right, y: src.bottom);
1980 textureCoordinateArray.addVertex(x: src.right, y: src.top);
1981 textureCoordinateArray.addVertex(x: src.left, y: src.top);
1982 textureCoordinateArray.addVertex(x: src.left, y: src.top);
1983 textureCoordinateArray.addVertex(x: src.left, y: src.bottom);
1984 textureCoordinateArray.addVertex(x: src.right, y: src.bottom);
1985
1986 qreal opacity = fragments[i].opacity * q->state()->opacity;
1987 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1988 allOpaque &= (opacity >= 0.99f);
1989 }
1990
1991 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1992 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1993 options: QGLContext::InternalBindOption
1994 | QGLContext::CanFlipNativePixmapBindOption);
1995
1996 if (texture->options & QGLContext::InvertedYBindOption) {
1997 // Flip texture y-coordinate.
1998 QGLPoint *data = textureCoordinateArray.data();
1999 for (int i = 0; i < 6 * fragmentCount; ++i)
2000 data[i].y = 1 - data[i].y;
2001 }
2002
2003 transferMode(newMode: ImageArrayDrawingMode);
2004
2005 bool isBitmap = pixmap.isQBitmap();
2006 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
2007
2008 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
2009 smoothPixmapTransform: q->state()->renderHints & QPainter::SmoothPixmapTransform, id: texture->id);
2010
2011 // Setup for texture drawing
2012 currentBrush = noBrush;
2013 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
2014 : QGLEngineShaderManager::ImageSrc);
2015 if (prepareForDraw(srcPixelsAreOpaque: isOpaque))
2016 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
2017
2018 if (isBitmap) {
2019 QColor col = qt_premultiplyColor(c: q->state()->pen.color(), opacity: (GLfloat)q->state()->opacity);
2020 shaderManager->currentProgram()->setUniformValue(location: location(uniform: QGLEngineShaderManager::PatternColor), color: col);
2021 }
2022
2023 glDrawArrays(GL_TRIANGLES, first: 0, count: 6 * fragmentCount);
2024}
2025
2026bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
2027{
2028 Q_D(QGL2PaintEngineEx);
2029
2030// qDebug("QGL2PaintEngineEx::begin()");
2031 if (pdev->devType() == QInternal::OpenGL)
2032 d->device = static_cast<QGLPaintDevice*>(pdev);
2033 else
2034 d->device = QGLPaintDevice::getDevice(pdev);
2035
2036 if (!d->device)
2037 return false;
2038
2039 d->ctx = d->device->context();
2040 d->ctx->d_ptr->active_engine = this;
2041
2042 d->resetOpenGLContextActiveEngine();
2043
2044 const QSize sz = d->device->size();
2045 d->width = sz.width();
2046 d->height = sz.height();
2047 d->mode = BrushDrawingMode;
2048 d->brushTextureDirty = true;
2049 d->brushUniformsDirty = true;
2050 d->matrixUniformDirty = true;
2051 d->matrixDirty = true;
2052 d->compositionModeDirty = true;
2053 d->opacityUniformDirty = true;
2054 d->translateZUniformDirty = true;
2055 d->needsSync = true;
2056 d->useSystemClip = !systemClip().isEmpty();
2057 d->currentBrush = QBrush();
2058
2059 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
2060 d->stencilClean = true;
2061
2062 // Calling begin paint should make the correct context current. So, any
2063 // code which calls into GL or otherwise needs a current context *must*
2064 // go after beginPaint:
2065 d->device->beginPaint();
2066
2067 d->initializeOpenGLFunctions();
2068
2069 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2070
2071 d->glDisable(GL_STENCIL_TEST);
2072 d->glDisable(GL_DEPTH_TEST);
2073 d->glDisable(GL_SCISSOR_TEST);
2074
2075#if !defined(QT_OPENGL_ES_2)
2076 if (!d->ctx->contextHandle()->isOpenGLES())
2077 d->glDisable(GL_MULTISAMPLE);
2078#endif
2079
2080 d->glyphCacheFormat = QFontEngine::Format_A8;
2081
2082#if !defined(QT_OPENGL_ES_2)
2083 if (!d->ctx->contextHandle()->isOpenGLES()) {
2084 d->glyphCacheFormat = QFontEngine::Format_A32;
2085 d->multisamplingAlwaysEnabled = false;
2086 } else {
2087 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2088 }
2089#else
2090 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2091 // multisampled, it's always multisampled.
2092 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2093#endif
2094
2095 return true;
2096}
2097
2098bool QGL2PaintEngineEx::end()
2099{
2100 Q_D(QGL2PaintEngineEx);
2101
2102 QGLContext *ctx = d->ctx;
2103 d->glUseProgram(program: 0);
2104 d->transferMode(newMode: BrushDrawingMode);
2105 d->device->endPaint();
2106
2107 ctx->d_ptr->active_engine = 0;
2108 ctx->makeCurrent();
2109 d->resetOpenGLContextActiveEngine();
2110 d->resetGLState();
2111
2112 delete d->shaderManager;
2113 d->shaderManager = 0;
2114 d->currentBrush = QBrush();
2115
2116#ifdef QT_OPENGL_CACHE_AS_VBOS
2117 if (!d->unusedVBOSToClean.isEmpty()) {
2118 d->glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2119 d->unusedVBOSToClean.clear();
2120 }
2121 if (!d->unusedIBOSToClean.isEmpty()) {
2122 d->glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2123 d->unusedIBOSToClean.clear();
2124 }
2125#endif
2126
2127 return false;
2128}
2129
2130void QGL2PaintEngineEx::ensureActive()
2131{
2132 Q_D(QGL2PaintEngineEx);
2133 QGLContext *ctx = d->ctx;
2134
2135 if (isActive() && (ctx->d_ptr->active_engine != this || d->resetOpenGLContextActiveEngine())) {
2136 ctx->d_ptr->active_engine = this;
2137 d->needsSync = true;
2138 }
2139
2140 d->device->ensureActiveTarget();
2141
2142 if (d->needsSync) {
2143 d->transferMode(newMode: BrushDrawingMode);
2144 d->glViewport(x: 0, y: 0, width: d->width, height: d->height);
2145 d->needsSync = false;
2146 d->lastMaskTextureUsed = 0;
2147 d->shaderManager->setDirty();
2148 d->ctx->d_func()->syncGlState();
2149 for (int i = 0; i < 3; ++i)
2150 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2151 setState(state());
2152 }
2153}
2154
2155void QGL2PaintEngineExPrivate::updateClipScissorTest()
2156{
2157 Q_Q(QGL2PaintEngineEx);
2158 if (q->state()->clipTestEnabled) {
2159 glEnable(GL_STENCIL_TEST);
2160 glStencilFunc(GL_LEQUAL, ref: q->state()->currentClip, mask: ~GL_STENCIL_HIGH_BIT);
2161 } else {
2162 glDisable(GL_STENCIL_TEST);
2163 glStencilFunc(GL_ALWAYS, ref: 0, mask: 0xff);
2164 }
2165
2166#ifdef QT_GL_NO_SCISSOR_TEST
2167 currentScissorBounds = QRect(0, 0, width, height);
2168#else
2169 QRect bounds = q->state()->rectangleClip;
2170 if (!q->state()->clipEnabled) {
2171 if (useSystemClip)
2172 bounds = systemClip.boundingRect();
2173 else
2174 bounds = QRect(0, 0, width, height);
2175 } else {
2176 if (useSystemClip)
2177 bounds = bounds.intersected(other: systemClip.boundingRect());
2178 else
2179 bounds = bounds.intersected(other: QRect(0, 0, width, height));
2180 }
2181
2182 currentScissorBounds = bounds;
2183
2184 if (bounds == QRect(0, 0, width, height)) {
2185 glDisable(GL_SCISSOR_TEST);
2186 } else {
2187 glEnable(GL_SCISSOR_TEST);
2188 setScissor(bounds);
2189 }
2190#endif
2191}
2192
2193void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2194{
2195 const int left = rect.left();
2196 const int width = rect.width();
2197 int bottom = height - (rect.top() + rect.height());
2198 if (device->isFlipped()) {
2199 bottom = rect.top();
2200 }
2201 const int height = rect.height();
2202
2203 glScissor(x: left, y: bottom, width, height);
2204}
2205
2206void QGL2PaintEngineEx::clipEnabledChanged()
2207{
2208 Q_D(QGL2PaintEngineEx);
2209
2210 state()->clipChanged = true;
2211
2212 if (painter()->hasClipping())
2213 d->regenerateClip();
2214 else
2215 d->systemStateChanged();
2216}
2217
2218void QGL2PaintEngineExPrivate::clearClip(uint value)
2219{
2220 dirtyStencilRegion -= currentScissorBounds;
2221
2222 glStencilMask(mask: 0xff);
2223 glClearStencil(s: value);
2224 glClear(GL_STENCIL_BUFFER_BIT);
2225 glStencilMask(mask: 0x0);
2226
2227 q->state()->needsClipBufferClear = false;
2228}
2229
2230void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2231{
2232 transferMode(newMode: BrushDrawingMode);
2233
2234 if (snapToPixelGrid) {
2235 snapToPixelGrid = false;
2236 matrixDirty = true;
2237 }
2238
2239 if (matrixDirty)
2240 updateMatrix();
2241
2242 stencilClean = false;
2243
2244 const bool singlePass = !path.hasWindingFill()
2245 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2246 || q->state()->needsClipBufferClear);
2247 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2248
2249 if (q->state()->needsClipBufferClear)
2250 clearClip(value: 1);
2251
2252 if (path.isEmpty()) {
2253 glEnable(GL_STENCIL_TEST);
2254 glStencilFunc(GL_LEQUAL, ref: value, mask: ~GL_STENCIL_HIGH_BIT);
2255 return;
2256 }
2257
2258 if (q->state()->clipTestEnabled)
2259 glStencilFunc(GL_LEQUAL, ref: q->state()->currentClip, mask: ~GL_STENCIL_HIGH_BIT);
2260 else
2261 glStencilFunc(GL_ALWAYS, ref: 0, mask: 0xff);
2262
2263 vertexCoordinateArray.clear();
2264 vertexCoordinateArray.addPath(path, curveInverseScale: inverseScale, outline: false);
2265
2266 if (!singlePass)
2267 fillStencilWithVertexArray(vertexArray&: vertexCoordinateArray, useWindingFill: path.hasWindingFill());
2268
2269 glColorMask(red: false, green: false, blue: false, alpha: false);
2270 glEnable(GL_STENCIL_TEST);
2271 useSimpleShader();
2272
2273 if (singlePass) {
2274 // Under these conditions we can set the new stencil value in a single
2275 // pass, by using the current value and the "new value" as the toggles
2276
2277 glStencilFunc(GL_LEQUAL, ref: referenceClipValue, mask: ~GL_STENCIL_HIGH_BIT);
2278 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2279 glStencilMask(mask: value ^ referenceClipValue);
2280
2281 drawVertexArrays(vertexArray&: vertexCoordinateArray, GL_TRIANGLE_FAN);
2282 } else {
2283 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2284 glStencilMask(mask: 0xff);
2285
2286 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2287 // Pass when any clip bit is set, set high bit
2288 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, mask: ~GL_STENCIL_HIGH_BIT);
2289 composite(boundingRect: vertexCoordinateArray.boundingRect());
2290 }
2291
2292 // Pass when high bit is set, replace stencil value with new clip value
2293 glStencilFunc(GL_NOTEQUAL, ref: value, GL_STENCIL_HIGH_BIT);
2294
2295 composite(boundingRect: vertexCoordinateArray.boundingRect());
2296 }
2297
2298 glStencilFunc(GL_LEQUAL, ref: value, mask: ~GL_STENCIL_HIGH_BIT);
2299 glStencilMask(mask: 0);
2300
2301 glColorMask(red: true, green: true, blue: true, alpha: true);
2302}
2303
2304void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2305{
2306// qDebug("QGL2PaintEngineEx::clip()");
2307 Q_D(QGL2PaintEngineEx);
2308
2309 state()->clipChanged = true;
2310
2311 ensureActive();
2312
2313 if (op == Qt::ReplaceClip) {
2314 op = Qt::IntersectClip;
2315 if (d->hasClipOperations()) {
2316 d->systemStateChanged();
2317 state()->canRestoreClip = false;
2318 }
2319 }
2320
2321#ifndef QT_GL_NO_SCISSOR_TEST
2322 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2323 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2324 QRectF rect(points[0], points[2]);
2325
2326 if (state()->matrix.type() <= QTransform::TxScale
2327 || (state()->matrix.type() == QTransform::TxRotate
2328 && qFuzzyIsNull(d: state()->matrix.m11())
2329 && qFuzzyIsNull(d: state()->matrix.m22())))
2330 {
2331 state()->rectangleClip = state()->rectangleClip.intersected(other: state()->matrix.mapRect(rect).toRect());
2332 d->updateClipScissorTest();
2333 return;
2334 }
2335 }
2336#endif
2337
2338 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2339
2340 switch (op) {
2341 case Qt::NoClip:
2342 if (d->useSystemClip) {
2343 state()->clipTestEnabled = true;
2344 state()->currentClip = 1;
2345 } else {
2346 state()->clipTestEnabled = false;
2347 }
2348 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2349 state()->canRestoreClip = false;
2350 d->updateClipScissorTest();
2351 break;
2352 case Qt::IntersectClip:
2353 state()->rectangleClip = state()->rectangleClip.intersected(other: pathRect);
2354 d->updateClipScissorTest();
2355 d->resetClipIfNeeded();
2356 ++d->maxClip;
2357 d->writeClip(path, value: d->maxClip);
2358 state()->currentClip = d->maxClip;
2359 state()->clipTestEnabled = true;
2360 break;
2361 default:
2362 break;
2363 }
2364}
2365
2366void QGL2PaintEngineExPrivate::regenerateClip()
2367{
2368 systemStateChanged();
2369 replayClipOperations();
2370}
2371
2372void QGL2PaintEngineExPrivate::systemStateChanged()
2373{
2374 Q_Q(QGL2PaintEngineEx);
2375
2376 q->state()->clipChanged = true;
2377
2378 if (systemClip.isEmpty()) {
2379 useSystemClip = false;
2380 } else {
2381 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2382 QWidgetPrivate *widgetPrivate = qt_widget_private(widget: static_cast<QWidget *>(currentClipDevice)->window());
2383 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2384 } else {
2385 useSystemClip = true;
2386 }
2387 }
2388
2389 q->state()->clipTestEnabled = false;
2390 q->state()->needsClipBufferClear = true;
2391
2392 q->state()->currentClip = 1;
2393 maxClip = 1;
2394
2395 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2396 updateClipScissorTest();
2397
2398 if (systemClip.rectCount() == 1) {
2399 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2400 useSystemClip = false;
2401#ifndef QT_GL_NO_SCISSOR_TEST
2402 // scissoring takes care of the system clip
2403 return;
2404#endif
2405 }
2406
2407 if (useSystemClip) {
2408 clearClip(value: 0);
2409
2410 QPainterPath path;
2411 path.addRegion(region: systemClip);
2412
2413 q->state()->currentClip = 0;
2414 writeClip(path: qtVectorPathForPath(path: q->state()->matrix.inverted().map(p: path)), value: 1);
2415 q->state()->currentClip = 1;
2416 q->state()->clipTestEnabled = true;
2417 }
2418}
2419
2420void QGL2PaintEngineEx::setTranslateZ(GLfloat z)
2421{
2422 Q_D(QGL2PaintEngineEx);
2423 if (d->translateZ != z) {
2424 d->translateZ = z;
2425 d->translateZUniformDirty = true;
2426 }
2427}
2428
2429void QGL2PaintEngineEx::setState(QPainterState *new_state)
2430{
2431 // qDebug("QGL2PaintEngineEx::setState()");
2432
2433 Q_D(QGL2PaintEngineEx);
2434
2435 QGL2PaintEngineState *s = static_cast<QGL2PaintEngineState *>(new_state);
2436 QGL2PaintEngineState *old_state = state();
2437
2438 QPaintEngineEx::setState(s);
2439
2440 if (s->isNew) {
2441 // Newly created state object. The call to setState()
2442 // will either be followed by a call to begin(), or we are
2443 // setting the state as part of a save().
2444 s->isNew = false;
2445 return;
2446 }
2447
2448 // Setting the state as part of a restore().
2449
2450 if (old_state == s || old_state->renderHintsChanged)
2451 renderHintsChanged();
2452
2453 if (old_state == s || old_state->matrixChanged)
2454 d->matrixDirty = true;
2455
2456 if (old_state == s || old_state->compositionModeChanged)
2457 d->compositionModeDirty = true;
2458
2459 if (old_state == s || old_state->opacityChanged)
2460 d->opacityUniformDirty = true;
2461
2462 if (old_state == s || old_state->clipChanged) {
2463 if (old_state && old_state != s && old_state->canRestoreClip) {
2464 d->updateClipScissorTest();
2465 d->glDepthFunc(GL_LEQUAL);
2466 } else {
2467 d->regenerateClip();
2468 }
2469 }
2470}
2471
2472QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2473{
2474 if (orig)
2475 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2476
2477 QGL2PaintEngineState *s;
2478 if (!orig)
2479 s = new QGL2PaintEngineState();
2480 else
2481 s = new QGL2PaintEngineState(*static_cast<QGL2PaintEngineState *>(orig));
2482
2483 s->matrixChanged = false;
2484 s->compositionModeChanged = false;
2485 s->opacityChanged = false;
2486 s->renderHintsChanged = false;
2487 s->clipChanged = false;
2488
2489 return s;
2490}
2491
2492QGL2PaintEngineState::QGL2PaintEngineState(QGL2PaintEngineState &other)
2493 : QPainterState(other)
2494{
2495 isNew = true;
2496 needsClipBufferClear = other.needsClipBufferClear;
2497 clipTestEnabled = other.clipTestEnabled;
2498 currentClip = other.currentClip;
2499 canRestoreClip = other.canRestoreClip;
2500 rectangleClip = other.rectangleClip;
2501}
2502
2503QGL2PaintEngineState::QGL2PaintEngineState()
2504{
2505 isNew = true;
2506 needsClipBufferClear = true;
2507 clipTestEnabled = false;
2508 canRestoreClip = true;
2509}
2510
2511QGL2PaintEngineState::~QGL2PaintEngineState()
2512{
2513}
2514
2515QT_END_NAMESPACE
2516

source code of qtbase/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp