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 GBARegisterDISPCNT gbaDispcnt = io[REG_DISPCNT >> 1];
158 int mode = GBARegisterDISPCNTGetMode(gbaDispcnt);
159
160 std::array<bool, 4> enabled{
161 bool(GBARegisterDISPCNTIsBg0Enable(gbaDispcnt)),
162 bool(GBARegisterDISPCNTIsBg1Enable(gbaDispcnt)),
163 bool(GBARegisterDISPCNTIsBg2Enable(gbaDispcnt)),
164 bool(GBARegisterDISPCNTIsBg3Enable(gbaDispcnt)),
165 };
166
167 if (GBARegisterDISPCNTIsWin0Enable(gbaDispcnt)) {
168 m_queue.append({
169 { LayerId::WINDOW, 0 },
170 !m_disabled.contains({ LayerId::WINDOW, 0 }),
171 {},
172 {}, {0, 0}, true, false
173 });
174 }
175
176 if (GBARegisterDISPCNTIsWin1Enable(gbaDispcnt)) {
177 m_queue.append({
178 { LayerId::WINDOW, 1 },
179 !m_disabled.contains({ LayerId::WINDOW, 1 }),
180 {},
181 {}, {0, 0}, true, false
182 });
183 }
184
185 if (GBARegisterDISPCNTIsObjwinEnable(gbaDispcnt)) {
186 m_queue.append({
187 { LayerId::WINDOW, 2 },
188 !m_disabled.contains({ LayerId::WINDOW, 2 }),
189 {},
190 {}, {0, 0}, true, false
191 });
192
193 }
194
195 for (int priority = 0; priority < 4; ++priority) {
196 for (int sprite = 0; sprite < 128; ++sprite) {
197 ObjInfo info;
198 lookupObj(sprite, &info);
199
200 if (!info.enabled || info.priority != priority) {
201 continue;
202 }
203
204 QPointF offset(info.x, info.y);
205 QImage obj(compositeObj(info));
206 if (info.hflip || info.vflip) {
207 obj = obj.mirrored(info.hflip, info.vflip);
208 }
209 if (!info.xform.isIdentity()) {
210 offset += QPointF(obj.width(), obj.height()) / 2;
211 obj = obj.transformed(info.xform);
212 offset -= QPointF(obj.width() / 2, obj.height() / 2);
213 }
214 m_queue.append({
215 { LayerId::SPRITE, sprite },
216 !m_disabled.contains({ LayerId::SPRITE, sprite }),
217 QPixmap::fromImage(obj),
218 {}, offset, false, false
219 });
220 if (m_queue.back().image.hasAlpha()) {
221 m_queue.back().mask = QRegion(m_queue.back().image.mask());
222 } else {
223 m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
224 }
225 }
226
227 for (int bg = 0; bg < 4; ++bg) {
228 if (!enabled[bg]) {
229 continue;
230 }
231 if (GBARegisterBGCNTGetPriority(io[(REG_BG0CNT >> 1) + bg]) != priority) {
232 continue;
233 }
234
235 QPointF offset;
236 if (mode == 0) {
237 offset.setX(-(io[(REG_BG0HOFS >> 1) + (bg << 1)] & 0x1FF));
238 offset.setY(-(io[(REG_BG0VOFS >> 1) + (bg << 1)] & 0x1FF));
239 };
240 m_queue.append({
241 { LayerId::BACKGROUND, bg },
242 !m_disabled.contains({ LayerId::BACKGROUND, bg }),
243 QPixmap::fromImage(compositeMap(bg, m_mapStatus[bg])),
244 {}, offset, true, false
245 });
246 if (m_queue.back().image.hasAlpha()) {
247 m_queue.back().mask = QRegion(m_queue.back().image.mask());
248 } else {
249 m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
250 }
251 }
252 }
253 QImage backdropImage(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS), QImage::Format_Mono);
254 backdropImage.fill(1);
255 backdropImage.setColorTable({backdrop, backdrop | 0xFF000000 });
256 m_queue.append({
257 { LayerId::BACKDROP },
258 !m_disabled.contains({ LayerId::BACKDROP }),
259 QPixmap::fromImage(backdropImage),
260 {}, {0, 0}, false, true
261 });
262 updateRendered();
263 }
264 invalidateQueue(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS));
265}
266
267void FrameView::injectGBA() {
268 mVideoLogger* logger = m_vl->videoLogger;
269 GBA* gba = static_cast<GBA*>(m_vl->board);
270 gba->video.renderer->highlightBG[0] = false;
271 gba->video.renderer->highlightBG[1] = false;
272 gba->video.renderer->highlightBG[2] = false;
273 gba->video.renderer->highlightBG[3] = false;
274 for (int i = 0; i < 128; ++i) {
275 gba->video.renderer->highlightOBJ[i] = false;
276 }
277 QPalette palette;
278 gba->video.renderer->highlightColor = palette.color(QPalette::HighlightedText).rgb();
279 gba->video.renderer->highlightAmount = sin(m_glowFrame * M_PI / 30) * 48 + 64;
280 if (!m_overrideBackdrop.isValid()) {
281 QRgb backdrop = M_RGB5_TO_RGB8(gba->video.palette[0]) | 0xFF000000;
282 m_backdropPicker.setColor(backdrop);
283 }
284
285 m_vl->reset(m_vl);
286 for (const Layer& layer : m_queue) {
287 switch (layer.id.type) {
288 case LayerId::SPRITE:
289 if (!layer.enabled) {
290 mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0x200);
291 }
292 if (layer.id == m_active) {
293 gba->video.renderer->highlightOBJ[layer.id.index] = true;
294 }
295 break;
296 case LayerId::BACKGROUND:
297 m_vl->enableVideoLayer(m_vl, layer.id.index, layer.enabled);
298 if (layer.id == m_active) {
299 gba->video.renderer->highlightBG[layer.id.index] = true;
300 }
301 break;
302 case LayerId::WINDOW:
303 m_vl->enableVideoLayer(m_vl, GBA_LAYER_WIN0 + layer.id.index, layer.enabled);
304 break;
305 }
306 }
307 if (m_overrideBackdrop.isValid()) {
308 mVideoLoggerInjectPalette(logger, 0, M_RGB8_TO_RGB5(m_overrideBackdrop.rgb()));
309 }
310}
311#endif
312
313#ifdef M_CORE_GB
314void FrameView::updateTilesGB(bool) {
315 if (m_ui.freeze->checkState() == Qt::Checked) {
316 return;
317 }
318 m_queue.clear();
319 {
320 CoreController::Interrupter interrupter(m_controller);
321 uint8_t* io = static_cast<GB*>(m_controller->thread()->core->board)->memory.io;
322 GBRegisterLCDC lcdc = io[GB_REG_LCDC];
323
324 for (int sprite = 0; sprite < 40; ++sprite) {
325 ObjInfo info;
326 lookupObj(sprite, &info);
327
328 if (!info.enabled) {
329 continue;
330 }
331
332 QPointF offset(info.x, info.y);
333 QImage obj(compositeObj(info));
334 if (info.hflip || info.vflip) {
335 obj = obj.mirrored(info.hflip, info.vflip);
336 }
337 m_queue.append({
338 { LayerId::SPRITE, sprite },
339 !m_disabled.contains({ LayerId::SPRITE, sprite }),
340 QPixmap::fromImage(obj),
341 {}, offset, false, false
342 });
343 if (m_queue.back().image.hasAlpha()) {
344 m_queue.back().mask = QRegion(m_queue.back().image.mask());
345 } else {
346 m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
347 }
348 }
349
350 if (GBRegisterLCDCIsWindow(lcdc)) {
351 m_queue.append({
352 { LayerId::WINDOW },
353 !m_disabled.contains({ LayerId::WINDOW }),
354 {},
355 {}, {0, 0}, false, false
356 });
357 }
358
359 m_queue.append({
360 { LayerId::BACKGROUND },
361 !m_disabled.contains({ LayerId::BACKGROUND }),
362 {},
363 {}, {0, 0}, false, false
364 });
365
366 updateRendered();
367 }
368 invalidateQueue(m_controller->screenDimensions());
369}
370
371void FrameView::injectGB() {
372 mVideoLogger* logger = m_vl->videoLogger;
373
374 m_vl->reset(m_vl);
375 for (const Layer& layer : m_queue) {
376 switch (layer.id.type) {
377 case LayerId::SPRITE:
378 if (!layer.enabled) {
379 mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0);
380 }
381 break;
382 case LayerId::BACKGROUND:
383 m_vl->enableVideoLayer(m_vl, GB_LAYER_BACKGROUND, layer.enabled);
384 break;
385 case LayerId::WINDOW:
386 m_vl->enableVideoLayer(m_vl, GB_LAYER_WINDOW, layer.enabled);
387 break;
388 }
389 }
390}
391#endif
392
393void FrameView::invalidateQueue(const QSize& dims) {
394 if (dims.isValid()) {
395 m_dims = dims;
396 }
397 bool blockSignals = m_ui.queue->blockSignals(true);
398 QMutexLocker locker(&m_mutex);
399 if (m_vl) {
400 mVideoLogger* logger = m_vl->videoLogger;
401 mVideoLoggerInjectionPoint(logger, LOGGER_INJECTION_FIRST_SCANLINE);
402 switch (m_controller->platform()) {
403#ifdef M_CORE_GBA
404 case PLATFORM_GBA:
405 injectGBA();
406 break;
407#endif
408#ifdef M_CORE_GB
409 case PLATFORM_GB:
410 injectGB();
411 break;
412#endif
413 }
414 if (m_ui.disableScanline->checkState() == Qt::Checked) {
415 mVideoLoggerIgnoreAfterInjection(logger, (1 << DIRTY_PALETTE) | (1 << DIRTY_OAM) | (1 << DIRTY_REGISTER));
416 } else {
417 mVideoLoggerIgnoreAfterInjection(logger, 0);
418 }
419 m_vl->runFrame(m_vl);
420 }
421
422 for (int i = 0; i < m_queue.count(); ++i) {
423 const Layer& layer = m_queue[i];
424 QListWidgetItem* item;
425 if (i >= m_ui.queue->count()) {
426 item = new QListWidgetItem;
427 m_ui.queue->addItem(item);
428 } else {
429 item = m_ui.queue->item(i);
430 }
431 item->setText(layer.id.readable());
432 item->setFlags(Qt::ItemIsSelectable | (layer.fixed ? Qt::NoItemFlags : Qt::ItemIsUserCheckable) | Qt::ItemIsEnabled);
433 item->setCheckState(layer.enabled ? Qt::Checked : Qt::Unchecked);
434 item->setData(Qt::UserRole, i);
435 item->setSelected(layer.id == m_active);
436 }
437
438 while (m_ui.queue->count() > m_queue.count()) {
439 delete m_ui.queue->takeItem(m_queue.count());
440 }
441 m_ui.queue->blockSignals(blockSignals);
442
443 QPixmap composited;
444 if (m_framebuffer.isNull()) {
445 updateRendered();
446 composited = m_rendered;
447 } else {
448 QImage framebuffer(m_framebuffer);
449 m_ui.exportButton->setEnabled(true);
450 if (framebuffer.size() != m_dims) {
451 framebuffer = framebuffer.copy({QPoint(), m_dims});
452 }
453 composited.convertFromImage(framebuffer);
454 }
455 m_composited = composited.scaled(m_dims * m_ui.magnification->value());
456 m_ui.compositedView->setPixmap(m_composited);
457}
458
459void FrameView::updateRendered() {
460 if (m_ui.freeze->checkState() == Qt::Checked) {
461 return;
462 }
463 m_rendered.convertFromImage(m_controller->getPixels());
464}
465
466bool FrameView::eventFilter(QObject* obj, QEvent* event) {
467 QPointF pos;
468 switch (event->type()) {
469 case QEvent::MouseButtonPress:
470 pos = static_cast<QMouseEvent*>(event)->localPos();
471 pos /= m_ui.magnification->value();
472 selectLayer(pos);
473 return true;
474 case QEvent::MouseButtonDblClick:
475 pos = static_cast<QMouseEvent*>(event)->localPos();
476 pos /= m_ui.magnification->value();
477 disableLayer(pos);
478 return true;
479 default:
480 break;
481 }
482 return false;
483}
484
485void FrameView::refreshVl() {
486 QMutexLocker locker(&m_mutex);
487 m_currentFrame = m_nextFrame;
488 m_nextFrame = VFileMemChunk(nullptr, 0);
489 if (m_currentFrame) {
490 m_controller->endVideoLog(false);
491 QMetaObject::invokeMethod(this, "newVl");
492 }
493 m_controller->endVideoLog();
494 m_controller->startVideoLog(m_nextFrame, false);
495}
496
497void FrameView::newVl() {
498 if (!m_glowTimer.isActive()) {
499 m_glowTimer.start();
500 }
501 QMutexLocker locker(&m_mutex);
502 if (!m_currentFrame) {
503 return;
504 }
505 if (m_vl) {
506 m_vl->deinit(m_vl);
507 }
508 m_vl = mCoreFindVF(m_currentFrame);
509 m_vl->init(m_vl);
510 m_vl->loadROM(m_vl, m_currentFrame);
511 m_currentFrame = nullptr;
512 mCoreInitConfig(m_vl, nullptr);
513 unsigned width, height;
514 m_vl->desiredVideoDimensions(m_vl, &width, &height);
515 m_framebuffer = QImage(width, height, QImage::Format_RGBX8888);
516 m_vl->setVideoBuffer(m_vl, reinterpret_cast<color_t*>(m_framebuffer.bits()), width);
517 m_vl->reset(m_vl);
518}
519
520void FrameView::frameCallback(FrameView* viewer, std::shared_ptr<bool> lock) {
521 if (!*lock) {
522 return;
523 }
524 CoreController::Interrupter interrupter(viewer->m_controller);
525 viewer->refreshVl();
526 viewer->m_controller->addFrameAction(std::bind(&FrameView::frameCallback, viewer, lock));
527}
528
529void FrameView::exportFrame() {
530 QString filename = GBAApp::app()->getSaveFileName(this, tr("Export frame"),
531 tr("Portable Network Graphics (*.png)"));
532 CoreController::Interrupter interrupter(m_controller);
533 m_framebuffer.save(filename, "PNG");
534}
535
536void FrameView::reset() {
537 m_disabled.clear();
538 for (Layer& layer : m_queue) {
539 layer.enabled = true;
540 }
541 m_overrideBackdrop = QColor();
542 invalidateQueue();
543}
544
545QString FrameView::LayerId::readable() const {
546 QString typeStr;
547 switch (type) {
548 case NONE:
549 return tr("None");
550 case BACKGROUND:
551 typeStr = tr("Background");
552 break;
553 case WINDOW:
554 typeStr = tr("Window");
555#ifdef M_CORE_GBA
556 if (index == 2) {
557 return tr("Objwin");
558 }
559#endif
560 break;
561 case SPRITE:
562 typeStr = tr("Sprite");
563 break;
564 case BACKDROP:
565 typeStr = tr("Backdrop");
566 break;
567 case FRAME:
568 typeStr = tr("Frame");
569 break;
570 }
571 if (index < 0) {
572 return typeStr;
573 }
574 return tr("%1 %2").arg(typeStr).arg(index);
575}