QOpenGLTextureBlitter fix allocating 4 times as much memory as needed
[qt:qtbase.git] / src / gui / opengl / qopengltextureblitter.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qopengltextureblitter_p.h"
43
44 #include <QtGui/QOpenGLBuffer>
45 #include <QtGui/QOpenGLShaderProgram>
46 #include <QtGui/QOpenGLVertexArrayObject>
47 #include <QtGui/QOpenGLContext>
48 #include <QtGui/QOpenGLFunctions>
49
50 QT_BEGIN_NAMESPACE
51
52 static const char vertex_shader150[] =
53     "#version 150 core\n"
54     "in vec3 vertexCoord;"
55     "in vec2 textureCoord;"
56     "out vec2 uv;"
57     "uniform mat4 vertexTransform;"
58     "uniform mat3 textureTransform;"
59     "void main() {"
60     "   uv = (textureTransform * vec3(textureCoord,1.0)).xy;"
61     "   gl_Position = vertexTransform * vec4(vertexCoord,1.0);"
62     "}";
63
64 static const char fragment_shader150[] =
65     "#version 150 core\n"
66     "in vec2 uv;"
67     "out vec4 fragcolor;"
68     "uniform sampler2D textureSampler;"
69     "uniform bool swizzle;"
70     "void main() {"
71     "   vec4 tmpFragColor = texture(textureSampler, uv);"
72     "   fragcolor = swizzle ? tmpFragColor.bgra : tmpFragColor;"
73     "}";
74
75 static const char vertex_shader[] =
76     "attribute highp vec3 vertexCoord;"
77     "attribute highp vec2 textureCoord;"
78     "varying highp vec2 uv;"
79     "uniform highp mat4 vertexTransform;"
80     "uniform highp mat3 textureTransform;"
81     "void main() {"
82     "   uv = (textureTransform * vec3(textureCoord,1.0)).xy;"
83     "   gl_Position = vertexTransform * vec4(vertexCoord,1.0);"
84     "}";
85
86 static const char fragment_shader[] =
87     "varying highp vec2 uv;"
88     "uniform sampler2D textureSampler;"
89     "uniform bool swizzle;"
90     "void main() {"
91     "   highp vec4 tmpFragColor = texture2D(textureSampler,uv);"
92     "   gl_FragColor = swizzle ? tmpFragColor.bgra : tmpFragColor;"
93     "}";
94
95 static const GLfloat vertex_buffer_data[] = {
96         -1,-1, 0,
97         -1, 1, 0,
98          1,-1, 0,
99         -1, 1, 0,
100          1,-1, 0,
101          1, 1, 0
102 };
103
104 static const GLfloat texture_buffer_data[] = {
105         0, 0,
106         0, 1,
107         1, 0,
108         0, 1,
109         1, 0,
110         1, 1
111 };
112
113 class TextureBinder
114 {
115 public:
116     TextureBinder(GLuint textureId)
117     {
118         QOpenGLContext::currentContext()->functions()->glBindTexture(GL_TEXTURE_2D, textureId);
119     }
120     ~TextureBinder()
121     {
122         QOpenGLContext::currentContext()->functions()->glBindTexture(GL_TEXTURE_2D, 0);
123     }
124 };
125
126 class QOpenGLTextureBlitterPrivate
127 {
128 public:
129     enum TextureMatrixUniform {
130         User,
131         Identity,
132         IdentityFlipped
133     };
134
135     QOpenGLTextureBlitterPrivate()
136         : program(0)
137         , vertexCoordAttribPos(0)
138         , vertexTransformUniformPos(0)
139         , textureCoordAttribPos(0)
140         , textureTransformUniformPos(0)
141         , swizzle(false)
142         , swizzleOld(false)
143         , textureMatrixUniformState(User)
144         , vao(new QOpenGLVertexArrayObject())
145     { }
146
147     void blit(GLuint texture, const QMatrix4x4 &vertexTransform, const QMatrix3x3 &textureTransform);
148     void blit(GLuint texture, const QMatrix4x4 &vertexTransform, QOpenGLTextureBlitter::Origin origin);
149
150     void prepareProgram(const QMatrix4x4 &vertexTransform)
151     {
152         vertexBuffer.bind();
153         program->setAttributeBuffer(vertexCoordAttribPos, GL_FLOAT, 0, 3, 0);
154         program->enableAttributeArray(vertexCoordAttribPos);
155         vertexBuffer.release();
156
157         program->setUniformValue(vertexTransformUniformPos, vertexTransform);
158
159         textureBuffer.bind();
160         program->setAttributeBuffer(textureCoordAttribPos, GL_FLOAT, 0, 2, 0);
161         program->enableAttributeArray(textureCoordAttribPos);
162         textureBuffer.release();
163
164         if (swizzle != swizzleOld) {
165             program->setUniformValue(swizzleUniformPos, swizzle);
166             swizzleOld = swizzle;
167         }
168     }
169
170     QOpenGLBuffer vertexBuffer;
171     QOpenGLBuffer textureBuffer;
172     QScopedPointer<QOpenGLShaderProgram> program;
173     GLuint vertexCoordAttribPos;
174     GLuint vertexTransformUniformPos;
175     GLuint textureCoordAttribPos;
176     GLuint textureTransformUniformPos;
177     GLuint swizzleUniformPos;
178     bool swizzle;
179     bool swizzleOld;
180     TextureMatrixUniform textureMatrixUniformState;
181     QScopedPointer<QOpenGLVertexArrayObject> vao;
182 };
183
184 void QOpenGLTextureBlitterPrivate::blit(GLuint texture,
185                                         const QMatrix4x4 &vertexTransform,
186                                         const QMatrix3x3 &textureTransform)
187 {
188     TextureBinder binder(texture);
189     prepareProgram(vertexTransform);
190
191     program->setUniformValue(textureTransformUniformPos, textureTransform);
192     textureMatrixUniformState = User;
193
194     QOpenGLContext::currentContext()->functions()->glDrawArrays(GL_TRIANGLES, 0, 6);
195 }
196
197 void QOpenGLTextureBlitterPrivate::blit(GLuint texture,
198                                         const QMatrix4x4 &vertexTransform,
199                                         QOpenGLTextureBlitter::Origin origin)
200 {
201     TextureBinder binder(texture);
202     prepareProgram(vertexTransform);
203
204     if (origin == QOpenGLTextureBlitter::OriginTopLeft) {
205         if (textureMatrixUniformState != IdentityFlipped) {
206             QMatrix3x3 flipped;
207             flipped(1,1) = -1;
208             flipped(1,2) = 1;
209             program->setUniformValue(textureTransformUniformPos, flipped);
210             textureMatrixUniformState = IdentityFlipped;
211         }
212     } else if (textureMatrixUniformState != Identity) {
213         program->setUniformValue(textureTransformUniformPos, QMatrix3x3());
214         textureMatrixUniformState = Identity;
215     }
216
217     QOpenGLContext::currentContext()->functions()->glDrawArrays(GL_TRIANGLES, 0, 6);
218 }
219
220 QOpenGLTextureBlitter::QOpenGLTextureBlitter()
221     : d_ptr(new QOpenGLTextureBlitterPrivate)
222 {
223 }
224
225 QOpenGLTextureBlitter::~QOpenGLTextureBlitter()
226 {
227 }
228
229 bool QOpenGLTextureBlitter::create()
230 {
231     QOpenGLContext *currentContext = QOpenGLContext::currentContext();
232     if (!currentContext)
233         return false;
234
235     Q_D(QOpenGLTextureBlitter);
236
237     d->vao->create();
238     d->vao->bind();
239
240     if (d->program)
241         return true;
242
243     d->program.reset(new QOpenGLShaderProgram());
244
245     QSurfaceFormat format = currentContext->format();
246
247     if (format.profile() == QSurfaceFormat::CoreProfile && format.version() >= qMakePair(3,2)) {
248         d->program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader150);
249         d->program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader150);
250     } else {
251         d->program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader);
252         d->program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader);
253     }
254     d->program->link();
255     if (!d->program->isLinked()) {
256         qWarning() << Q_FUNC_INFO << "Could not link shader program:\n" << d->program->log();
257         return false;
258     }
259
260     d->program->bind();
261
262     d->vertexBuffer.create();
263     d->vertexBuffer.bind();
264     d->vertexBuffer.allocate(vertex_buffer_data, sizeof(vertex_buffer_data));
265     d->vertexBuffer.release();
266
267     d->textureBuffer.create();
268     d->textureBuffer.bind();
269     d->textureBuffer.allocate(texture_buffer_data, sizeof(texture_buffer_data));
270     d->textureBuffer.release();
271
272     d->vertexCoordAttribPos = d->program->attributeLocation("vertexCoord");
273     d->vertexTransformUniformPos = d->program->uniformLocation("vertexTransform");
274     d->textureCoordAttribPos = d->program->attributeLocation("textureCoord");
275     d->textureTransformUniformPos = d->program->uniformLocation("textureTransform");
276     d->swizzleUniformPos = d->program->uniformLocation("swizzle");
277
278     d->program->setUniformValue(d->swizzleUniformPos,false);
279
280     d->vao->release();
281
282     return true;
283 }
284
285 bool QOpenGLTextureBlitter::isCreated() const
286 {
287     Q_D(const QOpenGLTextureBlitter);
288     return d->program;
289 }
290
291 void QOpenGLTextureBlitter::destroy()
292 {
293     Q_D(QOpenGLTextureBlitter);
294     d->program.reset();
295     d->vertexBuffer.destroy();
296     d->textureBuffer.destroy();
297     d->vao.reset();
298 }
299
300 void QOpenGLTextureBlitter::bind()
301 {
302     Q_D(QOpenGLTextureBlitter);
303
304     d->vao->bind();
305
306     d->program->bind();
307
308     d->vertexBuffer.bind();
309     d->program->setAttributeBuffer(d->vertexCoordAttribPos, GL_FLOAT, 0, 3, 0);
310     d->program->enableAttributeArray(d->vertexCoordAttribPos);
311     d->vertexBuffer.release();
312
313     d->textureBuffer.bind();
314     d->program->setAttributeBuffer(d->textureCoordAttribPos, GL_FLOAT, 0, 2, 0);
315     d->program->enableAttributeArray(d->textureCoordAttribPos);
316     d->textureBuffer.release();
317 }
318
319 void QOpenGLTextureBlitter::release()
320 {
321     Q_D(QOpenGLTextureBlitter);
322     d->program->release();
323     d->vao->release();
324 }
325
326 void QOpenGLTextureBlitter::setSwizzleRB(bool swizzle)
327 {
328     Q_D(QOpenGLTextureBlitter);
329     d->swizzle = swizzle;
330 }
331
332 void QOpenGLTextureBlitter::blit(GLuint texture,
333                                  const QMatrix4x4 &targetTransform,
334                                  Origin sourceOrigin)
335 {
336     Q_D(QOpenGLTextureBlitter);
337     d->blit(texture,targetTransform, sourceOrigin);
338 }
339
340 void QOpenGLTextureBlitter::blit(GLuint texture,
341                                  const QMatrix4x4 &targetTransform,
342                                  const QMatrix3x3 &sourceTransform)
343 {
344     Q_D(QOpenGLTextureBlitter);
345     d->blit(texture, targetTransform, sourceTransform);
346 }
347
348 QMatrix4x4 QOpenGLTextureBlitter::targetTransform(const QRectF &target,
349                                                   const QRect &viewport)
350 {
351     qreal x_scale = target.width() / viewport.width();
352     qreal y_scale = target.height() / viewport.height();
353
354     const QPointF relative_to_viewport = target.topLeft() - viewport.topLeft();
355     qreal x_translate = x_scale - 1 + ((relative_to_viewport.x() / viewport.width()) * 2);
356     qreal y_translate = -y_scale + 1 - ((relative_to_viewport.y() / viewport.height()) * 2);
357
358     QMatrix4x4 matrix;
359     matrix(0,3) = x_translate;
360     matrix(1,3) = y_translate;
361
362     matrix(0,0) = x_scale;
363     matrix(1,1) = y_scale;
364
365     return matrix;
366 }
367
368 QMatrix3x3 QOpenGLTextureBlitter::sourceTransform(const QRectF &subTexture,
369                                                   const QSize &textureSize,
370                                                   Origin origin)
371 {
372     qreal x_scale = subTexture.width() / textureSize.width();
373     qreal y_scale = subTexture.height() / textureSize.height();
374
375     const QPointF topLeft = subTexture.topLeft();
376     qreal x_translate = topLeft.x() / textureSize.width();
377     qreal y_translate = topLeft.y() / textureSize.height();
378
379     if (origin == OriginTopLeft) {
380         y_scale = -y_scale;
381         y_translate = 1 - y_translate;
382     }
383
384     QMatrix3x3 matrix;
385     matrix(0,2) = x_translate;
386     matrix(1,2) = y_translate;
387
388     matrix(0,0) = x_scale;
389     matrix(1,1) = y_scale;
390
391     return matrix;
392 }
393
394 QT_END_NAMESPACE