all repos — mgba @ 8708a0db52de758753a675bc646fb7b6cdafb874

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