1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "glwidget.h"
52#include <qmath.h>
53#include <QGuiApplication>
54
55GLWidget::GLWidget(QWidget *parent)
56 : QOpenGLWidget(parent)
57{
58 setMinimumSize(300, 250);
59
60 connect(this, &QOpenGLWidget::aboutToCompose, this, &GLWidget::onAboutToCompose);
61 connect(this, &QOpenGLWidget::frameSwapped, this, &GLWidget::onFrameSwapped);
62 connect(this, &QOpenGLWidget::aboutToResize, this, &GLWidget::onAboutToResize);
63 connect(this, &QOpenGLWidget::resized, this, &GLWidget::onResized);
64
65 m_thread = new QThread;
66 m_renderer = new Renderer(this);
67 m_renderer->moveToThread(m_thread);
68 connect(m_thread, &QThread::finished, m_renderer, &QObject::deleteLater);
69
70 connect(this, &GLWidget::renderRequested, m_renderer, &Renderer::render);
71 connect(m_renderer, &Renderer::contextWanted, this, &GLWidget::grabContext);
72
73 m_thread->start();
74}
75
76GLWidget::~GLWidget()
77{
78 m_renderer->prepareExit();
79 m_thread->quit();
80 m_thread->wait();
81 delete m_thread;
82}
83
84void GLWidget::onAboutToCompose()
85{
86 // We are on the gui thread here. Composition is about to
87 // begin. Wait until the render thread finishes.
88 m_renderer->lockRenderer();
89}
90
91void GLWidget::onFrameSwapped()
92{
93 m_renderer->unlockRenderer();
94 // Assuming a blocking swap, our animation is driven purely by the
95 // vsync in this example.
96 emit renderRequested();
97}
98
99void GLWidget::onAboutToResize()
100{
101 m_renderer->lockRenderer();
102}
103
104void GLWidget::onResized()
105{
106 m_renderer->unlockRenderer();
107}
108
109void GLWidget::grabContext()
110{
111 m_renderer->lockRenderer();
112 QMutexLocker lock(m_renderer->grabMutex());
113 context()->moveToThread(m_thread);
114 m_renderer->grabCond()->wakeAll();
115 m_renderer->unlockRenderer();
116}
117
118Renderer::Renderer(GLWidget *w) : m_glwidget(w) {}
119
120void Renderer::paintQtLogo()
121{
122 vbo.bind();
123 program.setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3);
124 program.setAttributeBuffer(normalAttr, GL_FLOAT, vertices.count() * 3 * sizeof(GLfloat), 3);
125 vbo.release();
126
127 program.enableAttributeArray(vertexAttr);
128 program.enableAttributeArray(normalAttr);
129
130 glDrawArrays(GL_TRIANGLES, 0, vertices.size());
131
132 program.disableAttributeArray(normalAttr);
133 program.disableAttributeArray(vertexAttr);
134}
135
136// Some OpenGL implementations have serious issues with compiling and linking
137// shaders on multiple threads concurrently. Avoid this.
138Q_GLOBAL_STATIC(QMutex, initMutex)
139
140void Renderer::render()
141{
142 if (m_exiting)
143 return;
144
145 QOpenGLContext *ctx = m_glwidget->context();
146 if (!ctx) // QOpenGLWidget not yet initialized
147 return;
148
149 // Grab the context.
150 m_grabMutex.lock();
151 emit contextWanted();
152 m_grabCond.wait(&m_grabMutex);
153 QMutexLocker lock(&m_renderMutex);
154 m_grabMutex.unlock();
155
156 if (m_exiting)
157 return;
158
159 Q_ASSERT(ctx->thread() == QThread::currentThread());
160
161 // Make the context (and an offscreen surface) current for this thread. The
162 // QOpenGLWidget's fbo is bound in the context.
163 m_glwidget->makeCurrent();
164
165 if (!m_inited) {
166 m_inited = true;
167 initializeOpenGLFunctions();
168
169 QMutexLocker initLock(initMutex());
170 QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
171 const char *vsrc =
172 "attribute highp vec4 vertex;\n"
173 "attribute mediump vec3 normal;\n"
174 "uniform mediump mat4 matrix;\n"
175 "varying mediump vec4 color;\n"
176 "void main(void)\n"
177 "{\n"
178 " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n"
179 " float angle = max(dot(normal, toLight), 0.0);\n"
180 " vec3 col = vec3(0.40, 1.0, 0.0);\n"
181 " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n"
182 " color = clamp(color, 0.0, 1.0);\n"
183 " gl_Position = matrix * vertex;\n"
184 "}\n";
185 vshader->compileSourceCode(vsrc);
186
187 QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
188 const char *fsrc =
189 "varying mediump vec4 color;\n"
190 "void main(void)\n"
191 "{\n"
192 " gl_FragColor = color;\n"
193 "}\n";
194 fshader->compileSourceCode(fsrc);
195
196 program.addShader(vshader);
197 program.addShader(fshader);
198 program.link();
199
200 vertexAttr = program.attributeLocation("vertex");
201 normalAttr = program.attributeLocation("normal");
202 matrixUniform = program.uniformLocation("matrix");
203
204 m_fAngle = 0;
205 m_fScale = 1;
206 createGeometry();
207
208 vbo.create();
209 vbo.bind();
210 const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
211 vbo.allocate(verticesSize * 2);
212 vbo.write(0, vertices.constData(), verticesSize);
213 vbo.write(verticesSize, normals.constData(), verticesSize);
214
215 m_elapsed.start();
216 }
217
218 //qDebug("%p elapsed %lld", QThread::currentThread(), m_elapsed.restart());
219
220 glClearColor(0.1f, 0.2f, 0.2f, 1.0f);
221 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
222
223 glFrontFace(GL_CW);
224 glCullFace(GL_FRONT);
225 glEnable(GL_CULL_FACE);
226 glEnable(GL_DEPTH_TEST);
227
228 QMatrix4x4 modelview;
229 modelview.rotate(m_fAngle, 0.0f, 1.0f, 0.0f);
230 modelview.rotate(m_fAngle, 1.0f, 0.0f, 0.0f);
231 modelview.rotate(m_fAngle, 0.0f, 0.0f, 1.0f);
232 modelview.scale(m_fScale);
233 modelview.translate(0.0f, -0.2f, 0.0f);
234
235 program.bind();
236 program.setUniformValue(matrixUniform, modelview);
237 paintQtLogo();
238 program.release();
239
240 glDisable(GL_DEPTH_TEST);
241 glDisable(GL_CULL_FACE);
242
243 m_fAngle += 1.0f;
244
245 // Make no context current on this thread and move the QOpenGLWidget's
246 // context back to the gui thread.
247 m_glwidget->doneCurrent();
248 ctx->moveToThread(qGuiApp->thread());
249
250 // Schedule composition. Note that this will use QueuedConnection, meaning
251 // that update() will be invoked on the gui thread.
252 QMetaObject::invokeMethod(m_glwidget, "update");
253}
254
255void Renderer::createGeometry()
256{
257 vertices.clear();
258 normals.clear();
259
260 qreal x1 = +0.06f;
261 qreal y1 = -0.14f;
262 qreal x2 = +0.14f;
263 qreal y2 = -0.06f;
264 qreal x3 = +0.08f;
265 qreal y3 = +0.00f;
266 qreal x4 = +0.30f;
267 qreal y4 = +0.22f;
268
269 quad(x1, y1, x2, y2, y2, x2, y1, x1);
270 quad(x3, y3, x4, y4, y4, x4, y3, x3);
271
272 extrude(x1, y1, x2, y2);
273 extrude(x2, y2, y2, x2);
274 extrude(y2, x2, y1, x1);
275 extrude(y1, x1, x1, y1);
276 extrude(x3, y3, x4, y4);
277 extrude(x4, y4, y4, x4);
278 extrude(y4, x4, y3, x3);
279
280 const int NumSectors = 100;
281 const qreal sectorAngle = 2 * qreal(M_PI) / NumSectors;
282
283 for (int i = 0; i < NumSectors; ++i) {
284 qreal angle = i * sectorAngle;
285 qreal x5 = 0.30 * sin(angle);
286 qreal y5 = 0.30 * cos(angle);
287 qreal x6 = 0.20 * sin(angle);
288 qreal y6 = 0.20 * cos(angle);
289
290 angle += sectorAngle;
291 qreal x7 = 0.20 * sin(angle);
292 qreal y7 = 0.20 * cos(angle);
293 qreal x8 = 0.30 * sin(angle);
294 qreal y8 = 0.30 * cos(angle);
295
296 quad(x5, y5, x6, y6, x7, y7, x8, y8);
297
298 extrude(x6, y6, x7, y7);
299 extrude(x8, y8, x5, y5);
300 }
301
302 for (int i = 0;i < vertices.size();i++)
303 vertices[i] *= 2.0f;
304}
305
306void Renderer::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4)
307{
308 vertices << QVector3D(x1, y1, -0.05f);
309 vertices << QVector3D(x2, y2, -0.05f);
310 vertices << QVector3D(x4, y4, -0.05f);
311
312 vertices << QVector3D(x3, y3, -0.05f);
313 vertices << QVector3D(x4, y4, -0.05f);
314 vertices << QVector3D(x2, y2, -0.05f);
315
316 QVector3D n = QVector3D::normal
317 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(x4 - x1, y4 - y1, 0.0f));
318
319 normals << n;
320 normals << n;
321 normals << n;
322
323 normals << n;
324 normals << n;
325 normals << n;
326
327 vertices << QVector3D(x4, y4, 0.05f);
328 vertices << QVector3D(x2, y2, 0.05f);
329 vertices << QVector3D(x1, y1, 0.05f);
330
331 vertices << QVector3D(x2, y2, 0.05f);
332 vertices << QVector3D(x4, y4, 0.05f);
333 vertices << QVector3D(x3, y3, 0.05f);
334
335 n = QVector3D::normal
336 (QVector3D(x2 - x4, y2 - y4, 0.0f), QVector3D(x1 - x4, y1 - y4, 0.0f));
337
338 normals << n;
339 normals << n;
340 normals << n;
341
342 normals << n;
343 normals << n;
344 normals << n;
345}
346
347void Renderer::extrude(qreal x1, qreal y1, qreal x2, qreal y2)
348{
349 vertices << QVector3D(x1, y1, +0.05f);
350 vertices << QVector3D(x2, y2, +0.05f);
351 vertices << QVector3D(x1, y1, -0.05f);
352
353 vertices << QVector3D(x2, y2, -0.05f);
354 vertices << QVector3D(x1, y1, -0.05f);
355 vertices << QVector3D(x2, y2, +0.05f);
356
357 QVector3D n = QVector3D::normal
358 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(0.0f, 0.0f, -0.1f));
359
360 normals << n;
361 normals << n;
362 normals << n;
363
364 normals << n;
365 normals << n;
366 normals << n;
367}
368