yuzu.cpp 15 KB

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