bootmanager.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <glad/glad.h>
  5. #include <QApplication>
  6. #include <QHBoxLayout>
  7. #include <QKeyEvent>
  8. #include <QMessageBox>
  9. #include <QPainter>
  10. #include <QScreen>
  11. #include <QString>
  12. #include <QStringList>
  13. #include <QWindow>
  14. #ifdef HAS_OPENGL
  15. #include <QOffscreenSurface>
  16. #include <QOpenGLContext>
  17. #endif
  18. #if !defined(WIN32)
  19. #include <qpa/qplatformnativeinterface.h>
  20. #endif
  21. #include <fmt/format.h>
  22. #include "common/assert.h"
  23. #include "common/microprofile.h"
  24. #include "common/scm_rev.h"
  25. #include "common/scope_exit.h"
  26. #include "common/settings.h"
  27. #include "core/core.h"
  28. #include "core/frontend/framebuffer_layout.h"
  29. #include "input_common/keyboard.h"
  30. #include "input_common/main.h"
  31. #include "input_common/mouse/mouse_input.h"
  32. #include "input_common/tas/tas_input.h"
  33. #include "video_core/renderer_base.h"
  34. #include "video_core/video_core.h"
  35. #include "yuzu/bootmanager.h"
  36. #include "yuzu/main.h"
  37. EmuThread::EmuThread(Core::System& system_) : system{system_} {}
  38. EmuThread::~EmuThread() = default;
  39. void EmuThread::run() {
  40. std::string name = "yuzu:EmuControlThread";
  41. MicroProfileOnThreadCreate(name.c_str());
  42. Common::SetCurrentThreadName(name.c_str());
  43. auto& gpu = system.GPU();
  44. auto stop_token = stop_source.get_token();
  45. system.RegisterHostThread();
  46. // Main process has been loaded. Make the context current to this thread and begin GPU and CPU
  47. // execution.
  48. gpu.Start();
  49. gpu.ObtainContext();
  50. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  51. if (Settings::values.use_disk_shader_cache.GetValue()) {
  52. system.Renderer().ReadRasterizer()->LoadDiskResources(
  53. system.GetCurrentProcessProgramID(), stop_token,
  54. [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  55. emit LoadProgress(stage, value, total);
  56. });
  57. }
  58. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  59. gpu.ReleaseContext();
  60. // Holds whether the cpu was running during the last iteration,
  61. // so that the DebugModeLeft signal can be emitted before the
  62. // next execution step
  63. bool was_active = false;
  64. while (!stop_token.stop_requested()) {
  65. if (running) {
  66. if (was_active) {
  67. emit DebugModeLeft();
  68. }
  69. running_guard = true;
  70. Core::SystemResultStatus result = system.Run();
  71. if (result != Core::SystemResultStatus::Success) {
  72. running_guard = false;
  73. this->SetRunning(false);
  74. emit ErrorThrown(result, system.GetStatusDetails());
  75. }
  76. running_wait.Wait();
  77. result = system.Pause();
  78. if (result != Core::SystemResultStatus::Success) {
  79. running_guard = false;
  80. this->SetRunning(false);
  81. emit ErrorThrown(result, system.GetStatusDetails());
  82. }
  83. running_guard = false;
  84. if (!stop_token.stop_requested()) {
  85. was_active = true;
  86. emit DebugModeEntered();
  87. }
  88. } else if (exec_step) {
  89. UNIMPLEMENTED();
  90. } else {
  91. std::unique_lock lock{running_mutex};
  92. running_cv.wait(lock, stop_token, [this] { return IsRunning() || exec_step; });
  93. }
  94. }
  95. // Shutdown the core emulation
  96. system.Shutdown();
  97. #if MICROPROFILE_ENABLED
  98. MicroProfileOnThreadExit();
  99. #endif
  100. }
  101. #ifdef HAS_OPENGL
  102. class OpenGLSharedContext : public Core::Frontend::GraphicsContext {
  103. public:
  104. /// Create the original context that should be shared from
  105. explicit OpenGLSharedContext(QSurface* surface) : surface(surface) {
  106. QSurfaceFormat format;
  107. format.setVersion(4, 6);
  108. format.setProfile(QSurfaceFormat::CompatibilityProfile);
  109. format.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
  110. if (Settings::values.renderer_debug) {
  111. format.setOption(QSurfaceFormat::FormatOption::DebugContext);
  112. }
  113. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  114. format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  115. format.setSwapInterval(0);
  116. context = std::make_unique<QOpenGLContext>();
  117. context->setFormat(format);
  118. if (!context->create()) {
  119. LOG_ERROR(Frontend, "Unable to create main openGL context");
  120. }
  121. }
  122. /// Create the shared contexts for rendering and presentation
  123. explicit OpenGLSharedContext(QOpenGLContext* share_context, QSurface* main_surface = nullptr) {
  124. // disable vsync for any shared contexts
  125. auto format = share_context->format();
  126. format.setSwapInterval(main_surface ? Settings::values.use_vsync.GetValue() : 0);
  127. context = std::make_unique<QOpenGLContext>();
  128. context->setShareContext(share_context);
  129. context->setFormat(format);
  130. if (!context->create()) {
  131. LOG_ERROR(Frontend, "Unable to create shared openGL context");
  132. }
  133. if (!main_surface) {
  134. offscreen_surface = std::make_unique<QOffscreenSurface>(nullptr);
  135. offscreen_surface->setFormat(format);
  136. offscreen_surface->create();
  137. surface = offscreen_surface.get();
  138. } else {
  139. surface = main_surface;
  140. }
  141. }
  142. ~OpenGLSharedContext() {
  143. DoneCurrent();
  144. }
  145. void SwapBuffers() override {
  146. context->swapBuffers(surface);
  147. }
  148. void MakeCurrent() override {
  149. // We can't track the current state of the underlying context in this wrapper class because
  150. // Qt may make the underlying context not current for one reason or another. In particular,
  151. // the WebBrowser uses GL, so it seems to conflict if we aren't careful.
  152. // Instead of always just making the context current (which does not have any caching to
  153. // check if the underlying context is already current) we can check for the current context
  154. // in the thread local data by calling `currentContext()` and checking if its ours.
  155. if (QOpenGLContext::currentContext() != context.get()) {
  156. context->makeCurrent(surface);
  157. }
  158. }
  159. void DoneCurrent() override {
  160. context->doneCurrent();
  161. }
  162. QOpenGLContext* GetShareContext() {
  163. return context.get();
  164. }
  165. const QOpenGLContext* GetShareContext() const {
  166. return context.get();
  167. }
  168. private:
  169. // Avoid using Qt parent system here since we might move the QObjects to new threads
  170. // As a note, this means we should avoid using slots/signals with the objects too
  171. std::unique_ptr<QOpenGLContext> context;
  172. std::unique_ptr<QOffscreenSurface> offscreen_surface{};
  173. QSurface* surface;
  174. };
  175. #endif
  176. class DummyContext : public Core::Frontend::GraphicsContext {};
  177. class RenderWidget : public QWidget {
  178. public:
  179. explicit RenderWidget(GRenderWindow* parent) : QWidget(parent), render_window(parent) {
  180. setAttribute(Qt::WA_NativeWindow);
  181. setAttribute(Qt::WA_PaintOnScreen);
  182. }
  183. virtual ~RenderWidget() = default;
  184. QPaintEngine* paintEngine() const override {
  185. return nullptr;
  186. }
  187. private:
  188. GRenderWindow* render_window;
  189. };
  190. class OpenGLRenderWidget : public RenderWidget {
  191. public:
  192. explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  193. windowHandle()->setSurfaceType(QWindow::OpenGLSurface);
  194. }
  195. void SetContext(std::unique_ptr<Core::Frontend::GraphicsContext>&& context_) {
  196. context = std::move(context_);
  197. }
  198. private:
  199. std::unique_ptr<Core::Frontend::GraphicsContext> context;
  200. };
  201. class VulkanRenderWidget : public RenderWidget {
  202. public:
  203. explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  204. windowHandle()->setSurfaceType(QWindow::VulkanSurface);
  205. }
  206. };
  207. static Core::Frontend::WindowSystemType GetWindowSystemType() {
  208. // Determine WSI type based on Qt platform.
  209. QString platform_name = QGuiApplication::platformName();
  210. if (platform_name == QStringLiteral("windows"))
  211. return Core::Frontend::WindowSystemType::Windows;
  212. else if (platform_name == QStringLiteral("xcb"))
  213. return Core::Frontend::WindowSystemType::X11;
  214. else if (platform_name == QStringLiteral("wayland"))
  215. return Core::Frontend::WindowSystemType::Wayland;
  216. LOG_CRITICAL(Frontend, "Unknown Qt platform!");
  217. return Core::Frontend::WindowSystemType::Windows;
  218. }
  219. static Core::Frontend::EmuWindow::WindowSystemInfo GetWindowSystemInfo(QWindow* window) {
  220. Core::Frontend::EmuWindow::WindowSystemInfo wsi;
  221. wsi.type = GetWindowSystemType();
  222. // Our Win32 Qt external doesn't have the private API.
  223. #if defined(WIN32) || defined(__APPLE__)
  224. wsi.render_surface = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
  225. #else
  226. QPlatformNativeInterface* pni = QGuiApplication::platformNativeInterface();
  227. wsi.display_connection = pni->nativeResourceForWindow("display", window);
  228. if (wsi.type == Core::Frontend::WindowSystemType::Wayland)
  229. wsi.render_surface = window ? pni->nativeResourceForWindow("surface", window) : nullptr;
  230. else
  231. wsi.render_surface = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
  232. #endif
  233. wsi.render_surface_scale = window ? static_cast<float>(window->devicePixelRatio()) : 1.0f;
  234. return wsi;
  235. }
  236. GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_,
  237. std::shared_ptr<InputCommon::InputSubsystem> input_subsystem_,
  238. Core::System& system_)
  239. : QWidget(parent),
  240. emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)}, system{system_} {
  241. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  242. .arg(QString::fromUtf8(Common::g_build_name),
  243. QString::fromUtf8(Common::g_scm_branch),
  244. QString::fromUtf8(Common::g_scm_desc)));
  245. setAttribute(Qt::WA_AcceptTouchEvents);
  246. auto* layout = new QHBoxLayout(this);
  247. layout->setContentsMargins(0, 0, 0, 0);
  248. setLayout(layout);
  249. input_subsystem->Initialize();
  250. this->setMouseTracking(true);
  251. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
  252. connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram,
  253. Qt::QueuedConnection);
  254. connect(this, &GRenderWindow::ExitSignal, parent, &GMainWindow::OnExit, Qt::QueuedConnection);
  255. connect(this, &GRenderWindow::TasPlaybackStateChanged, parent, &GMainWindow::OnTasStateChanged);
  256. }
  257. void GRenderWindow::ExecuteProgram(std::size_t program_index) {
  258. emit ExecuteProgramSignal(program_index);
  259. }
  260. void GRenderWindow::Exit() {
  261. emit ExitSignal();
  262. }
  263. GRenderWindow::~GRenderWindow() {
  264. input_subsystem->Shutdown();
  265. }
  266. void GRenderWindow::OnFrameDisplayed() {
  267. input_subsystem->GetTas()->UpdateThread();
  268. TasInput::TasState new_tas_state = std::get<0>(input_subsystem->GetTas()->GetStatus());
  269. if (!first_frame) {
  270. last_tas_state = new_tas_state;
  271. first_frame = true;
  272. emit FirstFrameDisplayed();
  273. }
  274. if (new_tas_state != last_tas_state) {
  275. last_tas_state = new_tas_state;
  276. emit TasPlaybackStateChanged();
  277. }
  278. }
  279. bool GRenderWindow::IsShown() const {
  280. return !isMinimized();
  281. }
  282. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  283. //
  284. // Older versions get the window size (density independent pixels),
  285. // and hence, do not support DPI scaling ("retina" displays).
  286. // The result will be a viewport that is smaller than the extent of the window.
  287. void GRenderWindow::OnFramebufferSizeChanged() {
  288. // Screen changes potentially incur a change in screen DPI, hence we should update the
  289. // framebuffer size
  290. const qreal pixel_ratio = windowPixelRatio();
  291. const u32 width = this->width() * pixel_ratio;
  292. const u32 height = this->height() * pixel_ratio;
  293. UpdateCurrentFramebufferLayout(width, height);
  294. }
  295. void GRenderWindow::BackupGeometry() {
  296. geometry = QWidget::saveGeometry();
  297. }
  298. void GRenderWindow::RestoreGeometry() {
  299. // We don't want to back up the geometry here (obviously)
  300. QWidget::restoreGeometry(geometry);
  301. }
  302. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  303. // Make sure users of this class don't need to deal with backing up the geometry themselves
  304. QWidget::restoreGeometry(geometry);
  305. BackupGeometry();
  306. }
  307. QByteArray GRenderWindow::saveGeometry() {
  308. // If we are a top-level widget, store the current geometry
  309. // otherwise, store the last backup
  310. if (parent() == nullptr) {
  311. return QWidget::saveGeometry();
  312. }
  313. return geometry;
  314. }
  315. qreal GRenderWindow::windowPixelRatio() const {
  316. return devicePixelRatioF();
  317. }
  318. std::pair<u32, u32> GRenderWindow::ScaleTouch(const QPointF& pos) const {
  319. const qreal pixel_ratio = windowPixelRatio();
  320. return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  321. static_cast<u32>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  322. }
  323. void GRenderWindow::closeEvent(QCloseEvent* event) {
  324. emit Closed();
  325. QWidget::closeEvent(event);
  326. }
  327. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  328. if (!event->isAutoRepeat()) {
  329. input_subsystem->GetKeyboard()->PressKey(event->key());
  330. }
  331. }
  332. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  333. if (!event->isAutoRepeat()) {
  334. input_subsystem->GetKeyboard()->ReleaseKey(event->key());
  335. }
  336. }
  337. MouseInput::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) {
  338. switch (button) {
  339. case Qt::LeftButton:
  340. return MouseInput::MouseButton::Left;
  341. case Qt::RightButton:
  342. return MouseInput::MouseButton::Right;
  343. case Qt::MiddleButton:
  344. return MouseInput::MouseButton::Wheel;
  345. case Qt::BackButton:
  346. return MouseInput::MouseButton::Backward;
  347. case Qt::ForwardButton:
  348. return MouseInput::MouseButton::Forward;
  349. case Qt::TaskButton:
  350. return MouseInput::MouseButton::Task;
  351. default:
  352. return MouseInput::MouseButton::Extra;
  353. }
  354. }
  355. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  356. // Touch input is handled in TouchBeginEvent
  357. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  358. return;
  359. }
  360. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  361. // coordinates and map them to the current render area
  362. const auto pos = mapFromGlobal(QCursor::pos());
  363. const auto [x, y] = ScaleTouch(pos);
  364. const auto button = QtButtonToMouseButton(event->button());
  365. input_subsystem->GetMouse()->PressButton(x, y, button);
  366. if (event->button() == Qt::LeftButton) {
  367. this->TouchPressed(x, y, 0);
  368. }
  369. emit MouseActivity();
  370. }
  371. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  372. // Touch input is handled in TouchUpdateEvent
  373. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  374. return;
  375. }
  376. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  377. // coordinates and map them to the current render area
  378. const auto pos = mapFromGlobal(QCursor::pos());
  379. const auto [x, y] = ScaleTouch(pos);
  380. const int center_x = width() / 2;
  381. const int center_y = height() / 2;
  382. input_subsystem->GetMouse()->MouseMove(x, y, center_x, center_y);
  383. this->TouchMoved(x, y, 0);
  384. if (Settings::values.mouse_panning) {
  385. QCursor::setPos(mapToGlobal({center_x, center_y}));
  386. }
  387. emit MouseActivity();
  388. }
  389. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  390. // Touch input is handled in TouchEndEvent
  391. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  392. return;
  393. }
  394. const auto button = QtButtonToMouseButton(event->button());
  395. input_subsystem->GetMouse()->ReleaseButton(button);
  396. if (event->button() == Qt::LeftButton) {
  397. this->TouchReleased(0);
  398. }
  399. }
  400. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  401. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  402. for (const auto& touch_point : touch_points) {
  403. if (!TouchUpdate(touch_point)) {
  404. TouchStart(touch_point);
  405. }
  406. }
  407. }
  408. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  409. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  410. for (const auto& touch_point : touch_points) {
  411. if (!TouchUpdate(touch_point)) {
  412. TouchStart(touch_point);
  413. }
  414. }
  415. // Release all inactive points
  416. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  417. if (!TouchExist(touch_ids[id], touch_points)) {
  418. touch_ids[id] = 0;
  419. this->TouchReleased(id + 1);
  420. }
  421. }
  422. }
  423. void GRenderWindow::TouchEndEvent() {
  424. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  425. if (touch_ids[id] != 0) {
  426. touch_ids[id] = 0;
  427. this->TouchReleased(id + 1);
  428. }
  429. }
  430. }
  431. bool GRenderWindow::TouchStart(const QTouchEvent::TouchPoint& touch_point) {
  432. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  433. if (touch_ids[id] == 0) {
  434. touch_ids[id] = touch_point.id() + 1;
  435. const auto [x, y] = ScaleTouch(touch_point.pos());
  436. this->TouchPressed(x, y, id + 1);
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. bool GRenderWindow::TouchUpdate(const QTouchEvent::TouchPoint& touch_point) {
  443. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  444. if (touch_ids[id] == static_cast<std::size_t>(touch_point.id() + 1)) {
  445. const auto [x, y] = ScaleTouch(touch_point.pos());
  446. this->TouchMoved(x, y, id + 1);
  447. return true;
  448. }
  449. }
  450. return false;
  451. }
  452. bool GRenderWindow::TouchExist(std::size_t id,
  453. const QList<QTouchEvent::TouchPoint>& touch_points) const {
  454. return std::any_of(touch_points.begin(), touch_points.end(), [id](const auto& point) {
  455. return id == static_cast<std::size_t>(point.id() + 1);
  456. });
  457. }
  458. bool GRenderWindow::event(QEvent* event) {
  459. if (event->type() == QEvent::TouchBegin) {
  460. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  461. return true;
  462. } else if (event->type() == QEvent::TouchUpdate) {
  463. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  464. return true;
  465. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  466. TouchEndEvent();
  467. return true;
  468. }
  469. return QWidget::event(event);
  470. }
  471. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  472. QWidget::focusOutEvent(event);
  473. input_subsystem->GetKeyboard()->ReleaseAllKeys();
  474. input_subsystem->GetMouse()->ReleaseAllButtons();
  475. this->TouchReleased(0);
  476. }
  477. void GRenderWindow::resizeEvent(QResizeEvent* event) {
  478. QWidget::resizeEvent(event);
  479. OnFramebufferSizeChanged();
  480. }
  481. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  482. #ifdef HAS_OPENGL
  483. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  484. auto c = static_cast<OpenGLSharedContext*>(main_context.get());
  485. // Bind the shared contexts to the main surface in case the backend wants to take over
  486. // presentation
  487. return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
  488. child_widget->windowHandle());
  489. }
  490. #endif
  491. return std::make_unique<DummyContext>();
  492. }
  493. bool GRenderWindow::InitRenderTarget() {
  494. ReleaseRenderTarget();
  495. {
  496. // Create a dummy render widget so that Qt
  497. // places the render window at the correct position.
  498. const RenderWidget dummy_widget{this};
  499. }
  500. first_frame = false;
  501. switch (Settings::values.renderer_backend.GetValue()) {
  502. case Settings::RendererBackend::OpenGL:
  503. if (!InitializeOpenGL()) {
  504. return false;
  505. }
  506. break;
  507. case Settings::RendererBackend::Vulkan:
  508. if (!InitializeVulkan()) {
  509. return false;
  510. }
  511. break;
  512. }
  513. // Update the Window System information with the new render target
  514. window_info = GetWindowSystemInfo(child_widget->windowHandle());
  515. child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  516. layout()->addWidget(child_widget);
  517. // Reset minimum required size to avoid resizing issues on the main window after restarting.
  518. setMinimumSize(1, 1);
  519. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  520. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  521. OnFramebufferSizeChanged();
  522. BackupGeometry();
  523. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  524. if (!LoadOpenGL()) {
  525. return false;
  526. }
  527. }
  528. return true;
  529. }
  530. void GRenderWindow::ReleaseRenderTarget() {
  531. if (child_widget) {
  532. layout()->removeWidget(child_widget);
  533. child_widget->deleteLater();
  534. child_widget = nullptr;
  535. }
  536. main_context.reset();
  537. }
  538. void GRenderWindow::CaptureScreenshot(const QString& screenshot_path) {
  539. auto& renderer = system.Renderer();
  540. const f32 res_scale = Settings::values.resolution_info.up_factor;
  541. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  542. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  543. renderer.RequestScreenshot(
  544. screenshot_image.bits(),
  545. [=, this](bool invert_y) {
  546. const std::string std_screenshot_path = screenshot_path.toStdString();
  547. if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
  548. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  549. } else {
  550. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  551. }
  552. },
  553. layout);
  554. }
  555. bool GRenderWindow::IsLoadingComplete() const {
  556. return first_frame;
  557. }
  558. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  559. setMinimumSize(minimal_size.first, minimal_size.second);
  560. }
  561. bool GRenderWindow::InitializeOpenGL() {
  562. #ifdef HAS_OPENGL
  563. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  564. // WA_DontShowOnScreen, WA_DeleteOnClose
  565. auto child = new OpenGLRenderWidget(this);
  566. child_widget = child;
  567. child_widget->windowHandle()->create();
  568. auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
  569. main_context = context;
  570. child->SetContext(
  571. std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));
  572. return true;
  573. #else
  574. QMessageBox::warning(this, tr("OpenGL not available!"),
  575. tr("yuzu has not been compiled with OpenGL support."));
  576. return false;
  577. #endif
  578. }
  579. bool GRenderWindow::InitializeVulkan() {
  580. auto child = new VulkanRenderWidget(this);
  581. child_widget = child;
  582. child_widget->windowHandle()->create();
  583. main_context = std::make_unique<DummyContext>();
  584. return true;
  585. }
  586. bool GRenderWindow::LoadOpenGL() {
  587. auto context = CreateSharedContext();
  588. auto scope = context->Acquire();
  589. if (!gladLoadGL()) {
  590. QMessageBox::warning(
  591. this, tr("Error while initializing OpenGL!"),
  592. tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
  593. return false;
  594. }
  595. const QString renderer =
  596. QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
  597. if (!GLAD_GL_VERSION_4_6) {
  598. LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
  599. QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
  600. tr("Your GPU may not support OpenGL 4.6, or you do not have the "
  601. "latest graphics driver.<br><br>GL Renderer:<br>%1")
  602. .arg(renderer));
  603. return false;
  604. }
  605. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  606. if (!unsupported_gl_extensions.empty()) {
  607. QMessageBox::warning(
  608. this, tr("Error while initializing OpenGL!"),
  609. tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
  610. "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
  611. "extensions:<br>%2")
  612. .arg(renderer)
  613. .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
  614. return false;
  615. }
  616. return true;
  617. }
  618. QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
  619. QStringList unsupported_ext;
  620. // Extensions required to support some texture formats.
  621. if (!GLAD_GL_EXT_texture_compression_s3tc) {
  622. unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
  623. }
  624. if (!GLAD_GL_ARB_texture_compression_rgtc) {
  625. unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
  626. }
  627. if (!unsupported_ext.empty()) {
  628. LOG_ERROR(Frontend, "GPU does not support all required extensions: {}",
  629. glGetString(GL_RENDERER));
  630. }
  631. for (const QString& ext : unsupported_ext) {
  632. LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  633. }
  634. return unsupported_ext;
  635. }
  636. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  637. this->emu_thread = emu_thread;
  638. }
  639. void GRenderWindow::OnEmulationStopping() {
  640. emu_thread = nullptr;
  641. }
  642. void GRenderWindow::showEvent(QShowEvent* event) {
  643. QWidget::showEvent(event);
  644. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  645. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  646. Qt::UniqueConnection);
  647. }
  648. bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
  649. if (event->type() == QEvent::HoverMove) {
  650. if (Settings::values.mouse_panning) {
  651. auto* hover_event = static_cast<QMouseEvent*>(event);
  652. mouseMoveEvent(hover_event);
  653. return false;
  654. }
  655. emit MouseActivity();
  656. }
  657. return false;
  658. }