all repos — mgba @ 9bbdd2ba350aac319ca9b24eba042ce81070df9f

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