yuzu.cpp 15 KB

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