bootmanager.cpp 25 KB

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