yuzu.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <chrono>
  4. #include <iostream>
  5. #include <memory>
  6. #include <regex>
  7. #include <string>
  8. #include <thread>
  9. #include <fmt/ostream.h>
  10. #include "common/detached_tasks.h"
  11. #include "common/logging/backend.h"
  12. #include "common/logging/log.h"
  13. #include "common/microprofile.h"
  14. #include "common/nvidia_flags.h"
  15. #include "common/scm_rev.h"
  16. #include "common/scope_exit.h"
  17. #include "common/settings.h"
  18. #include "common/string_util.h"
  19. #include "common/telemetry.h"
  20. #include "core/core.h"
  21. #include "core/core_timing.h"
  22. #include "core/cpu_manager.h"
  23. #include "core/crypto/key_manager.h"
  24. #include "core/file_sys/registered_cache.h"
  25. #include "core/file_sys/vfs/vfs_real.h"
  26. #include "core/hle/service/am/applet_manager.h"
  27. #include "core/hle/service/filesystem/filesystem.h"
  28. #include "core/loader/loader.h"
  29. #include "core/telemetry_session.h"
  30. #include "frontend_common/config.h"
  31. #include "input_common/main.h"
  32. #include "network/network.h"
  33. #include "sdl_config.h"
  34. #include "video_core/renderer_base.h"
  35. #include "yuzu_cmd/emu_window/emu_window_sdl2.h"
  36. #include "yuzu_cmd/emu_window/emu_window_sdl2_gl.h"
  37. #include "yuzu_cmd/emu_window/emu_window_sdl2_null.h"
  38. #include "yuzu_cmd/emu_window/emu_window_sdl2_vk.h"
  39. #ifdef _WIN32
  40. // windows.h needs to be included before shellapi.h
  41. #include <windows.h>
  42. #include <shellapi.h>
  43. #include "common/windows/timer_resolution.h"
  44. #endif
  45. #undef _UNICODE
  46. #include <getopt.h>
  47. #ifndef _MSC_VER
  48. #include <unistd.h>
  49. #endif
  50. #ifdef _WIN32
  51. extern "C" {
  52. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  53. // graphics
  54. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  55. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  56. }
  57. #endif
  58. #ifdef __unix__
  59. #include "common/linux/gamemode.h"
  60. #endif
  61. static void PrintHelp(const char* argv0) {
  62. std::cout << "Usage: " << argv0
  63. << " [options] <filename>\n"
  64. "-c, --config Load the specified configuration file\n"
  65. "-f, --fullscreen Start in fullscreen mode\n"
  66. "-g, --game File path of the game to load\n"
  67. "-h, --help Display this help and exit\n"
  68. "-m, --multiplayer=nick:password@address:port"
  69. " Nickname, password, address and port for multiplayer\n"
  70. "-p, --program Pass following string as arguments to executable\n"
  71. "-u, --user Select a specific user profile from 0 to 7\n"
  72. "-v, --version Output version information and exit\n";
  73. }
  74. static void PrintVersion() {
  75. std::cout << "yuzu " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl;
  76. }
  77. static void OnStateChanged(const Network::RoomMember::State& state) {
  78. switch (state) {
  79. case Network::RoomMember::State::Idle:
  80. LOG_DEBUG(Network, "Network is idle");
  81. break;
  82. case Network::RoomMember::State::Joining:
  83. LOG_DEBUG(Network, "Connection sequence to room started");
  84. break;
  85. case Network::RoomMember::State::Joined:
  86. LOG_DEBUG(Network, "Successfully joined to the room");
  87. break;
  88. case Network::RoomMember::State::Moderator:
  89. LOG_DEBUG(Network, "Successfully joined the room as a moderator");
  90. break;
  91. default:
  92. break;
  93. }
  94. }
  95. static void OnNetworkError(const Network::RoomMember::Error& error) {
  96. switch (error) {
  97. case Network::RoomMember::Error::LostConnection:
  98. LOG_DEBUG(Network, "Lost connection to the room");
  99. break;
  100. case Network::RoomMember::Error::CouldNotConnect:
  101. LOG_ERROR(Network, "Error: Could not connect");
  102. exit(1);
  103. break;
  104. case Network::RoomMember::Error::NameCollision:
  105. LOG_ERROR(
  106. Network,
  107. "You tried to use the same nickname as another user that is connected to the Room");
  108. exit(1);
  109. break;
  110. case Network::RoomMember::Error::IpCollision:
  111. LOG_ERROR(Network, "You tried to use the same fake IP-Address as another user that is "
  112. "connected to the Room");
  113. exit(1);
  114. break;
  115. case Network::RoomMember::Error::WrongPassword:
  116. LOG_ERROR(Network, "Room replied with: Wrong password");
  117. exit(1);
  118. break;
  119. case Network::RoomMember::Error::WrongVersion:
  120. LOG_ERROR(Network,
  121. "You are using a different version than the room you are trying to connect to");
  122. exit(1);
  123. break;
  124. case Network::RoomMember::Error::RoomIsFull:
  125. LOG_ERROR(Network, "The room is full");
  126. exit(1);
  127. break;
  128. case Network::RoomMember::Error::HostKicked:
  129. LOG_ERROR(Network, "You have been kicked by the host");
  130. break;
  131. case Network::RoomMember::Error::HostBanned:
  132. LOG_ERROR(Network, "You have been banned by the host");
  133. break;
  134. case Network::RoomMember::Error::UnknownError:
  135. LOG_ERROR(Network, "UnknownError");
  136. break;
  137. case Network::RoomMember::Error::PermissionDenied:
  138. LOG_ERROR(Network, "PermissionDenied");
  139. break;
  140. case Network::RoomMember::Error::NoSuchUser:
  141. LOG_ERROR(Network, "NoSuchUser");
  142. break;
  143. }
  144. }
  145. static void OnMessageReceived(const Network::ChatEntry& msg) {
  146. std::cout << std::endl << msg.nickname << ": " << msg.message << std::endl << std::endl;
  147. }
  148. static void OnStatusMessageReceived(const Network::StatusMessageEntry& msg) {
  149. std::string message;
  150. switch (msg.type) {
  151. case Network::IdMemberJoin:
  152. message = fmt::format("{} has joined", msg.nickname);
  153. break;
  154. case Network::IdMemberLeave:
  155. message = fmt::format("{} has left", msg.nickname);
  156. break;
  157. case Network::IdMemberKicked:
  158. message = fmt::format("{} has been kicked", msg.nickname);
  159. break;
  160. case Network::IdMemberBanned:
  161. message = fmt::format("{} has been banned", msg.nickname);
  162. break;
  163. case Network::IdAddressUnbanned:
  164. message = fmt::format("{} has been unbanned", msg.nickname);
  165. break;
  166. }
  167. if (!message.empty())
  168. std::cout << std::endl << "* " << message << std::endl << std::endl;
  169. }
  170. /// Application entry point
  171. int main(int argc, char** argv) {
  172. #ifdef _WIN32
  173. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  174. freopen("CONOUT$", "wb", stdout);
  175. freopen("CONOUT$", "wb", stderr);
  176. }
  177. #endif
  178. Common::Log::Initialize();
  179. Common::Log::SetColorConsoleBackendEnabled(true);
  180. Common::Log::Start();
  181. Common::DetachedTasks detached_tasks;
  182. int option_index = 0;
  183. #ifdef _WIN32
  184. int argc_w;
  185. auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w);
  186. if (argv_w == nullptr) {
  187. LOG_CRITICAL(Frontend, "Failed to get command line arguments");
  188. return -1;
  189. }
  190. #endif
  191. std::string filepath;
  192. std::optional<std::string> config_path;
  193. std::string program_args;
  194. std::optional<int> selected_user;
  195. bool use_multiplayer = false;
  196. bool fullscreen = false;
  197. std::string nickname{};
  198. std::string password{};
  199. std::string address{};
  200. u16 port = Network::DefaultRoomPort;
  201. static struct option long_options[] = {
  202. // clang-format off
  203. {"config", required_argument, 0, 'c'},
  204. {"fullscreen", no_argument, 0, 'f'},
  205. {"help", no_argument, 0, 'h'},
  206. {"game", required_argument, 0, 'g'},
  207. {"multiplayer", required_argument, 0, 'm'},
  208. {"program", optional_argument, 0, 'p'},
  209. {"user", required_argument, 0, 'u'},
  210. {"version", no_argument, 0, 'v'},
  211. {0, 0, 0, 0},
  212. // clang-format on
  213. };
  214. while (optind < argc) {
  215. int arg = getopt_long(argc, argv, "g:fhvp::c:u:", long_options, &option_index);
  216. if (arg != -1) {
  217. switch (static_cast<char>(arg)) {
  218. case 'c':
  219. config_path = optarg;
  220. break;
  221. case 'f':
  222. fullscreen = true;
  223. LOG_INFO(Frontend, "Starting in fullscreen mode...");
  224. break;
  225. case 'h':
  226. PrintHelp(argv[0]);
  227. return 0;
  228. case 'g': {
  229. const std::string str_arg(optarg);
  230. filepath = str_arg;
  231. break;
  232. }
  233. case 'm': {
  234. use_multiplayer = true;
  235. const std::string str_arg(optarg);
  236. // regex to check if the format is nickname:password@ip:port
  237. // with optional :password
  238. const std::regex re("^([^:]+)(?::(.+))?@([^:]+)(?::([0-9]+))?$");
  239. if (!std::regex_match(str_arg, re)) {
  240. std::cout << "Wrong format for option --multiplayer\n";
  241. PrintHelp(argv[0]);
  242. return 0;
  243. }
  244. std::smatch match;
  245. std::regex_search(str_arg, match, re);
  246. ASSERT(match.size() == 5);
  247. nickname = match[1];
  248. password = match[2];
  249. address = match[3];
  250. if (!match[4].str().empty()) {
  251. port = static_cast<u16>(std::strtoul(match[4].str().c_str(), nullptr, 0));
  252. }
  253. std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$");
  254. if (!std::regex_match(nickname, nickname_re)) {
  255. std::cout
  256. << "Nickname is not valid. Must be 4 to 20 alphanumeric characters.\n";
  257. return 0;
  258. }
  259. if (address.empty()) {
  260. std::cout << "Address to room must not be empty.\n";
  261. return 0;
  262. }
  263. break;
  264. }
  265. case 'p':
  266. program_args = argv[optind];
  267. ++optind;
  268. break;
  269. case 'u':
  270. selected_user = atoi(optarg);
  271. break;
  272. case 'v':
  273. PrintVersion();
  274. return 0;
  275. }
  276. } else {
  277. #ifdef _WIN32
  278. filepath = Common::UTF16ToUTF8(argv_w[optind]);
  279. #else
  280. filepath = argv[optind];
  281. #endif
  282. optind++;
  283. }
  284. }
  285. SdlConfig config{config_path};
  286. // apply the log_filter setting
  287. // the logger was initialized before and doesn't pick up the filter on its own
  288. Common::Log::Filter filter;
  289. filter.ParseFilterString(Settings::values.log_filter.GetValue());
  290. Common::Log::SetGlobalFilter(filter);
  291. if (!program_args.empty()) {
  292. Settings::values.program_args = program_args;
  293. }
  294. if (selected_user.has_value()) {
  295. Settings::values.current_user = std::clamp(*selected_user, 0, 7);
  296. }
  297. #ifdef _WIN32
  298. LocalFree(argv_w);
  299. #endif
  300. MicroProfileOnThreadCreate("EmuThread");
  301. SCOPE_EXIT {
  302. MicroProfileShutdown();
  303. };
  304. Common::ConfigureNvidiaEnvironmentFlags();
  305. if (filepath.empty()) {
  306. LOG_CRITICAL(Frontend, "Failed to load ROM: No ROM specified");
  307. return -1;
  308. }
  309. Core::System system{};
  310. system.Initialize();
  311. InputCommon::InputSubsystem input_subsystem{};
  312. // Apply the command line arguments
  313. system.ApplySettings();
  314. std::unique_ptr<EmuWindow_SDL2> emu_window;
  315. switch (Settings::values.renderer_backend.GetValue()) {
  316. case Settings::RendererBackend::OpenGL:
  317. emu_window = std::make_unique<EmuWindow_SDL2_GL>(&input_subsystem, system, fullscreen);
  318. break;
  319. case Settings::RendererBackend::Vulkan:
  320. emu_window = std::make_unique<EmuWindow_SDL2_VK>(&input_subsystem, system, fullscreen);
  321. break;
  322. case Settings::RendererBackend::Null:
  323. emu_window = std::make_unique<EmuWindow_SDL2_Null>(&input_subsystem, system, fullscreen);
  324. break;
  325. }
  326. #ifdef _WIN32
  327. Common::Windows::SetCurrentTimerResolutionToMaximum();
  328. system.CoreTiming().SetTimerResolutionNs(Common::Windows::GetCurrentTimerResolution());
  329. #endif
  330. system.SetContentProvider(std::make_unique<FileSys::ContentProviderUnion>());
  331. system.SetFilesystem(std::make_shared<FileSys::RealVfsFilesystem>());
  332. system.GetFileSystemController().CreateFactories(*system.GetFilesystem());
  333. system.GetUserChannel().clear();
  334. Service::AM::FrontendAppletParameters load_parameters{
  335. .applet_id = Service::AM::AppletId::Application,
  336. };
  337. const Core::SystemResultStatus load_result{system.Load(*emu_window, filepath, load_parameters)};
  338. switch (load_result) {
  339. case Core::SystemResultStatus::ErrorGetLoader:
  340. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filepath);
  341. return -1;
  342. case Core::SystemResultStatus::ErrorLoader:
  343. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  344. return -1;
  345. case Core::SystemResultStatus::ErrorNotInitialized:
  346. LOG_CRITICAL(Frontend, "CPUCore not initialized");
  347. return -1;
  348. case Core::SystemResultStatus::ErrorVideoCore:
  349. LOG_CRITICAL(Frontend, "Failed to initialize VideoCore!");
  350. return -1;
  351. case Core::SystemResultStatus::Success:
  352. break; // Expected case
  353. default:
  354. if (static_cast<u32>(load_result) >
  355. static_cast<u32>(Core::SystemResultStatus::ErrorLoader)) {
  356. const u16 loader_id = static_cast<u16>(Core::SystemResultStatus::ErrorLoader);
  357. const u16 error_id = static_cast<u16>(load_result) - loader_id;
  358. LOG_CRITICAL(Frontend,
  359. "While attempting to load the ROM requested, an error occurred. Please "
  360. "refer to the yuzu wiki for more information or the yuzu discord for "
  361. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  362. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id));
  363. }
  364. break;
  365. }
  366. system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL");
  367. if (use_multiplayer) {
  368. if (auto member = system.GetRoomNetwork().GetRoomMember().lock()) {
  369. member->BindOnChatMessageReceived(OnMessageReceived);
  370. member->BindOnStatusMessageReceived(OnStatusMessageReceived);
  371. member->BindOnStateChanged(OnStateChanged);
  372. member->BindOnError(OnNetworkError);
  373. LOG_DEBUG(Network, "Start connection to {}:{} with nickname {}", address, port,
  374. nickname);
  375. member->Join(nickname, address.c_str(), port, 0, Network::NoPreferredIP, password);
  376. } else {
  377. LOG_ERROR(Network, "Could not access RoomMember");
  378. return 0;
  379. }
  380. }
  381. // Core is loaded, start the GPU (makes the GPU contexts current to this thread)
  382. system.GPU().Start();
  383. system.GetCpuManager().OnGpuReady();
  384. if (Settings::values.use_disk_shader_cache.GetValue()) {
  385. system.Renderer().ReadRasterizer()->LoadDiskResources(
  386. system.GetApplicationProcessProgramID(), std::stop_token{},
  387. [](VideoCore::LoadCallbackStage, size_t value, size_t total) {});
  388. }
  389. system.RegisterExitCallback([&] {
  390. // Just exit right away.
  391. exit(0);
  392. });
  393. #ifdef __unix__
  394. Common::Linux::StartGamemode();
  395. #endif
  396. void(system.Run());
  397. if (system.DebuggerEnabled()) {
  398. system.InitializeDebugger();
  399. }
  400. while (emu_window->IsOpen()) {
  401. emu_window->WaitEvent();
  402. }
  403. system.DetachDebugger();
  404. void(system.Pause());
  405. system.ShutdownMainProcess();
  406. #ifdef __unix__
  407. Common::Linux::StopGamemode();
  408. #endif
  409. detached_tasks.WaitForAllTasks();
  410. return 0;
  411. }