bootmanager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #include <QApplication>
  2. #include <QHBoxLayout>
  3. #include <QKeyEvent>
  4. #include <QScreen>
  5. #include <QWindow>
  6. #include <fmt/format.h>
  7. #include "common/microprofile.h"
  8. #include "common/scm_rev.h"
  9. #include "core/core.h"
  10. #include "core/frontend/framebuffer_layout.h"
  11. #include "core/settings.h"
  12. #include "input_common/keyboard.h"
  13. #include "input_common/main.h"
  14. #include "input_common/motion_emu.h"
  15. #include "video_core/renderer_base.h"
  16. #include "video_core/video_core.h"
  17. #include "yuzu/bootmanager.h"
  18. #include "yuzu/main.h"
  19. EmuThread::EmuThread(GRenderWindow* render_window) : render_window(render_window) {}
  20. void EmuThread::run() {
  21. if (!Settings::values.use_multi_core) {
  22. // Single core mode must acquire OpenGL context for entire emulation session
  23. render_window->MakeCurrent();
  24. }
  25. MicroProfileOnThreadCreate("EmuThread");
  26. stop_run = false;
  27. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  28. Core::System::GetInstance().Renderer().Rasterizer().LoadDiskResources(
  29. stop_run, [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  30. emit LoadProgress(stage, value, total);
  31. });
  32. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  33. // holds whether the cpu was running during the last iteration,
  34. // so that the DebugModeLeft signal can be emitted before the
  35. // next execution step
  36. bool was_active = false;
  37. while (!stop_run) {
  38. if (running) {
  39. if (!was_active)
  40. emit DebugModeLeft();
  41. Core::System::ResultStatus result = Core::System::GetInstance().RunLoop();
  42. if (result != Core::System::ResultStatus::Success) {
  43. this->SetRunning(false);
  44. emit ErrorThrown(result, Core::System::GetInstance().GetStatusDetails());
  45. }
  46. was_active = running || exec_step;
  47. if (!was_active && !stop_run)
  48. emit DebugModeEntered();
  49. } else if (exec_step) {
  50. if (!was_active)
  51. emit DebugModeLeft();
  52. exec_step = false;
  53. Core::System::GetInstance().SingleStep();
  54. emit DebugModeEntered();
  55. yieldCurrentThread();
  56. was_active = false;
  57. } else {
  58. std::unique_lock<std::mutex> lock(running_mutex);
  59. running_cv.wait(lock, [this] { return IsRunning() || exec_step || stop_run; });
  60. }
  61. }
  62. // Shutdown the core emulation
  63. Core::System::GetInstance().Shutdown();
  64. #if MICROPROFILE_ENABLED
  65. MicroProfileOnThreadExit();
  66. #endif
  67. render_window->moveContext();
  68. }
  69. // This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL
  70. // context.
  71. // The corresponding functionality is handled in EmuThread instead
  72. class GGLWidgetInternal : public QGLWidget {
  73. public:
  74. GGLWidgetInternal(QGLFormat fmt, GRenderWindow* parent)
  75. : QGLWidget(fmt, parent), parent(parent) {}
  76. void paintEvent(QPaintEvent* ev) override {
  77. if (do_painting) {
  78. QPainter painter(this);
  79. }
  80. }
  81. void resizeEvent(QResizeEvent* ev) override {
  82. parent->OnClientAreaResized(ev->size().width(), ev->size().height());
  83. parent->OnFramebufferSizeChanged();
  84. }
  85. void DisablePainting() {
  86. do_painting = false;
  87. }
  88. void EnablePainting() {
  89. do_painting = true;
  90. }
  91. private:
  92. GRenderWindow* parent;
  93. bool do_painting;
  94. };
  95. GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread)
  96. : QWidget(parent), child(nullptr), emu_thread(emu_thread) {
  97. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  98. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  99. setAttribute(Qt::WA_AcceptTouchEvents);
  100. InputCommon::Init();
  101. InputCommon::StartJoystickEventHandler();
  102. connect(this, &GRenderWindow::FirstFrameDisplayed, static_cast<GMainWindow*>(parent),
  103. &GMainWindow::OnLoadComplete);
  104. }
  105. GRenderWindow::~GRenderWindow() {
  106. InputCommon::Shutdown();
  107. }
  108. void GRenderWindow::moveContext() {
  109. DoneCurrent();
  110. // If the thread started running, move the GL Context to the new thread. Otherwise, move it
  111. // back.
  112. auto thread = (QThread::currentThread() == qApp->thread() && emu_thread != nullptr)
  113. ? emu_thread
  114. : qApp->thread();
  115. child->context()->moveToThread(thread);
  116. }
  117. void GRenderWindow::SwapBuffers() {
  118. // In our multi-threaded QGLWidget use case we shouldn't need to call `makeCurrent`,
  119. // since we never call `doneCurrent` in this thread.
  120. // However:
  121. // - The Qt debug runtime prints a bogus warning on the console if `makeCurrent` wasn't called
  122. // since the last time `swapBuffers` was executed;
  123. // - On macOS, if `makeCurrent` isn't called explicitely, resizing the buffer breaks.
  124. child->makeCurrent();
  125. child->swapBuffers();
  126. if (!first_frame) {
  127. emit FirstFrameDisplayed();
  128. first_frame = true;
  129. }
  130. }
  131. void GRenderWindow::MakeCurrent() {
  132. child->makeCurrent();
  133. }
  134. void GRenderWindow::DoneCurrent() {
  135. child->doneCurrent();
  136. }
  137. void GRenderWindow::PollEvents() {}
  138. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  139. //
  140. // Older versions get the window size (density independent pixels),
  141. // and hence, do not support DPI scaling ("retina" displays).
  142. // The result will be a viewport that is smaller than the extent of the window.
  143. void GRenderWindow::OnFramebufferSizeChanged() {
  144. // Screen changes potentially incur a change in screen DPI, hence we should update the
  145. // framebuffer size
  146. qreal pixelRatio = windowPixelRatio();
  147. unsigned width = child->QPaintDevice::width() * pixelRatio;
  148. unsigned height = child->QPaintDevice::height() * pixelRatio;
  149. UpdateCurrentFramebufferLayout(width, height);
  150. }
  151. void GRenderWindow::BackupGeometry() {
  152. geometry = ((QGLWidget*)this)->saveGeometry();
  153. }
  154. void GRenderWindow::RestoreGeometry() {
  155. // We don't want to back up the geometry here (obviously)
  156. QWidget::restoreGeometry(geometry);
  157. }
  158. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  159. // Make sure users of this class don't need to deal with backing up the geometry themselves
  160. QWidget::restoreGeometry(geometry);
  161. BackupGeometry();
  162. }
  163. QByteArray GRenderWindow::saveGeometry() {
  164. // If we are a top-level widget, store the current geometry
  165. // otherwise, store the last backup
  166. if (parent() == nullptr)
  167. return ((QGLWidget*)this)->saveGeometry();
  168. else
  169. return geometry;
  170. }
  171. qreal GRenderWindow::windowPixelRatio() const {
  172. // windowHandle() might not be accessible until the window is displayed to screen.
  173. return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
  174. }
  175. std::pair<unsigned, unsigned> GRenderWindow::ScaleTouch(const QPointF pos) const {
  176. const qreal pixel_ratio = windowPixelRatio();
  177. return {static_cast<unsigned>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  178. static_cast<unsigned>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  179. }
  180. void GRenderWindow::closeEvent(QCloseEvent* event) {
  181. emit Closed();
  182. QWidget::closeEvent(event);
  183. }
  184. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  185. InputCommon::GetKeyboard()->PressKey(event->key());
  186. }
  187. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  188. InputCommon::GetKeyboard()->ReleaseKey(event->key());
  189. }
  190. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  191. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  192. return; // touch input is handled in TouchBeginEvent
  193. auto pos = event->pos();
  194. if (event->button() == Qt::LeftButton) {
  195. const auto [x, y] = ScaleTouch(pos);
  196. this->TouchPressed(x, y);
  197. } else if (event->button() == Qt::RightButton) {
  198. InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y());
  199. }
  200. }
  201. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  202. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  203. return; // touch input is handled in TouchUpdateEvent
  204. auto pos = event->pos();
  205. const auto [x, y] = ScaleTouch(pos);
  206. this->TouchMoved(x, y);
  207. InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y());
  208. }
  209. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  210. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  211. return; // touch input is handled in TouchEndEvent
  212. if (event->button() == Qt::LeftButton)
  213. this->TouchReleased();
  214. else if (event->button() == Qt::RightButton)
  215. InputCommon::GetMotionEmu()->EndTilt();
  216. }
  217. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  218. // TouchBegin always has exactly one touch point, so take the .first()
  219. const auto [x, y] = ScaleTouch(event->touchPoints().first().pos());
  220. this->TouchPressed(x, y);
  221. }
  222. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  223. QPointF pos;
  224. int active_points = 0;
  225. // average all active touch points
  226. for (const auto tp : event->touchPoints()) {
  227. if (tp.state() & (Qt::TouchPointPressed | Qt::TouchPointMoved | Qt::TouchPointStationary)) {
  228. active_points++;
  229. pos += tp.pos();
  230. }
  231. }
  232. pos /= active_points;
  233. const auto [x, y] = ScaleTouch(pos);
  234. this->TouchMoved(x, y);
  235. }
  236. void GRenderWindow::TouchEndEvent() {
  237. this->TouchReleased();
  238. }
  239. bool GRenderWindow::event(QEvent* event) {
  240. if (event->type() == QEvent::TouchBegin) {
  241. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  242. return true;
  243. } else if (event->type() == QEvent::TouchUpdate) {
  244. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  245. return true;
  246. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  247. TouchEndEvent();
  248. return true;
  249. }
  250. return QWidget::event(event);
  251. }
  252. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  253. QWidget::focusOutEvent(event);
  254. InputCommon::GetKeyboard()->ReleaseAllKeys();
  255. }
  256. void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height) {
  257. NotifyClientAreaSizeChanged(std::make_pair(width, height));
  258. }
  259. void GRenderWindow::InitRenderTarget() {
  260. if (child) {
  261. delete child;
  262. }
  263. if (layout()) {
  264. delete layout();
  265. }
  266. first_frame = false;
  267. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  268. // WA_DontShowOnScreen, WA_DeleteOnClose
  269. QGLFormat fmt;
  270. fmt.setVersion(4, 3);
  271. fmt.setProfile(QGLFormat::CoreProfile);
  272. fmt.setSwapInterval(false);
  273. // Requests a forward-compatible context, which is required to get a 3.2+ context on OS X
  274. fmt.setOption(QGL::NoDeprecatedFunctions);
  275. child = new GGLWidgetInternal(fmt, this);
  276. QBoxLayout* layout = new QHBoxLayout(this);
  277. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  278. layout->addWidget(child);
  279. layout->setMargin(0);
  280. setLayout(layout);
  281. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  282. OnFramebufferSizeChanged();
  283. NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
  284. BackupGeometry();
  285. }
  286. void GRenderWindow::CaptureScreenshot(u16 res_scale, const QString& screenshot_path) {
  287. auto& renderer = Core::System::GetInstance().Renderer();
  288. if (!res_scale)
  289. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  290. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  291. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  292. renderer.RequestScreenshot(screenshot_image.bits(),
  293. [=] {
  294. screenshot_image.mirrored(false, true).save(screenshot_path);
  295. LOG_INFO(Frontend, "The screenshot is saved.");
  296. },
  297. layout);
  298. }
  299. void GRenderWindow::OnMinimalClientAreaChangeRequest(
  300. const std::pair<unsigned, unsigned>& minimal_size) {
  301. setMinimumSize(minimal_size.first, minimal_size.second);
  302. }
  303. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  304. this->emu_thread = emu_thread;
  305. child->DisablePainting();
  306. }
  307. void GRenderWindow::OnEmulationStopping() {
  308. emu_thread = nullptr;
  309. child->EnablePainting();
  310. }
  311. void GRenderWindow::showEvent(QShowEvent* event) {
  312. QWidget::showEvent(event);
  313. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  314. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  315. Qt::UniqueConnection);
  316. }