source: trunk/src/opengl/qpaintengine_opengl.cpp@ 636

Last change on this file since 636 was 561, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.1 sources.

File size: 176.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtOpenGL module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <qdebug.h>
43#include <private/qfontengine_p.h>
44#include <qmath.h>
45#include <private/qmath_p.h>
46#include <private/qdrawhelper_p.h>
47#include <private/qpaintengine_p.h>
48#include "qapplication.h"
49#include "qbrush.h"
50#include "qgl.h"
51#include <private/qgl_p.h>
52#include <private/qglpaintdevice_p.h>
53#include <private/qpainter_p.h>
54#include "qmap.h"
55#include <private/qpaintengine_opengl_p.h>
56#include <private/qdatabuffer_p.h>
57#include "qpen.h"
58#include "qvarlengtharray.h"
59#include <private/qpainter_p.h>
60#include <private/qglpixelbuffer_p.h>
61#include <private/qbezier_p.h>
62#include <qglframebufferobject.h>
63
64#include "private/qtessellator_p.h"
65
66#include "util/fragmentprograms_p.h"
67
68#ifdef Q_WS_QWS
69#include "private/qglwindowsurface_qws_p.h"
70#include "qwsmanager_qws.h"
71#include "private/qwsmanager_p.h"
72#endif
73
74#ifdef QT_OPENGL_ES_1_CL
75#include "qgl_cl_p.h"
76#endif
77
78#define QGL_FUNC_CONTEXT QGLContext *ctx = const_cast<QGLContext *>(device->context());
79
80#include <stdlib.h>
81#include "qpaintengine_opengl_p.h"
82
83QT_BEGIN_NAMESPACE
84
85extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp
86#ifdef QT_MAC_USE_COCOA
87extern void *qt_current_nsopengl_context(); // qgl_mac.mm
88#endif
89
90#define QREAL_MAX 9e100
91#define QREAL_MIN -9e100
92
93extern int qt_next_power_of_two(int v);
94
95#define DISABLE_DEBUG_ONCE
96
97//#define DEBUG_DISPLAY_MASK_TEXTURE
98
99#ifdef DISABLE_DEBUG_ONCE
100#define DEBUG_OVERRIDE(state) ;
101#define DEBUG_ONCE_STR(str) ;
102#define DEBUG_ONCE if (0)
103#else
104static int DEBUG_OVERRIDE_FLAG = 0;
105static bool DEBUG_TEMP_FLAG;
106#define DEBUG_OVERRIDE(state) { state ? ++DEBUG_OVERRIDE_FLAG : --DEBUG_OVERRIDE_FLAG; }
107#define DEBUG_ONCE if ((DEBUG_TEMP_FLAG = DEBUG_OVERRIDE_FLAG) && 0) ; else for (static int DEBUG_ONCE_FLAG = false; !DEBUG_ONCE_FLAG || DEBUG_TEMP_FLAG; DEBUG_ONCE_FLAG = true, DEBUG_TEMP_FLAG = false)
108#define DEBUG_ONCE_STR(str) DEBUG_ONCE qDebug() << (str);
109#endif
110
111static inline void qt_glColor4ubv(unsigned char *col)
112{
113 glColor4f(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, col[3]/255.0f);
114}
115
116struct QT_PointF {
117 qreal x;
118 qreal y;
119};
120
121struct QGLTrapezoid
122{
123 QGLTrapezoid()
124 {}
125
126 QGLTrapezoid(qreal top_, qreal bottom_, qreal topLeftX_, qreal topRightX_, qreal bottomLeftX_, qreal bottomRightX_)
127 : top(top_),
128 bottom(bottom_),
129 topLeftX(topLeftX_),
130 topRightX(topRightX_),
131 bottomLeftX(bottomLeftX_),
132 bottomRightX(bottomRightX_)
133 {}
134
135 const QGLTrapezoid translated(const QPointF &delta) const;
136
137 qreal top;
138 qreal bottom;
139 qreal topLeftX;
140 qreal topRightX;
141 qreal bottomLeftX;
142 qreal bottomRightX;
143};
144
145const QGLTrapezoid QGLTrapezoid::translated(const QPointF &delta) const
146{
147 QGLTrapezoid trap(*this);
148 trap.top += delta.y();
149 trap.bottom += delta.y();
150 trap.topLeftX += delta.x();
151 trap.topRightX += delta.x();
152 trap.bottomLeftX += delta.x();
153 trap.bottomRightX += delta.x();
154 return trap;
155}
156
157
158class QOpenGLImmediateModeTessellator;
159class QGLMaskGenerator;
160class QGLOffscreen;
161
162class QGLMaskTextureCache
163{
164public:
165 void setOffscreenSize(const QSize &offscreenSize);
166 void setDrawableSize(const QSize &drawableSize);
167
168 struct CacheLocation {
169 QRect rect;
170 int channel;
171
172 QRect screen_rect;
173 };
174
175 struct CacheInfo {
176 inline CacheInfo(const QPainterPath &p, const QTransform &m, qreal w = -1) :
177 path(p), matrix(m), stroke_width(w), age(0) {}
178
179 QPainterPath path;
180 QTransform matrix;
181 qreal stroke_width;
182
183 CacheLocation loc;
184
185 int age;
186 };
187
188 struct QuadTreeNode {
189 quint64 key;
190
191 int largest_available_block;
192 int largest_used_block;
193 };
194
195 CacheLocation getMask(QGLMaskGenerator &maskGenerator, QOpenGLPaintEnginePrivate *engine);
196
197 typedef QMultiHash<quint64, CacheInfo> QGLTextureCacheHash;
198
199 enum {block_size = 64};
200
201 // throw out keys that are too old
202 void maintainCache();
203 void clearCache();
204
205private:
206 quint64 hash(const QPainterPath &p, const QTransform &m, qreal w);
207
208 void createMask(quint64 key, CacheInfo &info, QGLMaskGenerator &maskGenerator);
209
210 QSize offscreenSize;
211 QSize drawableSize;
212
213 QGLTextureCacheHash cache;
214
215 QVector<QuadTreeNode> occupied_quadtree[4];
216
217 void quadtreeUpdate(int channel, int node, int current_block_size);
218 void quadtreeAllocate(quint64 key, const QSize &size, QRect *rect, int *channel);
219
220 bool quadtreeFindAvailableLocation(const QSize &size, QRect *rect, int *channel);
221 void quadtreeFindExistingLocation(const QSize &size, QRect *rect, int *channel);
222
223 void quadtreeInsert(int channel, quint64 key, const QRect &rect, int node = 0);
224 void quadtreeClear(int channel, const QRect &rect, int node = 0);
225
226 int quadtreeBlocksize(int node);
227 QPoint quadtreeLocation(int node);
228
229 QOpenGLPaintEnginePrivate *engine;
230};
231
232Q_GLOBAL_STATIC(QGLMaskTextureCache, qt_mask_texture_cache)
233
234class QGLOffscreen : public QObject
235{
236 Q_OBJECT
237public:
238 QGLOffscreen()
239 : QObject(),
240 offscreen(0),
241 ctx(0),
242 mask_dim(0),
243 activated(false),
244 bound(false)
245 {
246 connect(QGLSignalProxy::instance(),
247 SIGNAL(aboutToDestroyContext(const QGLContext*)),
248 SLOT(cleanupGLContextRefs(const QGLContext*)));
249 }
250
251 inline void setDevice(QPaintDevice *pdev);
252
253 void begin();
254 void end();
255
256 inline void bind();
257 inline void release();
258
259 inline bool isBound() const;
260
261 inline QSize drawableSize() const;
262 inline QSize offscreenSize() const;
263
264 inline GLuint offscreenTexture() const;
265
266 QGLContext *context() const;
267
268 static bool isSupported();
269
270 inline void initialize();
271
272 inline bool isValid() const;
273
274public Q_SLOTS:
275 void cleanupGLContextRefs(const QGLContext *context) {
276 if (context == ctx) {
277 delete offscreen;
278 ctx = 0;
279 offscreen = 0;
280 mask_dim = 0;
281 }
282 }
283
284private:
285 QGLPaintDevice* device;
286
287 QGLFramebufferObject *offscreen;
288 QGLContext *ctx;
289
290 // dimensions of mask texture (square)
291 int mask_dim;
292 QSize last_failed_size;
293
294 bool drawable_fbo;
295
296 bool activated;
297 bool initialized;
298
299 bool bound;
300};
301
302inline void QGLOffscreen::setDevice(QPaintDevice *pdev)
303{
304 if (pdev->devType() == QInternal::OpenGL)
305 device = static_cast<QGLPaintDevice*>(pdev);
306 else
307 device = QGLPaintDevice::getDevice(pdev);
308
309 if (!device)
310 return;
311
312 drawable_fbo = (pdev->devType() == QInternal::FramebufferObject);
313}
314
315void QGLOffscreen::begin()
316{
317#ifndef QT_OPENGL_ES
318 initialized = false;
319
320 if (activated)
321 initialize();
322#endif
323}
324
325void QGLOffscreen::initialize()
326{
327#ifndef QT_OPENGL_ES
328 if (initialized)
329 return;
330
331 activated = true;
332 initialized = true;
333
334 int dim = qMax(2048, static_cast<int>(qt_next_power_of_two(qMax(device->size().width(), device->size().height()))));
335
336 bool shared_context = QGLContext::areSharing(device->context(), ctx);
337 bool would_fail = last_failed_size.isValid() &&
338 (device->size().width() >= last_failed_size.width() ||
339 device->size().height() >= last_failed_size.height());
340 bool needs_refresh = dim > mask_dim || !shared_context;
341
342 if (needs_refresh && !would_fail) {
343 DEBUG_ONCE qDebug() << "QGLOffscreen::initialize(): creating offscreen of size" << dim;
344 delete offscreen;
345 offscreen = new QGLFramebufferObject(dim, dim, GLenum(GL_TEXTURE_2D));
346 mask_dim = dim;
347
348 if (!offscreen->isValid()) {
349 qWarning("QGLOffscreen: Invalid offscreen fbo (size %dx%d)", mask_dim, mask_dim);
350 delete offscreen;
351 offscreen = 0;
352 mask_dim = 0;
353 last_failed_size = device->size();
354 }
355 }
356
357 qt_mask_texture_cache()->setOffscreenSize(offscreenSize());
358 qt_mask_texture_cache()->setDrawableSize(device->size());
359 ctx = device->context();
360#endif
361}
362
363inline bool QGLOffscreen::isValid() const
364{
365 return offscreen;
366}
367
368void QGLOffscreen::end()
369{
370 if (bound)
371 release();
372#ifdef DEBUG_DISPLAY_MASK_TEXTURE
373 glReadBuffer(GL_BACK);
374 glDrawBuffer(GL_BACK);
375 glMatrixMode(GL_MODELVIEW);
376 glLoadIdentity();
377 glColor4f(1, 1, 1, 1);
378 glDisable(GL_DEPTH_TEST);
379 glBlendFunc(GL_ONE, GL_ZERO);
380 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
381 glEnable(GL_TEXTURE_2D);
382 glBindTexture(GL_TEXTURE_2D, offscreen->texture());
383
384 glBegin(GL_QUADS);
385 glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0);
386 glTexCoord2f(1.0, 1.0); glVertex2f(drawable.size().width(), 0.0);
387 glTexCoord2f(1.0, 0.0); glVertex2f(drawable.size().width(), drawable.size().height());
388 glTexCoord2f(0.0, 0.0); glVertex2f(0.0, drawable.size().height());
389 glEnd();
390
391 glBindTexture(GL_TEXTURE_2D, 0);
392 glDisable(GL_TEXTURE_2D);
393#endif
394}
395
396inline void QGLOffscreen::bind()
397{
398#ifndef QT_OPENGL_ES
399 Q_ASSERT(initialized);
400
401 if (!offscreen || bound)
402 return;
403
404 DEBUG_ONCE qDebug() << "QGLOffscreen: binding offscreen";
405 offscreen->bind();
406
407 bound = true;
408
409 glViewport(0, 0, offscreenSize().width(), offscreenSize().height());
410
411 glMatrixMode(GL_PROJECTION);
412 glLoadIdentity();
413 glOrtho(0, offscreenSize().width(), offscreenSize().height(), 0, -999999, 999999);
414 glMatrixMode(GL_MODELVIEW);
415#endif
416}
417
418inline void QGLOffscreen::release()
419{
420#ifndef QT_OPENGL_ES
421 if (!offscreen || !bound)
422 return;
423
424#ifdef Q_WS_X11
425 // workaround for bug in nvidia driver versions 9x.xx
426 if (QGLExtensions::nvidiaFboNeedsFinish)
427 glFinish();
428#endif
429
430 DEBUG_ONCE_STR("QGLOffscreen: releasing offscreen");
431
432 if (drawable_fbo)
433 device->ensureActiveTarget(); //###
434 else
435 offscreen->release();
436
437 QSize sz(device->size());
438 glViewport(0, 0, sz.width(), sz.height());
439
440 glMatrixMode(GL_PROJECTION);
441 glLoadIdentity();
442#ifndef QT_OPENGL_ES
443 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
444#else
445 glOrthof(0, sz.width(), sz.height(), 0, -999999, 999999);
446#endif
447 glMatrixMode(GL_MODELVIEW);
448
449 bound = false;
450#endif
451}
452
453inline bool QGLOffscreen::isBound() const
454{
455 return bound;
456}
457
458inline QSize QGLOffscreen::drawableSize() const
459{
460 return device->size();
461}
462
463inline QSize QGLOffscreen::offscreenSize() const
464{
465 return QSize(mask_dim, mask_dim);
466}
467
468inline GLuint QGLOffscreen::offscreenTexture() const
469{
470 return offscreen ? offscreen->texture() : 0;
471}
472
473inline QGLContext *QGLOffscreen::context() const
474{
475 return ctx;
476}
477
478bool QGLOffscreen::isSupported()
479{
480 return (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject); // for fbo
481}
482
483struct QDrawQueueItem
484{
485 QDrawQueueItem(qreal _opacity,
486 QBrush _brush,
487 const QPointF &_brush_origion,
488 QPainter::CompositionMode _composition_mode,
489 const QTransform &_matrix,
490 QGLMaskTextureCache::CacheLocation _location)
491 : opacity(_opacity),
492 brush(_brush),
493 brush_origin(_brush_origion),
494 composition_mode(_composition_mode),
495 matrix(_matrix),
496 location(_location) {}
497 qreal opacity;
498 QBrush brush;
499 QPointF brush_origin;
500 QPainter::CompositionMode composition_mode;
501
502 QTransform matrix;
503 QGLMaskTextureCache::CacheLocation location;
504};
505
506////////// GL program cache: start
507
508typedef struct {
509 int brush; // brush index or mask index
510 int mode; // composition mode index
511 bool mask;
512 GLuint program;
513} GLProgram;
514
515typedef QMultiHash<const QGLContext *, GLProgram> QGLProgramHash;
516
517class QGLProgramCache : public QObject
518{
519 Q_OBJECT
520public:
521 QGLProgramCache() {
522 // we have to know when a context is deleted so we can free
523 // any program handles it holds
524 connect(QGLSignalProxy::instance(), SIGNAL(aboutToDestroyContext(const QGLContext*)),
525 SLOT(cleanupPrograms(const QGLContext*)));
526
527 }
528 ~QGLProgramCache() {
529 // at this point the cache should contain 0 elements
530 // Q_ASSERT(program.size() == 0);
531 }
532
533 GLuint getProgram(const QGLContext *ctx, int brush, int mode, bool mask_mode)
534 {
535 // 1. see if we have an entry for the ctx context
536 QList<GLProgram> progs = programs.values(ctx);
537 for (int i=0; i<progs.size(); ++i) {
538 const GLProgram &prg = progs.at(i);
539 if (mask_mode) {
540 if (prg.mask && prg.brush == brush)
541 return prg.program;
542 } else {
543 if (!prg.mask && prg.brush == brush && prg.mode == mode)
544 return prg.program;
545 }
546 }
547
548 // 2. try to find a match in a shared context, and update the
549 // hash with the entry found
550 QList<const QGLContext *> contexts = programs.uniqueKeys();
551 for (int i=0; i<contexts.size(); ++i) {
552 const QGLContext *cx = contexts.at(i);
553 if (cx != ctx && QGLContext::areSharing(cx, ctx)) {
554 QList<GLProgram> progs = programs.values(cx);
555 for (int k=0; k<progs.size(); ++k) {
556 const GLProgram &prg = progs.at(k);
557 if (mask_mode) {
558 if (prg.mask && prg.brush == brush) {
559 programs.insert(ctx, prg);
560 return prg.program;
561 }
562 } else {
563 if (!prg.mask && prg.brush == brush && prg.mode == mode) {
564 programs.insert(ctx, prg);
565 return prg.program;
566 }
567 }
568 }
569 }
570 }
571
572 // 3. compile a new program and place it into the cache
573 // NB! assumes ctx is the current GL context
574 GLProgram prg;
575 prg.brush = brush;
576 prg.mode = mode;
577 prg.mask = mask_mode;
578 glGenProgramsARB(1, &prg.program);
579 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prg.program);
580 const char *src = mask_mode
581 ? mask_fragment_program_sources[brush]
582 : painter_fragment_program_sources[brush][mode];
583 // necessary for .NET 2002, apparently
584 const GLbyte *gl_src = reinterpret_cast<const GLbyte *>(src);
585
586 while (glGetError() != GL_NO_ERROR) {} // reset error state
587 glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
588 int(strlen(src)), gl_src);
589 if (glGetError() != GL_NO_ERROR) {
590// qDebug() << "QGLProgramCache: Unable to compile fragment program.";
591 glDeleteProgramsARB(1, &prg.program);
592 return 0;
593 }
594
595// qDebug() << "QGLProgramCache: Creating GL program:" << prg.program << hex << ctx;
596 programs.insert(ctx, prg);
597 return prg.program;
598 }
599
600public Q_SLOTS:
601 void cleanupPrograms(const QGLContext *context)
602 {
603 QGLProgramHash::iterator it = programs.begin();
604 while (it != programs.end()) {
605 if (it.key() == context) {
606 if (!context->isSharing()) {
607 // the ctx variable below is needed for the glDeleteProgramARB call
608 // since it is resolved from our extension system
609 // NB! assumes context is the current GL context
610 const QGLContext *ctx = context;
611 // qDebug() << "QGLProgramHash: Deleting GL program:" << it.value().program << hex << it.key();
612 glDeleteProgramsARB(1, &it.value().program);
613 }
614 it = programs.erase(it);
615 } else {
616 ++it;
617 }
618 }
619 }
620
621private:
622 QGLProgramHash programs;
623};
624
625Q_GLOBAL_STATIC(QGLProgramCache, qt_gl_program_cache)
626
627////////// GL program cache: end
628
629class QOpenGLPaintEnginePrivate;
630class QGLPrivateCleanup : public QObject
631{
632 Q_OBJECT
633public:
634 QGLPrivateCleanup(QOpenGLPaintEnginePrivate *priv)
635 : p(priv)
636 {
637 connect(QGLSignalProxy::instance(),
638 SIGNAL(aboutToDestroyContext(const QGLContext*)),
639 SLOT(cleanupGLContextRefs(const QGLContext*)));
640 }
641
642public Q_SLOTS:
643 void cleanupGLContextRefs(const QGLContext *context);
644
645private:
646 QOpenGLPaintEnginePrivate *p;
647};
648
649class QOpenGLPaintEnginePrivate : public QPaintEngineExPrivate
650{
651 Q_DECLARE_PUBLIC(QOpenGLPaintEngine)
652public:
653 QOpenGLPaintEnginePrivate()
654 : opacity(1)
655 , composition_mode(QPainter::CompositionMode_SourceOver)
656 , has_fast_pen(false)
657 , use_stencil_method(false)
658 , dirty_drawable_texture(false)
659 , has_stencil_face_ext(false)
660 , use_fragment_programs(false)
661 , high_quality_antialiasing(false)
662 , use_smooth_pixmap_transform(false)
663 , use_emulation(false)
664 , txop(QTransform::TxNone)
665 , inverseScale(1)
666 , moveToCount(0)
667 , last_created_state(0)
668 , shader_ctx(0)
669 , grad_palette(0)
670 , drawable_texture(0)
671 , ref_cleaner(this)
672 {}
673
674 inline void setGLPen(const QColor &c) {
675 uint alpha = qRound(c.alpha() * opacity);
676 pen_color[0] = qt_div_255(c.red() * alpha);
677 pen_color[1] = qt_div_255(c.green() * alpha);
678 pen_color[2] = qt_div_255(c.blue() * alpha);
679 pen_color[3] = alpha;
680 }
681
682 inline void setGLBrush(const QColor &c) {
683 uint alpha = qRound(c.alpha() * opacity);
684 brush_color[0] = qt_div_255(c.red() * alpha);
685 brush_color[1] = qt_div_255(c.green() * alpha);
686 brush_color[2] = qt_div_255(c.blue() * alpha);
687 brush_color[3] = alpha;
688 }
689
690 inline void setGradientOps(const QBrush &brush, const QRectF &bounds);
691 void createGradientPaletteTexture(const QGradient& g);
692
693 void updateGradient(const QBrush &brush, const QRectF &bounds);
694
695 inline void lineToStencil(qreal x, qreal y);
696 inline void curveToStencil(const QPointF &cp1, const QPointF &cp2, const QPointF &ep);
697 void pathToVertexArrays(const QPainterPath &path);
698 void fillVertexArray(Qt::FillRule fillRule);
699 void drawVertexArrays();
700 void fillPath(const QPainterPath &path);
701 void fillPolygon_dev(const QPointF *polygonPoints, int pointCount,
702 Qt::FillRule fill);
703
704 void drawFastRect(const QRectF &rect);
705 void strokePath(const QPainterPath &path, bool use_cache);
706 void strokePathFastPen(const QPainterPath &path, bool needsResolving);
707 void strokeLines(const QPainterPath &path);
708
709 void updateDepthClip();
710 void systemStateChanged();
711
712 void cleanupGLContextRefs(const QGLContext *context) {
713 if (context == shader_ctx)
714 shader_ctx = 0;
715 }
716
717 inline void updateFastPen() {
718 qreal pen_width = cpen.widthF();
719 has_fast_pen =
720 ((pen_width == 0 || (pen_width <= 1 && matrix.type() <= QTransform::TxTranslate))
721 || cpen.isCosmetic())
722 && cpen.style() == Qt::SolidLine
723 && cpen.isSolid();
724
725 }
726
727 void disableClipping();
728 void enableClipping();
729 void ensureDrawableTexture();
730
731 QPen cpen;
732 QBrush cbrush;
733 Qt::BrushStyle brush_style;
734 QPointF brush_origin;
735 Qt::BrushStyle pen_brush_style;
736 qreal opacity;
737 QPainter::CompositionMode composition_mode;
738
739 Qt::BrushStyle current_style;
740
741 uint has_pen : 1;
742 uint has_brush : 1;
743 uint has_fast_pen : 1;
744 uint use_stencil_method : 1;
745 uint dirty_drawable_texture : 1;
746 uint has_stencil_face_ext : 1;
747 uint use_fragment_programs : 1;
748 uint high_quality_antialiasing : 1;
749 uint has_antialiasing : 1;
750 uint has_fast_composition_mode : 1;
751 uint use_smooth_pixmap_transform : 1;
752 uint use_system_clip : 1;
753 uint use_emulation : 1;
754
755 QRegion dirty_stencil;
756
757 void updateUseEmulation();
758
759 QTransform matrix;
760 GLubyte pen_color[4];
761 GLubyte brush_color[4];
762 QTransform::TransformationType txop;
763 QGLPaintDevice* device;
764 QGLOffscreen offscreen;
765
766 qreal inverseScale;
767
768 int moveToCount;
769 QPointF path_start;
770
771 bool isFastRect(const QRectF &r);
772
773 void drawImageAsPath(const QRectF &r, const QImage &img, const QRectF &sr);
774 void drawTiledImageAsPath(const QRectF &r, const QImage &img, qreal sx, qreal sy, const QPointF &offset);
775
776 void drawOffscreenPath(const QPainterPath &path);
777
778 void composite(const QRectF &rect, const QPoint &maskOffset = QPoint());
779 void composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset = QPoint());
780
781 bool createFragmentPrograms();
782 void deleteFragmentPrograms();
783 void updateFragmentProgramData(int locations[]);
784
785 void cacheItemErased(int channel, const QRect &rect);
786
787 void addItem(const QGLMaskTextureCache::CacheLocation &location);
788 void drawItem(const QDrawQueueItem &item);
789 void flushDrawQueue();
790
791 void copyDrawable(const QRectF &rect);
792
793 void updateGLMatrix() const;
794
795 mutable QPainterState *last_created_state;
796
797 QGLContext *shader_ctx;
798 GLuint grad_palette;
799
800 GLuint painter_fragment_programs[num_fragment_brushes][num_fragment_composition_modes];
801 GLuint mask_fragment_programs[num_fragment_masks];
802
803 float inv_matrix_data[3][4];
804 float fmp_data[4];
805 float fmp2_m_radius2_data[4];
806 float angle_data[4];
807 float linear_data[4];
808
809 float porterduff_ab_data[4];
810 float porterduff_xyz_data[4];
811
812 float mask_offset_data[4];
813 float mask_channel_data[4];
814
815 FragmentBrushType fragment_brush;
816 FragmentCompositionModeType fragment_composition_mode;
817
818 void setPorterDuffData(float a, float b, float x, float y, float z);
819 void setInvMatrixData(const QTransform &inv_matrix);
820
821 qreal max_x;
822 qreal max_y;
823 qreal min_x;
824 qreal min_y;
825
826 QDataBuffer<QPointF> tess_points;
827 QVector<int> tess_points_stops;
828
829 GLdouble projection_matrix[4][4];
830
831#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2)
832 GLfloat mv_matrix[4][4];
833#else
834 GLdouble mv_matrix[4][4];
835#endif
836
837 QList<QDrawQueueItem> drawQueue;
838
839 GLuint drawable_texture;
840 QSize drawable_texture_size;
841
842 int max_texture_size;
843
844 QGLPrivateCleanup ref_cleaner;
845 friend class QGLMaskTextureCache;
846};
847
848class QOpenGLCoordinateOffset
849{
850public:
851 QOpenGLCoordinateOffset(QOpenGLPaintEnginePrivate *d);
852 ~QOpenGLCoordinateOffset();
853
854 static void enableOffset(QOpenGLPaintEnginePrivate *d);
855 static void disableOffset(QOpenGLPaintEnginePrivate *d);
856
857private:
858 QOpenGLPaintEnginePrivate *d;
859};
860
861QOpenGLCoordinateOffset::QOpenGLCoordinateOffset(QOpenGLPaintEnginePrivate *d_)
862 : d(d_)
863{
864 enableOffset(d);
865}
866
867void QOpenGLCoordinateOffset::enableOffset(QOpenGLPaintEnginePrivate *d)
868{
869 if (!d->has_antialiasing) {
870 glMatrixMode(GL_MODELVIEW);
871 glPushMatrix();
872 d->mv_matrix[3][0] += 0.5;
873 d->mv_matrix[3][1] += 0.5;
874 d->updateGLMatrix();
875 }
876}
877
878QOpenGLCoordinateOffset::~QOpenGLCoordinateOffset()
879{
880 disableOffset(d);
881}
882
883void QOpenGLCoordinateOffset::disableOffset(QOpenGLPaintEnginePrivate *d)
884{
885 if (!d->has_antialiasing) {
886 glMatrixMode(GL_MODELVIEW);
887 glPopMatrix();
888 d->mv_matrix[3][0] -= 0.5;
889 d->mv_matrix[3][1] -= 0.5;
890 }
891}
892
893void QGLPrivateCleanup::cleanupGLContextRefs(const QGLContext *context)
894{
895 p->cleanupGLContextRefs(context);
896}
897
898
899static inline void updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform)
900{
901 if (smoothPixmapTransform) {
902 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
903 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
904 } else {
905 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
906 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
907 }
908 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
909 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
910}
911
912static inline QPainterPath strokeForPath(const QPainterPath &path, const QPen &cpen) {
913 QPainterPathStroker stroker;
914 if (cpen.style() == Qt::CustomDashLine)
915 stroker.setDashPattern(cpen.dashPattern());
916 else
917 stroker.setDashPattern(cpen.style());
918
919 stroker.setCapStyle(cpen.capStyle());
920 stroker.setJoinStyle(cpen.joinStyle());
921 stroker.setMiterLimit(cpen.miterLimit());
922
923 qreal width = cpen.widthF();
924 if (width == 0)
925 stroker.setWidth(1);
926 else
927 stroker.setWidth(width);
928
929 QPainterPath stroke = stroker.createStroke(path);
930 stroke.setFillRule(Qt::WindingFill);
931 return stroke;
932}
933
934class QGLStrokeCache
935{
936 struct CacheInfo
937 {
938 inline CacheInfo(QPainterPath p, QPainterPath sp, QPen stroke_pen) :
939 path(p), stroked_path(sp), pen(stroke_pen) {}
940 QPainterPath path;
941 QPainterPath stroked_path;
942 QPen pen;
943 };
944
945 typedef QMultiHash<quint64, CacheInfo> QGLStrokeTableHash;
946
947public:
948 inline QPainterPath getStrokedPath(const QPainterPath &path, const QPen &pen) {
949 quint64 hash_val = 0;
950
951 for (int i = 0; i < path.elementCount() && i <= 2; i++) {
952 hash_val += quint64(path.elementAt(i).x);
953 hash_val += quint64(path.elementAt(i).y);
954 }
955
956 QGLStrokeTableHash::const_iterator it = cache.constFind(hash_val);
957
958 if (it == cache.constEnd())
959 return addCacheElement(hash_val, path, pen);
960 else {
961 do {
962 const CacheInfo &cache_info = it.value();
963 if (cache_info.path == path && cache_info.pen == pen)
964 return cache_info.stroked_path;
965 ++it;
966 } while (it != cache.constEnd() && it.key() == hash_val);
967 // an exact match for this path was not found, create new cache element
968 return addCacheElement(hash_val, path, pen);
969 }
970 }
971
972protected:
973 inline int maxCacheSize() const { return 500; }
974 QPainterPath addCacheElement(quint64 hash_val, QPainterPath path, const QPen &pen) {
975 if (cache.size() == maxCacheSize()) {
976 int elem_to_remove = qrand() % maxCacheSize();
977 cache.remove(cache.keys()[elem_to_remove]); // may remove more than 1, but OK
978 }
979 QPainterPath stroke = strokeForPath(path, pen);
980 CacheInfo cache_entry(path, stroke, pen);
981 return cache.insert(hash_val, cache_entry).value().stroked_path;
982 }
983
984 QGLStrokeTableHash cache;
985};
986
987Q_GLOBAL_STATIC(QGLStrokeCache, qt_opengl_stroke_cache)
988
989class QGLGradientCache : public QObject
990{
991 Q_OBJECT
992 struct CacheInfo
993 {
994 inline CacheInfo(QGradientStops s, qreal op, QGradient::InterpolationMode mode) :
995 stops(s), opacity(op), interpolationMode(mode) {}
996
997 GLuint texId;
998 QGradientStops stops;
999 qreal opacity;
1000 QGradient::InterpolationMode interpolationMode;
1001 };
1002
1003 typedef QMultiHash<quint64, CacheInfo> QGLGradientColorTableHash;
1004
1005public:
1006 QGLGradientCache() : QObject(), buffer_ctx(0)
1007 {
1008 connect(QGLSignalProxy::instance(),
1009 SIGNAL(aboutToDestroyContext(const QGLContext*)),
1010 SLOT(cleanupGLContextRefs(const QGLContext*)));
1011 }
1012
1013 inline GLuint getBuffer(const QGradient &gradient, qreal opacity, QGLContext *ctx) {
1014 if (buffer_ctx && !QGLContext::areSharing(buffer_ctx, ctx))
1015 cleanCache();
1016
1017 buffer_ctx = ctx;
1018
1019 quint64 hash_val = 0;
1020
1021 QGradientStops stops = gradient.stops();
1022 for (int i = 0; i < stops.size() && i <= 2; i++)
1023 hash_val += stops[i].second.rgba();
1024
1025 QGLGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
1026
1027 if (it == cache.constEnd())
1028 return addCacheElement(hash_val, gradient, opacity);
1029 else {
1030 do {
1031 const CacheInfo &cache_info = it.value();
1032 if (cache_info.stops == stops && cache_info.opacity == opacity && cache_info.interpolationMode == gradient.interpolationMode()) {
1033 return cache_info.texId;
1034 }
1035 ++it;
1036 } while (it != cache.constEnd() && it.key() == hash_val);
1037 // an exact match for these stops and opacity was not found, create new cache
1038 return addCacheElement(hash_val, gradient, opacity);
1039 }
1040 }
1041
1042 inline int paletteSize() const { return 1024; }
1043
1044protected:
1045 inline int maxCacheSize() const { return 60; }
1046 inline void generateGradientColorTable(const QGradient& g,
1047 uint *colorTable,
1048 int size, qreal opacity) const;
1049 GLuint addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity) {
1050 if (cache.size() == maxCacheSize()) {
1051 int elem_to_remove = qrand() % maxCacheSize();
1052 quint64 key = cache.keys()[elem_to_remove];
1053
1054 // need to call glDeleteTextures on each removed cache entry:
1055 QGLGradientColorTableHash::const_iterator it = cache.constFind(key);
1056 do {
1057 glDeleteTextures(1, &it.value().texId);
1058 } while (++it != cache.constEnd() && it.key() == key);
1059 cache.remove(key); // may remove more than 1, but OK
1060 }
1061 CacheInfo cache_entry(gradient.stops(), opacity, gradient.interpolationMode());
1062 uint buffer[1024];
1063 generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
1064 glGenTextures(1, &cache_entry.texId);
1065#ifndef QT_OPENGL_ES
1066 glBindTexture(GL_TEXTURE_1D, cache_entry.texId);
1067 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, paletteSize(),
1068 0, GL_BGRA, GL_UNSIGNED_BYTE, buffer);
1069#else
1070 // create 2D one-line texture instead. This requires an impl of manual GL_TEXGEN for all primitives
1071#endif
1072 return cache.insert(hash_val, cache_entry).value().texId;
1073 }
1074
1075 void cleanCache() {
1076 QGLShareContextScope scope(buffer_ctx);
1077 QGLGradientColorTableHash::const_iterator it = cache.constBegin();
1078 for (; it != cache.constEnd(); ++it) {
1079 const CacheInfo &cache_info = it.value();
1080 glDeleteTextures(1, &cache_info.texId);
1081 }
1082 cache.clear();
1083 }
1084
1085 QGLGradientColorTableHash cache;
1086
1087 QGLContext *buffer_ctx;
1088
1089public Q_SLOTS:
1090 void cleanupGLContextRefs(const QGLContext *context) {
1091 if (context == buffer_ctx) {
1092 cleanCache();
1093 buffer_ctx = 0;
1094 }
1095 }
1096};
1097
1098static inline uint endianColor(uint c)
1099{
1100#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
1101 return c;
1102#else
1103 return ( (c << 24) & 0xff000000)
1104 | ((c >> 24) & 0x000000ff)
1105 | ((c << 8) & 0x00ff0000)
1106 | ((c >> 8) & 0x0000ff00);
1107#endif // Q_BYTE_ORDER
1108}
1109
1110void QGLGradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
1111{
1112 int pos = 0;
1113 QGradientStops s = gradient.stops();
1114 QVector<uint> colors(s.size());
1115
1116 for (int i = 0; i < s.size(); ++i)
1117 colors[i] = s[i].second.rgba();
1118
1119 bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
1120
1121 uint alpha = qRound(opacity * 256);
1122 uint current_color = ARGB_COMBINE_ALPHA(colors[0], alpha);
1123 qreal incr = 1.0 / qreal(size);
1124 qreal fpos = 1.5 * incr;
1125 colorTable[pos++] = endianColor(PREMUL(current_color));
1126
1127 while (fpos <= s.first().first) {
1128 colorTable[pos] = colorTable[pos - 1];
1129 pos++;
1130 fpos += incr;
1131 }
1132
1133 if (colorInterpolation)
1134 current_color = PREMUL(current_color);
1135
1136 for (int i = 0; i < s.size() - 1; ++i) {
1137 qreal delta = 1/(s[i+1].first - s[i].first);
1138 uint next_color = ARGB_COMBINE_ALPHA(colors[i+1], alpha);
1139 if (colorInterpolation)
1140 next_color = PREMUL(next_color);
1141
1142 while (fpos < s[i+1].first && pos < size) {
1143 int dist = int(256 * ((fpos - s[i].first) * delta));
1144 int idist = 256 - dist;
1145 if (colorInterpolation)
1146 colorTable[pos] = endianColor(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
1147 else
1148 colorTable[pos] = endianColor(PREMUL(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist)));
1149 ++pos;
1150 fpos += incr;
1151 }
1152 current_color = next_color;
1153 }
1154
1155 Q_ASSERT(s.size() > 0);
1156
1157 uint last_color = endianColor(PREMUL(ARGB_COMBINE_ALPHA(colors[s.size() - 1], alpha)));
1158 for (;pos < size; ++pos)
1159 colorTable[pos] = last_color;
1160
1161 // Make sure the last color stop is represented at the end of the table
1162 colorTable[size-1] = last_color;
1163}
1164
1165#ifndef Q_WS_QWS
1166Q_GLOBAL_STATIC(QGLGradientCache, qt_opengl_gradient_cache)
1167#endif
1168
1169void QOpenGLPaintEnginePrivate::createGradientPaletteTexture(const QGradient& g)
1170{
1171#ifdef QT_OPENGL_ES //###
1172 Q_UNUSED(g);
1173#else
1174 GLuint texId = qt_opengl_gradient_cache()->getBuffer(g, opacity, device->context());
1175 glBindTexture(GL_TEXTURE_1D, texId);
1176 grad_palette = texId;
1177 if (g.spread() == QGradient::RepeatSpread || g.type() == QGradient::ConicalGradient)
1178 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1179 else if (g.spread() == QGradient::ReflectSpread)
1180 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT_IBM);
1181 else
1182 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1183
1184 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1185 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1186
1187#endif
1188}
1189
1190
1191inline void QOpenGLPaintEnginePrivate::setGradientOps(const QBrush &brush, const QRectF &bounds)
1192{
1193 current_style = brush.style();
1194
1195 if (current_style < Qt::LinearGradientPattern || current_style > Qt::ConicalGradientPattern) {
1196 setGLBrush(brush.color());
1197 qt_glColor4ubv(brush_color);
1198 }
1199
1200 updateGradient(brush, bounds);
1201
1202#ifndef QT_OPENGL_ES //### GLES does not have GL_TEXTURE_GEN_ so we are falling back for gradients
1203 glDisable(GL_TEXTURE_GEN_S);
1204 glDisable(GL_TEXTURE_1D);
1205
1206 if (current_style == Qt::LinearGradientPattern) {
1207 if (high_quality_antialiasing || !has_fast_composition_mode) {
1208 fragment_brush = FRAGMENT_PROGRAM_BRUSH_LINEAR;
1209 } else {
1210 glEnable(GL_TEXTURE_GEN_S);
1211 glEnable(GL_TEXTURE_1D);
1212 }
1213 } else {
1214 if (use_fragment_programs) {
1215 if (current_style == Qt::RadialGradientPattern)
1216 fragment_brush = FRAGMENT_PROGRAM_BRUSH_RADIAL;
1217 else if (current_style == Qt::ConicalGradientPattern)
1218 fragment_brush = FRAGMENT_PROGRAM_BRUSH_CONICAL;
1219 else if (current_style == Qt::SolidPattern)
1220 fragment_brush = FRAGMENT_PROGRAM_BRUSH_SOLID;
1221 else if (current_style == Qt::TexturePattern && !brush.texture().isQBitmap())
1222 fragment_brush = FRAGMENT_PROGRAM_BRUSH_TEXTURE;
1223 else
1224 fragment_brush = FRAGMENT_PROGRAM_BRUSH_PATTERN;
1225 }
1226 }
1227#endif
1228}
1229
1230QOpenGLPaintEngine::QOpenGLPaintEngine()
1231 : QPaintEngineEx(*(new QOpenGLPaintEnginePrivate))
1232{
1233}
1234
1235QOpenGLPaintEngine::~QOpenGLPaintEngine()
1236{
1237}
1238
1239bool QOpenGLPaintEngine::begin(QPaintDevice *pdev)
1240{
1241 Q_D(QOpenGLPaintEngine);
1242
1243 if (pdev->devType() == QInternal::OpenGL)
1244 d->device = static_cast<QGLPaintDevice*>(pdev);
1245 else
1246 d->device = QGLPaintDevice::getDevice(pdev);
1247
1248 if (!d->device)
1249 return false;
1250
1251 d->offscreen.setDevice(pdev);
1252 d->has_fast_pen = false;
1253 d->inverseScale = 1;
1254 d->opacity = 1;
1255 d->device->beginPaint();
1256 d->matrix = QTransform();
1257 d->has_antialiasing = false;
1258 d->high_quality_antialiasing = false;
1259
1260 QSize sz(d->device->size());
1261 d->dirty_stencil = QRect(0, 0, sz.width(), sz.height());
1262
1263 d->use_emulation = false;
1264
1265 for (int i = 0; i < 4; ++i)
1266 for (int j = 0; j < 4; ++j)
1267 d->mv_matrix[i][j] = (i == j ? qreal(1) : qreal(0));
1268
1269 bool has_frag_program = (QGLExtensions::glExtensions & QGLExtensions::FragmentProgram)
1270 && (pdev->devType() != QInternal::Pixmap);
1271
1272 QGLContext *ctx = const_cast<QGLContext *>(d->device->context());
1273 if (!ctx) {
1274 qWarning() << "QOpenGLPaintEngine: paint device doesn't have a valid GL context.";
1275 return false;
1276 }
1277
1278 if (has_frag_program)
1279 has_frag_program = qt_resolve_frag_program_extensions(ctx) && qt_resolve_version_1_3_functions(ctx);
1280
1281 d->use_stencil_method = d->device->format().stencil()
1282 && (QGLExtensions::glExtensions & QGLExtensions::StencilWrap);
1283 if (d->device->format().directRendering()
1284 && (d->use_stencil_method && QGLExtensions::glExtensions & QGLExtensions::StencilTwoSide))
1285 d->has_stencil_face_ext = qt_resolve_stencil_face_extension(ctx);
1286
1287#ifndef QT_OPENGL_ES
1288 if (!ctx->d_ptr->internal_context) {
1289 glGetDoublev(GL_PROJECTION_MATRIX, &d->projection_matrix[0][0]);
1290 glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
1291 glPushAttrib(GL_ALL_ATTRIB_BITS);
1292
1293 glDisableClientState(GL_EDGE_FLAG_ARRAY);
1294 glDisableClientState(GL_INDEX_ARRAY);
1295 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1296 glDisable(GL_TEXTURE_1D);
1297 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1298 glPixelTransferi(GL_MAP_COLOR, false);
1299 glPixelTransferi(GL_MAP_STENCIL, false);
1300 glDisable(GL_TEXTURE_GEN_S);
1301
1302 glPixelStorei(GL_PACK_SWAP_BYTES, false);
1303 glPixelStorei(GL_PACK_LSB_FIRST, false);
1304 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
1305 glPixelStorei(GL_PACK_SKIP_ROWS, 0);
1306 glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
1307 glPixelStorei(GL_PACK_ALIGNMENT, 4);
1308
1309 glPixelStorei(GL_UNPACK_SWAP_BYTES, false);
1310 glPixelStorei(GL_UNPACK_LSB_FIRST, false);
1311 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1312 glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
1313 glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
1314 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1315
1316 if (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2) {
1317 glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
1318 glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
1319 glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
1320 glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
1321 }
1322 }
1323#endif
1324
1325 if (!ctx->d_ptr->internal_context) {
1326 glMatrixMode(GL_MODELVIEW);
1327 glPushMatrix();
1328 glMatrixMode(GL_TEXTURE);
1329 glPushMatrix();
1330 glLoadIdentity();
1331 glDisableClientState(GL_COLOR_ARRAY);
1332 glDisableClientState(GL_NORMAL_ARRAY);
1333 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1334 glDisableClientState(GL_VERTEX_ARRAY);
1335
1336 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
1337 glDisable(GL_MULTISAMPLE);
1338 glDisable(GL_TEXTURE_2D);
1339 if (QGLExtensions::glExtensions & QGLExtensions::TextureRectangle)
1340 glDisable(GL_TEXTURE_RECTANGLE_NV);
1341 glDisable(GL_STENCIL_TEST);
1342 glDisable(GL_CULL_FACE);
1343 glDisable(GL_LIGHTING);
1344 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1345 }
1346
1347 d->offscreen.begin();
1348
1349 glViewport(0, 0, sz.width(), sz.height()); // XXX (Embedded): We need a solution for GLWidgets that draw in a part or a bigger surface...
1350 glMatrixMode(GL_PROJECTION);
1351 glLoadIdentity();
1352#ifdef QT_OPENGL_ES
1353 glOrthof(0, sz.width(), sz.height(), 0, -999999, 999999);
1354#else
1355 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
1356#endif
1357 glMatrixMode(GL_MODELVIEW);
1358 glLoadIdentity();
1359 glEnable(GL_BLEND);
1360 d->composition_mode = QPainter::CompositionMode_SourceOver;
1361
1362#ifdef QT_OPENGL_ES
1363 d->max_texture_size = ctx->d_func()->maxTextureSize();
1364#else
1365 bool shared_ctx = QGLContext::areSharing(d->device->context(), d->shader_ctx);
1366
1367 if (shared_ctx) {
1368 d->max_texture_size = d->shader_ctx->d_func()->maxTextureSize();
1369 } else {
1370 d->max_texture_size = ctx->d_func()->maxTextureSize();
1371
1372 if (d->shader_ctx) {
1373 d->shader_ctx->makeCurrent();
1374 glBindTexture(GL_TEXTURE_1D, 0);
1375 glDeleteTextures(1, &d->grad_palette);
1376
1377 if (has_frag_program && d->use_fragment_programs)
1378 glDeleteTextures(1, &d->drawable_texture);
1379 ctx->makeCurrent();
1380 }
1381 d->shader_ctx = d->device->context();
1382 glGenTextures(1, &d->grad_palette);
1383
1384 qt_mask_texture_cache()->clearCache();
1385 d->use_fragment_programs = has_frag_program;
1386 }
1387
1388 if (d->use_fragment_programs && (!shared_ctx || sz.width() > d->drawable_texture_size.width()
1389 || sz.height() > d->drawable_texture_size.height()))
1390 {
1391 // delete old texture if size has increased, otherwise it was deleted earlier
1392 if (shared_ctx)
1393 glDeleteTextures(1, &d->drawable_texture);
1394
1395 d->dirty_drawable_texture = true;
1396 d->drawable_texture_size = QSize(qt_next_power_of_two(sz.width()),
1397 qt_next_power_of_two(sz.height()));
1398 }
1399#endif
1400
1401 updateClipRegion(QRegion(), Qt::NoClip);
1402 penChanged();
1403 brushChanged();
1404 opacityChanged();
1405 compositionModeChanged();
1406 renderHintsChanged();
1407 transformChanged();
1408 return true;
1409}
1410
1411bool QOpenGLPaintEngine::end()
1412{
1413 Q_D(QOpenGLPaintEngine);
1414 d->flushDrawQueue();
1415 d->offscreen.end();
1416 QGLContext *ctx = const_cast<QGLContext *>(d->device->context());
1417 if (!ctx->d_ptr->internal_context) {
1418 glMatrixMode(GL_TEXTURE);
1419 glPopMatrix();
1420 glMatrixMode(GL_MODELVIEW);
1421 glPopMatrix();
1422 }
1423#ifndef QT_OPENGL_ES
1424 if (ctx->d_ptr->internal_context) {
1425 glDisable(GL_SCISSOR_TEST);
1426 } else {
1427 glMatrixMode(GL_PROJECTION);
1428 glLoadMatrixd(&d->projection_matrix[0][0]);
1429 glPopAttrib();
1430 glPopClientAttrib();
1431 }
1432#endif
1433 d->device->endPaint();
1434 qt_mask_texture_cache()->maintainCache();
1435
1436 return true;
1437}
1438
1439void QOpenGLPaintEngine::updateState(const QPaintEngineState &state)
1440{
1441 Q_D(QOpenGLPaintEngine);
1442 QPaintEngine::DirtyFlags flags = state.state();
1443
1444 bool update_fast_pen = false;
1445
1446 if (flags & DirtyOpacity) {
1447 update_fast_pen = true;
1448 d->opacity = state.opacity();
1449 if (d->opacity > 1.0f)
1450 d->opacity = 1.0f;
1451 if (d->opacity < 0.f)
1452 d->opacity = 0.f;
1453 // force update
1454 flags |= DirtyPen;
1455 flags |= DirtyBrush;
1456 }
1457
1458 if (flags & DirtyTransform) {
1459 update_fast_pen = true;
1460 updateMatrix(state.transform());
1461 // brush setup depends on transform state
1462 if (state.brush().style() != Qt::NoBrush)
1463 flags |= DirtyBrush;
1464 }
1465
1466 if (flags & DirtyPen) {
1467 update_fast_pen = true;
1468 updatePen(state.pen());
1469 }
1470
1471 if (flags & (DirtyBrush | DirtyBrushOrigin)) {
1472 updateBrush(state.brush(), state.brushOrigin());
1473 }
1474
1475 if (flags & DirtyFont) {
1476 updateFont(state.font());
1477 }
1478
1479 if (state.state() & DirtyClipEnabled) {
1480 if (state.isClipEnabled())
1481 updateClipRegion(painter()->clipRegion(), Qt::ReplaceClip);
1482 else
1483 updateClipRegion(QRegion(), Qt::NoClip);
1484 }
1485
1486 if (flags & DirtyClipPath) {
1487 updateClipRegion(QRegion(state.clipPath().toFillPolygon().toPolygon(),
1488 state.clipPath().fillRule()),
1489 state.clipOperation());
1490 }
1491
1492 if (flags & DirtyClipRegion) {
1493 updateClipRegion(state.clipRegion(), state.clipOperation());
1494 }
1495
1496 if (flags & DirtyHints) {
1497 updateRenderHints(state.renderHints());
1498 }
1499
1500 if (flags & DirtyCompositionMode) {
1501 updateCompositionMode(state.compositionMode());
1502 }
1503
1504 if (update_fast_pen) {
1505 Q_D(QOpenGLPaintEngine);
1506 qreal pen_width = d->cpen.widthF();
1507 d->has_fast_pen =
1508 ((pen_width == 0 || (pen_width <= 1 && d->txop <= QTransform::TxTranslate))
1509 || d->cpen.isCosmetic())
1510 && d->cpen.style() == Qt::SolidLine
1511 && d->cpen.isSolid();
1512 }
1513}
1514
1515
1516void QOpenGLPaintEnginePrivate::setInvMatrixData(const QTransform &inv_matrix)
1517{
1518 inv_matrix_data[0][0] = inv_matrix.m11();
1519 inv_matrix_data[1][0] = inv_matrix.m21();
1520 inv_matrix_data[2][0] = inv_matrix.m31();
1521
1522 inv_matrix_data[0][1] = inv_matrix.m12();
1523 inv_matrix_data[1][1] = inv_matrix.m22();
1524 inv_matrix_data[2][1] = inv_matrix.m32();
1525
1526 inv_matrix_data[0][2] = inv_matrix.m13();
1527 inv_matrix_data[1][2] = inv_matrix.m23();
1528 inv_matrix_data[2][2] = inv_matrix.m33();
1529}
1530
1531
1532void QOpenGLPaintEnginePrivate::updateGradient(const QBrush &brush, const QRectF &)
1533{
1534#ifdef QT_OPENGL_ES
1535 Q_UNUSED(brush);
1536#else
1537 bool has_mirrored_repeat = QGLExtensions::glExtensions & QGLExtensions::MirroredRepeat;
1538 Qt::BrushStyle style = brush.style();
1539
1540 QTransform m = brush.transform();
1541
1542 if (has_mirrored_repeat && style == Qt::LinearGradientPattern) {
1543 const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
1544 QTransform m = brush.transform();
1545 QPointF realStart = g->start();
1546 QPointF realFinal = g->finalStop();
1547 QPointF start = m.map(realStart);
1548 QPointF stop;
1549
1550 if (qFuzzyCompare(m.m11(), m.m22()) && m.m12() == 0.0 && m.m21() == 0.0) {
1551 // It is a simple uniform scale and/or translation
1552 stop = m.map(realFinal);
1553 } else {
1554 // It is not enough to just transform the endpoints.
1555 // We have to make sure the _pattern_ is transformed correctly.
1556
1557 qreal odx = realFinal.x() - realStart.x();
1558 qreal ody = realFinal.y() - realStart.y();
1559
1560 // nx, ny and dx, dy are normal and gradient direction after transform:
1561 qreal nx = m.m11()*ody - m.m21()*odx;
1562 qreal ny = m.m12()*ody - m.m22()*odx;
1563
1564 qreal dx = m.m11()*odx + m.m21()*ody;
1565 qreal dy = m.m12()*odx + m.m22()*ody;
1566
1567 qreal lx = 1 / (dx - dy*nx/ny);
1568 qreal ly = 1 / (dy - dx*ny/nx);
1569 qreal l = 1 / qSqrt(lx*lx+ly*ly);
1570
1571 stop = start + QPointF(-ny, nx) * l/qSqrt(nx*nx+ny*ny);
1572 }
1573
1574 float tr[4], f;
1575 tr[0] = stop.x() - start.x();
1576 tr[1] = stop.y() - start.y();
1577 f = 1.0 / (tr[0]*tr[0] + tr[1]*tr[1]);
1578 tr[0] *= f;
1579 tr[1] *= f;
1580 tr[2] = 0;
1581 tr[3] = -(start.x()*tr[0] + start.y()*tr[1]);
1582 brush_color[0] = brush_color[1] = brush_color[2] = brush_color[3] = 255;
1583 qt_glColor4ubv(brush_color);
1584 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
1585 glTexGenfv(GL_S, GL_OBJECT_PLANE, tr);
1586 }
1587
1588 if (use_fragment_programs) {
1589 if (style == Qt::RadialGradientPattern) {
1590 const QRadialGradient *g = static_cast<const QRadialGradient *>(brush.gradient());
1591 QPointF realCenter = g->center();
1592 QPointF realFocal = g->focalPoint();
1593 qreal realRadius = g->radius();
1594 QTransform translate(1, 0, 0, 1, -realFocal.x(), -realFocal.y());
1595 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1596 QTransform m = QTransform(matrix).translate(brush_origin.x(), brush_origin.y());
1597 QTransform inv_matrix = gl_to_qt * (brush.transform() * m).inverted() * translate;
1598
1599 setInvMatrixData(inv_matrix);
1600
1601 fmp_data[0] = realCenter.x() - realFocal.x();
1602 fmp_data[1] = realCenter.y() - realFocal.y();
1603
1604 fmp2_m_radius2_data[0] = -fmp_data[0] * fmp_data[0] - fmp_data[1] * fmp_data[1] + realRadius * realRadius;
1605 } else if (style == Qt::ConicalGradientPattern) {
1606 const QConicalGradient *g = static_cast<const QConicalGradient *>(brush.gradient());
1607 QPointF realCenter = g->center();
1608 QTransform translate(1, 0, 0, 1, -realCenter.x(), -realCenter.y());
1609 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1610 QTransform m = QTransform(matrix).translate(brush_origin.x(), brush_origin.y());
1611 QTransform inv_matrix = gl_to_qt * (brush.transform() * m).inverted() * translate;
1612
1613 setInvMatrixData(inv_matrix);
1614
1615 angle_data[0] = -(g->angle() * 2 * Q_PI) / 360.0;
1616 } else if (style == Qt::LinearGradientPattern) {
1617 const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
1618
1619 QPointF realStart = g->start();
1620 QPointF realFinal = g->finalStop();
1621 QTransform translate(1, 0, 0, 1, -realStart.x(), -realStart.y());
1622 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1623 QTransform m = QTransform(matrix).translate(brush_origin.x(), brush_origin.y());
1624 QTransform inv_matrix = gl_to_qt * (brush.transform() * m).inverted() * translate;
1625
1626 setInvMatrixData(inv_matrix);
1627
1628 QPointF l = realFinal - realStart;
1629
1630 linear_data[0] = l.x();
1631 linear_data[1] = l.y();
1632
1633 linear_data[2] = 1.0f / (l.x() * l.x() + l.y() * l.y());
1634 } else if (style != Qt::SolidPattern) {
1635 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1636 QTransform m = QTransform(matrix).translate(brush_origin.x(), brush_origin.y());
1637 QTransform inv_matrix = gl_to_qt * (brush.transform() * m).inverted();
1638
1639 setInvMatrixData(inv_matrix);
1640 }
1641 }
1642
1643 if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
1644 createGradientPaletteTexture(*brush.gradient());
1645 }
1646#endif
1647}
1648
1649
1650class QOpenGLTessellator : public QTessellator
1651{
1652public:
1653 QOpenGLTessellator() {}
1654 ~QOpenGLTessellator() { }
1655 QGLTrapezoid toGLTrapezoid(const Trapezoid &trap);
1656};
1657
1658QGLTrapezoid QOpenGLTessellator::toGLTrapezoid(const Trapezoid &trap)
1659{
1660 QGLTrapezoid t;
1661
1662 t.top = Q27Dot5ToDouble(trap.top);
1663 t.bottom = Q27Dot5ToDouble(trap.bottom);
1664
1665 Q27Dot5 y = trap.topLeft->y - trap.bottomLeft->y;
1666
1667 qreal topLeftY = Q27Dot5ToDouble(trap.topLeft->y);
1668
1669 qreal tx = Q27Dot5ToDouble(trap.topLeft->x);
1670 qreal m = (-tx + Q27Dot5ToDouble(trap.bottomLeft->x)) / Q27Dot5ToDouble(y);
1671 t.topLeftX = tx + m * (topLeftY - t.top);
1672 t.bottomLeftX = tx + m * (topLeftY - t.bottom);
1673
1674 y = trap.topRight->y - trap.bottomRight->y;
1675
1676 qreal topRightY = Q27Dot5ToDouble(trap.topRight->y);
1677
1678 tx = Q27Dot5ToDouble(trap.topRight->x);
1679 m = (-tx + Q27Dot5ToDouble(trap.bottomRight->x)) / Q27Dot5ToDouble(y);
1680
1681 t.topRightX = tx + m * (topRightY - Q27Dot5ToDouble(trap.top));
1682 t.bottomRightX = tx + m * (topRightY - Q27Dot5ToDouble(trap.bottom));
1683
1684 return t;
1685}
1686
1687class QOpenGLImmediateModeTessellator : public QOpenGLTessellator
1688{
1689public:
1690 void addTrap(const Trapezoid &trap);
1691 void tessellate(const QPointF *points, int nPoints, bool winding) {
1692 trapezoids.reserve(trapezoids.size() + nPoints);
1693 setWinding(winding);
1694 QTessellator::tessellate(points, nPoints);
1695 }
1696
1697 QVector<QGLTrapezoid> trapezoids;
1698};
1699
1700void QOpenGLImmediateModeTessellator::addTrap(const Trapezoid &trap)
1701{
1702 trapezoids.append(toGLTrapezoid(trap));
1703}
1704
1705#ifndef QT_OPENGL_ES
1706static void drawTrapezoid(const QGLTrapezoid &trap, const qreal offscreenHeight, QGLContext *ctx)
1707{
1708 qreal minX = qMin(trap.topLeftX, trap.bottomLeftX);
1709 qreal maxX = qMax(trap.topRightX, trap.bottomRightX);
1710
1711 if (qFuzzyCompare(trap.top, trap.bottom) || qFuzzyCompare(minX, maxX) ||
1712 (qFuzzyCompare(trap.topLeftX, trap.topRightX) && qFuzzyCompare(trap.bottomLeftX, trap.bottomRightX)))
1713 return;
1714
1715 const qreal xpadding = 1.0;
1716 const qreal ypadding = 1.0;
1717
1718 qreal topDist = offscreenHeight - trap.top;
1719 qreal bottomDist = offscreenHeight - trap.bottom;
1720
1721 qreal reciprocal = bottomDist / (bottomDist - topDist);
1722
1723 qreal leftB = trap.bottomLeftX + (trap.topLeftX - trap.bottomLeftX) * reciprocal;
1724 qreal rightB = trap.bottomRightX + (trap.topRightX - trap.bottomRightX) * reciprocal;
1725
1726 const bool topZero = qFuzzyIsNull(topDist);
1727
1728 reciprocal = topZero ? 1.0 / bottomDist : 1.0 / topDist;
1729
1730 qreal leftA = topZero ? (trap.bottomLeftX - leftB) * reciprocal : (trap.topLeftX - leftB) * reciprocal;
1731 qreal rightA = topZero ? (trap.bottomRightX - rightB) * reciprocal : (trap.topRightX - rightB) * reciprocal;
1732
1733 qreal invLeftA = qFuzzyIsNull(leftA) ? 0.0 : 1.0 / leftA;
1734 qreal invRightA = qFuzzyIsNull(rightA) ? 0.0 : 1.0 / rightA;
1735
1736 // fragment program needs the negative of invRightA as it mirrors the line
1737 glTexCoord4f(topDist, bottomDist, invLeftA, -invRightA);
1738 glMultiTexCoord4f(GL_TEXTURE1, leftA, leftB, rightA, rightB);
1739
1740 qreal topY = trap.top - ypadding;
1741 qreal bottomY = trap.bottom + ypadding;
1742
1743 qreal bounds_bottomLeftX = leftA * (offscreenHeight - bottomY) + leftB;
1744 qreal bounds_bottomRightX = rightA * (offscreenHeight - bottomY) + rightB;
1745 qreal bounds_topLeftX = leftA * (offscreenHeight - topY) + leftB;
1746 qreal bounds_topRightX = rightA * (offscreenHeight - topY) + rightB;
1747
1748 QPointF leftNormal(1, -leftA);
1749 leftNormal /= qSqrt(leftNormal.x() * leftNormal.x() + leftNormal.y() * leftNormal.y());
1750 QPointF rightNormal(1, -rightA);
1751 rightNormal /= qSqrt(rightNormal.x() * rightNormal.x() + rightNormal.y() * rightNormal.y());
1752
1753 qreal left_padding = xpadding / qAbs(leftNormal.x());
1754 qreal right_padding = xpadding / qAbs(rightNormal.x());
1755
1756 glVertex2d(bounds_topLeftX - left_padding, topY);
1757 glVertex2d(bounds_topRightX + right_padding, topY);
1758 glVertex2d(bounds_bottomRightX + right_padding, bottomY);
1759 glVertex2d(bounds_bottomLeftX - left_padding, bottomY);
1760
1761 glTexCoord4f(0.0f, 0.0f, 0.0f, 1.0f);
1762}
1763#endif // !Q_WS_QWS
1764
1765class QOpenGLTrapezoidToArrayTessellator : public QOpenGLTessellator
1766{
1767public:
1768 QOpenGLTrapezoidToArrayTessellator() : vertices(0), allocated(0), size(0) {}
1769 ~QOpenGLTrapezoidToArrayTessellator() { free(vertices); }
1770 q_vertexType *vertices;
1771 int allocated;
1772 int size;
1773 QRectF bounds;
1774 void addTrap(const Trapezoid &trap);
1775 void tessellate(const QPointF *points, int nPoints, bool winding) {
1776 size = 0;
1777 setWinding(winding);
1778 bounds = QTessellator::tessellate(points, nPoints);
1779 }
1780};
1781
1782void QOpenGLTrapezoidToArrayTessellator::addTrap(const Trapezoid &trap)
1783{
1784 // On OpenGL ES we convert the trap to 2 triangles
1785#ifndef QT_OPENGL_ES
1786 if (size > allocated - 8) {
1787#else
1788 if (size > allocated - 12) {
1789#endif
1790 allocated = qMax(2*allocated, 512);
1791 vertices = (q_vertexType *)realloc(vertices, allocated * sizeof(q_vertexType));
1792 }
1793
1794 QGLTrapezoid t = toGLTrapezoid(trap);
1795
1796#ifndef QT_OPENGL_ES
1797 vertices[size++] = f2vt(t.topLeftX);
1798 vertices[size++] = f2vt(t.top);
1799 vertices[size++] = f2vt(t.topRightX);
1800 vertices[size++] = f2vt(t.top);
1801 vertices[size++] = f2vt(t.bottomRightX);
1802 vertices[size++] = f2vt(t.bottom);
1803 vertices[size++] = f2vt(t.bottomLeftX);
1804 vertices[size++] = f2vt(t.bottom);
1805#else
1806 // First triangle
1807 vertices[size++] = f2vt(t.topLeftX);
1808 vertices[size++] = f2vt(t.top);
1809 vertices[size++] = f2vt(t.topRightX);
1810 vertices[size++] = f2vt(t.top);
1811 vertices[size++] = f2vt(t.bottomRightX);
1812 vertices[size++] = f2vt(t.bottom);
1813
1814 // Second triangle
1815 vertices[size++] = f2vt(t.bottomLeftX);
1816 vertices[size++] = f2vt(t.bottom);
1817 vertices[size++] = f2vt(t.topLeftX);
1818 vertices[size++] = f2vt(t.top);
1819 vertices[size++] = f2vt(t.bottomRightX);
1820 vertices[size++] = f2vt(t.bottom);
1821#endif
1822}
1823
1824
1825void QOpenGLPaintEnginePrivate::fillPolygon_dev(const QPointF *polygonPoints, int pointCount,
1826 Qt::FillRule fill)
1827{
1828 QOpenGLTrapezoidToArrayTessellator tessellator;
1829 tessellator.tessellate(polygonPoints, pointCount, fill == Qt::WindingFill);
1830
1831 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon with" << pointCount << "points using fillPolygon_dev";
1832
1833 setGradientOps(cbrush, tessellator.bounds);
1834
1835 bool fast_style = current_style == Qt::LinearGradientPattern
1836 || current_style == Qt::SolidPattern;
1837
1838#ifndef QT_OPENGL_ES
1839 GLenum geometry_mode = GL_QUADS;
1840#else
1841 GLenum geometry_mode = GL_TRIANGLES;
1842#endif
1843
1844 if (use_fragment_programs && !(fast_style && has_fast_composition_mode)) {
1845 composite(geometry_mode, tessellator.vertices, tessellator.size / 2);
1846 } else {
1847 glVertexPointer(2, q_vertexTypeEnum, 0, tessellator.vertices);
1848 glEnableClientState(GL_VERTEX_ARRAY);
1849 glDrawArrays(geometry_mode, 0, tessellator.size/2);
1850 glDisableClientState(GL_VERTEX_ARRAY);
1851 }
1852}
1853
1854
1855inline void QOpenGLPaintEnginePrivate::lineToStencil(qreal x, qreal y)
1856{
1857 tess_points.add(QPointF(x, y));
1858
1859 if (x > max_x)
1860 max_x = x;
1861 else if (x < min_x)
1862 min_x = x;
1863 if (y > max_y)
1864 max_y = y;
1865 else if (y < min_y)
1866 min_y = y;
1867}
1868
1869inline void QOpenGLPaintEnginePrivate::curveToStencil(const QPointF &cp1, const QPointF &cp2, const QPointF &ep)
1870{
1871 qreal inverseScaleHalf = inverseScale / 2;
1872
1873 QBezier beziers[32];
1874 beziers[0] = QBezier::fromPoints(tess_points.last(), cp1, cp2, ep);
1875 QBezier *b = beziers;
1876 while (b >= beziers) {
1877 // check if we can pop the top bezier curve from the stack
1878 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
1879 qreal d;
1880 if (l > inverseScale) {
1881 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2) - (b->y4 - b->y1)*(b->x1 - b->x2) )
1882 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3) - (b->y4 - b->y1)*(b->x1 - b->x3) );
1883 d /= l;
1884 } else {
1885 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
1886 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
1887 }
1888 if (d < inverseScaleHalf || b == beziers + 31) {
1889 // good enough, we pop it off and add the endpoint
1890 lineToStencil(b->x4, b->y4);
1891 --b;
1892 } else {
1893 // split, second half of the polygon goes lower into the stack
1894 b->split(b+1, b);
1895 ++b;
1896 }
1897 }
1898}
1899
1900
1901void QOpenGLPaintEnginePrivate::pathToVertexArrays(const QPainterPath &path)
1902{
1903 const QPainterPath::Element &first = path.elementAt(0);
1904 min_x = max_x = first.x;
1905 min_y = max_y = first.y;
1906
1907 tess_points.reset();
1908 tess_points_stops.clear();
1909 lineToStencil(first.x, first.y);
1910
1911 for (int i=1; i<path.elementCount(); ++i) {
1912 const QPainterPath::Element &e = path.elementAt(i);
1913 switch (e.type) {
1914 case QPainterPath::MoveToElement:
1915 tess_points_stops.append(tess_points.size());
1916 lineToStencil(e.x, e.y);
1917 break;
1918 case QPainterPath::LineToElement:
1919 lineToStencil(e.x, e.y);
1920 break;
1921 case QPainterPath::CurveToElement:
1922 curveToStencil(e, path.elementAt(i+1), path.elementAt(i+2));
1923 i+=2;
1924 break;
1925 default:
1926 break;
1927 }
1928 }
1929 lineToStencil(first.x, first.y);
1930 tess_points_stops.append(tess_points.size());
1931}
1932
1933
1934void QOpenGLPaintEnginePrivate::drawVertexArrays()
1935{
1936 glEnableClientState(GL_VERTEX_ARRAY);
1937 glVertexPointer(2, GL_DOUBLE, 0, tess_points.data());
1938 int previous_stop = 0;
1939 foreach(int stop, tess_points_stops) {
1940 glDrawArrays(GL_TRIANGLE_FAN, previous_stop, stop-previous_stop);
1941 previous_stop = stop;
1942 }
1943 glDisableClientState(GL_VERTEX_ARRAY);
1944}
1945
1946void QOpenGLPaintEnginePrivate::fillVertexArray(Qt::FillRule fillRule)
1947{
1948 Q_Q(QOpenGLPaintEngine);
1949
1950 QRect rect = dirty_stencil.boundingRect();
1951
1952 if (use_system_clip)
1953 rect = q->systemClip().intersected(dirty_stencil).boundingRect();
1954
1955 glStencilMask(~0);
1956
1957 if (!rect.isEmpty()) {
1958 disableClipping();
1959
1960 glEnable(GL_SCISSOR_TEST);
1961
1962 const int left = rect.left();
1963 const int width = rect.width();
1964 const int bottom = device->size().height() - (rect.bottom() + 1);
1965 const int height = rect.height();
1966
1967 glScissor(left, bottom, width, height);
1968
1969 glClearStencil(0);
1970 glClear(GL_STENCIL_BUFFER_BIT);
1971 dirty_stencil -= rect;
1972
1973 glDisable(GL_SCISSOR_TEST);
1974
1975 enableClipping();
1976 }
1977
1978 // Enable stencil.
1979 glEnable(GL_STENCIL_TEST);
1980
1981 // Disable color writes.
1982 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1983
1984 GLuint stencilMask = 0;
1985
1986 if (fillRule == Qt::OddEvenFill) {
1987 stencilMask = 1;
1988
1989 // Enable stencil writes.
1990 glStencilMask(stencilMask);
1991
1992 // Set stencil xor mode.
1993 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
1994
1995 // Disable stencil func.
1996 glStencilFunc(GL_ALWAYS, 0, ~0);
1997
1998 drawVertexArrays();
1999 } else if (fillRule == Qt::WindingFill) {
2000 stencilMask = ~0;
2001
2002 if (has_stencil_face_ext) {
2003 QGL_FUNC_CONTEXT;
2004 glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
2005
2006 glActiveStencilFaceEXT(GL_BACK);
2007 glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP_EXT);
2008 glStencilFunc(GL_ALWAYS, 0, ~0);
2009
2010 glActiveStencilFaceEXT(GL_FRONT);
2011 glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP_EXT);
2012 glStencilFunc(GL_ALWAYS, 0, ~0);
2013
2014 drawVertexArrays();
2015
2016 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
2017 } else {
2018 glStencilFunc(GL_ALWAYS, 0, ~0);
2019 glEnable(GL_CULL_FACE);
2020
2021 glCullFace(GL_BACK);
2022 glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP_EXT);
2023 drawVertexArrays();
2024
2025 glCullFace(GL_FRONT);
2026 glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP_EXT);
2027 drawVertexArrays();
2028
2029 glDisable(GL_CULL_FACE);
2030 }
2031 }
2032
2033 // Enable color writes.
2034 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2035 glStencilMask(stencilMask);
2036
2037 setGradientOps(cbrush, QRectF(QPointF(min_x, min_y), QSizeF(max_x - min_x, max_y - min_y)));
2038
2039 bool fast_fill = has_fast_composition_mode && (current_style == Qt::LinearGradientPattern || current_style == Qt::SolidPattern);
2040
2041 if (use_fragment_programs && !fast_fill) {
2042 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon using stencil method (fragment programs)";
2043 QRectF rect(QPointF(min_x, min_y), QSizeF(max_x - min_x, max_y - min_y));
2044
2045 // Enable stencil func.
2046 glStencilFunc(GL_NOTEQUAL, 0, stencilMask);
2047 glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
2048 composite(rect);
2049 } else {
2050 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon using stencil method (no fragment programs)";
2051
2052 // Enable stencil func.
2053 glStencilFunc(GL_NOTEQUAL, 0, stencilMask);
2054 glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
2055#ifndef QT_OPENGL_ES
2056 glBegin(GL_QUADS);
2057 glVertex2f(min_x, min_y);
2058 glVertex2f(max_x, min_y);
2059 glVertex2f(max_x, max_y);
2060 glVertex2f(min_x, max_y);
2061 glEnd();
2062#endif
2063 }
2064
2065 // Disable stencil writes.
2066 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2067 glStencilMask(0);
2068 glDisable(GL_STENCIL_TEST);
2069}
2070
2071void QOpenGLPaintEnginePrivate::fillPath(const QPainterPath &path)
2072{
2073 if (path.isEmpty())
2074 return;
2075
2076 if (use_stencil_method && !high_quality_antialiasing) {
2077 pathToVertexArrays(path);
2078 fillVertexArray(path.fillRule());
2079 return;
2080 }
2081
2082 glMatrixMode(GL_MODELVIEW);
2083 glLoadIdentity();
2084
2085 if (high_quality_antialiasing)
2086 drawOffscreenPath(path);
2087 else {
2088 QPolygonF poly = path.toFillPolygon(matrix);
2089 fillPolygon_dev(poly.data(), poly.count(),
2090 path.fillRule());
2091 }
2092
2093 updateGLMatrix();
2094}
2095
2096
2097static inline bool needsEmulation(Qt::BrushStyle style)
2098{
2099 return !(style == Qt::SolidPattern
2100 || (style == Qt::LinearGradientPattern
2101 && (QGLExtensions::glExtensions & QGLExtensions::MirroredRepeat)));
2102}
2103
2104void QOpenGLPaintEnginePrivate::updateUseEmulation()
2105{
2106 use_emulation = !use_fragment_programs
2107 && ((has_pen && needsEmulation(pen_brush_style))
2108 || (has_brush && needsEmulation(brush_style)));
2109}
2110
2111void QOpenGLPaintEngine::updatePen(const QPen &pen)
2112{
2113 Q_D(QOpenGLPaintEngine);
2114 Qt::PenStyle pen_style = pen.style();
2115 d->pen_brush_style = pen.brush().style();
2116 d->cpen = pen;
2117 d->has_pen = (pen_style != Qt::NoPen) && (d->pen_brush_style != Qt::NoBrush);
2118 d->updateUseEmulation();
2119
2120 if (pen.isCosmetic()) {
2121 GLfloat width = pen.widthF() == 0.0f ? 1.0f : pen.widthF();
2122 glLineWidth(width);
2123 glPointSize(width);
2124 }
2125
2126 if (d->pen_brush_style >= Qt::LinearGradientPattern
2127 && d->pen_brush_style <= Qt::ConicalGradientPattern)
2128 {
2129 d->setGLPen(Qt::white);
2130 } else {
2131 d->setGLPen(pen.color());
2132 }
2133
2134 d->updateFastPen();
2135}
2136
2137void QOpenGLPaintEngine::updateBrush(const QBrush &brush, const QPointF &origin)
2138{
2139 Q_D(QOpenGLPaintEngine);
2140 d->cbrush = brush;
2141 d->brush_style = brush.style();
2142 d->brush_origin = origin;
2143 d->has_brush = (d->brush_style != Qt::NoBrush);
2144 d->updateUseEmulation();
2145}
2146
2147void QOpenGLPaintEngine::updateFont(const QFont &)
2148{
2149}
2150
2151void QOpenGLPaintEngine::updateMatrix(const QTransform &mtx)
2152{
2153 Q_D(QOpenGLPaintEngine);
2154
2155 d->matrix = mtx;
2156
2157 d->mv_matrix[0][0] = mtx.m11();
2158 d->mv_matrix[0][1] = mtx.m12();
2159 d->mv_matrix[0][2] = 0;
2160 d->mv_matrix[0][3] = mtx.m13();
2161
2162 d->mv_matrix[1][0] = mtx.m21();
2163 d->mv_matrix[1][1] = mtx.m22();
2164 d->mv_matrix[1][2] = 0;
2165 d->mv_matrix[1][3] = mtx.m23();
2166
2167 d->mv_matrix[2][0] = 0;
2168 d->mv_matrix[2][1] = 0;
2169 d->mv_matrix[2][2] = 1;
2170 d->mv_matrix[2][3] = 0;
2171
2172 d->mv_matrix[3][0] = mtx.dx();
2173 d->mv_matrix[3][1] = mtx.dy();
2174 d->mv_matrix[3][2] = 0;
2175 d->mv_matrix[3][3] = mtx.m33();
2176
2177 d->txop = mtx.type();
2178
2179 // 1/10000 == 0.0001, so we have good enough res to cover curves
2180 // that span the entire widget...
2181 d->inverseScale = qMax(1 / qMax( qMax(qAbs(mtx.m11()), qAbs(mtx.m22())),
2182 qMax(qAbs(mtx.m12()), qAbs(mtx.m21())) ),
2183 qreal(0.0001));
2184
2185 d->updateGLMatrix();
2186 d->updateFastPen();
2187}
2188
2189void QOpenGLPaintEnginePrivate::updateGLMatrix() const
2190{
2191 glMatrixMode(GL_MODELVIEW);
2192#ifndef QT_OPENGL_ES
2193 glLoadMatrixd(&mv_matrix[0][0]);
2194#else
2195 glLoadMatrixf(&mv_matrix[0][0]);
2196#endif
2197}
2198
2199void QOpenGLPaintEnginePrivate::disableClipping()
2200{
2201 glDisable(GL_DEPTH_TEST);
2202 glDisable(GL_SCISSOR_TEST);
2203}
2204
2205void QOpenGLPaintEnginePrivate::enableClipping()
2206{
2207 Q_Q(QOpenGLPaintEngine);
2208 if (!q->state()->hasClipping)
2209 return;
2210
2211 if (q->state()->fastClip.isEmpty())
2212 glEnable(GL_DEPTH_TEST);
2213 else
2214 updateDepthClip(); // this will enable the scissor test
2215}
2216
2217void QOpenGLPaintEnginePrivate::updateDepthClip()
2218{
2219 Q_Q(QOpenGLPaintEngine);
2220
2221 ++q->state()->depthClipId;
2222
2223 glDisable(GL_DEPTH_TEST);
2224 glDisable(GL_SCISSOR_TEST);
2225
2226 if (!q->state()->hasClipping)
2227 return;
2228
2229 QRect fastClip;
2230 if (q->state()->clipEnabled) {
2231 fastClip = q->state()->fastClip;
2232 } else if (use_system_clip && q->systemClip().rects().count() == 1) {
2233 fastClip = q->systemClip().rects().at(0);
2234 }
2235
2236 if (!fastClip.isEmpty()) {
2237 glEnable(GL_SCISSOR_TEST);
2238
2239 const int left = fastClip.left();
2240 const int width = fastClip.width();
2241 const int bottom = device->size().height() - (fastClip.bottom() + 1);
2242 const int height = fastClip.height();
2243
2244 glScissor(left, bottom, width, height);
2245 return;
2246 }
2247
2248#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2) || defined(QT_OPENGL_ES_1_CL)
2249 glClearDepthf(0.0f);
2250#else
2251 glClearDepth(0.0f);
2252#endif
2253
2254 glEnable(GL_DEPTH_TEST);
2255 glDepthMask(GL_TRUE);
2256 glClear(GL_DEPTH_BUFFER_BIT);
2257
2258 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2259 glDepthFunc(GL_ALWAYS);
2260
2261 const QVector<QRect> rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects();
2262
2263 // rectangle count * 2 (triangles) * vertex count * component count (Z omitted)
2264 QDataBuffer<q_vertexType> clipVertex(rects.size()*2*3*2);
2265 for (int i = 0; i < rects.size(); ++i) {
2266 q_vertexType x = i2vt(rects.at(i).left());
2267 q_vertexType w = i2vt(rects.at(i).width());
2268 q_vertexType h = i2vt(rects.at(i).height());
2269 q_vertexType y = i2vt(rects.at(i).top());
2270
2271 // First triangle
2272 clipVertex.add(x);
2273 clipVertex.add(y);
2274
2275 clipVertex.add(x);
2276 clipVertex.add(y + h);
2277
2278 clipVertex.add(x + w);
2279 clipVertex.add(y);
2280
2281 // Second triangle
2282 clipVertex.add(x);
2283 clipVertex.add(y + h);
2284
2285 clipVertex.add(x + w);
2286 clipVertex.add(y + h);
2287
2288 clipVertex.add (x + w);
2289 clipVertex.add(y);
2290 }
2291
2292 if (rects.size()) {
2293 glMatrixMode(GL_MODELVIEW);
2294 glLoadIdentity();
2295
2296 glEnableClientState(GL_VERTEX_ARRAY);
2297 glVertexPointer(2, q_vertexTypeEnum, 0, clipVertex.data());
2298
2299 glDrawArrays(GL_TRIANGLES, 0, rects.size()*2*3);
2300 glDisableClientState(GL_VERTEX_ARRAY);
2301 updateGLMatrix();
2302 }
2303
2304 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2305 glDepthMask(GL_FALSE);
2306 glDepthFunc(GL_LEQUAL);
2307}
2308
2309void QOpenGLPaintEnginePrivate::systemStateChanged()
2310{
2311 Q_Q(QOpenGLPaintEngine);
2312 if (q->painter()->hasClipping())
2313 q->updateClipRegion(q->painter()->clipRegion(), Qt::ReplaceClip);
2314 else
2315 q->updateClipRegion(QRegion(), Qt::NoClip);
2316}
2317
2318void QOpenGLPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
2319{
2320 Q_D(QOpenGLPaintEngine);
2321
2322 // clipping is only supported when a stencil or depth buffer is
2323 // available
2324 if (!d->device->format().depth())
2325 return;
2326
2327 d->use_system_clip = false;
2328 QRegion sysClip = systemClip();
2329 if (!sysClip.isEmpty()) {
2330 if (d->pdev->devType() != QInternal::Widget) {
2331 d->use_system_clip = true;
2332 } else {
2333#ifndef Q_WS_QWS
2334 // Only use the system clip if we're currently rendering a widget with a GL painter.
2335 if (d->currentClipWidget) {
2336 QWidgetPrivate *widgetPrivate = qt_widget_private(d->currentClipWidget->window());
2337 d->use_system_clip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2338 }
2339#endif
2340 }
2341 }
2342
2343 d->flushDrawQueue();
2344
2345 if (op == Qt::NoClip && !d->use_system_clip) {
2346 state()->hasClipping = false;
2347 state()->clipRegion = QRegion();
2348 d->updateDepthClip();
2349 return;
2350 }
2351
2352 bool isScreenClip = false;
2353 if (!d->use_system_clip) {
2354 QVector<QRect> untransformedRects = clipRegion.rects();
2355
2356 if (untransformedRects.size() == 1) {
2357 QPainterPath path;
2358 path.addRect(untransformedRects[0]);
2359 path = d->matrix.map(path);
2360
2361 if (path.contains(QRectF(QPointF(), d->device->size())))
2362 isScreenClip = true;
2363 }
2364 }
2365
2366 QRegion region = isScreenClip ? QRegion() : clipRegion * d->matrix;
2367 switch (op) {
2368 case Qt::NoClip:
2369 if (!d->use_system_clip)
2370 break;
2371 state()->clipRegion = sysClip;
2372 break;
2373 case Qt::IntersectClip:
2374 if (isScreenClip)
2375 return;
2376 if (state()->hasClipping) {
2377 state()->clipRegion &= region;
2378 break;
2379 }
2380 // fall through
2381 case Qt::ReplaceClip:
2382 if (d->use_system_clip)
2383 state()->clipRegion = region & sysClip;
2384 else
2385 state()->clipRegion = region;
2386 break;
2387 case Qt::UniteClip:
2388 state()->clipRegion |= region;
2389 if (d->use_system_clip)
2390 state()->clipRegion &= sysClip;
2391 break;
2392 default:
2393 break;
2394 }
2395
2396 if (isScreenClip) {
2397 state()->hasClipping = false;
2398 state()->clipRegion = QRegion();
2399 } else {
2400 state()->hasClipping = op != Qt::NoClip || d->use_system_clip;
2401 }
2402
2403 if (state()->hasClipping && state()->clipRegion.rects().size() == 1)
2404 state()->fastClip = state()->clipRegion.rects().at(0);
2405 else
2406 state()->fastClip = QRect();
2407
2408 d->updateDepthClip();
2409}
2410
2411void QOpenGLPaintEngine::updateRenderHints(QPainter::RenderHints hints)
2412{
2413 Q_D(QOpenGLPaintEngine);
2414
2415 d->flushDrawQueue();
2416 d->use_smooth_pixmap_transform = bool(hints & QPainter::SmoothPixmapTransform);
2417 if ((hints & QPainter::Antialiasing) || (hints & QPainter::HighQualityAntialiasing)) {
2418 if (d->use_fragment_programs && QGLOffscreen::isSupported()
2419 && (hints & QPainter::HighQualityAntialiasing)) {
2420 d->high_quality_antialiasing = true;
2421 } else {
2422 d->high_quality_antialiasing = false;
2423 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2424 glEnable(GL_MULTISAMPLE);
2425 }
2426 } else {
2427 d->high_quality_antialiasing = false;
2428 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2429 glDisable(GL_MULTISAMPLE);
2430 }
2431
2432 if (d->high_quality_antialiasing) {
2433 d->offscreen.initialize();
2434
2435 if (!d->offscreen.isValid()) {
2436 DEBUG_ONCE_STR("Unable to initialize offscreen, disabling high quality antialiasing");
2437 d->high_quality_antialiasing = false;
2438 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2439 glEnable(GL_MULTISAMPLE);
2440 }
2441 }
2442
2443 d->has_antialiasing = d->high_quality_antialiasing
2444 || ((hints & QPainter::Antialiasing)
2445 && (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers));
2446}
2447
2448
2449void QOpenGLPaintEnginePrivate::setPorterDuffData(float a, float b, float x, float y, float z)
2450{
2451 porterduff_ab_data[0] = a;
2452 porterduff_ab_data[1] = b;
2453
2454 porterduff_xyz_data[0] = x;
2455 porterduff_xyz_data[1] = y;
2456 porterduff_xyz_data[2] = z;
2457}
2458
2459
2460void QOpenGLPaintEngine::updateCompositionMode(QPainter::CompositionMode composition_mode)
2461{
2462 Q_D(QOpenGLPaintEngine);
2463
2464 if (!d->use_fragment_programs && composition_mode > QPainter::CompositionMode_Plus)
2465 composition_mode = QPainter::CompositionMode_SourceOver;
2466
2467 d->composition_mode = composition_mode;
2468
2469 d->has_fast_composition_mode = (!d->high_quality_antialiasing && composition_mode <= QPainter::CompositionMode_Plus)
2470 || composition_mode == QPainter::CompositionMode_SourceOver
2471 || composition_mode == QPainter::CompositionMode_Destination
2472 || composition_mode == QPainter::CompositionMode_DestinationOver
2473 || composition_mode == QPainter::CompositionMode_DestinationOut
2474 || composition_mode == QPainter::CompositionMode_SourceAtop
2475 || composition_mode == QPainter::CompositionMode_Xor
2476 || composition_mode == QPainter::CompositionMode_Plus;
2477
2478 if (d->has_fast_composition_mode)
2479 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODE_BLEND_MODE_MASK : COMPOSITION_MODE_BLEND_MODE_NOMASK;
2480 else if (composition_mode <= QPainter::CompositionMode_Plus)
2481 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SIMPLE_PORTER_DUFF : COMPOSITION_MODES_SIMPLE_PORTER_DUFF_NOMASK;
2482 else
2483 switch (composition_mode) {
2484 case QPainter::CompositionMode_Multiply:
2485 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_MULTIPLY : COMPOSITION_MODES_MULTIPLY_NOMASK;
2486 break;
2487 case QPainter::CompositionMode_Screen:
2488 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SCREEN : COMPOSITION_MODES_SCREEN_NOMASK;
2489 break;
2490 case QPainter::CompositionMode_Overlay:
2491 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_OVERLAY : COMPOSITION_MODES_OVERLAY_NOMASK;
2492 break;
2493 case QPainter::CompositionMode_Darken:
2494 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_DARKEN : COMPOSITION_MODES_DARKEN_NOMASK;
2495 break;
2496 case QPainter::CompositionMode_Lighten:
2497 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_LIGHTEN : COMPOSITION_MODES_LIGHTEN_NOMASK;
2498 break;
2499 case QPainter::CompositionMode_ColorDodge:
2500 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_COLORDODGE : COMPOSITION_MODES_COLORDODGE_NOMASK;
2501 break;
2502 case QPainter::CompositionMode_ColorBurn:
2503 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_COLORBURN : COMPOSITION_MODES_COLORBURN_NOMASK;
2504 break;
2505 case QPainter::CompositionMode_HardLight:
2506 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_HARDLIGHT : COMPOSITION_MODES_HARDLIGHT_NOMASK;
2507 break;
2508 case QPainter::CompositionMode_SoftLight:
2509 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SOFTLIGHT : COMPOSITION_MODES_SOFTLIGHT_NOMASK;
2510 break;
2511 case QPainter::CompositionMode_Difference:
2512 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_DIFFERENCE : COMPOSITION_MODES_DIFFERENCE_NOMASK;
2513 break;
2514 case QPainter::CompositionMode_Exclusion:
2515 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_EXCLUSION : COMPOSITION_MODES_EXCLUSION_NOMASK;
2516 break;
2517 default:
2518 Q_ASSERT(false);
2519 }
2520
2521 switch(composition_mode) {
2522 case QPainter::CompositionMode_DestinationOver:
2523 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
2524 d->setPorterDuffData(0, 1, 1, 1, 1);
2525 break;
2526 case QPainter::CompositionMode_Clear:
2527 glBlendFunc(GL_ZERO, GL_ZERO);
2528 d->setPorterDuffData(0, 0, 0, 0, 0);
2529 break;
2530 case QPainter::CompositionMode_Source:
2531 glBlendFunc(GL_ONE, GL_ZERO);
2532 d->setPorterDuffData(1, 0, 1, 1, 0);
2533 break;
2534 case QPainter::CompositionMode_Destination:
2535 glBlendFunc(GL_ZERO, GL_ONE);
2536 d->setPorterDuffData(0, 1, 1, 0, 1);
2537 break;
2538 case QPainter::CompositionMode_SourceIn:
2539 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
2540 d->setPorterDuffData(1, 0, 1, 0, 0);
2541 break;
2542 case QPainter::CompositionMode_DestinationIn:
2543 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
2544 d->setPorterDuffData(0, 1, 1, 0, 0);
2545 break;
2546 case QPainter::CompositionMode_SourceOut:
2547 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
2548 d->setPorterDuffData(0, 0, 0, 1, 0);
2549 break;
2550 case QPainter::CompositionMode_DestinationOut:
2551 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
2552 d->setPorterDuffData(0, 0, 0, 0, 1);
2553 break;
2554 case QPainter::CompositionMode_SourceAtop:
2555 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2556 d->setPorterDuffData(1, 0, 1, 0, 1);
2557 break;
2558 case QPainter::CompositionMode_DestinationAtop:
2559 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
2560 d->setPorterDuffData(0, 1, 1, 1, 0);
2561 break;
2562 case QPainter::CompositionMode_Xor:
2563 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2564 d->setPorterDuffData(0, 0, 0, 1, 1);
2565 break;
2566 case QPainter::CompositionMode_SourceOver:
2567 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2568 d->setPorterDuffData(1, 0, 1, 1, 1);
2569 break;
2570 case QPainter::CompositionMode_Plus:
2571 glBlendFunc(GL_ONE, GL_ONE);
2572 d->setPorterDuffData(1, 1, 1, 1, 1);
2573 break;
2574 default:
2575 break;
2576 }
2577}
2578
2579class QGLMaskGenerator
2580{
2581public:
2582 QGLMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal stroke_width = -1)
2583 : p(path),
2584 m(matrix),
2585 w(stroke_width)
2586 {
2587 }
2588
2589 virtual QRect screenRect() = 0;
2590 virtual void drawMask(const QRect &rect) = 0;
2591
2592 QPainterPath path() const { return p; }
2593 QTransform matrix() const { return m; }
2594 qreal strokeWidth() const { return w; }
2595
2596 virtual ~QGLMaskGenerator() {}
2597
2598private:
2599 QPainterPath p;
2600 QTransform m;
2601 qreal w;
2602};
2603
2604void QGLMaskTextureCache::setOffscreenSize(const QSize &sz)
2605{
2606 Q_ASSERT(sz.width() == sz.height());
2607
2608 if (offscreenSize != sz) {
2609 offscreenSize = sz;
2610 clearCache();
2611 }
2612}
2613
2614void QGLMaskTextureCache::clearCache()
2615{
2616 cache.clear();
2617
2618 int quad_tree_size = 1;
2619
2620 for (int i = block_size; i < offscreenSize.width(); i *= 2)
2621 quad_tree_size += quad_tree_size * 4;
2622
2623 for (int i = 0; i < 4; ++i) {
2624 occupied_quadtree[i].resize(quad_tree_size);
2625
2626 occupied_quadtree[i][0].key = 0;
2627 occupied_quadtree[i][0].largest_available_block = offscreenSize.width();
2628 occupied_quadtree[i][0].largest_used_block = 0;
2629
2630 DEBUG_ONCE qDebug() << "QGLMaskTextureCache:: created quad tree of size" << quad_tree_size;
2631 }
2632}
2633
2634void QGLMaskTextureCache::setDrawableSize(const QSize &sz)
2635{
2636 drawableSize = sz;
2637}
2638
2639void QGLMaskTextureCache::maintainCache()
2640{
2641 QGLTextureCacheHash::iterator it = cache.begin();
2642 QGLTextureCacheHash::iterator end = cache.end();
2643
2644 while (it != end) {
2645 CacheInfo &cache_info = it.value();
2646 ++cache_info.age;
2647
2648 if (cache_info.age > 1) {
2649 quadtreeInsert(cache_info.loc.channel, 0, cache_info.loc.rect);
2650 it = cache.erase(it);
2651 } else {
2652 ++it;
2653 }
2654 }
2655}
2656
2657//#define DISABLE_MASK_CACHE
2658
2659QGLMaskTextureCache::CacheLocation QGLMaskTextureCache::getMask(QGLMaskGenerator &maskGenerator, QOpenGLPaintEnginePrivate *e)
2660{
2661#ifndef DISABLE_MASK_CACHE
2662 engine = e;
2663
2664 quint64 key = hash(maskGenerator.path(), maskGenerator.matrix(), maskGenerator.strokeWidth());
2665
2666 if (key == 0)
2667 key = 1;
2668
2669 CacheInfo info(maskGenerator.path(), maskGenerator.matrix(), maskGenerator.strokeWidth());
2670
2671 QGLTextureCacheHash::iterator it = cache.find(key);
2672
2673 while (it != cache.end() && it.key() == key) {
2674 CacheInfo &cache_info = it.value();
2675 if (info.stroke_width == cache_info.stroke_width && info.matrix == cache_info.matrix && info.path == cache_info.path) {
2676 DEBUG_ONCE_STR("QGLMaskTextureCache::getMask(): Using cached mask");
2677
2678 cache_info.age = 0;
2679 return cache_info.loc;
2680 }
2681 ++it;
2682 }
2683
2684 // mask was not found, create new mask
2685
2686 DEBUG_ONCE_STR("QGLMaskTextureCache::getMask(): Creating new mask...");
2687
2688 createMask(key, info, maskGenerator);
2689
2690 cache.insert(key, info);
2691
2692 return info.loc;
2693#else
2694 CacheInfo info(maskGenerator.path(), maskGenerator.matrix());
2695 createMask(0, info, maskGenerator);
2696 return info.loc;
2697#endif
2698}
2699
2700#ifndef FloatToQuint64
2701#define FloatToQuint64(i) (quint64)((i) * 32)
2702#endif
2703
2704quint64 QGLMaskTextureCache::hash(const QPainterPath &p, const QTransform &m, qreal w)
2705{
2706 Q_ASSERT(sizeof(quint64) == 8);
2707
2708 quint64 h = 0;
2709
2710 for (int i = 0; i < p.elementCount(); ++i) {
2711 h += FloatToQuint64(p.elementAt(i).x) << 32;
2712 h += FloatToQuint64(p.elementAt(i).y);
2713 h += p.elementAt(i).type;
2714 }
2715
2716 h += FloatToQuint64(m.m11());
2717#ifndef Q_OS_WINCE // ###
2718 //Compiler crashes for arm on WinCE
2719 h += FloatToQuint64(m.m12()) << 4;
2720 h += FloatToQuint64(m.m13()) << 8;
2721 h += FloatToQuint64(m.m21()) << 12;
2722 h += FloatToQuint64(m.m22()) << 16;
2723 h += FloatToQuint64(m.m23()) << 20;
2724 h += FloatToQuint64(m.m31()) << 24;
2725 h += FloatToQuint64(m.m32()) << 28;
2726#endif
2727 h += FloatToQuint64(m.m33()) << 32;
2728
2729 h += FloatToQuint64(w);
2730
2731 return h;
2732}
2733
2734void QGLMaskTextureCache::createMask(quint64 key, CacheInfo &info, QGLMaskGenerator &maskGenerator)
2735{
2736 info.loc.screen_rect = maskGenerator.screenRect();
2737
2738 if (info.loc.screen_rect.isEmpty()) {
2739 info.loc.channel = 0;
2740 info.loc.rect = QRect();
2741 return;
2742 }
2743
2744 quadtreeAllocate(key, info.loc.screen_rect.size(), &info.loc.rect, &info.loc.channel);
2745
2746 int ch = info.loc.channel;
2747 glColorMask(ch == 0, ch == 1, ch == 2, ch == 3);
2748
2749 maskGenerator.drawMask(info.loc.rect);
2750
2751 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2752}
2753
2754int QGLMaskTextureCache::quadtreeBlocksize(int node)
2755{
2756 DEBUG_ONCE qDebug() << "Offscreen size:" << offscreenSize.width();
2757
2758 int blocksize = offscreenSize.width();
2759
2760 while (node) {
2761 node = (node - 1) / 4;
2762 blocksize /= 2;
2763 }
2764
2765 return blocksize;
2766}
2767
2768QPoint QGLMaskTextureCache::quadtreeLocation(int node)
2769{
2770 QPoint location;
2771 int blocksize = quadtreeBlocksize(node);
2772
2773 while (node) {
2774 --node;
2775
2776 if (node & 1)
2777 location.setX(location.x() + blocksize);
2778
2779 if (node & 2)
2780 location.setY(location.y() + blocksize);
2781
2782 node /= 4;
2783 blocksize *= 2;
2784 }
2785
2786 return location;
2787}
2788
2789void QGLMaskTextureCache::quadtreeUpdate(int channel, int node, int current_block_size)
2790{
2791 while (node) {
2792 node = (node - 1) / 4;
2793
2794 int first_child = node * 4 + 1;
2795
2796 int largest_available = 0;
2797 int largest_used = 0;
2798
2799 bool all_empty = true;
2800
2801 for (int i = 0; i < 4; ++i) {
2802 largest_available = qMax(largest_available, occupied_quadtree[channel][first_child + i].largest_available_block);
2803 largest_used = qMax(largest_used, occupied_quadtree[channel][first_child + i].largest_used_block);
2804
2805 if (occupied_quadtree[channel][first_child + i].largest_available_block < current_block_size)
2806 all_empty = false;
2807 }
2808
2809 current_block_size *= 2;
2810
2811 if (all_empty) {
2812 occupied_quadtree[channel][node].largest_available_block = current_block_size;
2813 occupied_quadtree[channel][node].largest_used_block = 0;
2814 } else {
2815 occupied_quadtree[channel][node].largest_available_block = largest_available;
2816 occupied_quadtree[channel][node].largest_used_block = largest_used;
2817 }
2818 }
2819}
2820
2821void QGLMaskTextureCache::quadtreeInsert(int channel, quint64 key, const QRect &rect, int node)
2822{
2823 int current_block_size = quadtreeBlocksize(node);
2824 QPoint location = quadtreeLocation(node);
2825 QRect relative = rect.translated(-location);
2826
2827 if (relative.left() >= current_block_size || relative.top() >= current_block_size
2828 || relative.right() < 0 || relative.bottom() < 0)
2829 return;
2830
2831 if (current_block_size == block_size // no more refining possible
2832 || (relative.top() < block_size && relative.bottom() >= (current_block_size - block_size)
2833 && relative.left() < block_size && relative.right() >= (current_block_size - block_size)))
2834 {
2835 if (key != 0) {
2836 occupied_quadtree[channel][node].largest_available_block = 0;
2837 occupied_quadtree[channel][node].largest_used_block = rect.width() * rect.height();
2838 } else {
2839 occupied_quadtree[channel][node].largest_available_block = current_block_size;
2840 occupied_quadtree[channel][node].largest_used_block = 0;
2841 }
2842
2843 occupied_quadtree[channel][node].key = key;
2844
2845 quadtreeUpdate(channel, node, current_block_size);
2846 } else {
2847 if (key && occupied_quadtree[channel][node].largest_available_block == current_block_size) {
2848 // refining the quad tree, initialize child nodes
2849 int half_block_size = current_block_size / 2;
2850
2851 int temp = node * 4 + 1;
2852 for (int sibling = 0; sibling < 4; ++sibling) {
2853 occupied_quadtree[channel][temp + sibling].largest_available_block = half_block_size;
2854 occupied_quadtree[channel][temp + sibling].largest_used_block = 0;
2855 occupied_quadtree[channel][temp + sibling].key = 0;
2856 }
2857 }
2858
2859 node = node * 4 + 1;
2860
2861 for (int sibling = 0; sibling < 4; ++sibling)
2862 quadtreeInsert(channel, key, rect, node + sibling);
2863 }
2864}
2865
2866void QGLMaskTextureCache::quadtreeClear(int channel, const QRect &rect, int node)
2867{
2868 const quint64 &key = occupied_quadtree[channel][node].key;
2869
2870 int current_block_size = quadtreeBlocksize(node);
2871 QPoint location = quadtreeLocation(node);
2872
2873 QRect relative = rect.translated(-location);
2874
2875 if (relative.left() >= current_block_size || relative.top() >= current_block_size
2876 || relative.right() < 0 || relative.bottom() < 0)
2877 return;
2878
2879 if (key != 0) {
2880 QGLTextureCacheHash::iterator it = cache.find(key);
2881
2882 Q_ASSERT(it != cache.end());
2883
2884 while (it != cache.end() && it.key() == key) {
2885 const CacheInfo &cache_info = it.value();
2886
2887 if (cache_info.loc.channel == channel
2888 && cache_info.loc.rect.left() <= location.x()
2889 && cache_info.loc.rect.top() <= location.y()
2890 && cache_info.loc.rect.right() >= location.x()
2891 && cache_info.loc.rect.bottom() >= location.y())
2892 {
2893 quadtreeInsert(channel, 0, cache_info.loc.rect);
2894 engine->cacheItemErased(channel, cache_info.loc.rect);
2895 cache.erase(it);
2896 goto found;
2897 } else {
2898 ++it;
2899 }
2900 }
2901
2902 // if we don't find the key there's an error in the quadtree
2903 Q_ASSERT(false);
2904found:
2905 Q_ASSERT(occupied_quadtree[channel][node].key == 0);
2906 } else if (occupied_quadtree[channel][node].largest_available_block < current_block_size) {
2907 Q_ASSERT(current_block_size >= block_size);
2908
2909 node = node * 4 + 1;
2910
2911 for (int sibling = 0; sibling < 4; ++sibling)
2912 quadtreeClear(channel, rect, node + sibling);
2913 }
2914}
2915
2916bool QGLMaskTextureCache::quadtreeFindAvailableLocation(const QSize &size, QRect *rect, int *channel)
2917{
2918 int needed_block_size = qMax(1, qMax(size.width(), size.height()));
2919
2920 for (int i = 0; i < 4; ++i) {
2921 int current_block_size = offscreenSize.width();
2922
2923 if (occupied_quadtree[i][0].largest_available_block >= needed_block_size) {
2924 int node = 0;
2925
2926 while (current_block_size != occupied_quadtree[i][node].largest_available_block) {
2927 Q_ASSERT(current_block_size > block_size);
2928 Q_ASSERT(current_block_size > occupied_quadtree[i][node].largest_available_block);
2929
2930 node = node * 4 + 1;
2931 current_block_size /= 2;
2932
2933 int sibling = 0;
2934
2935 while (occupied_quadtree[i][node + sibling].largest_available_block < needed_block_size)
2936 ++sibling;
2937
2938 Q_ASSERT(sibling < 4);
2939 node += sibling;
2940 }
2941
2942 *channel = i;
2943 *rect = QRect(quadtreeLocation(node), size);
2944
2945 return true;
2946 }
2947 }
2948
2949 return false;
2950}
2951
2952void QGLMaskTextureCache::quadtreeFindExistingLocation(const QSize &size, QRect *rect, int *channel)
2953{
2954 // try to pick small masks to throw out, as large masks are more expensive to recompute
2955 *channel = qrand() % 4;
2956 for (int i = 0; i < 4; ++i)
2957 if (occupied_quadtree[i][0].largest_used_block < occupied_quadtree[*channel][0].largest_used_block)
2958 *channel = i;
2959
2960 int needed_block_size = qt_next_power_of_two(qMax(1, qMax(size.width(), size.height())));
2961
2962 int node = 0;
2963 int current_block_size = offscreenSize.width();
2964
2965 while (current_block_size > block_size
2966 && current_block_size >= needed_block_size * 2
2967 && occupied_quadtree[*channel][node].key == 0)
2968 {
2969 node = node * 4 + 1;
2970
2971 int sibling = 0;
2972
2973 for (int i = 1; i < 4; ++i) {
2974 if (occupied_quadtree[*channel][node + i].largest_used_block
2975 <= occupied_quadtree[*channel][node + sibling].largest_used_block)
2976 {
2977 sibling = i;
2978 }
2979 }
2980
2981 node += sibling;
2982 current_block_size /= 2;
2983 }
2984
2985 *rect = QRect(quadtreeLocation(node), size);
2986}
2987
2988void QGLMaskTextureCache::quadtreeAllocate(quint64 key, const QSize &size, QRect *rect, int *channel)
2989{
2990#ifndef DISABLE_MASK_CACHE
2991 if (!quadtreeFindAvailableLocation(size, rect, channel)) {
2992 quadtreeFindExistingLocation(size, rect, channel);
2993 quadtreeClear(*channel, *rect);
2994 }
2995
2996 quadtreeInsert(*channel, key, *rect);
2997#else
2998 *channel = 0;
2999 *rect = QRect(QPoint(), size);
3000#endif
3001}
3002
3003class QGLTrapezoidMaskGenerator : public QGLMaskGenerator
3004{
3005public:
3006 QGLTrapezoidMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram, qreal strokeWidth = -1.0);
3007
3008 QRect screenRect();
3009 void drawMask(const QRect &rect);
3010
3011private:
3012 QRect screen_rect;
3013 bool has_screen_rect;
3014
3015 QGLOffscreen *offscreen;
3016
3017 GLuint maskFragmentProgram;
3018
3019 virtual QVector<QGLTrapezoid> generateTrapezoids() = 0;
3020 virtual QRect computeScreenRect() = 0;
3021};
3022
3023class QGLPathMaskGenerator : public QGLTrapezoidMaskGenerator
3024{
3025public:
3026 QGLPathMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3027
3028private:
3029 QVector<QGLTrapezoid> generateTrapezoids();
3030 QRect computeScreenRect();
3031
3032 QPolygonF poly;
3033};
3034
3035class QGLLineMaskGenerator : public QGLTrapezoidMaskGenerator
3036{
3037public:
3038 QGLLineMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal width, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3039
3040private:
3041 QVector<QGLTrapezoid> generateTrapezoids();
3042 QRect computeScreenRect();
3043
3044 QPainterPath transformedPath;
3045};
3046
3047class QGLRectMaskGenerator : public QGLTrapezoidMaskGenerator
3048{
3049public:
3050 QGLRectMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3051
3052private:
3053 QVector<QGLTrapezoid> generateTrapezoids();
3054 QRect computeScreenRect();
3055
3056 QPainterPath transformedPath;
3057};
3058
3059class QGLEllipseMaskGenerator : public QGLMaskGenerator
3060{
3061public:
3062 QGLEllipseMaskGenerator(const QRectF &rect, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram, int *maskVariableLocations);
3063
3064 QRect screenRect();
3065 void drawMask(const QRect &rect);
3066
3067private:
3068 QRect screen_rect;
3069
3070 QRectF ellipseRect;
3071
3072 QGLOffscreen *offscreen;
3073
3074 GLuint maskFragmentProgram;
3075
3076 int *maskVariableLocations;
3077
3078 float vertexArray[4 * 2];
3079};
3080
3081QGLTrapezoidMaskGenerator::QGLTrapezoidMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program, qreal stroke_width)
3082 : QGLMaskGenerator(path, matrix, stroke_width)
3083 , has_screen_rect(false)
3084 , offscreen(&offs)
3085 , maskFragmentProgram(program)
3086{
3087}
3088
3089extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array);
3090extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array);
3091
3092void QGLTrapezoidMaskGenerator::drawMask(const QRect &rect)
3093{
3094#ifdef QT_OPENGL_ES
3095 Q_UNUSED(rect);
3096#else
3097 glMatrixMode(GL_MODELVIEW);
3098 glPushMatrix();
3099 glLoadIdentity();
3100
3101 QGLContext *ctx = offscreen->context();
3102 offscreen->bind();
3103
3104 glDisable(GL_TEXTURE_GEN_S);
3105 glDisable(GL_TEXTURE_1D);
3106
3107 GLfloat vertexArray[4 * 2];
3108 qt_add_rect_to_array(rect, vertexArray);
3109
3110 bool needs_scissor = rect != screen_rect;
3111
3112 if (needs_scissor) {
3113 glEnable(GL_SCISSOR_TEST);
3114 glScissor(rect.left(), offscreen->offscreenSize().height() - rect.bottom() - 1, rect.width(), rect.height());
3115 }
3116
3117 QVector<QGLTrapezoid> trapezoids = generateTrapezoids();
3118
3119 // clear mask
3120 glBlendFunc(GL_ZERO, GL_ZERO); // clear
3121 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3122 glEnableClientState(GL_VERTEX_ARRAY);
3123 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3124 glDisableClientState(GL_VERTEX_ARRAY);
3125
3126 glBlendFunc(GL_ONE, GL_ONE); // add mask
3127 glEnable(GL_FRAGMENT_PROGRAM_ARB);
3128 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, maskFragmentProgram);
3129
3130 QPoint delta = rect.topLeft() - screen_rect.topLeft();
3131 glBegin(GL_QUADS);
3132 for (int i = 0; i < trapezoids.size(); ++i)
3133 drawTrapezoid(trapezoids[i].translated(delta), offscreen->offscreenSize().height(), ctx);
3134 glEnd();
3135
3136 if (needs_scissor)
3137 glDisable(GL_SCISSOR_TEST);
3138
3139 glDisable(GL_FRAGMENT_PROGRAM_ARB);
3140
3141 glMatrixMode(GL_MODELVIEW);
3142 glPopMatrix();
3143#endif
3144}
3145
3146QRect QGLTrapezoidMaskGenerator::screenRect()
3147{
3148 if (!has_screen_rect) {
3149 screen_rect = computeScreenRect();
3150 has_screen_rect = true;
3151 }
3152
3153 screen_rect = screen_rect.intersected(QRect(QPoint(), offscreen->drawableSize()));
3154
3155 return screen_rect;
3156}
3157
3158QGLPathMaskGenerator::QGLPathMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program)
3159 : QGLTrapezoidMaskGenerator(path, matrix, offs, program)
3160{
3161}
3162
3163QRect QGLPathMaskGenerator::computeScreenRect()
3164{
3165 poly = path().toFillPolygon(matrix());
3166 return poly.boundingRect().toAlignedRect();
3167}
3168
3169QVector<QGLTrapezoid> QGLPathMaskGenerator::generateTrapezoids()
3170{
3171 QOpenGLImmediateModeTessellator tessellator;
3172 tessellator.tessellate(poly.data(), poly.count(), path().fillRule() == Qt::WindingFill);
3173 return tessellator.trapezoids;
3174}
3175
3176QGLRectMaskGenerator::QGLRectMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program)
3177 : QGLTrapezoidMaskGenerator(path, matrix, offs, program)
3178{
3179}
3180
3181QGLLineMaskGenerator::QGLLineMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal width, QGLOffscreen &offs, GLuint program)
3182 : QGLTrapezoidMaskGenerator(path, matrix, offs, program, width)
3183{
3184}
3185
3186QRect QGLRectMaskGenerator::computeScreenRect()
3187{
3188 transformedPath = matrix().map(path());
3189
3190 return transformedPath.controlPointRect().adjusted(-1, -1, 1, 1).toAlignedRect();
3191}
3192
3193QRect QGLLineMaskGenerator::computeScreenRect()
3194{
3195 transformedPath = matrix().map(path());
3196
3197 return transformedPath.controlPointRect().adjusted(-1, -1, 1, 1).toAlignedRect();
3198}
3199
3200QVector<QGLTrapezoid> QGLLineMaskGenerator::generateTrapezoids()
3201{
3202 QOpenGLImmediateModeTessellator tessellator;
3203 QPointF last;
3204 for (int i = 0; i < transformedPath.elementCount(); ++i) {
3205 QPainterPath::Element element = transformedPath.elementAt(i);
3206
3207 Q_ASSERT(!element.isCurveTo());
3208
3209 if (element.isLineTo())
3210 tessellator.tessellateRect(last, element, strokeWidth());
3211
3212 last = element;
3213 }
3214
3215 return tessellator.trapezoids;
3216}
3217
3218QVector<QGLTrapezoid> QGLRectMaskGenerator::generateTrapezoids()
3219{
3220 Q_ASSERT(transformedPath.elementCount() == 5);
3221
3222 QOpenGLImmediateModeTessellator tessellator;
3223 if (matrix().type() <= QTransform::TxScale) {
3224 QPointF a = transformedPath.elementAt(0);
3225 QPointF b = transformedPath.elementAt(1);
3226 QPointF c = transformedPath.elementAt(2);
3227 QPointF d = transformedPath.elementAt(3);
3228
3229 QPointF first = (a + d) * 0.5;
3230 QPointF last = (b + c) * 0.5;
3231
3232 QPointF delta = a - d;
3233
3234 // manhattan distance (no rotation)
3235 qreal width = qAbs(delta.x()) + qAbs(delta.y());
3236
3237 Q_ASSERT(qFuzzyIsNull(delta.x()) || qFuzzyIsNull(delta.y()));
3238
3239 tessellator.tessellateRect(first, last, width);
3240 } else {
3241 QPointF points[5];
3242
3243 for (int i = 0; i < 5; ++i)
3244 points[i] = transformedPath.elementAt(i);
3245
3246 tessellator.tessellateConvex(points, 5);
3247 }
3248 return tessellator.trapezoids;
3249}
3250
3251static QPainterPath ellipseRectToPath(const QRectF &rect)
3252{
3253 QPainterPath path;
3254 path.addEllipse(rect);
3255 return path;
3256}
3257
3258QGLEllipseMaskGenerator::QGLEllipseMaskGenerator(const QRectF &rect, const QTransform &matrix, QGLOffscreen &offs, GLuint program, int *locations)
3259 : QGLMaskGenerator(ellipseRectToPath(rect), matrix),
3260 ellipseRect(rect),
3261 offscreen(&offs),
3262 maskFragmentProgram(program),
3263 maskVariableLocations(locations)
3264{
3265}
3266
3267QRect QGLEllipseMaskGenerator::screenRect()
3268{
3269 QPointF center = ellipseRect.center();
3270
3271 QPointF points[] = {
3272 QPointF(ellipseRect.left(), center.y()),
3273 QPointF(ellipseRect.right(), center.y()),
3274 QPointF(center.x(), ellipseRect.top()),
3275 QPointF(center.x(), ellipseRect.bottom())
3276 };
3277
3278 qreal min_screen_delta_len = QREAL_MAX;
3279
3280 for (int i = 0; i < 4; ++i) {
3281 QPointF delta = points[i] - center;
3282
3283 // normalize
3284 delta /= qSqrt(delta.x() * delta.x() + delta.y() * delta.y());
3285
3286 QPointF screen_delta(matrix().m11() * delta.x() + matrix().m21() * delta.y(),
3287 matrix().m12() * delta.x() + matrix().m22() * delta.y());
3288
3289 min_screen_delta_len = qMin(min_screen_delta_len,
3290 qreal(qSqrt(screen_delta.x() * screen_delta.x() + screen_delta.y() * screen_delta.y())));
3291 }
3292
3293 const qreal padding = 2.0f;
3294
3295 qreal grow = padding / min_screen_delta_len;
3296
3297 QRectF boundingRect = ellipseRect.adjusted(-grow, -grow, grow, grow);
3298
3299 boundingRect = matrix().mapRect(boundingRect);
3300
3301 QPointF p(0.5, 0.5);
3302
3303 screen_rect = QRect((boundingRect.topLeft() - p).toPoint(),
3304 (boundingRect.bottomRight() + p).toPoint());
3305
3306 return screen_rect;
3307}
3308
3309void QGLEllipseMaskGenerator::drawMask(const QRect &rect)
3310{
3311#ifdef QT_OPENGL_ES
3312 Q_UNUSED(rect);
3313#else
3314 QGLContext *ctx = offscreen->context();
3315 offscreen->bind();
3316
3317 glDisable(GL_TEXTURE_GEN_S);
3318 glDisable(GL_TEXTURE_1D);
3319
3320 // fragment program needs the inverse radii of the ellipse
3321 glTexCoord2f(1.0f / (ellipseRect.width() * 0.5f),
3322 1.0f / (ellipseRect.height() * 0.5f));
3323
3324 QTransform translate(1, 0, 0, 1, -ellipseRect.center().x(), -ellipseRect.center().y());
3325 QTransform gl_to_qt(1, 0, 0, -1, 0, offscreen->drawableSize().height());
3326 QTransform inv_matrix = gl_to_qt * matrix().inverted() * translate;
3327
3328 float m[3][4] = { { inv_matrix.m11(), inv_matrix.m12(), inv_matrix.m13() },
3329 { inv_matrix.m21(), inv_matrix.m22(), inv_matrix.m23() },
3330 { inv_matrix.m31(), inv_matrix.m32(), inv_matrix.m33() } };
3331
3332 QPoint offs(screen_rect.left() - rect.left(), (offscreen->drawableSize().height() - screen_rect.top())
3333 - (offscreen->offscreenSize().height() - rect.top()));
3334
3335 // last component needs to be 1.0f to avoid Nvidia bug on linux
3336 float ellipse_offset[4] = { offs.x(), offs.y(), 0.0f, 1.0f };
3337
3338 GLfloat vertexArray[4 * 2];
3339 qt_add_rect_to_array(rect, vertexArray);
3340
3341 glBlendFunc(GL_ONE, GL_ZERO); // set mask
3342 glEnable(GL_FRAGMENT_PROGRAM_ARB);
3343 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, maskFragmentProgram);
3344
3345 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M0], m[0]);
3346 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M1], m[1]);
3347 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M2], m[2]);
3348
3349 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_ELLIPSE_OFFSET], ellipse_offset);
3350
3351 glEnableClientState(GL_VERTEX_ARRAY);
3352 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3353 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3354 glDisableClientState(GL_VERTEX_ARRAY);
3355 glDisable(GL_FRAGMENT_PROGRAM_ARB);
3356#endif
3357}
3358
3359void QOpenGLPaintEnginePrivate::drawOffscreenPath(const QPainterPath &path)
3360{
3361#ifdef Q_WS_QWS
3362 Q_UNUSED(path);
3363#else
3364 DEBUG_ONCE_STR("QOpenGLPaintEnginePrivate::drawOffscreenPath()");
3365
3366 disableClipping();
3367
3368 GLuint program = qt_gl_program_cache()->getProgram(device->context(),
3369 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
3370 QGLPathMaskGenerator maskGenerator(path, matrix, offscreen, program);
3371 addItem(qt_mask_texture_cache()->getMask(maskGenerator, this));
3372
3373 enableClipping();
3374#endif
3375}
3376
3377void QOpenGLPaintEnginePrivate::drawFastRect(const QRectF &r)
3378{
3379 Q_Q(QOpenGLPaintEngine);
3380 DEBUG_ONCE_STR("QOpenGLPaintEngine::drawRects(): drawing fast rect");
3381
3382 q_vertexType vertexArray[10];
3383 qt_add_rect_to_array(r, vertexArray);
3384
3385 if (has_pen)
3386 QOpenGLCoordinateOffset::enableOffset(this);
3387
3388 if (has_brush) {
3389 flushDrawQueue();
3390
3391 bool temp = high_quality_antialiasing;
3392 high_quality_antialiasing = false;
3393
3394 q->updateCompositionMode(composition_mode);
3395
3396 setGradientOps(cbrush, r);
3397
3398 bool fast_style = current_style == Qt::LinearGradientPattern
3399 || current_style == Qt::SolidPattern;
3400
3401 if (fast_style && has_fast_composition_mode) {
3402 glEnableClientState(GL_VERTEX_ARRAY);
3403 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3404 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3405 glDisableClientState(GL_VERTEX_ARRAY);
3406 } else {
3407 composite(r);
3408 }
3409
3410 high_quality_antialiasing = temp;
3411
3412 q->updateCompositionMode(composition_mode);
3413 }
3414
3415 if (has_pen) {
3416 if (has_fast_pen && !high_quality_antialiasing) {
3417 setGradientOps(cpen.brush(), r);
3418
3419 vertexArray[8] = vertexArray[0];
3420 vertexArray[9] = vertexArray[1];
3421
3422 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3423 glEnableClientState(GL_VERTEX_ARRAY);
3424 glDrawArrays(GL_LINE_STRIP, 0, 5);
3425 glDisableClientState(GL_VERTEX_ARRAY);
3426 } else {
3427 QPainterPath path;
3428 path.setFillRule(Qt::WindingFill);
3429
3430 qreal left = r.left();
3431 qreal right = r.right();
3432 qreal top = r.top();
3433 qreal bottom = r.bottom();
3434
3435 path.moveTo(left, top);
3436 path.lineTo(right, top);
3437 path.lineTo(right, bottom);
3438 path.lineTo(left, bottom);
3439 path.lineTo(left, top);
3440
3441 strokePath(path, false);
3442 }
3443
3444 QOpenGLCoordinateOffset::disableOffset(this);
3445 }
3446}
3447
3448bool QOpenGLPaintEnginePrivate::isFastRect(const QRectF &rect)
3449{
3450 if (matrix.type() < QTransform::TxRotate) {
3451 QRectF r = matrix.mapRect(rect);
3452 return r.topLeft().toPoint() == r.topLeft()
3453 && r.bottomRight().toPoint() == r.bottomRight();
3454 }
3455
3456 return false;
3457}
3458
3459void QOpenGLPaintEngine::drawRects(const QRect *rects, int rectCount)
3460{
3461 struct RectF {
3462 qreal x;
3463 qreal y;
3464 qreal w;
3465 qreal h;
3466 };
3467 Q_ASSERT(sizeof(RectF) == sizeof(QRectF));
3468 RectF fr[256];
3469 while (rectCount) {
3470 int i = 0;
3471 while (i < rectCount && i < 256) {
3472 fr[i].x = rects[i].x();
3473 fr[i].y = rects[i].y();
3474 fr[i].w = rects[i].width();
3475 fr[i].h = rects[i].height();
3476 ++i;
3477 }
3478 drawRects((QRectF *)(void *)fr, i);
3479 rects += i;
3480 rectCount -= i;
3481 }
3482}
3483
3484void QOpenGLPaintEngine::drawRects(const QRectF *rects, int rectCount)
3485{
3486 Q_D(QOpenGLPaintEngine);
3487
3488 if (d->use_emulation) {
3489 QPaintEngineEx::drawRects(rects, rectCount);
3490 return;
3491 }
3492
3493 for (int i=0; i<rectCount; ++i) {
3494 const QRectF &r = rects[i];
3495
3496 // optimization for rects which can be drawn aliased
3497 if (!d->high_quality_antialiasing || d->isFastRect(r)) {
3498 d->drawFastRect(r);
3499 } else {
3500 QPainterPath path;
3501 path.addRect(r);
3502
3503 if (d->has_brush) {
3504 d->disableClipping();
3505 GLuint program = qt_gl_program_cache()->getProgram(d->device->context(),
3506 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
3507
3508 if (d->matrix.type() >= QTransform::TxProject) {
3509 QGLPathMaskGenerator maskGenerator(path, d->matrix, d->offscreen, program);
3510 d->addItem(qt_mask_texture_cache()->getMask(maskGenerator, d));
3511 } else {
3512 QGLRectMaskGenerator maskGenerator(path, d->matrix, d->offscreen, program);
3513 d->addItem(qt_mask_texture_cache()->getMask(maskGenerator, d));
3514 }
3515
3516 d->enableClipping();
3517 }
3518
3519 if (d->has_pen) {
3520 if (d->has_fast_pen)
3521 d->strokeLines(path);
3522 else
3523 d->strokePath(path, false);
3524 }
3525 }
3526 }
3527}
3528
3529static void addQuadAsTriangle(q_vertexType *quad, q_vertexType *triangle)
3530{
3531 triangle[0] = quad[0];
3532 triangle[1] = quad[1];
3533
3534 triangle[2] = quad[2];
3535 triangle[3] = quad[3];
3536
3537 triangle[4] = quad[4];
3538 triangle[5] = quad[5];
3539
3540 triangle[6] = quad[4];
3541 triangle[7] = quad[5];
3542
3543 triangle[8] = quad[6];
3544 triangle[9] = quad[7];
3545
3546 triangle[10] = quad[0];
3547 triangle[11] = quad[1];
3548}
3549
3550void QOpenGLPaintEngine::drawPoints(const QPoint *points, int pointCount)
3551{
3552 Q_ASSERT(sizeof(QT_PointF) == sizeof(QPointF));
3553 QT_PointF fp[256];
3554 while (pointCount) {
3555 int i = 0;
3556 while (i < pointCount && i < 256) {
3557 fp[i].x = points[i].x();
3558 fp[i].y = points[i].y();
3559 ++i;
3560 }
3561 drawPoints((QPointF *)(void *)fp, i);
3562 points += i;
3563 pointCount -= i;
3564 }
3565}
3566
3567void QOpenGLPaintEngine::drawPoints(const QPointF *points, int pointCount)
3568{
3569 Q_D(QOpenGLPaintEngine);
3570
3571 if (d->use_emulation) {
3572 QPaintEngineEx::drawPoints(points, pointCount);
3573 return;
3574 }
3575
3576 d->setGradientOps(d->cpen.brush(), QRectF());
3577
3578 if (!d->cpen.isCosmetic() || d->high_quality_antialiasing) {
3579 Qt::PenCapStyle capStyle = d->cpen.capStyle();
3580 if (capStyle == Qt::FlatCap)
3581 d->cpen.setCapStyle(Qt::SquareCap);
3582 QPaintEngine::drawPoints(points, pointCount);
3583 d->cpen.setCapStyle(capStyle);
3584 return;
3585 }
3586
3587 d->flushDrawQueue();
3588
3589 if (d->has_fast_pen) {
3590 QVarLengthArray<q_vertexType> vertexArray(6 * pointCount);
3591
3592 glMatrixMode(GL_MODELVIEW);
3593 glPushMatrix();
3594 glLoadIdentity();
3595
3596 int j = 0;
3597 for (int i = 0; i < pointCount; ++i) {
3598 QPointF mapped = d->matrix.map(points[i]);
3599
3600 qreal xf = qRound(mapped.x());
3601 qreal yf = qRound(mapped.y());
3602
3603 q_vertexType x = f2vt(xf);
3604 q_vertexType y = f2vt(yf);
3605
3606 vertexArray[j++] = x;
3607 vertexArray[j++] = y - f2vt(0.5);
3608
3609 vertexArray[j++] = x + f2vt(1.5);
3610 vertexArray[j++] = y + f2vt(1.0);
3611
3612 vertexArray[j++] = x;
3613 vertexArray[j++] = y + f2vt(1.0);
3614 }
3615
3616 glEnableClientState(GL_VERTEX_ARRAY);
3617
3618 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3619 glDrawArrays(GL_TRIANGLES, 0, pointCount*3);
3620
3621 glDisableClientState(GL_VERTEX_ARRAY);
3622
3623 glPopMatrix();
3624 return;
3625 }
3626
3627 const qreal *vertexArray = reinterpret_cast<const qreal*>(&points[0]);
3628
3629 if (sizeof(qreal) == sizeof(double)) {
3630 Q_ASSERT(sizeof(QPointF) == 16);
3631 glVertexPointer(2, GL_DOUBLE, 0, vertexArray);
3632 }
3633 else {
3634 Q_ASSERT(sizeof(QPointF) == 8);
3635 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3636 }
3637
3638 glEnableClientState(GL_VERTEX_ARRAY);
3639 glDrawArrays(GL_POINTS, 0, pointCount);
3640 glDisableClientState(GL_VERTEX_ARRAY);
3641}
3642
3643void QOpenGLPaintEngine::drawLines(const QLine *lines, int lineCount)
3644{
3645 struct PointF {
3646 qreal x;
3647 qreal y;
3648 };
3649 struct LineF {
3650 PointF p1;
3651 PointF p2;
3652 };
3653 Q_ASSERT(sizeof(PointF) == sizeof(QPointF));
3654 Q_ASSERT(sizeof(LineF) == sizeof(QLineF));
3655 LineF fl[256];
3656 while (lineCount) {
3657 int i = 0;
3658 while (i < lineCount && i < 256) {
3659 fl[i].p1.x = lines[i].x1();
3660 fl[i].p1.y = lines[i].y1();
3661 fl[i].p2.x = lines[i].x2();
3662 fl[i].p2.y = lines[i].y2();
3663 ++i;
3664 }
3665 drawLines((QLineF *)(void *)fl, i);
3666 lines += i;
3667 lineCount -= i;
3668 }
3669}
3670
3671void QOpenGLPaintEngine::drawLines(const QLineF *lines, int lineCount)
3672{
3673 Q_D(QOpenGLPaintEngine);
3674
3675 if (d->use_emulation) {
3676 QPaintEngineEx::drawLines(lines, lineCount);
3677 return;
3678 }
3679
3680 if (d->has_pen) {
3681 QOpenGLCoordinateOffset offset(d);
3682 if (d->has_fast_pen && !d->high_quality_antialiasing) {
3683 //### gradient resolving on lines isn't correct
3684 d->setGradientOps(d->cpen.brush(), QRectF());
3685
3686 bool useRects = false;
3687 // scale or 90 degree rotation?
3688 if (d->matrix.type() <= QTransform::TxTranslate
3689 || (!d->cpen.isCosmetic()
3690 && (d->matrix.type() <= QTransform::TxScale
3691 || (d->matrix.type() == QTransform::TxRotate
3692 && d->matrix.m11() == 0 && d->matrix.m22() == 0)))) {
3693 useRects = true;
3694 for (int i = 0; i < lineCount; ++i) {
3695 if (lines[i].p1().x() != lines[i].p2().x()
3696 && lines[i].p1().y() != lines[i].p2().y()) {
3697 useRects = false;
3698 break;
3699 }
3700 }
3701 }
3702
3703 q_vertexType endCap = f2vt(d->cpen.capStyle() == Qt::FlatCap ? 0 : 0.5);
3704 if (useRects) {
3705 QVarLengthArray<q_vertexType> vertexArray(12 * lineCount);
3706
3707 q_vertexType quad[8];
3708 for (int i = 0; i < lineCount; ++i) {
3709 q_vertexType x1 = f2vt(lines[i].x1());
3710 q_vertexType x2 = f2vt(lines[i].x2());
3711 q_vertexType y1 = f2vt(lines[i].y1());
3712 q_vertexType y2 = f2vt(lines[i].y2());
3713
3714 if (x1 == x2) {
3715 if (y1 > y2)
3716 qSwap(y1, y2);
3717
3718 quad[0] = x1 - f2vt(0.5);
3719 quad[1] = y1 - endCap;
3720
3721 quad[2] = x1 + f2vt(0.5);
3722 quad[3] = y1 - endCap;
3723
3724 quad[4] = x1 + f2vt(0.5);
3725 quad[5] = y2 + endCap;
3726
3727 quad[6] = x1 - f2vt(0.5);
3728 quad[7] = y2 + endCap;
3729 } else {
3730 if (x1 > x2)
3731 qSwap(x1, x2);
3732
3733 quad[0] = x1 - endCap;
3734 quad[1] = y1 + f2vt(0.5);
3735
3736 quad[2] = x1 - endCap;
3737 quad[3] = y1 - f2vt(0.5);
3738
3739 quad[4] = x2 + endCap;
3740 quad[5] = y1 - f2vt(0.5);
3741
3742 quad[6] = x2 + endCap;
3743 quad[7] = y1 + f2vt(0.5);
3744 }
3745
3746 addQuadAsTriangle(quad, &vertexArray[12*i]);
3747 }
3748
3749 glEnableClientState(GL_VERTEX_ARRAY);
3750
3751 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3752 glDrawArrays(GL_TRIANGLES, 0, lineCount*6);
3753
3754 glDisableClientState(GL_VERTEX_ARRAY);
3755 } else {
3756 QVarLengthArray<q_vertexType> vertexArray(4 * lineCount);
3757 for (int i = 0; i < lineCount; ++i) {
3758 const QPointF a = lines[i].p1();
3759 vertexArray[4*i] = f2vt(lines[i].x1());
3760 vertexArray[4*i+1] = f2vt(lines[i].y1());
3761 vertexArray[4*i+2] = f2vt(lines[i].x2());
3762 vertexArray[4*i+3] = f2vt(lines[i].y2());
3763 }
3764
3765 glEnableClientState(GL_VERTEX_ARRAY);
3766
3767 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3768 glDrawArrays(GL_LINES, 0, lineCount*2);
3769
3770 glVertexPointer(2, q_vertexTypeEnum, 4*sizeof(q_vertexType), vertexArray.constData() + 2);
3771 glDrawArrays(GL_POINTS, 0, lineCount);
3772
3773 glDisableClientState(GL_VERTEX_ARRAY);
3774 }
3775 } else {
3776 QPainterPath path;
3777 path.setFillRule(Qt::WindingFill);
3778 for (int i=0; i<lineCount; ++i) {
3779 const QLineF &l = lines[i];
3780
3781 if (l.p1() == l.p2()) {
3782 if (d->cpen.capStyle() != Qt::FlatCap) {
3783 QPointF p = l.p1();
3784 drawPoints(&p, 1);
3785 }
3786 continue;
3787 }
3788
3789 path.moveTo(l.x1(), l.y1());
3790 path.lineTo(l.x2(), l.y2());
3791 }
3792
3793 if (d->has_fast_pen && d->high_quality_antialiasing)
3794 d->strokeLines(path);
3795 else
3796 d->strokePath(path, false);
3797 }
3798 }
3799}
3800
3801void QOpenGLPaintEngine::drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
3802{
3803 Q_ASSERT(sizeof(QT_PointF) == sizeof(QPointF));
3804 QVarLengthArray<QT_PointF> p(pointCount);
3805 for (int i=0; i<pointCount; ++i) {
3806 p[i].x = points[i].x();
3807 p[i].y = points[i].y();
3808 }
3809 drawPolygon((QPointF *)p.data(), pointCount, mode);
3810}
3811
3812void QOpenGLPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
3813{
3814 Q_D(QOpenGLPaintEngine);
3815 if(pointCount < 2)
3816 return;
3817
3818 if (d->use_emulation) {
3819 QPaintEngineEx::drawPolygon(points, pointCount, mode);
3820 return;
3821 }
3822
3823 QRectF bounds;
3824 if ((mode == ConvexMode && !d->high_quality_antialiasing && state()->brushNeedsResolving()) ||
3825 ((d->has_fast_pen && !d->high_quality_antialiasing) && state()->penNeedsResolving())) {
3826 qreal minx = points[0].x(), miny = points[0].y(),
3827 maxx = points[0].x(), maxy = points[0].y();
3828 for (int i = 1; i < pointCount; ++i) {
3829 const QPointF &pt = points[i];
3830 if (minx > pt.x())
3831 minx = pt.x();
3832 if (miny > pt.y())
3833 miny = pt.y();
3834 if (maxx < pt.x())
3835 maxx = pt.x();
3836 if (maxy < pt.y())
3837 maxy = pt.y();
3838 }
3839 bounds = QRectF(minx, maxx, maxx-minx, maxy-miny);
3840 }
3841
3842 QOpenGLCoordinateOffset offset(d);
3843
3844 if (d->has_brush && mode != PolylineMode) {
3845 if (mode == ConvexMode && !d->high_quality_antialiasing) {
3846 //### resolving on polygon from points isn't correct
3847 d->setGradientOps(d->cbrush, bounds);
3848
3849 const qreal *vertexArray = reinterpret_cast<const qreal*>(&points[0]);
3850
3851 if (sizeof(qreal) == sizeof(double)) {
3852 Q_ASSERT(sizeof(QPointF) == 16);
3853 glVertexPointer(2, GL_DOUBLE, 0, vertexArray);
3854 }
3855 else {
3856 Q_ASSERT(sizeof(QPointF) == 8);
3857 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3858 }
3859
3860 glEnableClientState(GL_VERTEX_ARRAY);
3861 glDrawArrays(GL_TRIANGLE_FAN, 0, pointCount);
3862 glDisableClientState(GL_VERTEX_ARRAY);
3863 } else {
3864 QPainterPath path;
3865 path.setFillRule(mode == WindingMode ? Qt::WindingFill : Qt::OddEvenFill);
3866 path.moveTo(points[0]);
3867 for (int i=1; i<pointCount; ++i)
3868 path.lineTo(points[i]);
3869 d->fillPath(path);
3870 }
3871 }
3872
3873 if (d->has_pen) {
3874 if (d->has_fast_pen && !d->high_quality_antialiasing) {
3875 d->setGradientOps(d->cpen.brush(), bounds);
3876 QVarLengthArray<q_vertexType> vertexArray(pointCount*2 + 2);
3877 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3878 int i;
3879 for (i=0; i<pointCount; ++i) {
3880 vertexArray[i*2] = f2vt(points[i].x());
3881 vertexArray[i*2+1] = f2vt(points[i].y());
3882 }
3883
3884 glEnableClientState(GL_VERTEX_ARRAY);
3885 if (mode != PolylineMode) {
3886 vertexArray[i*2] = vertexArray[0];
3887 vertexArray[i*2+1] = vertexArray[1];
3888 glDrawArrays(GL_LINE_STRIP, 0, pointCount+1);
3889 } else {
3890 glDrawArrays(GL_LINE_STRIP, 0, pointCount);
3891 glDrawArrays(GL_POINTS, pointCount-1, 1);
3892 }
3893 glDisableClientState(GL_VERTEX_ARRAY);
3894 } else {
3895 QPainterPath path(points[0]);
3896 for (int i = 1; i < pointCount; ++i)
3897 path.lineTo(points[i]);
3898 if (mode != PolylineMode)
3899 path.lineTo(points[0]);
3900
3901 if (d->has_fast_pen)
3902 d->strokeLines(path);
3903 else
3904 d->strokePath(path, true);
3905 }
3906 }
3907}
3908
3909void QOpenGLPaintEnginePrivate::strokeLines(const QPainterPath &path)
3910{
3911 DEBUG_ONCE_STR("QOpenGLPaintEnginePrivate::strokeLines()");
3912
3913 qreal penWidth = cpen.widthF();
3914
3915 GLuint program = qt_gl_program_cache()->getProgram(device->context(),
3916 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
3917 QGLLineMaskGenerator maskGenerator(path, matrix, penWidth == 0 ? 1.0 : penWidth,
3918 offscreen, program);
3919
3920 disableClipping();
3921
3922 QBrush temp = cbrush;
3923 QPointF origin = brush_origin;
3924
3925 cbrush = cpen.brush();
3926 brush_origin = QPointF();
3927
3928 addItem(qt_mask_texture_cache()->getMask(maskGenerator, this));
3929
3930 cbrush = temp;
3931 brush_origin = origin;
3932
3933 enableClipping();
3934}
3935
3936extern bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
3937
3938void QOpenGLPaintEnginePrivate::strokePath(const QPainterPath &path, bool use_cache)
3939{
3940 QBrush old_brush = cbrush;
3941 cbrush = cpen.brush();
3942
3943 qreal txscale = 1;
3944 if (cpen.isCosmetic() || (qt_scaleForTransform(matrix, &txscale) && txscale != 1)) {
3945 QTransform temp = matrix;
3946 matrix = QTransform();
3947 glPushMatrix();
3948
3949 if (has_antialiasing) {
3950 glLoadIdentity();
3951 } else {
3952 float offs_matrix[] =
3953 { 1, 0, 0, 0,
3954 0, 1, 0, 0,
3955 0, 0, 1, 0,
3956 0.5, 0.5, 0, 1 };
3957 glLoadMatrixf(offs_matrix);
3958 }
3959
3960 QPen pen = cpen;
3961 if (txscale != 1)
3962 pen.setWidthF(pen.widthF() * txscale);
3963 if (use_cache)
3964 fillPath(qt_opengl_stroke_cache()->getStrokedPath(temp.map(path), pen));
3965 else
3966 fillPath(strokeForPath(temp.map(path), pen));
3967
3968 glPopMatrix();
3969 matrix = temp;
3970 } else if (use_cache) {
3971 fillPath(qt_opengl_stroke_cache()->getStrokedPath(path, cpen));
3972 } else {
3973 fillPath(strokeForPath(path, cpen));
3974 }
3975
3976 cbrush = old_brush;
3977}
3978
3979void QOpenGLPaintEnginePrivate::strokePathFastPen(const QPainterPath &path, bool needsResolving)
3980{
3981#ifndef QT_OPENGL_ES
3982 QRectF bounds;
3983 if (needsResolving)
3984 bounds = path.controlPointRect();
3985 setGradientOps(cpen.brush(), bounds);
3986
3987 QBezier beziers[32];
3988 for (int i=0; i<path.elementCount(); ++i) {
3989 const QPainterPath::Element &e = path.elementAt(i);
3990 switch (e.type) {
3991 case QPainterPath::MoveToElement:
3992 if (i != 0)
3993 glEnd(); // GL_LINE_STRIP
3994 glBegin(GL_LINE_STRIP);
3995 glVertex2d(e.x, e.y);
3996
3997 break;
3998 case QPainterPath::LineToElement:
3999 glVertex2d(e.x, e.y);
4000 break;
4001
4002 case QPainterPath::CurveToElement:
4003 {
4004 QPointF sp = path.elementAt(i-1);
4005 QPointF cp2 = path.elementAt(i+1);
4006 QPointF ep = path.elementAt(i+2);
4007 i+=2;
4008
4009 qreal inverseScaleHalf = inverseScale / 2;
4010 beziers[0] = QBezier::fromPoints(sp, e, cp2, ep);
4011 QBezier *b = beziers;
4012 while (b >= beziers) {
4013 // check if we can pop the top bezier curve from the stack
4014 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
4015 qreal d;
4016 if (l > inverseScale) {
4017 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2)
4018 - (b->y4 - b->y1)*(b->x1 - b->x2) )
4019 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3)
4020 - (b->y4 - b->y1)*(b->x1 - b->x3) );
4021 d /= l;
4022 } else {
4023 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
4024 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
4025 }
4026 if (d < inverseScaleHalf || b == beziers + 31) {
4027 // good enough, we pop it off and add the endpoint
4028 glVertex2d(b->x4, b->y4);
4029 --b;
4030 } else {
4031 // split, second half of the polygon goes lower into the stack
4032 b->split(b+1, b);
4033 ++b;
4034 }
4035 }
4036 } // case CurveToElement
4037 default:
4038 break;
4039 } // end of switch
4040 }
4041 glEnd(); // GL_LINE_STRIP
4042#else
4043 // have to use vertex arrays on embedded
4044 QRectF bounds;
4045 if (needsResolving)
4046 bounds = path.controlPointRect();
4047 setGradientOps(cpen.brush(), bounds);
4048
4049 glEnableClientState(GL_VERTEX_ARRAY);
4050 tess_points.reset();
4051 QBezier beziers[32];
4052 for (int i=0; i<path.elementCount(); ++i) {
4053 const QPainterPath::Element &e = path.elementAt(i);
4054 switch (e.type) {
4055 case QPainterPath::MoveToElement:
4056 if (i != 0) {
4057 glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
4058 glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
4059 tess_points.reset();
4060 }
4061 tess_points.add(QPointF(e.x, e.y));
4062
4063 break;
4064 case QPainterPath::LineToElement:
4065 tess_points.add(QPointF(e.x, e.y));
4066 break;
4067
4068 case QPainterPath::CurveToElement:
4069 {
4070 QPointF sp = path.elementAt(i-1);
4071 QPointF cp2 = path.elementAt(i+1);
4072 QPointF ep = path.elementAt(i+2);
4073 i+=2;
4074
4075 qreal inverseScaleHalf = inverseScale / 2;
4076 beziers[0] = QBezier::fromPoints(sp, e, cp2, ep);
4077 QBezier *b = beziers;
4078 while (b >= beziers) {
4079 // check if we can pop the top bezier curve from the stack
4080 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
4081 qreal d;
4082 if (l > inverseScale) {
4083 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2)
4084 - (b->y4 - b->y1)*(b->x1 - b->x2) )
4085 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3)
4086 - (b->y4 - b->y1)*(b->x1 - b->x3) );
4087 d /= l;
4088 } else {
4089 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
4090 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
4091 }
4092 if (d < inverseScaleHalf || b == beziers + 31) {
4093 // good enough, we pop it off and add the endpoint
4094 tess_points.add(QPointF(b->x4, b->y4));
4095 --b;
4096 } else {
4097 // split, second half of the polygon goes lower into the stack
4098 b->split(b+1, b);
4099 ++b;
4100 }
4101 }
4102 } // case CurveToElement
4103 default:
4104 break;
4105 } // end of switch
4106 }
4107 glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
4108 glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
4109 glDisableClientState(GL_VERTEX_ARRAY);
4110#endif
4111}
4112
4113static bool pathClosed(const QPainterPath &path)
4114{
4115 QPointF lastMoveTo = path.elementAt(0);
4116 QPointF lastPoint = lastMoveTo;
4117
4118 for (int i = 1; i < path.elementCount(); ++i) {
4119 const QPainterPath::Element &e = path.elementAt(i);
4120 switch (e.type) {
4121 case QPainterPath::MoveToElement:
4122 if (lastMoveTo != lastPoint)
4123 return false;
4124 lastMoveTo = lastPoint = e;
4125 break;
4126 case QPainterPath::LineToElement:
4127 lastPoint = e;
4128 break;
4129 case QPainterPath::CurveToElement:
4130 lastPoint = path.elementAt(i + 2);
4131 i+=2;
4132 break;
4133 default:
4134 break;
4135 }
4136 }
4137
4138 return lastMoveTo == lastPoint;
4139}
4140
4141void QOpenGLPaintEngine::drawPath(const QPainterPath &path)
4142{
4143 Q_D(QOpenGLPaintEngine);
4144
4145 if (path.isEmpty())
4146 return;
4147
4148 if (d->use_emulation) {
4149 QPaintEngineEx::drawPath(path);
4150 return;
4151 }
4152
4153 QOpenGLCoordinateOffset offset(d);
4154
4155 if (d->has_brush) {
4156 bool path_closed = pathClosed(path);
4157
4158 bool has_thick_pen =
4159 path_closed
4160 && d->has_pen
4161 && d->cpen.style() == Qt::SolidLine
4162 && d->cpen.isSolid()
4163 && d->cpen.color().alpha() == 255
4164 && d->txop < QTransform::TxProject
4165 && d->cpen.widthF() >= 2 / qSqrt(qMin(d->matrix.m11() * d->matrix.m11()
4166 + d->matrix.m21() * d->matrix.m21(),
4167 d->matrix.m12() * d->matrix.m12()
4168 + d->matrix.m22() * d->matrix.m22()));
4169
4170 if (has_thick_pen) {
4171 DEBUG_ONCE qDebug() << "QOpenGLPaintEngine::drawPath(): Using thick pen optimization, style:" << d->cbrush.style();
4172
4173 d->flushDrawQueue();
4174
4175 bool temp = d->high_quality_antialiasing;
4176 d->high_quality_antialiasing = false;
4177
4178 updateCompositionMode(d->composition_mode);
4179
4180 d->fillPath(path);
4181
4182 d->high_quality_antialiasing = temp;
4183 updateCompositionMode(d->composition_mode);
4184 } else {
4185 d->fillPath(path);
4186 }
4187 }
4188
4189 if (d->has_pen) {
4190 if (d->has_fast_pen && !d->high_quality_antialiasing)
4191 d->strokePathFastPen(path, state()->penNeedsResolving());
4192 else
4193 d->strokePath(path, true);
4194 }
4195}
4196
4197void QOpenGLPaintEnginePrivate::drawImageAsPath(const QRectF &r, const QImage &img, const QRectF &sr)
4198{
4199 QBrush old_brush = cbrush;
4200 QPointF old_brush_origin = brush_origin;
4201
4202 qreal scaleX = r.width() / sr.width();
4203 qreal scaleY = r.height() / sr.height();
4204
4205 QTransform brush_matrix = QTransform::fromTranslate(r.left(), r.top());
4206 brush_matrix.scale(scaleX, scaleY);
4207 brush_matrix.translate(-sr.left(), -sr.top());
4208
4209 cbrush = QBrush(img);
4210 cbrush.setTransform(brush_matrix);
4211 brush_origin = QPointF();
4212
4213 QPainterPath p;
4214 p.addRect(r);
4215 fillPath(p);
4216
4217 cbrush = old_brush;
4218 brush_origin = old_brush_origin;
4219}
4220
4221void QOpenGLPaintEnginePrivate::drawTiledImageAsPath(const QRectF &r, const QImage &img, qreal sx, qreal sy,
4222 const QPointF &offset)
4223{
4224 QBrush old_brush = cbrush;
4225 QPointF old_brush_origin = brush_origin;
4226
4227 QTransform brush_matrix = QTransform::fromTranslate(r.left(), r.top());
4228 brush_matrix.scale(sx, sy);
4229 brush_matrix.translate(-offset.x(), -offset.y());
4230
4231 cbrush = QBrush(img);
4232 cbrush.setTransform(brush_matrix);
4233 brush_origin = QPointF();
4234
4235 QPainterPath p;
4236 p.addRect(r);
4237 fillPath(p);
4238
4239 cbrush = old_brush;
4240 brush_origin = old_brush_origin;
4241}
4242
4243static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
4244{
4245 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
4246}
4247
4248template <typename T>
4249static const T qSubImage(const T &image, const QRectF &src, QRectF *srcNew)
4250{
4251 const int sx1 = qMax(0, qFloor(src.left()));
4252 const int sy1 = qMax(0, qFloor(src.top()));
4253 const int sx2 = qMin(image.width(), qCeil(src.right()));
4254 const int sy2 = qMin(image.height(), qCeil(src.bottom()));
4255
4256 const T sub = image.copy(sx1, sy1, sx2 - sx1, sy2 - sy1);
4257
4258 if (srcNew)
4259 *srcNew = src.translated(-sx1, -sy1);
4260
4261 return sub;
4262}
4263
4264void QOpenGLPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
4265{
4266 Q_D(QOpenGLPaintEngine);
4267 if (pm.depth() == 1) {
4268 QPixmap tpx(pm.size());
4269 tpx.fill(Qt::transparent);
4270 QPainter p(&tpx);
4271 p.setPen(d->cpen);
4272 p.drawPixmap(0, 0, pm);
4273 p.end();
4274 drawPixmap(r, tpx, sr);
4275 return;
4276 }
4277
4278 const int sz = d->max_texture_size;
4279 if (pm.width() > sz || pm.height() > sz) {
4280 QRectF subsr;
4281 const QPixmap sub = qSubImage(pm, sr, &subsr);
4282
4283 if (sub.width() <= sz && sub.height() <= sz) {
4284 drawPixmap(r, sub, subsr);
4285 } else {
4286 const QPixmap scaled = sub.scaled(sz, sz, Qt::KeepAspectRatio);
4287 const qreal sx = scaled.width() / qreal(sub.width());
4288 const qreal sy = scaled.height() / qreal(sub.height());
4289
4290 drawPixmap(r, scaled, scaleRect(subsr, sx, sy));
4291 }
4292 return;
4293 }
4294
4295
4296 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r)))
4297 d->drawImageAsPath(r, pm.toImage(), sr);
4298 else {
4299 GLenum target = qt_gl_preferredTextureTarget();
4300 d->flushDrawQueue();
4301 QGLTexture *tex =
4302 d->device->context()->d_func()->bindTexture(pm, target, GL_RGBA,
4303 QGLContext::InternalBindOption);
4304 drawTextureRect(pm.width(), pm.height(), r, sr, target, tex);
4305 }
4306}
4307
4308void QOpenGLPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &offset)
4309{
4310 Q_D(QOpenGLPaintEngine);
4311 if (pm.depth() == 1) {
4312 QPixmap tpx(pm.size());
4313 tpx.fill(Qt::transparent);
4314 QPainter p(&tpx);
4315 p.setPen(d->cpen);
4316 p.drawPixmap(0, 0, pm);
4317 p.end();
4318 drawTiledPixmap(r, tpx, offset);
4319 return;
4320 }
4321
4322 QImage scaled;
4323 const int sz = d->max_texture_size;
4324 if (pm.width() > sz || pm.height() > sz) {
4325 int rw = qCeil(r.width());
4326 int rh = qCeil(r.height());
4327 if (rw < pm.width() && rh < pm.height()) {
4328 drawTiledPixmap(r, pm.copy(0, 0, rw, rh), offset);
4329 return;
4330 }
4331
4332 scaled = pm.toImage().scaled(sz, sz, Qt::KeepAspectRatio);
4333 }
4334
4335 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r))) {
4336 if (scaled.isNull())
4337 d->drawTiledImageAsPath(r, pm.toImage(), 1, 1, offset);
4338 else {
4339 const qreal sx = pm.width() / qreal(scaled.width());
4340 const qreal sy = pm.height() / qreal(scaled.height());
4341 d->drawTiledImageAsPath(r, scaled, sx, sy, offset);
4342 }
4343 } else {
4344 d->flushDrawQueue();
4345
4346 QGLTexture *tex;
4347 if (scaled.isNull())
4348 tex = d->device->context()->d_func()->bindTexture(pm, GL_TEXTURE_2D, GL_RGBA,
4349 QGLContext::InternalBindOption);
4350 else
4351 tex = d->device->context()->d_func()->bindTexture(scaled, GL_TEXTURE_2D, GL_RGBA,
4352 QGLContext::InternalBindOption);
4353 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, d->use_smooth_pixmap_transform);
4354
4355#ifndef QT_OPENGL_ES
4356 glPushAttrib(GL_CURRENT_BIT);
4357 glDisable(GL_TEXTURE_GEN_S);
4358#endif
4359 glColor4f(d->opacity, d->opacity, d->opacity, d->opacity);
4360 glEnable(GL_TEXTURE_2D);
4361
4362 GLdouble tc_w = r.width()/pm.width();
4363 GLdouble tc_h = r.height()/pm.height();
4364
4365 // Rotate the texture so that it is aligned correctly and the
4366 // wrapping is done correctly
4367 if (tex->options & QGLContext::InvertedYBindOption) {
4368 glMatrixMode(GL_TEXTURE);
4369 glPushMatrix();
4370 glRotatef(180.0, 0.0, 1.0, 0.0);
4371 glRotatef(180.0, 0.0, 0.0, 1.0);
4372 }
4373
4374 q_vertexType vertexArray[4*2];
4375 q_vertexType texCoordArray[4*2];
4376
4377 double offset_x = offset.x() / pm.width();
4378 double offset_y = offset.y() / pm.height();
4379
4380 qt_add_rect_to_array(r, vertexArray);
4381 qt_add_texcoords_to_array(offset_x, offset_y,
4382 tc_w + offset_x, tc_h + offset_y, texCoordArray);
4383
4384 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4385 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
4386
4387 glEnableClientState(GL_VERTEX_ARRAY);
4388 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4389 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
4390 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4391 glDisableClientState(GL_VERTEX_ARRAY);
4392 if (tex->options & QGLContext::InvertedYBindOption)
4393 glPopMatrix();
4394
4395 glDisable(GL_TEXTURE_2D);
4396#ifndef QT_OPENGL_ES
4397 glPopAttrib();
4398#endif
4399 }
4400}
4401
4402void QOpenGLPaintEngine::drawImage(const QRectF &r, const QImage &image, const QRectF &sr,
4403 Qt::ImageConversionFlags)
4404{
4405 Q_D(QOpenGLPaintEngine);
4406
4407 const int sz = d->max_texture_size;
4408 if (image.width() > sz || image.height() > sz) {
4409 QRectF subsr;
4410 const QImage sub = qSubImage(image, sr, &subsr);
4411
4412 if (sub.width() <= sz && sub.height() <= sz) {
4413 drawImage(r, sub, subsr, 0);
4414 } else {
4415 const QImage scaled = sub.scaled(sz, sz, Qt::KeepAspectRatio);
4416 const qreal sx = scaled.width() / qreal(sub.width());
4417 const qreal sy = scaled.height() / qreal(sub.height());
4418
4419 drawImage(r, scaled, scaleRect(subsr, sx, sy), 0);
4420 }
4421 return;
4422 }
4423
4424 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r)))
4425 d->drawImageAsPath(r, image, sr);
4426 else {
4427 GLenum target = qt_gl_preferredTextureTarget();
4428 d->flushDrawQueue();
4429 QGLTexture *tex =
4430 d->device->context()->d_func()->bindTexture(image, target, GL_RGBA,
4431 QGLContext::InternalBindOption);
4432 drawTextureRect(image.width(), image.height(), r, sr, target, tex);
4433 }
4434}
4435
4436void QOpenGLPaintEngine::drawTextureRect(int tx_width, int tx_height, const QRectF &r,
4437 const QRectF &sr, GLenum target, QGLTexture *tex)
4438{
4439 Q_D(QOpenGLPaintEngine);
4440#ifndef QT_OPENGL_ES
4441 glPushAttrib(GL_CURRENT_BIT);
4442 glDisable(GL_TEXTURE_GEN_S);
4443#endif
4444 glColor4f(d->opacity, d->opacity, d->opacity, d->opacity);
4445 glEnable(target);
4446 updateTextureFilter(target, GL_CLAMP_TO_EDGE, d->use_smooth_pixmap_transform);
4447
4448 qreal x1, x2, y1, y2;
4449 if (target == GL_TEXTURE_2D) {
4450 x1 = sr.x() / tx_width;
4451 x2 = x1 + sr.width() / tx_width;
4452 if (tex->options & QGLContext::InvertedYBindOption) {
4453 y1 = 1 - (sr.bottom() / tx_height);
4454 y2 = 1 - (sr.y() / tx_height);
4455 } else {
4456 y1 = sr.bottom() / tx_height;
4457 y2 = sr.y() / tx_height;
4458 }
4459 } else {
4460 x1 = sr.x();
4461 x2 = sr.right();
4462 y1 = sr.bottom();
4463 y2 = sr.y();
4464 }
4465
4466 q_vertexType vertexArray[4*2];
4467 q_vertexType texCoordArray[4*2];
4468
4469 qt_add_rect_to_array(r, vertexArray);
4470 qt_add_texcoords_to_array(x1, y2, x2, y1, texCoordArray);
4471
4472 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4473 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
4474
4475 glEnableClientState(GL_VERTEX_ARRAY);
4476 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4477 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
4478 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4479 glDisableClientState(GL_VERTEX_ARRAY);
4480
4481 glDisable(target);
4482#ifndef QT_OPENGL_ES
4483 glPopAttrib();
4484#endif
4485}
4486
4487#ifdef Q_WS_WIN
4488HDC
4489#else
4490Qt::HANDLE
4491#endif
4492QOpenGLPaintEngine::handle() const
4493{
4494 return 0;
4495}
4496
4497static const int x_margin = 1;
4498static const int y_margin = 0;
4499
4500struct QGLGlyphCoord {
4501 // stores the offset and size of a glyph texture
4502 qreal x;
4503 qreal y;
4504 qreal width;
4505 qreal height;
4506 qreal log_width;
4507 qreal log_height;
4508 QFixed x_offset;
4509 QFixed y_offset;
4510};
4511
4512struct QGLFontTexture {
4513 int x_offset; // glyph offset within the
4514 int y_offset;
4515 GLuint texture;
4516 int width;
4517 int height;
4518};
4519
4520typedef QHash<glyph_t, QGLGlyphCoord*> QGLGlyphHash;
4521typedef QHash<QFontEngine*, QGLGlyphHash*> QGLFontGlyphHash;
4522typedef QHash<quint64, QGLFontTexture*> QGLFontTexHash;
4523typedef QHash<const QGLContext*, QGLFontGlyphHash*> QGLContextHash;
4524
4525static inline void qt_delete_glyph_hash(QGLGlyphHash *hash)
4526{
4527 qDeleteAll(*hash);
4528 delete hash;
4529}
4530
4531class QGLGlyphCache : public QObject
4532{
4533 Q_OBJECT
4534public:
4535 QGLGlyphCache() : QObject(0) { current_cache = 0; }
4536 ~QGLGlyphCache();
4537 QGLGlyphCoord *lookup(QFontEngine *, glyph_t);
4538 void cacheGlyphs(QGLContext *, const QTextItemInt &, const QVarLengthArray<glyph_t> &);
4539 void cleanCache();
4540 void allocTexture(int width, int height, GLuint texture);
4541
4542public slots:
4543 void cleanupContext(const QGLContext *);
4544 void fontEngineDestroyed(QObject *);
4545 void widgetDestroyed(QObject *);
4546
4547protected:
4548 QGLGlyphHash *current_cache;
4549 QGLFontTexHash qt_font_textures;
4550 QGLContextHash qt_context_cache;
4551};
4552
4553QGLGlyphCache::~QGLGlyphCache()
4554{
4555// qDebug() << "cleaning out the QGLGlyphCache";
4556 cleanCache();
4557}
4558
4559void QGLGlyphCache::fontEngineDestroyed(QObject *o)
4560{
4561// qDebug() << "fontEngineDestroyed()";
4562 QFontEngine *fe = static_cast<QFontEngine *>(o); // safe, since only the type is used
4563 QList<const QGLContext *> keys = qt_context_cache.keys();
4564 const QGLContext *ctx = 0;
4565
4566 for (int i=0; i < keys.size(); ++i) {
4567 QGLFontGlyphHash *font_cache = qt_context_cache.value(keys.at(i));
4568 if (font_cache->find(fe) != font_cache->end()) {
4569 ctx = keys.at(i);
4570 QGLGlyphHash *cache = font_cache->take(fe);
4571 qt_delete_glyph_hash(cache);
4572 break;
4573 }
4574 }
4575
4576 quint64 font_key = (reinterpret_cast<quint64>(ctx) << 32) | reinterpret_cast<quint64>(fe);
4577 QGLFontTexture *tex = qt_font_textures.take(font_key);
4578 if (tex) {
4579#ifdef Q_WS_MAC
4580 if (
4581# ifndef QT_MAC_USE_COCOA
4582 aglGetCurrentContext() != 0
4583# else
4584 qt_current_nsopengl_context() != 0
4585# endif
4586 )
4587#endif
4588 glDeleteTextures(1, &tex->texture);
4589 delete tex;
4590 }
4591}
4592
4593void QGLGlyphCache::widgetDestroyed(QObject *)
4594{
4595// qDebug() << "widget destroyed";
4596 cleanCache(); // ###
4597}
4598
4599void QGLGlyphCache::cleanupContext(const QGLContext *ctx)
4600{
4601// qDebug() << "==> cleaning for: " << hex << ctx;
4602 QGLFontGlyphHash *font_cache = qt_context_cache.take(ctx);
4603
4604 if (font_cache) {
4605 QList<QFontEngine *> keys = font_cache->keys();
4606 for (int i=0; i < keys.size(); ++i) {
4607 QFontEngine *fe = keys.at(i);
4608 qt_delete_glyph_hash(font_cache->take(fe));
4609 quint64 font_key = (reinterpret_cast<quint64>(ctx) << 32) | reinterpret_cast<quint64>(fe);
4610 QGLFontTexture *font_tex = qt_font_textures.take(font_key);
4611 if (font_tex) {
4612#ifdef Q_WS_MAC
4613 if (
4614# ifndef QT_MAC_USE_COCOA
4615 aglGetCurrentContext() == 0
4616# else
4617 qt_current_nsopengl_context() != 0
4618# endif
4619 )
4620#endif
4621 glDeleteTextures(1, &font_tex->texture);
4622 delete font_tex;
4623 }
4624 }
4625 delete font_cache;
4626 }
4627// qDebug() << "<=== done cleaning, num tex:" << qt_font_textures.size() << "num ctx:" << qt_context_cache.size();
4628}
4629
4630void QGLGlyphCache::cleanCache()
4631{
4632 QGLFontTexHash::const_iterator it = qt_font_textures.constBegin();
4633 if (QGLContext::currentContext()) {
4634 while (it != qt_font_textures.constEnd()) {
4635#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
4636 if (qt_current_nsopengl_context() == 0)
4637 break;
4638#endif
4639 glDeleteTextures(1, &it.value()->texture);
4640 ++it;
4641 }
4642 }
4643 qDeleteAll(qt_font_textures);
4644 qt_font_textures.clear();
4645
4646 QList<const QGLContext *> keys = qt_context_cache.keys();
4647 for (int i=0; i < keys.size(); ++i) {
4648 QGLFontGlyphHash *font_cache = qt_context_cache.value(keys.at(i));
4649 QGLFontGlyphHash::Iterator it = font_cache->begin();
4650 for (; it != font_cache->end(); ++it)
4651 qt_delete_glyph_hash(it.value());
4652 font_cache->clear();
4653 }
4654 qDeleteAll(qt_context_cache);
4655 qt_context_cache.clear();
4656}
4657
4658void QGLGlyphCache::allocTexture(int width, int height, GLuint texture)
4659{
4660 uchar *tex_data = (uchar *) malloc(width*height*2);
4661 memset(tex_data, 0, width*height*2);
4662 glBindTexture(GL_TEXTURE_2D, texture);
4663#ifndef QT_OPENGL_ES
4664 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8_ALPHA8,
4665 width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
4666#else
4667 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA,
4668 width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
4669#endif
4670 free(tex_data);
4671}
4672
4673#if 0
4674// useful for debugging the glyph cache
4675static QImage getCurrentTexture(const QColor &color, QGLFontTexture *font_tex)
4676{
4677 ushort *old_tex_data = (ushort *) malloc(font_tex->width*font_tex->height*2);
4678 glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4679 QImage im(font_tex->width, font_tex->height, QImage::Format_ARGB32);
4680 for (int y=0; y<font_tex->height; ++y) {
4681 for (int x=0; x<font_tex->width; ++x) {
4682 im.setPixel(x, y, ((*(old_tex_data+x+y*font_tex->width)) << 24) | (0x00ffffff & color.rgb()));
4683 }
4684 }
4685 delete old_tex_data;
4686 return im;
4687}
4688#endif
4689
4690void QGLGlyphCache::cacheGlyphs(QGLContext *context, const QTextItemInt &ti,
4691 const QVarLengthArray<glyph_t> &glyphs)
4692{
4693 QGLContextHash::const_iterator dev_it = qt_context_cache.constFind(context);
4694 QGLFontGlyphHash *font_cache = 0;
4695 const QGLContext *context_key = 0;
4696
4697 if (dev_it == qt_context_cache.constEnd()) {
4698 // check for shared contexts
4699 QList<const QGLContext *> contexts = qt_context_cache.keys();
4700 for (int i=0; i<contexts.size(); ++i) {
4701 const QGLContext *ctx = contexts.at(i);
4702 if (ctx != context && QGLContext::areSharing(context, ctx)) {
4703 context_key = ctx;
4704 dev_it = qt_context_cache.constFind(context_key);
4705 break;
4706 }
4707 }
4708 }
4709
4710 if (dev_it == qt_context_cache.constEnd()) {
4711 // no shared contexts either - create a new entry
4712 font_cache = new QGLFontGlyphHash;
4713// qDebug() << "new context" << context << font_cache;
4714 qt_context_cache.insert(context, font_cache);
4715 if (context->isValid() && context->device()->devType() == QInternal::Widget) {
4716 QWidget *widget = static_cast<QWidget *>(context->device());
4717 connect(widget, SIGNAL(destroyed(QObject*)), SLOT(widgetDestroyed(QObject*)));
4718 connect(QGLSignalProxy::instance(),
4719 SIGNAL(aboutToDestroyContext(const QGLContext*)),
4720 SLOT(cleanupContext(const QGLContext*)));
4721 }
4722 } else {
4723 font_cache = dev_it.value();
4724 }
4725 Q_ASSERT(font_cache != 0);
4726
4727 QGLFontGlyphHash::const_iterator cache_it = font_cache->constFind(ti.fontEngine);
4728 QGLGlyphHash *cache = 0;
4729 if (cache_it == font_cache->constEnd()) {
4730 cache = new QGLGlyphHash;
4731 font_cache->insert(ti.fontEngine, cache);
4732 connect(ti.fontEngine, SIGNAL(destroyed(QObject*)), SLOT(fontEngineDestroyed(QObject*)));
4733 } else {
4734 cache = cache_it.value();
4735 }
4736 current_cache = cache;
4737
4738 quint64 font_key = (reinterpret_cast<quint64>(context_key ? context_key : context) << 32)
4739 | reinterpret_cast<quint64>(ti.fontEngine);
4740 QGLFontTexHash::const_iterator it = qt_font_textures.constFind(font_key);
4741 QGLFontTexture *font_tex;
4742 if (it == qt_font_textures.constEnd()) {
4743 GLuint font_texture;
4744 glGenTextures(1, &font_texture);
4745 GLint tex_height = qt_next_power_of_two(qRound(ti.ascent.toReal() + ti.descent.toReal())+2);
4746 GLint tex_width = qt_next_power_of_two(tex_height*30); // ###
4747 GLint max_tex_size;
4748 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
4749 Q_ASSERT(max_tex_size > 0);
4750 if (tex_width > max_tex_size)
4751 tex_width = max_tex_size;
4752 allocTexture(tex_width, tex_height, font_texture);
4753 font_tex = new QGLFontTexture;
4754 font_tex->texture = font_texture;
4755 font_tex->x_offset = x_margin;
4756 font_tex->y_offset = y_margin;
4757 font_tex->width = tex_width;
4758 font_tex->height = tex_height;
4759// qDebug() << "new font tex - width:" << tex_width << "height:"<< tex_height
4760// << hex << "tex id:" << font_tex->texture << "key:" << font_key << "num cached:" << qt_font_textures.size();
4761 qt_font_textures.insert(font_key, font_tex);
4762 } else {
4763 font_tex = it.value();
4764 glBindTexture(GL_TEXTURE_2D, font_tex->texture);
4765 }
4766
4767 for (int i=0; i< glyphs.size(); ++i) {
4768 QGLGlyphHash::const_iterator it = cache->constFind(glyphs[i]);
4769 if (it == cache->constEnd()) {
4770 // render new glyph and put it in the cache
4771 glyph_metrics_t metrics = ti.fontEngine->boundingBox(glyphs[i]);
4772 int glyph_width = qRound(metrics.width.toReal())+2;
4773 int glyph_height = qRound(ti.ascent.toReal() + ti.descent.toReal())+2;
4774
4775 if (font_tex->x_offset + glyph_width + x_margin > font_tex->width) {
4776 int strip_height = qt_next_power_of_two(qRound(ti.ascent.toReal() + ti.descent.toReal())+2);
4777 font_tex->x_offset = x_margin;
4778 font_tex->y_offset += strip_height;
4779 if (font_tex->y_offset >= font_tex->height) {
4780 // get hold of the old font texture
4781 uchar *old_tex_data = (uchar *) malloc(font_tex->width*font_tex->height*2);
4782 int old_tex_height = font_tex->height;
4783#ifndef QT_OPENGL_ES
4784 glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4785#endif
4786
4787 // realloc a larger texture
4788 glDeleteTextures(1, &font_tex->texture);
4789 glGenTextures(1, &font_tex->texture);
4790 font_tex->height = qt_next_power_of_two(font_tex->height + strip_height);
4791 allocTexture(font_tex->width, font_tex->height, font_tex->texture);
4792
4793 // write back the old texture data
4794 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, font_tex->width, old_tex_height,
4795 GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4796 free(old_tex_data);
4797
4798 // update the texture coords and the y offset for the existing glyphs in
4799 // the cache, because of the texture size change
4800 QGLGlyphHash::iterator it = cache->begin();
4801 while (it != cache->end()) {
4802 it.value()->height = (it.value()->height * old_tex_height) / font_tex->height;
4803 it.value()->y = (it.value()->y * old_tex_height) / font_tex->height;
4804 ++it;
4805 }
4806 }
4807 }
4808
4809 QImage glyph_im(ti.fontEngine->alphaMapForGlyph(glyphs[i]));
4810 glyph_im = glyph_im.convertToFormat(QImage::Format_Indexed8);
4811 glyph_width = glyph_im.width();
4812 Q_ASSERT(glyph_width >= 0);
4813 // pad the glyph width to an even number
4814 if (glyph_width%2 != 0)
4815 ++glyph_width;
4816
4817 QGLGlyphCoord *qgl_glyph = new QGLGlyphCoord;
4818 qgl_glyph->x = qreal(font_tex->x_offset) / font_tex->width;
4819 qgl_glyph->y = qreal(font_tex->y_offset) / font_tex->height;
4820 qgl_glyph->width = qreal(glyph_width) / font_tex->width;
4821 qgl_glyph->height = qreal(glyph_height) / font_tex->height;
4822 qgl_glyph->log_width = qreal(glyph_width);
4823 qgl_glyph->log_height = qgl_glyph->height * font_tex->height;
4824#ifdef Q_WS_MAC
4825 qgl_glyph->x_offset = -metrics.x + 1;
4826 qgl_glyph->y_offset = metrics.y - 2;
4827#else
4828 qgl_glyph->x_offset = -metrics.x;
4829 qgl_glyph->y_offset = metrics.y;
4830#endif
4831
4832 if (!glyph_im.isNull()) {
4833
4834 int idx = 0;
4835 uchar *tex_data = (uchar *) malloc(glyph_width*glyph_im.height()*2);
4836 memset(tex_data, 0, glyph_width*glyph_im.height()*2);
4837
4838 for (int y=0; y<glyph_im.height(); ++y) {
4839 uchar *s = (uchar *) glyph_im.scanLine(y);
4840 for (int x=0; x<glyph_im.width(); ++x) {
4841 uchar alpha = qAlpha(glyph_im.color(*s));
4842 tex_data[idx] = alpha;
4843 tex_data[idx+1] = alpha;
4844 ++s;
4845 idx += 2;
4846 }
4847 if (glyph_im.width()%2 != 0)
4848 idx += 2;
4849 }
4850 glTexSubImage2D(GL_TEXTURE_2D, 0, font_tex->x_offset, font_tex->y_offset,
4851 glyph_width, glyph_im.height(),
4852 GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
4853 free(tex_data);
4854 }
4855 if (font_tex->x_offset + glyph_width + x_margin > font_tex->width) {
4856 font_tex->x_offset = x_margin;
4857 font_tex->y_offset += glyph_height + y_margin;
4858 } else {
4859 font_tex->x_offset += glyph_width + x_margin;
4860 }
4861
4862 cache->insert(glyphs[i], qgl_glyph);
4863 }
4864 }
4865}
4866
4867QGLGlyphCoord *QGLGlyphCache::lookup(QFontEngine *, glyph_t g)
4868{
4869 Q_ASSERT(current_cache != 0);
4870 // ### careful here
4871 QGLGlyphHash::const_iterator it = current_cache->constFind(g);
4872 if (it == current_cache->constEnd())
4873 return 0;
4874 else
4875 return it.value();
4876}
4877
4878Q_GLOBAL_STATIC(QGLGlyphCache, qt_glyph_cache)
4879
4880//
4881// assumption: the context that this is called for has to be the
4882// current context
4883//
4884void qgl_cleanup_glyph_cache(QGLContext *ctx)
4885{
4886 qt_glyph_cache()->cleanupContext(ctx);
4887}
4888
4889void QOpenGLPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
4890{
4891 Q_D(QOpenGLPaintEngine);
4892
4893 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
4894
4895 // fall back to drawing a polygon if the scale factor is large, or
4896 // we use a gradient pen
4897 if ((d->matrix.det() > 1) || (d->pen_brush_style >= Qt::LinearGradientPattern
4898 && d->pen_brush_style <= Qt::ConicalGradientPattern)) {
4899 QPaintEngine::drawTextItem(p, textItem);
4900 return;
4901 }
4902
4903 d->flushDrawQueue();
4904
4905 // add the glyphs used to the glyph texture cache
4906 QVarLengthArray<QFixedPoint> positions;
4907 QVarLengthArray<glyph_t> glyphs;
4908 QTransform matrix = QTransform::fromTranslate(qRound(p.x()), qRound(p.y()));
4909 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
4910
4911 // make sure the glyphs we want to draw are in the cache
4912 qt_glyph_cache()->cacheGlyphs(d->device->context(), ti, glyphs);
4913
4914 d->setGradientOps(Qt::SolidPattern, QRectF()); // turns off gradient ops
4915 qt_glColor4ubv(d->pen_color);
4916 glEnable(GL_TEXTURE_2D);
4917
4918#ifdef Q_WS_QWS
4919 // XXX: it is necessary to disable alpha writes on GLES/embedded because we don't want
4920 // text rendering to update the alpha in the window surface.
4921 // XXX: This may not be needed as this behavior does seem to be caused by driver bug
4922 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
4923#endif
4924
4925 // do the actual drawing
4926 q_vertexType vertexArray[4*2];
4927 q_vertexType texCoordArray[4*2];
4928
4929 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4930 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
4931
4932 glEnableClientState(GL_VERTEX_ARRAY);
4933 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4934 bool antialias = !(ti.fontEngine->fontDef.styleStrategy & QFont::NoAntialias);
4935 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, antialias ? GL_LINEAR : GL_NEAREST);
4936 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, antialias ? GL_LINEAR : GL_NEAREST);
4937
4938 for (int i=0; i< glyphs.size(); ++i) {
4939 QGLGlyphCoord *g = qt_glyph_cache()->lookup(ti.fontEngine, glyphs[i]);
4940
4941 // we don't cache glyphs with no width/height
4942 if (!g)
4943 continue;
4944
4945 qreal x1, x2, y1, y2;
4946 x1 = g->x;
4947 y1 = g->y;
4948 x2 = x1 + g->width;
4949 y2 = y1 + g->height;
4950
4951 QPointF logical_pos((positions[i].x - g->x_offset).toReal(),
4952 (positions[i].y + g->y_offset).toReal());
4953
4954 qt_add_rect_to_array(QRectF(logical_pos, QSizeF(g->log_width, g->log_height)), vertexArray);
4955 qt_add_texcoords_to_array(x1, y1, x2, y2, texCoordArray);
4956
4957 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
4958 }
4959
4960 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4961 glDisableClientState(GL_VERTEX_ARRAY);
4962
4963 glDisable(GL_TEXTURE_2D);
4964
4965#ifdef Q_WS_QWS
4966 // XXX: This may not be needed as this behavior does seem to be caused by driver bug
4967 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
4968#endif
4969}
4970
4971
4972void QOpenGLPaintEngine::drawEllipse(const QRectF &rect)
4973{
4974#ifndef Q_WS_QWS
4975 Q_D(QOpenGLPaintEngine);
4976
4977 if (d->use_emulation) {
4978 QPaintEngineEx::drawEllipse(rect);
4979 return;
4980 }
4981
4982 if (d->high_quality_antialiasing) {
4983 if (d->has_brush) {
4984 d->disableClipping();
4985
4986 glMatrixMode(GL_MODELVIEW);
4987 glPushMatrix();
4988 glLoadIdentity();
4989
4990 GLuint program = qt_gl_program_cache()->getProgram(d->device->context(),
4991 FRAGMENT_PROGRAM_MASK_ELLIPSE_AA, 0, true);
4992 QGLEllipseMaskGenerator maskGenerator(rect,
4993 d->matrix,
4994 d->offscreen,
4995 program,
4996 mask_variable_locations[FRAGMENT_PROGRAM_MASK_ELLIPSE_AA]);
4997
4998 d->addItem(qt_mask_texture_cache()->getMask(maskGenerator, d));
4999
5000 d->enableClipping();
5001
5002 glMatrixMode(GL_MODELVIEW);
5003 glPopMatrix();
5004 }
5005
5006 if (d->has_pen) {
5007 QPainterPath path;
5008 path.addEllipse(rect);
5009
5010 d->strokePath(path, false);
5011 }
5012 } else {
5013 DEBUG_ONCE_STR("QOpenGLPaintEngine::drawEllipse(): falling back to drawPath()");
5014
5015 QPainterPath path;
5016 path.addEllipse(rect);
5017 drawPath(path);
5018 }
5019#else
5020 QPaintEngineEx::drawEllipse(rect);
5021#endif
5022}
5023
5024
5025void QOpenGLPaintEnginePrivate::updateFragmentProgramData(int locations[])
5026{
5027#ifdef Q_WS_QWS
5028 Q_UNUSED(locations);
5029#else
5030 QGL_FUNC_CONTEXT;
5031
5032 QSize sz = offscreen.offscreenSize();
5033
5034 float inv_mask_size_data[4] = { 1.0f / sz.width(), 1.0f / sz.height(), 0.0f, 0.0f };
5035
5036 sz = drawable_texture_size;
5037
5038 float inv_dst_size_data[4] = { 1.0f / sz.width(), 1.0f / sz.height(), 0.0f, 0.0f };
5039
5040 // default inv size 0.125f == 1.0f / 8.0f for pattern brushes
5041 float inv_brush_texture_size_data[4] = { 0.125f, 0.125f };
5042
5043 // texture patterns have their own size
5044 if (current_style == Qt::TexturePattern) {
5045 QSize sz = cbrush.texture().size();
5046
5047 inv_brush_texture_size_data[0] = 1.0f / sz.width();
5048 inv_brush_texture_size_data[1] = 1.0f / sz.height();
5049 }
5050
5051 for (unsigned int i = 0; i < num_fragment_variables; ++i) {
5052 int location = locations[i];
5053
5054 if (location < 0)
5055 continue;
5056
5057 switch (i) {
5058 case VAR_ANGLE:
5059 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, angle_data);
5060 break;
5061 case VAR_LINEAR:
5062 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, linear_data);
5063 break;
5064 case VAR_FMP:
5065 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, fmp_data);
5066 break;
5067 case VAR_FMP2_M_RADIUS2:
5068 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, fmp2_m_radius2_data);
5069 break;
5070 case VAR_INV_MASK_SIZE:
5071 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_mask_size_data);
5072 break;
5073 case VAR_INV_DST_SIZE:
5074 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_dst_size_data);
5075 break;
5076 case VAR_INV_MATRIX_M0:
5077 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[0]);
5078 break;
5079 case VAR_INV_MATRIX_M1:
5080 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[1]);
5081 break;
5082 case VAR_INV_MATRIX_M2:
5083 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[2]);
5084 break;
5085 case VAR_PORTERDUFF_AB:
5086 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, porterduff_ab_data);
5087 break;
5088 case VAR_PORTERDUFF_XYZ:
5089 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, porterduff_xyz_data);
5090 break;
5091 case VAR_INV_BRUSH_TEXTURE_SIZE:
5092 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_brush_texture_size_data);
5093 break;
5094 case VAR_MASK_OFFSET:
5095 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, mask_offset_data);
5096 break;
5097 case VAR_MASK_CHANNEL:
5098 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, mask_channel_data);
5099 break;
5100 case VAR_DST_TEXTURE:
5101 case VAR_MASK_TEXTURE:
5102 case VAR_PALETTE:
5103 case VAR_BRUSH_TEXTURE:
5104 // texture variables, not handled here
5105 break;
5106 default:
5107 qDebug() << "QOpenGLPaintEnginePrivate: Unhandled fragment variable:" << i;
5108 }
5109 }
5110#endif
5111}
5112
5113
5114void QOpenGLPaintEnginePrivate::copyDrawable(const QRectF &rect)
5115{
5116#ifdef Q_WS_QWS
5117 Q_UNUSED(rect);
5118#else
5119 ensureDrawableTexture();
5120
5121 DEBUG_ONCE qDebug() << "Refreshing drawable_texture for rectangle" << rect;
5122 QRectF screen_rect = rect.adjusted(-1, -1, 1, 1);
5123
5124 int left = qMax(0, static_cast<int>(screen_rect.left()));
5125 int width = qMin(device->size().width() - left, static_cast<int>(screen_rect.width()) + 1);
5126
5127 int bottom = qMax(0, static_cast<int>(device->size().height() - screen_rect.bottom()));
5128 int height = qMin(device->size().height() - bottom, static_cast<int>(screen_rect.height()) + 1);
5129
5130 glBindTexture(GL_TEXTURE_2D, drawable_texture);
5131 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, left, bottom, left, bottom, width, height);
5132#endif
5133}
5134
5135
5136void QOpenGLPaintEnginePrivate::composite(const QRectF &rect, const QPoint &maskOffset)
5137{
5138#ifdef Q_WS_QWS
5139 Q_UNUSED(rect);
5140 Q_UNUSED(maskOffset);
5141#else
5142 q_vertexType vertexArray[8];
5143 qt_add_rect_to_array(rect, vertexArray);
5144
5145 composite(GL_TRIANGLE_FAN, vertexArray, 4, maskOffset);
5146#endif
5147}
5148
5149
5150void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset)
5151{
5152#ifdef QT_OPENGL_ES
5153 Q_UNUSED(primitive);
5154 Q_UNUSED(vertexArray);
5155 Q_UNUSED(vertexCount);
5156 Q_UNUSED(maskOffset);
5157#else
5158 Q_Q(QOpenGLPaintEngine);
5159 QGL_FUNC_CONTEXT;
5160
5161 if (current_style == Qt::NoBrush)
5162 return;
5163
5164 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Using compositing program: fragment_brush ="
5165 << fragment_brush << ", fragment_composition_mode =" << fragment_composition_mode;
5166
5167 if (has_fast_composition_mode)
5168 q->updateCompositionMode(composition_mode);
5169 else {
5170 qreal minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
5171
5172 for (int i = 0; i < vertexCount; ++i) {
5173 qreal x = vt2f(vertexArray[2 * i]);
5174 qreal y = vt2f(vertexArray[2 * i + 1]);
5175
5176 qreal tx, ty;
5177 matrix.map(x, y, &tx, &ty);
5178
5179 minX = qMin(minX, tx);
5180 minY = qMin(minY, ty);
5181 maxX = qMax(maxX, tx);
5182 maxY = qMax(maxY, ty);
5183 }
5184
5185 QRectF r(minX, minY, maxX - minX, maxY - minY);
5186 copyDrawable(r);
5187
5188 glBlendFunc(GL_ONE, GL_ZERO);
5189 }
5190
5191 int *locations = painter_variable_locations[fragment_brush][fragment_composition_mode];
5192
5193 int texture_locations[] = { locations[VAR_DST_TEXTURE],
5194 locations[VAR_MASK_TEXTURE],
5195 locations[VAR_PALETTE] };
5196
5197 int brush_texture_location = locations[VAR_BRUSH_TEXTURE];
5198
5199 GLuint texture_targets[] = { GL_TEXTURE_2D,
5200 GL_TEXTURE_2D,
5201 GL_TEXTURE_1D };
5202
5203 GLuint textures[] = { drawable_texture,
5204 offscreen.offscreenTexture(),
5205 grad_palette };
5206
5207 const int num_textures = sizeof(textures) / sizeof(*textures);
5208
5209 Q_ASSERT(num_textures == sizeof(texture_locations) / sizeof(*texture_locations));
5210 Q_ASSERT(num_textures == sizeof(texture_targets) / sizeof(*texture_targets));
5211
5212 for (int i = 0; i < num_textures; ++i)
5213 if (texture_locations[i] >= 0) {
5214 glActiveTexture(GL_TEXTURE0 + texture_locations[i]);
5215 glBindTexture(texture_targets[i], textures[i]);
5216 }
5217
5218 if (brush_texture_location >= 0) {
5219 glActiveTexture(GL_TEXTURE0 + brush_texture_location);
5220
5221 if (current_style == Qt::TexturePattern)
5222 device->context()->d_func()->bindTexture(cbrush.textureImage(), GL_TEXTURE_2D, GL_RGBA,
5223 QGLContext::InternalBindOption);
5224 else
5225 device->context()->d_func()->bindTexture(qt_imageForBrush(current_style, false),
5226 GL_TEXTURE_2D, GL_RGBA,
5227 QGLContext::InternalBindOption);
5228
5229 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, use_smooth_pixmap_transform);
5230 }
5231
5232 glEnableClientState(GL_VERTEX_ARRAY);
5233 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
5234 glEnable(GL_FRAGMENT_PROGRAM_ARB);
5235 GLuint program = qt_gl_program_cache()->getProgram(device->context(),
5236 fragment_brush,
5237 fragment_composition_mode, false);
5238 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program);
5239
5240 mask_offset_data[0] = maskOffset.x();
5241 mask_offset_data[1] = -maskOffset.y();
5242
5243 updateFragmentProgramData(locations);
5244
5245 glDrawArrays(primitive, 0, vertexCount);
5246
5247 glDisable(GL_FRAGMENT_PROGRAM_ARB);
5248 glDisableClientState(GL_VERTEX_ARRAY);
5249
5250 for (int i = 0; i < num_textures; ++i)
5251 if (texture_locations[i] >= 0) {
5252 glActiveTexture(GL_TEXTURE0 + texture_locations[i]);
5253 glBindTexture(texture_targets[i], 0);
5254 }
5255
5256 if (brush_texture_location >= 0) {
5257 glActiveTexture(GL_TEXTURE0 + brush_texture_location);
5258 glBindTexture(GL_TEXTURE_2D, 0);
5259 }
5260
5261 glActiveTexture(GL_TEXTURE0);
5262
5263 if (!has_fast_composition_mode)
5264 q->updateCompositionMode(composition_mode);
5265#endif
5266}
5267
5268void QOpenGLPaintEnginePrivate::cacheItemErased(int channel, const QRect &rect)
5269{
5270 bool isInDrawQueue = false;
5271
5272 foreach (const QDrawQueueItem &item, drawQueue) {
5273 if (item.location.channel == channel && item.location.rect == rect) {
5274 isInDrawQueue = true;
5275 break;
5276 }
5277 }
5278
5279 if (isInDrawQueue)
5280 flushDrawQueue();
5281}
5282
5283void QOpenGLPaintEnginePrivate::addItem(const QGLMaskTextureCache::CacheLocation &location)
5284{
5285 drawQueue << QDrawQueueItem(opacity, cbrush, brush_origin, composition_mode, matrix, location);
5286}
5287
5288void QOpenGLPaintEnginePrivate::drawItem(const QDrawQueueItem &item)
5289{
5290 Q_Q(QOpenGLPaintEngine);
5291
5292 opacity = item.opacity;
5293 brush_origin = item.brush_origin;
5294 q->updateCompositionMode(item.composition_mode);
5295 matrix = item.matrix;
5296 cbrush = item.brush;
5297 brush_style = item.brush.style();
5298
5299 mask_channel_data[0] = item.location.channel == 0;
5300 mask_channel_data[1] = item.location.channel == 1;
5301 mask_channel_data[2] = item.location.channel == 2;
5302 mask_channel_data[3] = item.location.channel == 3;
5303
5304 setGradientOps(item.brush, item.location.screen_rect);
5305
5306 composite(item.location.screen_rect, item.location.rect.topLeft() - item.location.screen_rect.topLeft()
5307 - QPoint(0, offscreen.offscreenSize().height() - device->size().height()));
5308}
5309
5310void QOpenGLPaintEnginePrivate::flushDrawQueue()
5311{
5312#ifndef QT_OPENGL_ES
5313 Q_Q(QOpenGLPaintEngine);
5314
5315 offscreen.release();
5316
5317 if (!drawQueue.isEmpty()) {
5318 DEBUG_ONCE qDebug() << "QOpenGLPaintEngine::flushDrawQueue():" << drawQueue.size() << "items";
5319
5320 glPushMatrix();
5321 glLoadIdentity();
5322 qreal old_opacity = opacity;
5323 QPointF old_brush_origin = brush_origin;
5324 QPainter::CompositionMode old_composition_mode = composition_mode;
5325 QTransform old_matrix = matrix;
5326 QBrush old_brush = cbrush;
5327
5328 bool hqaa_old = high_quality_antialiasing;
5329
5330 high_quality_antialiasing = true;
5331
5332 foreach (const QDrawQueueItem &item, drawQueue)
5333 drawItem(item);
5334
5335 opacity = old_opacity;
5336 brush_origin = old_brush_origin;
5337 q->updateCompositionMode(old_composition_mode);
5338 matrix = old_matrix;
5339 cbrush = old_brush;
5340 brush_style = old_brush.style();
5341
5342 high_quality_antialiasing = hqaa_old;
5343
5344 setGLBrush(old_brush.color());
5345 qt_glColor4ubv(brush_color);
5346
5347 drawQueue.clear();
5348
5349 glPopMatrix();
5350 }
5351#endif
5352}
5353
5354void QOpenGLPaintEngine::clipEnabledChanged()
5355{
5356 Q_D(QOpenGLPaintEngine);
5357
5358 d->updateDepthClip();
5359}
5360
5361void QOpenGLPaintEngine::penChanged()
5362{
5363 updatePen(state()->pen);
5364}
5365
5366void QOpenGLPaintEngine::brushChanged()
5367{
5368 updateBrush(state()->brush, state()->brushOrigin);
5369}
5370
5371void QOpenGLPaintEngine::brushOriginChanged()
5372{
5373 updateBrush(state()->brush, state()->brushOrigin);
5374}
5375
5376void QOpenGLPaintEngine::opacityChanged()
5377{
5378 Q_D(QOpenGLPaintEngine);
5379 QPainterState *s = state();
5380 d->opacity = s->opacity;
5381 updateBrush(s->brush, s->brushOrigin);
5382 updatePen(s->pen);
5383}
5384
5385void QOpenGLPaintEngine::compositionModeChanged()
5386{
5387 updateCompositionMode(state()->composition_mode);
5388}
5389
5390void QOpenGLPaintEngine::renderHintsChanged()
5391{
5392 updateRenderHints(state()->renderHints);
5393}
5394
5395void QOpenGLPaintEngine::transformChanged()
5396{
5397 updateMatrix(state()->matrix);
5398}
5399
5400static QPainterPath painterPathFromVectorPath(const QVectorPath &path)
5401{
5402 const qreal *points = path.points();
5403 const QPainterPath::ElementType *types = path.elements();
5404
5405 QPainterPath p;
5406 if (types) {
5407 int id = 0;
5408 for (int i=0; i<path.elementCount(); ++i) {
5409 switch(types[i]) {
5410 case QPainterPath::MoveToElement:
5411 p.moveTo(QPointF(points[id], points[id+1]));
5412 id+=2;
5413 break;
5414 case QPainterPath::LineToElement:
5415 p.lineTo(QPointF(points[id], points[id+1]));
5416 id+=2;
5417 break;
5418 case QPainterPath::CurveToElement: {
5419 QPointF p1(points[id], points[id+1]);
5420 QPointF p2(points[id+2], points[id+3]);
5421 QPointF p3(points[id+4], points[id+5]);
5422 p.cubicTo(p1, p2, p3);
5423 id+=6;
5424 break;
5425 }
5426 case QPainterPath::CurveToDataElement:
5427 ;
5428 break;
5429 }
5430 }
5431 } else {
5432 p.moveTo(QPointF(points[0], points[1]));
5433 int id = 2;
5434 for (int i=1; i<path.elementCount(); ++i) {
5435 p.lineTo(QPointF(points[id], points[id+1]));
5436 id+=2;
5437 }
5438 }
5439 if (path.hints() & QVectorPath::WindingFill)
5440 p.setFillRule(Qt::WindingFill);
5441
5442 return p;
5443}
5444
5445void QOpenGLPaintEngine::fill(const QVectorPath &path, const QBrush &brush)
5446{
5447 Q_D(QOpenGLPaintEngine);
5448
5449 if (brush.style() == Qt::NoBrush)
5450 return;
5451
5452 if (!d->use_fragment_programs && needsEmulation(brush.style())) {
5453 QPainter *p = painter();
5454 QBrush oldBrush = p->brush();
5455 p->setBrush(brush);
5456 qt_draw_helper(p->d_ptr.data(), painterPathFromVectorPath(path), QPainterPrivate::FillDraw);
5457 p->setBrush(oldBrush);
5458 return;
5459 }
5460
5461 QBrush old_brush = state()->brush;
5462 updateBrush(brush, state()->brushOrigin);
5463
5464 const qreal *points = path.points();
5465 const QPainterPath::ElementType *types = path.elements();
5466 if (!types && path.shape() == QVectorPath::RectangleHint) {
5467 QRectF r(points[0], points[1], points[4]-points[0], points[5]-points[1]);
5468 QPen old_pen = state()->pen;
5469 updatePen(Qt::NoPen);
5470 drawRects(&r, 1);
5471 updatePen(old_pen);
5472 } else {
5473 d->fillPath(painterPathFromVectorPath(path));
5474 }
5475
5476 updateBrush(old_brush, state()->brushOrigin);
5477}
5478
5479template <typename T> static inline bool isRect(const T *pts, int elementCount) {
5480 return (elementCount == 5 // 5-point polygon, check for closed rect
5481 && pts[0] == pts[8] && pts[1] == pts[9] // last point == first point
5482 && pts[0] == pts[6] && pts[2] == pts[4] // x values equal
5483 && pts[1] == pts[3] && pts[5] == pts[7] // y values equal...
5484 ) ||
5485 (elementCount == 4 // 4-point polygon, check for unclosed rect
5486 && pts[0] == pts[6] && pts[2] == pts[4] // x values equal
5487 && pts[1] == pts[3] && pts[5] == pts[7] // y values equal...
5488 );
5489}
5490
5491void QOpenGLPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op)
5492{
5493 const qreal *points = path.points();
5494 const QPainterPath::ElementType *types = path.elements();
5495 if (!types && path.shape() == QVectorPath::RectangleHint) {
5496 QRectF r(points[0], points[1], points[4]-points[0], points[5]-points[1]);
5497 updateClipRegion(QRegion(r.toRect()), op);
5498 return;
5499 }
5500
5501 QPainterPath p;
5502 if (types) {
5503 int id = 0;
5504 for (int i=0; i<path.elementCount(); ++i) {
5505 switch(types[i]) {
5506 case QPainterPath::MoveToElement:
5507 p.moveTo(QPointF(points[id], points[id+1]));
5508 id+=2;
5509 break;
5510 case QPainterPath::LineToElement:
5511 p.lineTo(QPointF(points[id], points[id+1]));
5512 id+=2;
5513 break;
5514 case QPainterPath::CurveToElement: {
5515 QPointF p1(points[id], points[id+1]);
5516 QPointF p2(points[id+2], points[id+3]);
5517 QPointF p3(points[id+4], points[id+5]);
5518 p.cubicTo(p1, p2, p3);
5519 id+=6;
5520 break;
5521 }
5522 case QPainterPath::CurveToDataElement:
5523 ;
5524 break;
5525 }
5526 }
5527 } else if (!path.isEmpty()) {
5528 p.moveTo(QPointF(points[0], points[1]));
5529 int id = 2;
5530 for (int i=1; i<path.elementCount(); ++i) {
5531 p.lineTo(QPointF(points[id], points[id+1]));
5532 id+=2;
5533 }
5534 }
5535 if (path.hints() & QVectorPath::WindingFill)
5536 p.setFillRule(Qt::WindingFill);
5537
5538 updateClipRegion(QRegion(p.toFillPolygon().toPolygon(), p.fillRule()), op);
5539 return;
5540}
5541
5542void QOpenGLPaintEngine::setState(QPainterState *s)
5543{
5544 Q_D(QOpenGLPaintEngine);
5545 QOpenGLPaintEngineState *new_state = static_cast<QOpenGLPaintEngineState *>(s);
5546 QOpenGLPaintEngineState *old_state = state();
5547
5548 QPaintEngineEx::setState(s);
5549
5550 // are we in a save() ?
5551 if (s == d->last_created_state) {
5552 d->last_created_state = 0;
5553 return;
5554 }
5555
5556 if (isActive()) {
5557 if (old_state->depthClipId != new_state->depthClipId)
5558 d->updateDepthClip();
5559 penChanged();
5560 brushChanged();
5561 opacityChanged();
5562 compositionModeChanged();
5563 renderHintsChanged();
5564 transformChanged();
5565 }
5566}
5567
5568QPainterState *QOpenGLPaintEngine::createState(QPainterState *orig) const
5569{
5570 const Q_D(QOpenGLPaintEngine);
5571
5572 QOpenGLPaintEngineState *s;
5573 if (!orig)
5574 s = new QOpenGLPaintEngineState();
5575 else
5576 s = new QOpenGLPaintEngineState(*static_cast<QOpenGLPaintEngineState *>(orig));
5577
5578 d->last_created_state = s;
5579 return s;
5580}
5581
5582//
5583// QOpenGLPaintEngineState
5584//
5585
5586QOpenGLPaintEngineState::QOpenGLPaintEngineState(QOpenGLPaintEngineState &other)
5587 : QPainterState(other)
5588{
5589 clipRegion = other.clipRegion;
5590 hasClipping = other.hasClipping;
5591 fastClip = other.fastClip;
5592 depthClipId = other.depthClipId;
5593}
5594
5595QOpenGLPaintEngineState::QOpenGLPaintEngineState()
5596{
5597 hasClipping = false;
5598 depthClipId = 0;
5599}
5600
5601QOpenGLPaintEngineState::~QOpenGLPaintEngineState()
5602{
5603}
5604
5605void QOpenGLPaintEnginePrivate::ensureDrawableTexture()
5606{
5607 if (!dirty_drawable_texture)
5608 return;
5609
5610 dirty_drawable_texture = false;
5611
5612#ifndef QT_OPENGL_ES
5613 glGenTextures(1, &drawable_texture);
5614 glBindTexture(GL_TEXTURE_2D, drawable_texture);
5615
5616 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
5617 drawable_texture_size.width(),
5618 drawable_texture_size.height(), 0,
5619 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
5620
5621 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
5622 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
5623 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
5624 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
5625#endif
5626}
5627
5628QT_END_NAMESPACE
5629
5630#include "qpaintengine_opengl.moc"
Note: See TracBrowser for help on using the repository browser.