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 "hellowindow.h"
52
53#include <QOpenGLContext>
54#include <QOpenGLFunctions>
55#include <QRandomGenerator>
56#include <qmath.h>
57#include <QElapsedTimer>
58
59Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen)
60 : m_initialized(false)
61 , m_format(format)
62{
63 m_context = new QOpenGLContext(this);
64 if (screen)
65 m_context->setScreen(screen);
66 m_context->setFormat(format);
67 if (share)
68 m_context->setShareContext(share->m_context);
69 m_context->create();
70
71 m_backgroundColor = QColor::fromRgbF(0.1f, 0.1f, 0.2f, 1.0f);
72 m_backgroundColor.setRed(QRandomGenerator::global()->bounded(64));
73 m_backgroundColor.setGreen(QRandomGenerator::global()->bounded(128));
74 m_backgroundColor.setBlue(QRandomGenerator::global()->bounded(256));
75}
76
77HelloWindow::HelloWindow(const QSharedPointer<Renderer> &renderer, QScreen *screen)
78 : m_colorIndex(0), m_renderer(renderer)
79{
80 setSurfaceType(QWindow::OpenGLSurface);
81 setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
82
83 setGeometry(QRect(10, 10, 640, 480));
84
85 setFormat(renderer->format());
86 if (screen)
87 setScreen(screen);
88
89 create();
90
91 updateColor();
92
93 connect(renderer.data(), &Renderer::requestUpdate, this, &QWindow::requestUpdate);
94}
95
96void HelloWindow::exposeEvent(QExposeEvent *)
97{
98 if (isExposed())
99 render();
100}
101
102bool HelloWindow::event(QEvent *ev)
103{
104 if (ev->type() == QEvent::UpdateRequest && isExposed())
105 render();
106 return QWindow::event(ev);
107}
108
109void HelloWindow::render()
110{
111 static QElapsedTimer timer;
112 if (!timer.isValid())
113 timer.start();
114 qreal a = (qreal)(((timer.elapsed() * 3) % 36000) / 100.0);
115 auto call = [this, r = m_renderer.data(), a, c = color()]() { r->render(this, a, c); };
116 QMetaObject::invokeMethod(m_renderer.data(), call);
117}
118
119void HelloWindow::mousePressEvent(QMouseEvent *)
120{
121 updateColor();
122}
123
124QColor HelloWindow::color() const
125{
126 return m_color;
127}
128
129void HelloWindow::updateColor()
130{
131 QColor colors[] =
132 {
133 QColor(100, 255, 0),
134 QColor(0, 100, 255)
135 };
136
137 m_color = colors[m_colorIndex];
138 m_colorIndex = 1 - m_colorIndex;
139}
140
141void Renderer::render(HelloWindow *surface, qreal angle, const QColor &color)
142{
143 if (!m_context->makeCurrent(surface))
144 return;
145
146 QSize viewSize = surface->size();
147
148 if (!m_initialized) {
149 initialize();
150 m_initialized = true;
151 }
152
153 QOpenGLFunctions *f = m_context->functions();
154 f->glViewport(0, 0, viewSize.width() * surface->devicePixelRatio(), viewSize.height() * surface->devicePixelRatio());
155 f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
156
157 f->glClearColor(m_backgroundColor.redF(), m_backgroundColor.greenF(), m_backgroundColor.blueF(), m_backgroundColor.alphaF());
158 f->glFrontFace(GL_CW);
159 f->glCullFace(GL_FRONT);
160 f->glEnable(GL_CULL_FACE);
161 f->glEnable(GL_DEPTH_TEST);
162
163 m_program->bind();
164 m_vbo.bind();
165
166 m_program->enableAttributeArray(vertexAttr);
167 m_program->enableAttributeArray(normalAttr);
168 m_program->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3);
169 const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
170 m_program->setAttributeBuffer(normalAttr, GL_FLOAT, verticesSize, 3);
171
172 QMatrix4x4 modelview;
173 modelview.rotate(angle, 0.0f, 1.0f, 0.0f);
174 modelview.rotate(angle, 1.0f, 0.0f, 0.0f);
175 modelview.rotate(angle, 0.0f, 0.0f, 1.0f);
176 modelview.translate(0.0f, -0.2f, 0.0f);
177
178 m_program->setUniformValue(matrixUniform, modelview);
179 m_program->setUniformValue(colorUniform, color);
180
181 m_context->functions()->glDrawArrays(GL_TRIANGLES, 0, vertices.size());
182
183 m_context->swapBuffers(surface);
184
185 emit requestUpdate();
186}
187
188Q_GLOBAL_STATIC(QMutex, initMutex)
189
190void Renderer::initialize()
191{
192 // Threaded shader compilation can confuse some drivers. Avoid it.
193 QMutexLocker lock(initMutex());
194
195 QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
196 vshader->compileSourceCode(
197 "attribute highp vec4 vertex;"
198 "attribute mediump vec3 normal;"
199 "uniform mediump mat4 matrix;"
200 "uniform lowp vec4 sourceColor;"
201 "varying mediump vec4 color;"
202 "void main(void)"
203 "{"
204 " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));"
205 " float angle = max(dot(normal, toLight), 0.0);"
206 " vec3 col = sourceColor.rgb;"
207 " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);"
208 " color = clamp(color, 0.0, 1.0);"
209 " gl_Position = matrix * vertex;"
210 "}");
211
212 QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
213 fshader->compileSourceCode(
214 "varying mediump vec4 color;"
215 "void main(void)"
216 "{"
217 " gl_FragColor = color;"
218 "}");
219
220 m_program = new QOpenGLShaderProgram(this);
221 m_program->addShader(vshader);
222 m_program->addShader(fshader);
223 m_program->link();
224 m_program->bind();
225
226 vertexAttr = m_program->attributeLocation("vertex");
227 normalAttr = m_program->attributeLocation("normal");
228 matrixUniform = m_program->uniformLocation("matrix");
229 colorUniform = m_program->uniformLocation("sourceColor");
230
231 createGeometry();
232
233 m_vbo.create();
234 m_vbo.bind();
235 const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
236 m_vbo.allocate(verticesSize * 2);
237 m_vbo.write(0, vertices.constData(), verticesSize);
238 m_vbo.write(verticesSize, normals.constData(), verticesSize);
239}
240
241void Renderer::createGeometry()
242{
243 vertices.clear();
244 normals.clear();
245
246 qreal x1 = +0.06f;
247 qreal y1 = -0.14f;
248 qreal x2 = +0.14f;
249 qreal y2 = -0.06f;
250 qreal x3 = +0.08f;
251 qreal y3 = +0.00f;
252 qreal x4 = +0.30f;
253 qreal y4 = +0.22f;
254
255 quad(x1, y1, x2, y2, y2, x2, y1, x1);
256 quad(x3, y3, x4, y4, y4, x4, y3, x3);
257
258 extrude(x1, y1, x2, y2);
259 extrude(x2, y2, y2, x2);
260 extrude(y2, x2, y1, x1);
261 extrude(y1, x1, x1, y1);
262 extrude(x3, y3, x4, y4);
263 extrude(x4, y4, y4, x4);
264 extrude(y4, x4, y3, x3);
265
266 const int NumSectors = 100;
267 const qreal sectorAngle = 2 * qreal(M_PI) / NumSectors;
268 for (int i = 0; i < NumSectors; ++i) {
269 qreal angle = i * sectorAngle;
270 qreal x5 = 0.30 * qSin(angle);
271 qreal y5 = 0.30 * qCos(angle);
272 qreal x6 = 0.20 * qSin(angle);
273 qreal y6 = 0.20 * qCos(angle);
274
275 angle += sectorAngle;
276 qreal x7 = 0.20 * qSin(angle);
277 qreal y7 = 0.20 * qCos(angle);
278 qreal x8 = 0.30 * qSin(angle);
279 qreal y8 = 0.30 * qCos(angle);
280
281 quad(x5, y5, x6, y6, x7, y7, x8, y8);
282
283 extrude(x6, y6, x7, y7);
284 extrude(x8, y8, x5, y5);
285 }
286
287 for (int i = 0;i < vertices.size();i++)
288 vertices[i] *= 2.0f;
289}
290
291void Renderer::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4)
292{
293 vertices << QVector3D(x1, y1, -0.05f);
294 vertices << QVector3D(x2, y2, -0.05f);
295 vertices << QVector3D(x4, y4, -0.05f);
296
297 vertices << QVector3D(x3, y3, -0.05f);
298 vertices << QVector3D(x4, y4, -0.05f);
299 vertices << QVector3D(x2, y2, -0.05f);
300
301 QVector3D n = QVector3D::normal
302 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(x4 - x1, y4 - y1, 0.0f));
303
304 normals << n;
305 normals << n;
306 normals << n;
307
308 normals << n;
309 normals << n;
310 normals << n;
311
312 vertices << QVector3D(x4, y4, 0.05f);
313 vertices << QVector3D(x2, y2, 0.05f);
314 vertices << QVector3D(x1, y1, 0.05f);
315
316 vertices << QVector3D(x2, y2, 0.05f);
317 vertices << QVector3D(x4, y4, 0.05f);
318 vertices << QVector3D(x3, y3, 0.05f);
319
320 n = QVector3D::normal
321 (QVector3D(x2 - x4, y2 - y4, 0.0f), QVector3D(x1 - x4, y1 - y4, 0.0f));
322
323 normals << n;
324 normals << n;
325 normals << n;
326
327 normals << n;
328 normals << n;
329 normals << n;
330}
331
332void Renderer::extrude(qreal x1, qreal y1, qreal x2, qreal y2)
333{
334 vertices << QVector3D(x1, y1, +0.05f);
335 vertices << QVector3D(x2, y2, +0.05f);
336 vertices << QVector3D(x1, y1, -0.05f);
337
338 vertices << QVector3D(x2, y2, -0.05f);
339 vertices << QVector3D(x1, y1, -0.05f);
340 vertices << QVector3D(x2, y2, +0.05f);
341
342 QVector3D n = QVector3D::normal
343 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(0.0f, 0.0f, -0.1f));
344
345 normals << n;
346 normals << n;
347 normals << n;
348
349 normals << n;
350 normals << n;
351 normals << n;
352}
353