bootmanager.cpp 15 KB

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