bootmanager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. EmuThread::~EmuThread() = default;
  27. void EmuThread::run() {
  28. render_window->MakeCurrent();
  29. MicroProfileOnThreadCreate("EmuThread");
  30. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  31. Core::System::GetInstance().Renderer().Rasterizer().LoadDiskResources(
  32. stop_run, [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  33. emit LoadProgress(stage, value, total);
  34. });
  35. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  36. if (Settings::values.use_asynchronous_gpu_emulation) {
  37. // Release OpenGL context for the GPU thread
  38. render_window->DoneCurrent();
  39. }
  40. // Holds whether the cpu was running during the last iteration,
  41. // so that the DebugModeLeft signal can be emitted before the
  42. // next execution step
  43. bool was_active = false;
  44. while (!stop_run) {
  45. if (running) {
  46. if (!was_active)
  47. emit DebugModeLeft();
  48. Core::System::ResultStatus result = Core::System::GetInstance().RunLoop();
  49. if (result != Core::System::ResultStatus::Success) {
  50. this->SetRunning(false);
  51. emit ErrorThrown(result, Core::System::GetInstance().GetStatusDetails());
  52. }
  53. was_active = running || exec_step;
  54. if (!was_active && !stop_run)
  55. emit DebugModeEntered();
  56. } else if (exec_step) {
  57. if (!was_active)
  58. emit DebugModeLeft();
  59. exec_step = false;
  60. Core::System::GetInstance().SingleStep();
  61. emit DebugModeEntered();
  62. yieldCurrentThread();
  63. was_active = false;
  64. } else {
  65. std::unique_lock lock{running_mutex};
  66. running_cv.wait(lock, [this] { return IsRunning() || exec_step || stop_run; });
  67. }
  68. }
  69. // Shutdown the core emulation
  70. Core::System::GetInstance().Shutdown();
  71. #if MICROPROFILE_ENABLED
  72. MicroProfileOnThreadExit();
  73. #endif
  74. render_window->moveContext();
  75. }
  76. class GGLContext : public Core::Frontend::GraphicsContext {
  77. public:
  78. explicit GGLContext(QOpenGLContext* shared_context) : shared_context{shared_context} {
  79. context.setFormat(shared_context->format());
  80. context.setShareContext(shared_context);
  81. context.create();
  82. }
  83. void MakeCurrent() override {
  84. context.makeCurrent(shared_context->surface());
  85. }
  86. void DoneCurrent() override {
  87. context.doneCurrent();
  88. }
  89. void SwapBuffers() override {}
  90. private:
  91. QOpenGLContext* shared_context;
  92. QOpenGLContext context;
  93. };
  94. // This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL
  95. // context.
  96. // The corresponding functionality is handled in EmuThread instead
  97. class GGLWidgetInternal : public QOpenGLWindow {
  98. public:
  99. GGLWidgetInternal(GRenderWindow* parent, QOpenGLContext* shared_context)
  100. : QOpenGLWindow(shared_context), parent(parent) {}
  101. void paintEvent(QPaintEvent* ev) override {
  102. if (do_painting) {
  103. QPainter painter(this);
  104. }
  105. }
  106. void resizeEvent(QResizeEvent* ev) override {
  107. parent->OnClientAreaResized(ev->size().width(), ev->size().height());
  108. parent->OnFramebufferSizeChanged();
  109. }
  110. void keyPressEvent(QKeyEvent* event) override {
  111. InputCommon::GetKeyboard()->PressKey(event->key());
  112. }
  113. void keyReleaseEvent(QKeyEvent* event) override {
  114. InputCommon::GetKeyboard()->ReleaseKey(event->key());
  115. }
  116. void mousePressEvent(QMouseEvent* event) override {
  117. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  118. return; // touch input is handled in TouchBeginEvent
  119. const auto pos{event->pos()};
  120. if (event->button() == Qt::LeftButton) {
  121. const auto [x, y] = parent->ScaleTouch(pos);
  122. parent->TouchPressed(x, y);
  123. } else if (event->button() == Qt::RightButton) {
  124. InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y());
  125. }
  126. }
  127. void mouseMoveEvent(QMouseEvent* event) override {
  128. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  129. return; // touch input is handled in TouchUpdateEvent
  130. const auto pos{event->pos()};
  131. const auto [x, y] = parent->ScaleTouch(pos);
  132. parent->TouchMoved(x, y);
  133. InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y());
  134. }
  135. void mouseReleaseEvent(QMouseEvent* event) override {
  136. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  137. return; // touch input is handled in TouchEndEvent
  138. if (event->button() == Qt::LeftButton)
  139. parent->TouchReleased();
  140. else if (event->button() == Qt::RightButton)
  141. InputCommon::GetMotionEmu()->EndTilt();
  142. }
  143. void DisablePainting() {
  144. do_painting = false;
  145. }
  146. void EnablePainting() {
  147. do_painting = true;
  148. }
  149. private:
  150. GRenderWindow* parent;
  151. bool do_painting;
  152. };
  153. GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread)
  154. : QWidget(parent), emu_thread(emu_thread) {
  155. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  156. .arg(QString::fromUtf8(Common::g_build_name),
  157. QString::fromUtf8(Common::g_scm_branch),
  158. QString::fromUtf8(Common::g_scm_desc)));
  159. setAttribute(Qt::WA_AcceptTouchEvents);
  160. InputCommon::Init();
  161. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &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. const qreal pixel_ratio = GetWindowPixelRatio();
  205. const u32 width = child->QPaintDevice::width() * pixel_ratio;
  206. const u32 height = child->QPaintDevice::height() * pixel_ratio;
  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<u32, u32> GRenderWindow::ScaleTouch(const QPointF pos) const {
  244. const qreal pixel_ratio = GetWindowPixelRatio();
  245. return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  246. static_cast<u32>(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(u32 width, u32 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. fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
  311. fmt.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
  312. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  313. fmt.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  314. shared_context = std::make_unique<QOpenGLContext>();
  315. shared_context->setFormat(fmt);
  316. shared_context->create();
  317. context = std::make_unique<QOpenGLContext>();
  318. context->setShareContext(shared_context.get());
  319. context->setFormat(fmt);
  320. context->create();
  321. fmt.setSwapInterval(0);
  322. child = new GGLWidgetInternal(this, shared_context.get());
  323. container = QWidget::createWindowContainer(child, this);
  324. QBoxLayout* layout = new QHBoxLayout(this);
  325. layout->addWidget(container);
  326. layout->setMargin(0);
  327. setLayout(layout);
  328. // Reset minimum size to avoid unwanted resizes when this function is called for a second time.
  329. setMinimumSize(1, 1);
  330. // Show causes the window to actually be created and the OpenGL context as well, but we don't
  331. // want the widget to be shown yet, so immediately hide it.
  332. show();
  333. hide();
  334. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  335. child->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  336. container->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  337. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  338. OnFramebufferSizeChanged();
  339. NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
  340. BackupGeometry();
  341. }
  342. void GRenderWindow::CaptureScreenshot(u32 res_scale, const QString& screenshot_path) {
  343. auto& renderer = Core::System::GetInstance().Renderer();
  344. if (res_scale == 0) {
  345. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  346. }
  347. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  348. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  349. renderer.RequestScreenshot(
  350. screenshot_image.bits(),
  351. [=] {
  352. const std::string std_screenshot_path = screenshot_path.toStdString();
  353. if (screenshot_image.mirrored(false, true).save(screenshot_path)) {
  354. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  355. } else {
  356. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  357. }
  358. },
  359. layout);
  360. }
  361. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  362. setMinimumSize(minimal_size.first, minimal_size.second);
  363. }
  364. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  365. this->emu_thread = emu_thread;
  366. child->DisablePainting();
  367. }
  368. void GRenderWindow::OnEmulationStopping() {
  369. emu_thread = nullptr;
  370. child->EnablePainting();
  371. }
  372. void GRenderWindow::showEvent(QShowEvent* event) {
  373. QWidget::showEvent(event);
  374. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  375. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  376. Qt::UniqueConnection);
  377. }