all repos — mgba @ 9064cb107be54ba78c0652e88d2eee5608754725

mGBA Game Boy Advance Emulator

src/platform/qt/FrameView.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 "FrameView.h"
  7
  8#include <QMouseEvent>
  9#include <QPalette>
 10
 11#include <array>
 12#include <cmath>
 13
 14#include "CoreController.h"
 15#include "GBAApp.h"
 16
 17#include <mgba/core/core.h>
 18#include <mgba/feature/video-logger.h>
 19#ifdef M_CORE_GBA
 20#include <mgba/internal/gba/gba.h>
 21#include <mgba/internal/gba/io.h>
 22#include <mgba/internal/gba/memory.h>
 23#include <mgba/internal/gba/video.h>
 24#endif
 25#ifdef M_CORE_GB
 26#include <mgba/internal/gb/gb.h>
 27#include <mgba/internal/gb/io.h>
 28#include <mgba/internal/gb/memory.h>
 29#endif
 30
 31using namespace QGBA;
 32
 33FrameView::FrameView(std::shared_ptr<CoreController> controller, QWidget* parent)
 34	: AssetView(controller, parent)
 35{
 36	m_ui.setupUi(this);
 37
 38	m_glowTimer.setInterval(33);
 39	connect(&m_glowTimer, &QTimer::timeout, this, [this]() {
 40		++m_glowFrame;
 41		invalidateQueue();
 42	});
 43
 44	m_ui.compositedView->installEventFilter(this);
 45
 46	connect(m_ui.queue, &QListWidget::itemChanged, this, [this](QListWidgetItem* item) {
 47		Layer& layer = m_queue[item->data(Qt::UserRole).toInt()];
 48		layer.enabled = item->checkState() == Qt::Checked;
 49		if (layer.enabled) {
 50			m_disabled.remove(layer.id);
 51		} else {
 52			m_disabled.insert(layer.id);
 53		}
 54		invalidateQueue();
 55	});
 56	connect(m_ui.queue, &QListWidget::currentItemChanged, this, [this](QListWidgetItem* item) {
 57		if (item) {
 58			m_active = m_queue[item->data(Qt::UserRole).toInt()].id;
 59		} else {
 60			m_active = {};
 61		}
 62		invalidateQueue();
 63	});
 64	connect(m_ui.magnification, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [this]() {
 65		invalidateQueue();
 66	});
 67	connect(m_ui.exportButton, &QAbstractButton::pressed, this, &FrameView::exportFrame);
 68	connect(m_ui.reset, &QAbstractButton::pressed, this, &FrameView::reset);
 69
 70	m_backdropPicker = ColorPicker(m_ui.backdrop, QColor(0, 0, 0, 0));
 71	connect(&m_backdropPicker, &ColorPicker::colorChanged, this, [this](const QColor& color) {
 72		m_overrideBackdrop = color;
 73	});
 74	m_controller->addFrameAction(std::bind(&FrameView::frameCallback, this, m_callbackLocker));
 75
 76	{
 77		CoreController::Interrupter interrupter(m_controller);
 78		refreshVl();
 79	}
 80	m_controller->frameAdvance();
 81}
 82
 83FrameView::~FrameView() {
 84	QMutexLocker locker(&m_mutex);
 85	*m_callbackLocker = false;
 86	if (m_vl) {
 87		m_vl->deinit(m_vl);
 88	}
 89}
 90
 91bool FrameView::lookupLayer(const QPointF& coord, Layer*& out) {
 92	for (Layer& layer : m_queue) {
 93		if (!layer.enabled || m_disabled.contains(layer.id)) {
 94			continue;
 95		}
 96		QPointF location = layer.location;
 97		QSizeF layerDims(layer.image.width(), layer.image.height());
 98		QRegion region;
 99		if (layer.repeats) {
100			if (location.x() + layerDims.width() < 0) {
101				location.setX(std::fmod(location.x(), layerDims.width()));
102			}
103			if (location.y() + layerDims.height() < 0) {
104				location.setY(std::fmod(location.y(), layerDims.height()));
105			}
106
107			region += layer.mask.translated(location.x(), location.y());
108			region += layer.mask.translated(location.x() + layerDims.width(), location.y());
109			region += layer.mask.translated(location.x(), location.y() + layerDims.height());
110			region += layer.mask.translated(location.x() + layerDims.width(), location.y() + layerDims.height());
111		} else {
112			region = layer.mask.translated(location.x(), location.y());
113		}
114
115		if (region.contains(QPoint(coord.x(), coord.y()))) {
116			out = &layer;
117			return true;
118		}
119	}
120	return false;
121}
122
123void FrameView::selectLayer(const QPointF& coord) {
124	Layer* layer;
125	if (!lookupLayer(coord, layer)) {
126		return;
127	}
128	if (layer->id == m_active) {
129		m_active = {};
130	} else {
131		m_active = layer->id;
132	}
133	m_glowFrame = 0;
134}
135
136void FrameView::disableLayer(const QPointF& coord) {
137	Layer* layer;
138	if (!lookupLayer(coord, layer)) {
139		return;
140	}
141	layer->enabled = false;
142	m_disabled.insert(layer->id);
143}
144
145#ifdef M_CORE_GBA
146void FrameView::updateTilesGBA(bool) {
147	if (m_ui.freeze->checkState() == Qt::Checked) {
148		return;
149	}
150	QMutexLocker locker(&m_mutex);
151	m_queue.clear();
152	{
153		CoreController::Interrupter interrupter(m_controller);
154
155		uint16_t* io = static_cast<GBA*>(m_controller->thread()->core->board)->memory.io;
156		QRgb backdrop = M_RGB5_TO_RGB8(static_cast<GBA*>(m_controller->thread()->core->board)->video.palette[0]);
157		m_gbaDispcnt = io[REG_DISPCNT >> 1];
158		int mode = GBARegisterDISPCNTGetMode(m_gbaDispcnt);
159
160		std::array<bool, 4> enabled{
161			bool(GBARegisterDISPCNTIsBg0Enable(m_gbaDispcnt)),
162			bool(GBARegisterDISPCNTIsBg1Enable(m_gbaDispcnt)),
163			bool(GBARegisterDISPCNTIsBg2Enable(m_gbaDispcnt)),
164			bool(GBARegisterDISPCNTIsBg3Enable(m_gbaDispcnt)),
165		};
166
167		for (int priority = 0; priority < 4; ++priority) {
168			for (int sprite = 0; sprite < 128; ++sprite) {
169				ObjInfo info;
170				lookupObj(sprite, &info);
171
172				if (!info.enabled || info.priority != priority) {
173					continue;
174				}
175
176				QPointF offset(info.x, info.y);
177				QImage obj(compositeObj(info));
178				if (info.hflip || info.vflip) {
179					obj = obj.mirrored(info.hflip, info.vflip);
180				}
181				if (!info.xform.isIdentity()) {
182					offset += QPointF(obj.width(), obj.height()) / 2;
183					obj = obj.transformed(info.xform);
184					offset -= QPointF(obj.width() / 2, obj.height() / 2);
185				}
186				m_queue.append({
187					{ LayerId::SPRITE, sprite },
188					!m_disabled.contains({ LayerId::SPRITE, sprite }),
189					QPixmap::fromImage(obj),
190					{}, offset, false, false
191				});
192				if (m_queue.back().image.hasAlpha()) {
193					m_queue.back().mask = QRegion(m_queue.back().image.mask());
194				} else {
195					m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
196				}
197			}
198
199			for (int bg = 0; bg < 4; ++bg) {
200				if (!enabled[bg]) {
201					continue;
202				}
203				if (GBARegisterBGCNTGetPriority(io[(REG_BG0CNT >> 1) + bg]) != priority) {
204					continue;
205				}
206
207				QPointF offset;
208				if (mode == 0) {
209					offset.setX(-(io[(REG_BG0HOFS >> 1) + (bg << 1)] & 0x1FF));
210					offset.setY(-(io[(REG_BG0VOFS >> 1) + (bg << 1)] & 0x1FF));
211				};
212				m_queue.append({
213					{ LayerId::BACKGROUND, bg },
214					!m_disabled.contains({ LayerId::BACKGROUND, bg }),
215					QPixmap::fromImage(compositeMap(bg, m_mapStatus[bg])),
216					{}, offset, true, false
217				});
218				if (m_queue.back().image.hasAlpha()) {
219					m_queue.back().mask = QRegion(m_queue.back().image.mask());
220				} else {
221					m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
222				}
223			}
224		}
225		QImage backdropImage(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS), QImage::Format_Mono);
226		backdropImage.fill(1);
227		backdropImage.setColorTable({backdrop, backdrop | 0xFF000000 });
228		m_queue.append({
229			{ LayerId::BACKDROP },
230			!m_disabled.contains({ LayerId::BACKDROP }),
231			QPixmap::fromImage(backdropImage),
232			{}, {0, 0}, false, true
233		});
234		updateRendered();
235	}
236	invalidateQueue(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS));
237}
238
239void FrameView::injectGBA() {
240	mVideoLogger* logger = m_vl->videoLogger;
241	GBA* gba = static_cast<GBA*>(m_vl->board);
242	gba->video.renderer->highlightBG[0] = false;
243	gba->video.renderer->highlightBG[1] = false;
244	gba->video.renderer->highlightBG[2] = false;
245	gba->video.renderer->highlightBG[3] = false;
246	for (int i = 0; i < 128; ++i) {
247		gba->video.renderer->highlightOBJ[i] = false;
248	}
249	QPalette palette;
250	gba->video.renderer->highlightColor = palette.color(QPalette::HighlightedText).rgb();
251	gba->video.renderer->highlightAmount = sin(m_glowFrame * M_PI / 30) * 48 + 64;
252	if (!m_overrideBackdrop.isValid()) {
253		QRgb backdrop = M_RGB5_TO_RGB8(gba->video.palette[0]) | 0xFF000000;
254		m_backdropPicker.setColor(backdrop);
255	}
256
257	m_vl->reset(m_vl);
258	for (const Layer& layer : m_queue) {
259		switch (layer.id.type) {
260		case LayerId::SPRITE:
261			if (!layer.enabled) {
262				mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0x200);
263			}
264			if (layer.id == m_active) {
265				gba->video.renderer->highlightOBJ[layer.id.index] = true;
266			}
267			break;
268		case LayerId::BACKGROUND:
269			m_vl->enableVideoLayer(m_vl, layer.id.index, layer.enabled);
270			if (layer.id == m_active) {
271				gba->video.renderer->highlightBG[layer.id.index] = true;
272			}
273			break;
274		}
275	}
276	if (m_overrideBackdrop.isValid()) {
277		mVideoLoggerInjectPalette(logger, 0, M_RGB8_TO_RGB5(m_overrideBackdrop.rgb()));
278	}
279}
280#endif
281
282#ifdef M_CORE_GB
283void FrameView::updateTilesGB(bool) {
284	if (m_ui.freeze->checkState() == Qt::Checked) {
285		return;
286	}
287	m_queue.clear();
288	{
289		CoreController::Interrupter interrupter(m_controller);
290		uint8_t* io = static_cast<GB*>(m_controller->thread()->core->board)->memory.io;
291		GBRegisterLCDC lcdc = io[GB_REG_LCDC];
292
293		for (int sprite = 0; sprite < 40; ++sprite) {
294			ObjInfo info;
295			lookupObj(sprite, &info);
296
297			if (!info.enabled) {
298				continue;
299			}
300
301			QPointF offset(info.x, info.y);
302			QImage obj(compositeObj(info));
303			if (info.hflip || info.vflip) {
304				obj = obj.mirrored(info.hflip, info.vflip);
305			}
306			m_queue.append({
307				{ LayerId::SPRITE, sprite },
308				!m_disabled.contains({ LayerId::SPRITE, sprite }),
309				QPixmap::fromImage(obj),
310				{}, offset, false, false
311			});
312			if (m_queue.back().image.hasAlpha()) {
313				m_queue.back().mask = QRegion(m_queue.back().image.mask());
314			} else {
315				m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
316			}
317		}
318
319		if (GBRegisterLCDCIsWindow(lcdc)) {
320			m_queue.append({
321				{ LayerId::WINDOW },
322				!m_disabled.contains({ LayerId::WINDOW }),
323				{},
324				{}, {0, 0}, false, false
325			});
326		}
327
328		m_queue.append({
329			{ LayerId::BACKGROUND },
330			!m_disabled.contains({ LayerId::BACKGROUND }),
331			{},
332			{}, {0, 0}, false, false
333		});
334
335		updateRendered();
336	}
337	invalidateQueue(m_controller->screenDimensions());
338}
339
340void FrameView::injectGB() {
341	mVideoLogger* logger = m_vl->videoLogger;
342
343	m_vl->reset(m_vl);
344	for (const Layer& layer : m_queue) {
345		switch (layer.id.type) {
346		case LayerId::SPRITE:
347			if (!layer.enabled) {
348				mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0);
349			}
350			break;
351		case LayerId::BACKGROUND:
352			m_vl->enableVideoLayer(m_vl, GB_LAYER_BACKGROUND, layer.enabled);
353			break;
354		case LayerId::WINDOW:
355			m_vl->enableVideoLayer(m_vl, GB_LAYER_WINDOW, layer.enabled);
356			break;
357		}
358	}
359}
360#endif
361
362void FrameView::invalidateQueue(const QSize& dims) {
363	if (dims.isValid()) {
364		m_dims = dims;
365	}
366	bool blockSignals = m_ui.queue->blockSignals(true);
367	QMutexLocker locker(&m_mutex);
368	if (m_vl) {
369		mVideoLogger* logger = m_vl->videoLogger;
370		mVideoLoggerInjectionPoint(logger, LOGGER_INJECTION_FIRST_SCANLINE);
371		switch (m_controller->platform()) {
372#ifdef M_CORE_GBA
373		case PLATFORM_GBA:
374			injectGBA();
375			break;
376#endif
377#ifdef M_CORE_GB
378		case PLATFORM_GB:
379			injectGB();
380			break;
381#endif
382		}
383		if (m_ui.disableScanline->checkState() == Qt::Checked) {
384			mVideoLoggerIgnoreAfterInjection(logger, (1 << DIRTY_PALETTE) | (1 << DIRTY_OAM) | (1 << DIRTY_REGISTER));
385		} else {
386			mVideoLoggerIgnoreAfterInjection(logger, 0);
387		}
388		m_vl->runFrame(m_vl);
389	}
390
391	for (int i = 0; i < m_queue.count(); ++i) {
392		const Layer& layer = m_queue[i];
393		QListWidgetItem* item;
394		if (i >= m_ui.queue->count()) {
395			item = new QListWidgetItem;
396			m_ui.queue->addItem(item);
397		} else {
398			item = m_ui.queue->item(i);
399		}
400		item->setText(layer.id.readable());
401		item->setFlags(Qt::ItemIsSelectable | (layer.fixed ? Qt::NoItemFlags : Qt::ItemIsUserCheckable) | Qt::ItemIsEnabled);
402		item->setCheckState(layer.enabled ? Qt::Checked : Qt::Unchecked);
403		item->setData(Qt::UserRole, i);
404		item->setSelected(layer.id == m_active);
405	}
406
407	while (m_ui.queue->count() > m_queue.count()) {
408		delete m_ui.queue->takeItem(m_queue.count());
409	}
410	m_ui.queue->blockSignals(blockSignals);
411
412	QPixmap composited;
413	if (m_framebuffer.isNull()) {
414		updateRendered();
415		composited = m_rendered;
416	} else {
417		QImage framebuffer(m_framebuffer);
418		m_ui.exportButton->setEnabled(true);
419		if (framebuffer.size() != m_dims) {
420			framebuffer = framebuffer.copy({QPoint(), m_dims});
421		}
422		composited.convertFromImage(framebuffer);
423	}
424	m_composited = composited.scaled(m_dims * m_ui.magnification->value());
425	m_ui.compositedView->setPixmap(m_composited);
426}
427
428void FrameView::updateRendered() {
429	if (m_ui.freeze->checkState() == Qt::Checked) {
430		return;
431	}
432	m_rendered.convertFromImage(m_controller->getPixels());
433}
434
435bool FrameView::eventFilter(QObject* obj, QEvent* event) {
436	QPointF pos;
437	switch (event->type()) {
438	case QEvent::MouseButtonPress:
439		pos = static_cast<QMouseEvent*>(event)->localPos();
440		pos /= m_ui.magnification->value();
441		selectLayer(pos);
442		return true;
443	case QEvent::MouseButtonDblClick:
444		pos = static_cast<QMouseEvent*>(event)->localPos();
445		pos /= m_ui.magnification->value();
446		disableLayer(pos);
447		return true;
448	default:
449		break;
450	}
451	return false;
452}
453
454void FrameView::refreshVl() {
455	QMutexLocker locker(&m_mutex);
456	m_currentFrame = m_nextFrame;
457	m_nextFrame = VFileMemChunk(nullptr, 0);
458	if (m_currentFrame) {
459		m_controller->endVideoLog(false);
460		QMetaObject::invokeMethod(this, "newVl");
461	}
462	m_controller->endVideoLog();
463	m_controller->startVideoLog(m_nextFrame, false);
464}
465
466void FrameView::newVl() {
467	if (!m_glowTimer.isActive()) {
468		m_glowTimer.start();
469	}
470	QMutexLocker locker(&m_mutex);
471	if (!m_currentFrame) {
472		return;
473	}
474	if (m_vl) {
475		m_vl->deinit(m_vl);
476	}
477	m_vl = mCoreFindVF(m_currentFrame);
478	m_vl->init(m_vl);
479	m_vl->loadROM(m_vl, m_currentFrame);
480	m_currentFrame = nullptr;
481	mCoreInitConfig(m_vl, nullptr);
482	unsigned width, height;
483	m_vl->desiredVideoDimensions(m_vl, &width, &height);
484	m_framebuffer = QImage(width, height, QImage::Format_RGBX8888);
485	m_vl->setVideoBuffer(m_vl, reinterpret_cast<color_t*>(m_framebuffer.bits()), width);
486	m_vl->reset(m_vl);
487}
488
489void FrameView::frameCallback(FrameView* viewer, std::shared_ptr<bool> lock) {
490	if (!*lock) {
491		return;
492	}
493	CoreController::Interrupter interrupter(viewer->m_controller, true);
494	viewer->refreshVl();
495	viewer->m_controller->addFrameAction(std::bind(&FrameView::frameCallback, viewer, lock));
496}
497
498void FrameView::exportFrame() {
499	QString filename = GBAApp::app()->getSaveFileName(this, tr("Export frame"),
500	                                                  tr("Portable Network Graphics (*.png)"));
501	CoreController::Interrupter interrupter(m_controller);
502	m_framebuffer.save(filename, "PNG");
503}
504
505void FrameView::reset() {
506	m_disabled.clear();
507	for (Layer& layer : m_queue) {
508		layer.enabled = true;
509	}
510	m_overrideBackdrop = QColor();
511	invalidateQueue();
512}
513
514QString FrameView::LayerId::readable() const {
515	QString typeStr;
516	switch (type) {
517	case NONE:
518		return tr("None");
519	case BACKGROUND:
520		typeStr = tr("Background");
521		break;
522	case WINDOW:
523		typeStr = tr("Window");
524		break;
525	case SPRITE:
526		typeStr = tr("Sprite");
527		break;
528	case BACKDROP:
529		typeStr = tr("Backdrop");
530		break;
531	case FRAME:
532		typeStr = tr("Frame");
533		break;
534	}
535	if (index < 0) {
536		return typeStr;
537	}
538	return tr("%1 %2").arg(typeStr).arg(index);
539}