1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtOpenGL module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
49 // This file is not part of the Qt API. It exists for the convenience
50 // of the QGLWidget class. This header file may change from
51 // version to version without notice, or even be removed.
56 #include "QtOpenGL/qgl.h"
57 #include "QtOpenGL/qglcolormap.h"
58 #include "QtCore/qmap.h"
59 #include "QtCore/qthread.h"
60 #include "QtCore/qthreadstorage.h"
61 #include "QtCore/qhash.h"
62 #include "QtCore/qatomic.h"
63 #include "QtWidgets/private/qwidget_p.h"
64 #include "QtGui/private/qopenglcontext_p.h"
66 #include "qglpaintdevice_p.h"
68 #include <QtGui/QOpenGLContext>
73 class QGLOverlayWidget;
76 QT_BEGIN_INCLUDE_NAMESPACE
77 #include <QtOpenGL/private/qglextensions_p.h>
78 QT_END_INCLUDE_NAMESPACE
80 class QGLFormatPrivate
86 opts = QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba | QGL::DirectRendering
87 | QGL::StencilBuffer | QGL::DeprecatedFunctions;
89 depthSize = accumSize = stencilSize = redSize = greenSize = blueSize = alphaSize = -1;
94 profile = QGLFormat::NoProfile;
96 QGLFormatPrivate(const QGLFormatPrivate *other)
100 depthSize(other->depthSize),
101 accumSize(other->accumSize),
102 stencilSize(other->stencilSize),
103 redSize(other->redSize),
104 greenSize(other->greenSize),
105 blueSize(other->blueSize),
106 alphaSize(other->alphaSize),
107 numSamples(other->numSamples),
108 swapInterval(other->swapInterval),
109 majorVersion(other->majorVersion),
110 minorVersion(other->minorVersion),
111 profile(other->profile)
115 QGL::FormatOptions opts;
128 QGLFormat::OpenGLContextProfile profile;
131 class Q_OPENGL_EXPORT QGLWidgetPrivate : public QWidgetPrivate
133 Q_DECLARE_PUBLIC(QGLWidget)
135 QGLWidgetPrivate() : QWidgetPrivate()
136 , disable_clear_on_painter_begin(false)
141 ~QGLWidgetPrivate() {}
143 void init(QGLContext *context, const QGLWidget* shareWidget);
144 void initContext(QGLContext *context, const QGLWidget* shareWidget);
145 bool renderCxPm(QPixmap *pixmap);
146 void cleanupColormaps();
147 void aboutToDestroy() {
153 QGLWidgetGLPaintDevice glDevice;
158 QMap<QString, int> displayListCache;
161 bool disable_clear_on_painter_begin;
164 // QGLContextPrivate has the responsibility of creating context groups.
165 // QGLContextPrivate maintains the reference counter and destroys
166 // context groups when needed.
167 class QGLContextGroup
172 QGLExtensionFuncs &extensionFuncs() {return m_extensionFuncs;}
173 const QGLContext *context() const {return m_context;}
174 bool isSharing() const { return m_shares.size() >= 2; }
175 QList<const QGLContext *> shares() const { return m_shares; }
177 static void addShare(const QGLContext *context, const QGLContext *share);
178 static void removeShare(const QGLContext *context);
181 QGLContextGroup(const QGLContext *context);
183 QGLExtensionFuncs m_extensionFuncs;
184 const QGLContext *m_context; // context group's representative
185 QList<const QGLContext *> m_shares;
188 friend class QGLContext;
189 friend class QGLContextPrivate;
190 friend class QGLContextGroupResourceBase;
193 // Get the context that resources for "ctx" will transfer to once
194 // "ctx" is destroyed. Returns null if nothing is sharing with ctx.
195 const QGLContext *qt_gl_transfer_context(const QGLContext *);
197 // GL extension definitions
198 class QGLExtensions {
201 TextureRectangle = 0x00000001,
202 SampleBuffers = 0x00000002,
203 GenerateMipmap = 0x00000004,
204 TextureCompression = 0x00000008,
205 FragmentProgram = 0x00000010,
206 MirroredRepeat = 0x00000020,
207 FramebufferObject = 0x00000040,
208 StencilTwoSide = 0x00000080,
209 StencilWrap = 0x00000100,
210 PackedDepthStencil = 0x00000200,
211 NVFloatBuffer = 0x00000400,
212 PixelBufferObject = 0x00000800,
213 FramebufferBlit = 0x00001000,
214 NPOTTextures = 0x00002000,
215 BGRATextureFormat = 0x00004000,
216 DDSTextureCompression = 0x00008000,
217 ETC1TextureCompression = 0x00010000,
218 PVRTCTextureCompression = 0x00020000,
219 FragmentShader = 0x00040000,
220 ElementIndexUint = 0x00080000,
221 Depth24 = 0x00100000,
222 SRGBFrameBuffer = 0x00200000
224 Q_DECLARE_FLAGS(Extensions, Extension)
226 static Extensions glExtensions();
227 static Extensions currentContextExtensions();
231 QGLTemporaryContext - the main objective of this class is to have a way of
232 creating a GL context and making it current, without going via QGLWidget
233 and friends. At certain points during GL initialization we need a current
234 context in order decide what GL features are available, and to resolve GL
235 extensions. Having a light-weight way of creating such a context saves
236 initial application startup time, and it doesn't wind up creating recursive
238 The class currently uses a private d pointer to hide the platform specific
239 types. This could possibly been done inline with #ifdef'ery, but it causes
240 major headaches on e.g. X11 due to namespace pollution.
242 class QGLTemporaryContextPrivate;
243 class QGLTemporaryContext {
245 QGLTemporaryContext(bool directRendering = true, QWidget *parent = 0);
246 ~QGLTemporaryContext();
249 QScopedPointer<QGLTemporaryContextPrivate> d;
253 class QGLTextureDestroyer;
255 // This probably needs to grow to GL_MAX_VERTEX_ATTRIBS, but 3 is ok for now as that's
256 // all the GL2 engine uses:
257 #define QT_GL_VERTEX_ARRAY_TRACKED_COUNT 3
259 class QGLContextResourceBase;
261 class QGLContextPrivate
263 Q_DECLARE_PUBLIC(QGLContext)
265 explicit QGLContextPrivate(QGLContext *context);
266 ~QGLContextPrivate();
267 QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format,
268 QGLContext::BindOptions options);
269 QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format, const qint64 key,
270 QGLContext::BindOptions options);
271 QGLTexture *bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
272 QGLContext::BindOptions options);
273 QGLTexture *textureCacheLookup(const qint64 key, GLenum target);
274 void init(QPaintDevice *dev, const QGLFormat &format);
275 QImage convertToGLFormat(const QImage &image, bool force_premul, GLenum texture_format);
276 int maxTextureSize();
280 void setVertexAttribArrayEnabled(int arrayIndex, bool enabled = true);
281 void syncGlState(); // Makes sure the GL context's state is what we think it is
282 void swapRegion(const QRegion ®ion);
284 QOpenGLContext *guiGlContext;
297 uint internal_context : 1;
298 uint version_flags_cached : 1;
299 uint extension_flags_cached : 1;
301 // workarounds for driver/hw bugs on different platforms
302 uint workaround_needsFullClearOnEveryFrame : 1;
303 uint workaround_brokenFBOReadBack : 1;
304 uint workaround_brokenTexSubImage : 1;
305 uint workaroundsCached : 1;
307 uint workaround_brokenTextureFromPixmap : 1;
308 uint workaround_brokenTextureFromPixmap_init : 1;
310 uint workaround_brokenAlphaTexSubImage : 1;
311 uint workaround_brokenAlphaTexSubImage_init : 1;
313 QPaintDevice *paintDevice;
316 QGLFormat::OpenGLVersionFlags version_flags;
317 QGLExtensions::Extensions extension_flags;
319 QGLContextGroup *group;
320 GLint max_texture_size;
324 QPaintEngine *active_engine;
325 QGLTextureDestroyer *texture_destroyer;
327 QGLFunctions *functions;
329 bool vertexAttributeArraysEnabledState[QT_GL_VERTEX_ARRAY_TRACKED_COUNT];
331 static inline QGLContextGroup *contextGroup(const QGLContext *ctx) { return ctx->d_ptr->group; }
333 static Q_OPENGL_EXPORT QGLExtensionFuncs qt_extensionFuncs;
334 static Q_OPENGL_EXPORT QGLExtensionFuncs& extensionFuncs(const QGLContext *);
336 static void setCurrentContext(QGLContext *context);
339 Q_DECLARE_OPERATORS_FOR_FLAGS(QGLExtensions::Extensions)
341 // Temporarily make a context current if not already current or
342 // shared with the current contex. The previous context is made
343 // current when the object goes out of scope.
344 class Q_OPENGL_EXPORT QGLShareContextScope
347 QGLShareContextScope(const QGLContext *ctx)
350 QGLContext *currentContext = const_cast<QGLContext *>(QGLContext::currentContext());
351 if (currentContext != ctx && !QGLContext::areSharing(ctx, currentContext)) {
352 m_oldContext = currentContext;
353 m_ctx = const_cast<QGLContext *>(ctx);
354 m_ctx->makeCurrent();
356 m_ctx = currentContext;
360 operator QGLContext *()
365 QGLContext *operator->()
370 ~QGLShareContextScope()
373 m_oldContext->makeCurrent();
377 QGLContext *m_oldContext;
381 class Q_OPENGL_EXPORT QGLTextureDestroyer : public QObject
385 QGLTextureDestroyer() : QObject() {
386 qRegisterMetaType<GLuint>("GLuint");
387 connect(this, SIGNAL(freeTexture(QGLContext *, QPlatformPixmap *, GLuint)),
388 this, SLOT(freeTexture_slot(QGLContext *, QPlatformPixmap *, GLuint)));
390 void emitFreeTexture(QGLContext *context, QPlatformPixmap *boundPixmap, GLuint id) {
391 emit freeTexture(context, boundPixmap, id);
395 void freeTexture(QGLContext *context, QPlatformPixmap *boundPixmap, GLuint id);
398 void freeTexture_slot(QGLContext *context, QPlatformPixmap *boundPixmap, GLuint id) {
399 Q_UNUSED(boundPixmap);
400 QGLShareContextScope scope(context);
401 glDeleteTextures(1, &id);
405 // ### make QGLContext a QObject in 5.0 and remove the proxy stuff
406 class Q_OPENGL_EXPORT QGLSignalProxy : public QObject
410 void emitAboutToDestroyContext(const QGLContext *context) {
411 emit aboutToDestroyContext(context);
413 static QGLSignalProxy *instance();
415 void aboutToDestroyContext(const QGLContext *context);
420 QGLTexture(QGLContext *ctx = 0, GLuint tx_id = 0, GLenum tx_target = GL_TEXTURE_2D,
421 QGLContext::BindOptions opt = QGLContext::DefaultBindOption)
429 if (options & QGLContext::MemoryManagedBindOption) {
431 QPlatformPixmap *boundPixmap = 0;
432 context->d_ptr->texture_destroyer->emitFreeTexture(context, boundPixmap, id);
440 QGLContext::BindOptions options;
442 bool canBindCompressedTexture
443 (const char *buf, int len, const char *format, bool *hasAlpha);
444 QSize bindCompressedTexture
445 (const QString& fileName, const char *format = 0);
446 QSize bindCompressedTexture
447 (const char *buf, int len, const char *format = 0);
448 QSize bindCompressedTextureDDS(const char *buf, int len);
449 QSize bindCompressedTexturePVR(const char *buf, int len);
452 struct QGLTextureCacheKey {
454 QGLContextGroup *group;
457 inline bool operator==(const QGLTextureCacheKey &a, const QGLTextureCacheKey &b)
459 return a.key == b.key && a.group == b.group;
462 inline uint qHash(const QGLTextureCacheKey &key)
464 return qHash(key.key) ^ qHash(key.group);
468 class Q_AUTOTEST_EXPORT QGLTextureCache {
473 void insert(QGLContext *ctx, qint64 key, QGLTexture *texture, int cost);
474 void remove(qint64 key);
476 inline void setMaxCost(int newMax);
477 inline int maxCost();
478 inline QGLTexture* getTexture(QGLContext *ctx, qint64 key);
480 bool remove(QGLContext *ctx, GLuint textureId);
481 void removeContextTextures(QGLContext *ctx);
482 static QGLTextureCache *instance();
483 static void cleanupTexturesForCacheKey(qint64 cacheKey);
484 static void cleanupTexturesForPixampData(QPlatformPixmap* pixmap);
485 static void cleanupBeforePixmapDestruction(QPlatformPixmap* pixmap);
488 QCache<QGLTextureCacheKey, QGLTexture> m_cache;
489 QReadWriteLock m_lock;
492 int QGLTextureCache::size() {
493 QReadLocker locker(&m_lock);
494 return m_cache.size();
497 void QGLTextureCache::setMaxCost(int newMax)
499 QWriteLocker locker(&m_lock);
500 m_cache.setMaxCost(newMax);
503 int QGLTextureCache::maxCost()
505 QReadLocker locker(&m_lock);
506 return m_cache.maxCost();
509 QGLTexture* QGLTextureCache::getTexture(QGLContext *ctx, qint64 key)
511 QReadLocker locker(&m_lock);
512 const QGLTextureCacheKey cacheKey = {key, QGLContextPrivate::contextGroup(ctx)};
513 return m_cache.object(cacheKey);
516 extern QPaintEngine* qt_qgl_paint_engine();
518 // Put a guard around a GL object identifier and its context.
519 // When the context goes away, a shared context will be used
520 // in its place. If there are no more shared contexts, then
521 // the identifier is returned as zero - it is assumed that the
522 // context destruction cleaned up the identifier in this case.
523 class QGLSharedResourceGuardBase : public QOpenGLSharedResource
526 QGLSharedResourceGuardBase(QGLContext *context, GLuint id)
527 : QOpenGLSharedResource(context->contextHandle()->shareGroup())
538 void invalidateResource()
543 void freeResource(QOpenGLContext *context)
546 freeResource(QGLContext::fromOpenGLContext(context), m_id);
550 virtual void freeResource(QGLContext *ctx, GLuint id) = 0;
556 template <typename Func>
557 class QGLSharedResourceGuard : public QGLSharedResourceGuardBase
560 QGLSharedResourceGuard(QGLContext *context, GLuint id, Func func)
561 : QGLSharedResourceGuardBase(context, id)
567 void freeResource(QGLContext *ctx, GLuint id)
576 template <typename Func>
577 QGLSharedResourceGuardBase *createSharedResourceGuard(QGLContext *context, GLuint id, Func cleanupFunc)
579 return new QGLSharedResourceGuard<Func>(context, id, cleanupFunc);
582 class QGLExtensionMatcher
585 QGLExtensionMatcher(const char *str);
586 QGLExtensionMatcher();
588 bool match(const char *str) const {
589 int str_length = qstrlen(str);
592 Q_ASSERT(str_length > 0);
593 Q_ASSERT(str[str_length-1] != ' ');
595 for (int i = 0; i < m_offsets.size(); ++i) {
596 const char *extension = m_extensions.constData() + m_offsets.at(i);
597 if (qstrncmp(extension, str, str_length) == 0 && extension[str_length] == ' ')
604 void init(const char *str);
606 QByteArray m_extensions;
607 QVector<int> m_offsets;
611 // this is a class that wraps a QThreadStorage object for storing
612 // thread local instances of the GL 1 and GL 2 paint engines
615 class QGLEngineThreadStorage
618 QPaintEngine *engine() {
619 QPaintEngine *&localEngine = storage.localData();
626 QThreadStorage<QPaintEngine *> storage;