all repos — mgba @ 67c3f386a4106d5d3017aea882f64dc0ae94a375

mGBA Game Boy Advance Emulator

src/platform/qt/DisplayGL.cpp (view raw)

  1/* Copyright (c) 2013-2019 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "DisplayGL.h"
  7
  8#if defined(BUILD_GL) || defined(BUILD_GLES2)
  9
 10#include "CoreController.h"
 11
 12#include <QApplication>
 13#include <QOpenGLContext>
 14#include <QOpenGLPaintDevice>
 15#include <QResizeEvent>
 16#include <QTimer>
 17#include <QWindow>
 18
 19#include <mgba/core/core.h>
 20#include <mgba-util/math.h>
 21#ifdef BUILD_GL
 22#include "platform/opengl/gl.h"
 23#endif
 24#ifdef BUILD_GLES2
 25#include "platform/opengl/gles2.h"
 26#ifdef _WIN32
 27#include <epoxy/wgl.h>
 28#endif
 29#endif
 30
 31using namespace QGBA;
 32
 33DisplayGL::DisplayGL(const QSurfaceFormat& format, QWidget* parent)
 34	: Display(parent)
 35	, m_gl(nullptr)
 36{
 37	setAttribute(Qt::WA_NativeWindow);
 38	windowHandle()->create();
 39
 40	// This can spontaneously re-enter into this->resizeEvent before creation is done, so we
 41	// need to make sure it's initialized to nullptr before we assign the new object to it
 42	m_gl = new QOpenGLContext;
 43	m_gl->setFormat(format);
 44	m_gl->create();
 45
 46	m_gl->makeCurrent(windowHandle());
 47#if defined(_WIN32) && defined(USE_EPOXY)
 48	epoxy_handle_external_wglMakeCurrent();
 49#endif
 50	auto version = m_gl->format().version();
 51	QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
 52	m_gl->doneCurrent();
 53
 54	if ((version == qMakePair(2, 1) && !extensions.contains("GL_ARB_framebuffer_object")) || version == qMakePair(2, 0)) {
 55		QSurfaceFormat newFormat(format);
 56		newFormat.setVersion(1, 4);
 57		m_gl->setFormat(newFormat);
 58		m_gl->create();
 59	}
 60
 61	m_painter = new PainterGL(&m_videoProxy, windowHandle(), m_gl);
 62	setUpdatesEnabled(false); // Prevent paint events, which can cause race conditions
 63}
 64
 65DisplayGL::~DisplayGL() {
 66	stopDrawing();
 67	delete m_painter;
 68	delete m_gl;
 69}
 70
 71bool DisplayGL::supportsShaders() const {
 72	return m_painter->supportsShaders();
 73}
 74
 75VideoShader* DisplayGL::shaders() {
 76	VideoShader* shaders = nullptr;
 77	if (m_drawThread) {
 78		QMetaObject::invokeMethod(m_painter, "shaders", Qt::BlockingQueuedConnection, Q_RETURN_ARG(VideoShader*, shaders));
 79	} else {
 80		shaders = m_painter->shaders();
 81	}
 82	return shaders;
 83}
 84
 85void DisplayGL::startDrawing(std::shared_ptr<CoreController> controller) {
 86	if (m_drawThread) {
 87		return;
 88	}
 89	m_isDrawing = true;
 90	m_painter->setContext(controller);
 91	m_painter->setMessagePainter(messagePainter());
 92	m_context = controller;
 93	m_painter->resize(size());
 94	m_drawThread = new QThread(this);
 95	m_drawThread->setObjectName("Painter Thread");
 96	m_gl->doneCurrent();
 97	m_gl->moveToThread(m_drawThread);
 98	m_painter->moveToThread(m_drawThread);
 99	m_videoProxy.moveToThread(m_drawThread);
100	connect(m_drawThread, &QThread::started, m_painter, &PainterGL::start);
101	m_drawThread->start();
102
103	lockAspectRatio(isAspectRatioLocked());
104	lockIntegerScaling(isIntegerScalingLocked());
105	filter(isFiltered());
106#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
107	messagePainter()->resize(size(), isAspectRatioLocked(), devicePixelRatioF());
108#else
109	messagePainter()->resize(size(), isAspectRatioLocked(), devicePixelRatio());
110#endif
111	resizePainter();
112	connect(m_context.get(), &CoreController::didReset, this, &DisplayGL::resizeContext);
113}
114
115void DisplayGL::stopDrawing() {
116	if (m_drawThread) {
117		m_isDrawing = false;
118		CoreController::Interrupter interrupter(m_context);
119		QMetaObject::invokeMethod(m_painter, "stop", Qt::BlockingQueuedConnection);
120		m_drawThread->exit();
121		m_drawThread = nullptr;
122
123		m_gl->makeCurrent(windowHandle());
124#if defined(_WIN32) && defined(USE_EPOXY)
125		epoxy_handle_external_wglMakeCurrent();
126#endif
127	}
128	m_context.reset();
129}
130
131void DisplayGL::pauseDrawing() {
132	if (m_drawThread) {
133		m_isDrawing = false;
134		CoreController::Interrupter interrupter(m_context);
135		QMetaObject::invokeMethod(m_painter, "pause", Qt::BlockingQueuedConnection);
136	}
137}
138
139void DisplayGL::unpauseDrawing() {
140	if (m_drawThread) {
141		m_isDrawing = true;
142		CoreController::Interrupter interrupter(m_context);
143		QMetaObject::invokeMethod(m_painter, "unpause", Qt::BlockingQueuedConnection);
144	}
145}
146
147void DisplayGL::forceDraw() {
148	if (m_drawThread) {
149		QMetaObject::invokeMethod(m_painter, "forceDraw");
150	}
151}
152
153void DisplayGL::lockAspectRatio(bool lock) {
154	Display::lockAspectRatio(lock);
155	if (m_drawThread) {
156		QMetaObject::invokeMethod(m_painter, "lockAspectRatio", Q_ARG(bool, lock));
157	}
158}
159
160void DisplayGL::lockIntegerScaling(bool lock) {
161	Display::lockIntegerScaling(lock);
162	if (m_drawThread) {
163		QMetaObject::invokeMethod(m_painter, "lockIntegerScaling", Q_ARG(bool, lock));
164	}
165}
166
167void DisplayGL::filter(bool filter) {
168	Display::filter(filter);
169	if (m_drawThread) {
170		QMetaObject::invokeMethod(m_painter, "filter", Q_ARG(bool, filter));
171	}
172}
173
174void DisplayGL::framePosted() {
175	if (m_drawThread) {
176		m_painter->enqueue(m_context->drawContext());
177		QMetaObject::invokeMethod(m_painter, "draw");
178	}
179}
180
181void DisplayGL::setShaders(struct VDir* shaders) {
182	if (m_drawThread) {
183		QMetaObject::invokeMethod(m_painter, "setShaders", Qt::BlockingQueuedConnection, Q_ARG(struct VDir*, shaders));
184	} else {
185		m_painter->setShaders(shaders);
186	}
187}
188
189void DisplayGL::clearShaders() {
190	QMetaObject::invokeMethod(m_painter, "clearShaders");
191}
192
193
194void DisplayGL::resizeContext() {
195	if (m_drawThread) {
196		m_isDrawing = false;
197		CoreController::Interrupter interrupter(m_context);
198		QMetaObject::invokeMethod(m_painter, "resizeContext", Qt::BlockingQueuedConnection);
199	}
200}
201
202void DisplayGL::resizeEvent(QResizeEvent* event) {
203	Display::resizeEvent(event);
204	resizePainter();
205}
206
207void DisplayGL::resizePainter() {
208	if (m_drawThread) {
209		QMetaObject::invokeMethod(m_painter, "resize", Qt::BlockingQueuedConnection, Q_ARG(QSize, size()));
210	}
211}
212
213VideoProxy* DisplayGL::videoProxy() {
214	if (supportsShaders()) {
215		return &m_videoProxy;
216	}
217	return nullptr;
218}
219
220int DisplayGL::framebufferHandle() {
221	return m_painter->glTex();
222}
223
224PainterGL::PainterGL(VideoProxy* proxy, QWindow* surface, QOpenGLContext* parent)
225	: m_gl(parent)
226	, m_surface(surface)
227	, m_videoProxy(proxy)
228{
229#ifdef BUILD_GL
230	mGLContext* glBackend;
231#endif
232#ifdef BUILD_GLES2
233	mGLES2Context* gl2Backend;
234#endif
235
236	m_gl->makeCurrent(m_surface);
237	m_window = new QOpenGLPaintDevice;
238#if defined(_WIN32) && defined(USE_EPOXY)
239	epoxy_handle_external_wglMakeCurrent();
240#endif
241
242#ifdef BUILD_GLES2
243	auto version = m_gl->format().version();
244	QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
245	if ((version == qMakePair(2, 1) && extensions.contains("GL_ARB_framebuffer_object")) || version.first > 2) {
246		gl2Backend = static_cast<mGLES2Context*>(malloc(sizeof(mGLES2Context)));
247		mGLES2ContextCreate(gl2Backend);
248		m_backend = &gl2Backend->d;
249		m_supportsShaders = true;
250	}
251#endif
252
253#ifdef BUILD_GL
254	 if (!m_backend) {
255		glBackend = static_cast<mGLContext*>(malloc(sizeof(mGLContext)));
256		mGLContextCreate(glBackend);
257		m_backend = &glBackend->d;
258		m_supportsShaders = false;
259	}
260#endif
261	m_backend->swap = [](VideoBackend* v) {
262		PainterGL* painter = static_cast<PainterGL*>(v->user);
263		if (!painter->m_swapTimer.isActive()) {
264			QMetaObject::invokeMethod(&painter->m_swapTimer, "start");
265		}
266	};
267
268	m_backend->init(m_backend, 0);
269#ifdef BUILD_GLES2
270	if (m_supportsShaders) {
271		m_shader.preprocessShader = static_cast<void*>(&reinterpret_cast<mGLES2Context*>(m_backend)->initialShader);
272	}
273#endif
274	m_gl->doneCurrent();
275
276	m_backend->user = this;
277	m_backend->filter = false;
278	m_backend->lockAspectRatio = false;
279
280	for (int i = 0; i < 2; ++i) {
281		m_free.append(new uint32_t[1024 * 2048]);
282	}
283
284	m_swapTimer.setInterval(16);
285	m_swapTimer.setSingleShot(true);
286	connect(&m_swapTimer, &QTimer::timeout, this, &PainterGL::swap);
287}
288
289PainterGL::~PainterGL() {
290	while (!m_queue.isEmpty()) {
291		delete[] m_queue.dequeue();
292	}
293	for (auto item : m_free) {
294		delete[] item;
295	}
296	m_gl->makeCurrent(m_surface);
297#if defined(_WIN32) && defined(USE_EPOXY)
298	epoxy_handle_external_wglMakeCurrent();
299#endif
300#ifdef BUILD_GLES2
301	if (m_shader.passes) {
302		mGLES2ShaderFree(&m_shader);
303	}
304#endif
305	m_backend->deinit(m_backend);
306	m_gl->doneCurrent();
307	free(m_backend);
308	m_backend = nullptr;
309	delete m_window;
310}
311
312void PainterGL::setContext(std::shared_ptr<CoreController> context) {
313	m_context = context;
314	resizeContext();
315}
316
317void PainterGL::resizeContext() {
318	if (!m_context) {
319		return;
320	}
321
322	QSize size = m_context->screenDimensions();
323	m_backend->setDimensions(m_backend, size.width(), size.height());
324}
325
326void PainterGL::setMessagePainter(MessagePainter* messagePainter) {
327	m_messagePainter = messagePainter;
328}
329
330void PainterGL::resize(const QSize& size) {
331	m_size = size;
332	if (m_started && !m_active) {
333		forceDraw();
334	}
335}
336
337void PainterGL::lockAspectRatio(bool lock) {
338	m_backend->lockAspectRatio = lock;
339	resize(m_size);
340}
341
342void PainterGL::lockIntegerScaling(bool lock) {
343	m_backend->lockIntegerScaling = lock;
344	resize(m_size);
345}
346
347void PainterGL::filter(bool filter) {
348	m_backend->filter = filter;
349	if (m_started && !m_active) {
350		forceDraw();
351	}
352}
353
354void PainterGL::start() {
355	m_gl->makeCurrent(m_surface);
356#if defined(_WIN32) && defined(USE_EPOXY)
357	epoxy_handle_external_wglMakeCurrent();
358#endif
359
360#ifdef BUILD_GLES2
361	if (m_supportsShaders && m_shader.passes) {
362		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
363	}
364#endif
365
366	m_active = true;
367	m_started = true;
368}
369
370void PainterGL::draw() {
371	if (m_queue.isEmpty()) {
372		return;
373	}
374
375	if (m_needsUnlock) {
376		QTimer::singleShot(0, this, &PainterGL::draw);
377		return;
378	}
379
380	if (mCoreSyncWaitFrameStart(&m_context->thread()->impl->sync) || !m_queue.isEmpty()) {
381		dequeue();
382		forceDraw();
383		if (m_context->thread()->impl->sync.videoFrameWait) {
384			m_needsUnlock = true;
385		} else {
386			mCoreSyncWaitFrameEnd(&m_context->thread()->impl->sync);
387		}
388	} else {
389		mCoreSyncWaitFrameEnd(&m_context->thread()->impl->sync);
390	}
391}
392
393void PainterGL::forceDraw() {
394	m_painter.begin(m_window);
395	performDraw();
396	m_painter.end();
397	m_backend->swap(m_backend);
398}
399
400void PainterGL::stop() {
401	m_active = false;
402	m_started = false;
403	dequeueAll();
404	m_backend->clear(m_backend);
405	m_backend->swap(m_backend);
406	if (m_swapTimer.isActive()) {
407		swap();
408		m_swapTimer.stop();
409	}
410	if (m_videoProxy) {
411		m_videoProxy->reset();
412	}
413	m_gl->doneCurrent();
414	m_gl->moveToThread(m_surface->thread());
415	m_context.reset();
416	moveToThread(m_gl->thread());
417	m_videoProxy->moveToThread(m_gl->thread());
418}
419
420void PainterGL::pause() {
421	m_active = false;
422}
423
424void PainterGL::unpause() {
425	m_active = true;
426}
427
428void PainterGL::performDraw() {
429	m_painter.beginNativePainting();
430	float r = m_surface->devicePixelRatio();
431	m_backend->resized(m_backend, m_size.width() * r, m_size.height() * r);
432	m_backend->drawFrame(m_backend);
433	m_painter.endNativePainting();
434	if (m_messagePainter) {
435		m_messagePainter->paint(&m_painter);
436	}
437	m_frameReady = true;
438}
439
440void PainterGL::swap() {
441	if (!m_gl->isValid()) {
442		return;
443	}
444	if (m_frameReady) {
445		m_gl->swapBuffers(m_surface);
446		m_gl->makeCurrent(m_surface);
447#if defined(_WIN32) && defined(USE_EPOXY)
448		epoxy_handle_external_wglMakeCurrent();
449#endif
450		m_frameReady = false;
451	}
452	if (m_needsUnlock) {
453		mCoreSyncWaitFrameEnd(&m_context->thread()->impl->sync);
454		m_needsUnlock = false;
455	}
456	if (!m_queue.isEmpty()) {
457		QMetaObject::invokeMethod(this, "draw", Qt::QueuedConnection);
458	} else {
459		m_swapTimer.start();
460	}
461}
462
463void PainterGL::enqueue(const uint32_t* backing) {
464	m_mutex.lock();
465	uint32_t* buffer = nullptr;
466	if (backing) {
467		if (m_free.isEmpty()) {
468			buffer = m_queue.dequeue();
469		} else {
470			buffer = m_free.takeLast();
471		}
472		QSize size = m_context->screenDimensions();
473		memcpy(buffer, backing, size.width() * size.height() * BYTES_PER_PIXEL);
474	}
475	m_queue.enqueue(buffer);
476	m_mutex.unlock();
477}
478
479void PainterGL::dequeue() {
480	m_mutex.lock();
481	if (m_queue.isEmpty()) {
482		m_mutex.unlock();
483		return;
484	}
485	uint32_t* buffer = m_queue.dequeue();
486	if (buffer) {
487		m_backend->postFrame(m_backend, buffer);
488		m_free.append(buffer);
489	}
490	m_mutex.unlock();
491}
492
493void PainterGL::dequeueAll() {
494	uint32_t* buffer = 0;
495	m_mutex.lock();
496	while (!m_queue.isEmpty()) {
497		buffer = m_queue.dequeue();
498		if (buffer) {
499			m_free.append(buffer);
500		}
501	}
502	if (buffer) {
503		m_backend->postFrame(m_backend, buffer);
504	}
505	m_mutex.unlock();
506}
507
508void PainterGL::setShaders(struct VDir* dir) {
509	if (!supportsShaders()) {
510		return;
511	}
512#ifdef BUILD_GLES2
513	if (m_shader.passes) {
514		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
515		mGLES2ShaderFree(&m_shader);
516	}
517	mGLES2ShaderLoad(&m_shader, dir);
518	if (m_started) {
519		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
520	}
521#endif
522}
523
524void PainterGL::clearShaders() {
525	if (!supportsShaders()) {
526		return;
527	}
528#ifdef BUILD_GLES2
529	if (m_shader.passes) {
530		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
531		mGLES2ShaderFree(&m_shader);
532	}
533#endif
534}
535
536VideoShader* PainterGL::shaders() {
537	return &m_shader;
538}
539
540int PainterGL::glTex() {
541#ifdef BUILD_GLES2
542	if (supportsShaders()) {
543		mGLES2Context* gl2Backend = reinterpret_cast<mGLES2Context*>(m_backend);
544		return gl2Backend->tex;
545	}
546#endif
547#ifdef BUILD_GL
548	mGLContext* glBackend = reinterpret_cast<mGLContext*>(m_backend);
549	return glBackend->tex;
550#else
551	return -1;
552#endif
553}
554
555#endif