all repos — mgba @ e217a1fefb8b87de47a62422f42dfc6009591d2c

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		setUpdatesEnabled(true);
149	}
150}
151
152void DisplayGL::unpauseDrawing() {
153	if (m_drawThread) {
154		m_isDrawing = true;
155		CoreController::Interrupter interrupter(m_context);
156		QMetaObject::invokeMethod(m_painter, "unpause", Qt::BlockingQueuedConnection);
157		setUpdatesEnabled(false);
158	}
159}
160
161void DisplayGL::forceDraw() {
162	if (m_drawThread) {
163		QMetaObject::invokeMethod(m_painter, "forceDraw");
164	}
165}
166
167void DisplayGL::lockAspectRatio(bool lock) {
168	Display::lockAspectRatio(lock);
169	if (m_drawThread) {
170		QMetaObject::invokeMethod(m_painter, "lockAspectRatio", Q_ARG(bool, lock));
171	}
172}
173
174void DisplayGL::lockIntegerScaling(bool lock) {
175	Display::lockIntegerScaling(lock);
176	if (m_drawThread) {
177		QMetaObject::invokeMethod(m_painter, "lockIntegerScaling", Q_ARG(bool, lock));
178	}
179}
180
181void DisplayGL::interframeBlending(bool enable) {
182	Display::interframeBlending(enable);
183	if (m_drawThread) {
184		QMetaObject::invokeMethod(m_painter, "interframeBlending", Q_ARG(bool, enable));
185	}
186}
187
188void DisplayGL::showOSDMessages(bool enable) {
189	Display::showOSDMessages(enable);
190	if (m_drawThread) {
191		QMetaObject::invokeMethod(m_painter, "showOSD", Q_ARG(bool, enable));
192	}
193}
194
195void DisplayGL::filter(bool filter) {
196	Display::filter(filter);
197	if (m_drawThread) {
198		QMetaObject::invokeMethod(m_painter, "filter", Q_ARG(bool, filter));
199	}
200}
201
202void DisplayGL::framePosted() {
203	if (m_drawThread) {
204		m_painter->enqueue(m_context->drawContext());
205		QMetaObject::invokeMethod(m_painter, "draw");
206	}
207}
208
209void DisplayGL::setShaders(struct VDir* shaders) {
210	if (m_drawThread) {
211		QMetaObject::invokeMethod(m_painter, "setShaders", Qt::BlockingQueuedConnection, Q_ARG(struct VDir*, shaders));
212	} else {
213		m_painter->setShaders(shaders);
214	}
215}
216
217void DisplayGL::clearShaders() {
218	QMetaObject::invokeMethod(m_painter, "clearShaders");
219}
220
221void DisplayGL::resizeContext() {
222	if (m_drawThread) {
223		m_isDrawing = false;
224		CoreController::Interrupter interrupter(m_context);
225		QMetaObject::invokeMethod(m_painter, "resizeContext", Qt::BlockingQueuedConnection);
226	}
227}
228
229void DisplayGL::setVideoScale(int scale) {
230	if (m_drawThread) {
231		m_isDrawing = false;
232		CoreController::Interrupter interrupter(m_context);
233		mCoreConfigSetIntValue(&m_context->thread()->core->config, "videoScale", scale);
234		QMetaObject::invokeMethod(m_painter, "resizeContext", Qt::BlockingQueuedConnection);
235	}
236}
237
238void DisplayGL::resizeEvent(QResizeEvent* event) {
239	Display::resizeEvent(event);
240	resizePainter();
241}
242
243void DisplayGL::resizePainter() {
244	if (m_drawThread) {
245		QMetaObject::invokeMethod(m_painter, "resize", Qt::BlockingQueuedConnection, Q_ARG(QSize, size()));
246	}
247}
248
249void DisplayGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
250	Display::setVideoProxy(proxy);
251	if (m_drawThread && proxy) {
252		proxy->moveToThread(m_drawThread);
253	}
254	m_painter->setVideoProxy(proxy);
255}
256
257int DisplayGL::framebufferHandle() {
258	return m_painter->glTex();
259}
260
261PainterGL::PainterGL(QWindow* surface, QOpenGLContext* parent, int forceVersion)
262	: m_gl(parent)
263	, m_surface(surface)
264{
265#ifdef BUILD_GL
266	mGLContext* glBackend;
267#endif
268#ifdef BUILD_GLES2
269	mGLES2Context* gl2Backend;
270#endif
271
272	m_gl->makeCurrent(m_surface);
273	m_window = new QOpenGLPaintDevice;
274	{
275		// XXX: Qt creates TLS for OpenGL objects in the local thread
276		// We need to prevent that thread from being the painter thread
277		// Qt also caches the engine object on the device if a different
278		// engine is active, so let's make a temporary one
279		QOpenGLPaintDevice* fakeDevice = new QOpenGLPaintDevice;
280		QPainter fakePainter(fakeDevice);
281		m_window->paintEngine();
282	}
283#if defined(_WIN32) && defined(USE_EPOXY)
284	epoxy_handle_external_wglMakeCurrent();
285#endif
286
287#ifdef BUILD_GLES2
288	auto version = m_gl->format().version();
289	QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
290	if (forceVersion != 1 && ((version == qMakePair(2, 1) && extensions.contains("GL_ARB_framebuffer_object")) || version.first > 2)) {
291		gl2Backend = static_cast<mGLES2Context*>(malloc(sizeof(mGLES2Context)));
292		mGLES2ContextCreate(gl2Backend);
293		m_backend = &gl2Backend->d;
294		m_supportsShaders = true;
295	}
296#endif
297
298#ifdef BUILD_GL
299	 if (!m_backend) {
300		glBackend = static_cast<mGLContext*>(malloc(sizeof(mGLContext)));
301		mGLContextCreate(glBackend);
302		m_backend = &glBackend->d;
303		m_supportsShaders = false;
304	}
305#endif
306	m_backend->swap = [](VideoBackend* v) {
307		PainterGL* painter = static_cast<PainterGL*>(v->user);
308		if (!painter->m_gl->isValid()) {
309			return;
310		}
311		painter->m_gl->swapBuffers(painter->m_surface);
312		painter->m_gl->makeCurrent(painter->m_surface);
313#if defined(_WIN32) && defined(USE_EPOXY)
314		epoxy_handle_external_wglMakeCurrent();
315#endif
316	};
317
318	m_backend->init(m_backend, 0);
319#ifdef BUILD_GLES2
320	if (m_supportsShaders) {
321		m_shader.preprocessShader = static_cast<void*>(&reinterpret_cast<mGLES2Context*>(m_backend)->initialShader);
322	}
323#endif
324
325	m_backend->user = this;
326	m_backend->filter = false;
327	m_backend->lockAspectRatio = false;
328	m_backend->interframeBlending = false;
329
330	for (int i = 0; i < 2; ++i) {
331		m_free.append(new uint32_t[1024 * 2048]);
332	}
333}
334
335PainterGL::~PainterGL() {
336	while (!m_queue.isEmpty()) {
337		delete[] m_queue.dequeue();
338	}
339	for (auto item : m_free) {
340		delete[] item;
341	}
342	m_gl->makeCurrent(m_surface);
343#if defined(_WIN32) && defined(USE_EPOXY)
344	epoxy_handle_external_wglMakeCurrent();
345#endif
346#ifdef BUILD_GLES2
347	if (m_shader.passes) {
348		mGLES2ShaderFree(&m_shader);
349	}
350#endif
351	m_backend->deinit(m_backend);
352	m_gl->doneCurrent();
353	free(m_backend);
354	m_backend = nullptr;
355	delete m_window;
356}
357
358void PainterGL::setContext(std::shared_ptr<CoreController> context) {
359	m_context = context;
360	resizeContext();
361}
362
363void PainterGL::resizeContext() {
364	if (!m_context) {
365		return;
366	}
367
368	if (m_started) {
369		mCore* core = m_context->thread()->core;
370		core->reloadConfigOption(core, "videoScale", NULL);
371	}
372
373	QSize size = m_context->screenDimensions();
374	m_backend->setDimensions(m_backend, size.width(), size.height());
375}
376
377void PainterGL::setMessagePainter(MessagePainter* messagePainter) {
378	m_messagePainter = messagePainter;
379}
380
381void PainterGL::resize(const QSize& size) {
382	m_size = size;
383	m_window->setSize(m_size);
384	if (m_started && !m_active) {
385		forceDraw();
386	}
387}
388
389void PainterGL::lockAspectRatio(bool lock) {
390	m_backend->lockAspectRatio = lock;
391	resize(m_size);
392}
393
394void PainterGL::lockIntegerScaling(bool lock) {
395	m_backend->lockIntegerScaling = lock;
396	resize(m_size);
397}
398
399void PainterGL::interframeBlending(bool enable) {
400	m_backend->interframeBlending = enable;
401}
402
403void PainterGL::showOSD(bool enable) {
404	m_showOSD = enable;
405}
406
407void PainterGL::filter(bool filter) {
408	m_backend->filter = filter;
409	if (m_started && !m_active) {
410		forceDraw();
411	}
412}
413
414void PainterGL::start() {
415	m_gl->makeCurrent(m_surface);
416#if defined(_WIN32) && defined(USE_EPOXY)
417	epoxy_handle_external_wglMakeCurrent();
418#endif
419
420#ifdef BUILD_GLES2
421	if (m_supportsShaders && m_shader.passes) {
422		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
423	}
424#endif
425
426	m_active = true;
427	m_started = true;
428}
429
430void PainterGL::draw() {
431	if (!m_active || m_queue.isEmpty()) {
432		return;
433	}
434	mCoreSync* sync = &m_context->thread()->impl->sync;
435	mCoreSyncWaitFrameStart(sync);
436	dequeue();
437	if (!m_delayTimer.isValid()) {
438		m_delayTimer.start();
439	} else if (sync->audioWait || sync->videoFrameWait) {
440		while (m_delayTimer.nsecsElapsed() + 2000000 < 1000000000 / sync->fpsTarget) {
441			QThread::usleep(500);
442		}
443		m_delayTimer.restart();
444	}
445	mCoreSyncWaitFrameEnd(sync);
446
447	forceDraw();
448}
449
450void PainterGL::forceDraw() {
451	m_painter.begin(m_window);
452	performDraw();
453	m_painter.end();
454	if (!m_context->thread()->impl->sync.audioWait && !m_context->thread()->impl->sync.videoFrameWait) {
455		if (m_delayTimer.elapsed() < 1000 / m_surface->screen()->refreshRate()) {
456			return;
457		}
458		m_delayTimer.restart();
459	}
460	m_backend->swap(m_backend);
461}
462
463void PainterGL::stop() {
464	m_active = false;
465	m_started = false;
466	dequeueAll();
467	m_backend->clear(m_backend);
468	m_backend->swap(m_backend);
469	if (m_videoProxy) {
470		m_videoProxy->reset();
471	}
472	m_gl->doneCurrent();
473	m_gl->moveToThread(m_surface->thread());
474	m_context.reset();
475	moveToThread(m_gl->thread());
476	if (m_videoProxy) {
477		m_videoProxy->moveToThread(m_gl->thread());
478	}
479}
480
481void PainterGL::pause() {
482	m_active = false;
483}
484
485void PainterGL::unpause() {
486	m_active = true;
487}
488
489void PainterGL::performDraw() {
490	m_painter.beginNativePainting();
491	float r = m_surface->devicePixelRatio();
492	m_backend->resized(m_backend, m_size.width() * r, m_size.height() * r);
493	m_backend->drawFrame(m_backend);
494	m_painter.endNativePainting();
495	if (m_showOSD && m_messagePainter) {
496		m_messagePainter->paint(&m_painter);
497	}
498}
499
500void PainterGL::enqueue(const uint32_t* backing) {
501	m_mutex.lock();
502	uint32_t* buffer = nullptr;
503	if (backing) {
504		if (m_free.isEmpty()) {
505			buffer = m_queue.dequeue();
506		} else {
507			buffer = m_free.takeLast();
508		}
509		QSize size = m_context->screenDimensions();
510		memcpy(buffer, backing, size.width() * size.height() * BYTES_PER_PIXEL);
511	}
512	m_queue.enqueue(buffer);
513	m_mutex.unlock();
514}
515
516void PainterGL::dequeue() {
517	m_mutex.lock();
518	if (m_queue.isEmpty()) {
519		m_mutex.unlock();
520		return;
521	}
522	uint32_t* buffer = m_queue.dequeue();
523	if (buffer) {
524		m_backend->postFrame(m_backend, buffer);
525		m_free.append(buffer);
526	}
527	m_mutex.unlock();
528}
529
530void PainterGL::dequeueAll() {
531	uint32_t* buffer = 0;
532	m_mutex.lock();
533	while (!m_queue.isEmpty()) {
534		buffer = m_queue.dequeue();
535		if (buffer) {
536			m_free.append(buffer);
537		}
538	}
539	if (buffer) {
540		m_backend->postFrame(m_backend, buffer);
541	}
542	m_mutex.unlock();
543}
544
545void PainterGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
546	m_videoProxy = proxy;
547}
548
549void PainterGL::setShaders(struct VDir* dir) {
550	if (!supportsShaders()) {
551		return;
552	}
553#ifdef BUILD_GLES2
554	if (!m_started) {
555		m_gl->makeCurrent(m_surface);
556#if defined(_WIN32) && defined(USE_EPOXY)
557		epoxy_handle_external_wglMakeCurrent();
558#endif
559	}
560	if (m_shader.passes) {
561		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
562		mGLES2ShaderFree(&m_shader);
563	}
564	mGLES2ShaderLoad(&m_shader, dir);
565	if (m_started) {
566		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
567	} else {
568		m_gl->doneCurrent();
569	}
570#endif
571}
572
573void PainterGL::clearShaders() {
574	if (!supportsShaders()) {
575		return;
576	}
577#ifdef BUILD_GLES2
578	if (!m_started) {
579		m_gl->makeCurrent(m_surface);
580#if defined(_WIN32) && defined(USE_EPOXY)
581		epoxy_handle_external_wglMakeCurrent();
582#endif
583	}
584	if (m_shader.passes) {
585		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
586		mGLES2ShaderFree(&m_shader);
587	}
588	if (!m_started) {
589		m_gl->doneCurrent();
590	}
591#endif
592}
593
594VideoShader* PainterGL::shaders() {
595	return &m_shader;
596}
597
598int PainterGL::glTex() {
599#ifdef BUILD_GLES2
600	if (supportsShaders()) {
601		mGLES2Context* gl2Backend = reinterpret_cast<mGLES2Context*>(m_backend);
602		return gl2Backend->tex;
603	}
604#endif
605#ifdef BUILD_GL
606	mGLContext* glBackend = reinterpret_cast<mGLContext*>(m_backend);
607	return glBackend->tex[0];
608#else
609	return -1;
610#endif
611}
612
613#endif