yuzu.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <chrono>
  5. #include <iostream>
  6. #include <memory>
  7. #include <regex>
  8. #include <string>
  9. #include <thread>
  10. #include <fmt/ostream.h>
  11. #include "common/detached_tasks.h"
  12. #include "common/logging/backend.h"
  13. #include "common/logging/log.h"
  14. #include "common/microprofile.h"
  15. #include "common/nvidia_flags.h"
  16. #include "common/scm_rev.h"
  17. #include "common/scope_exit.h"
  18. #include "common/settings.h"
  19. #include "common/string_util.h"
  20. #include "common/telemetry.h"
  21. #include "core/core.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_vk.h"
  36. #ifdef _WIN32
  37. // windows.h needs to be included before shellapi.h
  38. #include <windows.h>
  39. #include <shellapi.h>
  40. #endif
  41. #undef _UNICODE
  42. #include <getopt.h>
  43. #ifndef _MSC_VER
  44. #include <unistd.h>
  45. #endif
  46. #ifdef _WIN32
  47. extern "C" {
  48. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  49. // graphics
  50. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  51. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  52. }
  53. #endif
  54. static void PrintHelp(const char* argv0) {
  55. std::cout << "Usage: " << argv0
  56. << " [options] <filename>\n"
  57. "-m, --multiplayer=nick:password@address:port"
  58. " Nickname, password, address and port for multiplayer\n"
  59. "-f, --fullscreen Start in fullscreen mode\n"
  60. "-h, --help Display this help and exit\n"
  61. "-v, --version Output version information and exit\n"
  62. "-p, --program Pass following string as arguments to executable\n"
  63. "-c, --config Load the specified configuration file\n";
  64. }
  65. static void PrintVersion() {
  66. std::cout << "yuzu " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl;
  67. }
  68. static void OnStateChanged(const Network::RoomMember::State& state) {
  69. switch (state) {
  70. case Network::RoomMember::State::Idle:
  71. LOG_DEBUG(Network, "Network is idle");
  72. break;
  73. case Network::RoomMember::State::Joining:
  74. LOG_DEBUG(Network, "Connection sequence to room started");
  75. break;
  76. case Network::RoomMember::State::Joined:
  77. LOG_DEBUG(Network, "Successfully joined to the room");
  78. break;
  79. case Network::RoomMember::State::Moderator:
  80. LOG_DEBUG(Network, "Successfully joined the room as a moderator");
  81. break;
  82. default:
  83. break;
  84. }
  85. }
  86. static void OnNetworkError(const Network::RoomMember::Error& error) {
  87. switch (error) {
  88. case Network::RoomMember::Error::LostConnection:
  89. LOG_DEBUG(Network, "Lost connection to the room");
  90. break;
  91. case Network::RoomMember::Error::CouldNotConnect:
  92. LOG_ERROR(Network, "Error: Could not connect");
  93. exit(1);
  94. break;
  95. case Network::RoomMember::Error::NameCollision:
  96. LOG_ERROR(
  97. Network,
  98. "You tried to use the same nickname as another user that is connected to the Room");
  99. exit(1);
  100. break;
  101. case Network::RoomMember::Error::MacCollision:
  102. LOG_ERROR(Network, "You tried to use the same MAC-Address as another user that is "
  103. "connected to the Room");
  104. exit(1);
  105. break;
  106. case Network::RoomMember::Error::ConsoleIdCollision:
  107. LOG_ERROR(Network, "Your Console ID conflicted with someone else in 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. Common::Log::Initialize();
  168. Common::Log::SetColorConsoleBackendEnabled(true);
  169. Common::Log::Start();
  170. Common::DetachedTasks detached_tasks;
  171. int option_index = 0;
  172. #ifdef _WIN32
  173. int argc_w;
  174. auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w);
  175. if (argv_w == nullptr) {
  176. LOG_CRITICAL(Frontend, "Failed to get command line arguments");
  177. return -1;
  178. }
  179. #endif
  180. std::string filepath;
  181. std::optional<std::string> config_path;
  182. std::string program_args;
  183. bool use_multiplayer = false;
  184. bool fullscreen = false;
  185. std::string nickname{};
  186. std::string password{};
  187. std::string address{};
  188. u16 port = Network::DefaultRoomPort;
  189. static struct option long_options[] = {
  190. // clang-format off
  191. {"multiplayer", required_argument, 0, 'm'},
  192. {"fullscreen", no_argument, 0, 'f'},
  193. {"help", no_argument, 0, 'h'},
  194. {"version", no_argument, 0, 'v'},
  195. {"program", optional_argument, 0, 'p'},
  196. {"config", required_argument, 0, 'c'},
  197. {0, 0, 0, 0},
  198. // clang-format on
  199. };
  200. while (optind < argc) {
  201. int arg = getopt_long(argc, argv, "g:fhvp::c:", long_options, &option_index);
  202. if (arg != -1) {
  203. switch (static_cast<char>(arg)) {
  204. case 'm': {
  205. use_multiplayer = true;
  206. const std::string str_arg(optarg);
  207. // regex to check if the format is nickname:password@ip:port
  208. // with optional :password
  209. const std::regex re("^([^:]+)(?::(.+))?@([^:]+)(?::([0-9]+))?$");
  210. if (!std::regex_match(str_arg, re)) {
  211. std::cout << "Wrong format for option --multiplayer\n";
  212. PrintHelp(argv[0]);
  213. return 0;
  214. }
  215. std::smatch match;
  216. std::regex_search(str_arg, match, re);
  217. ASSERT(match.size() == 5);
  218. nickname = match[1];
  219. password = match[2];
  220. address = match[3];
  221. if (!match[4].str().empty())
  222. port = std::stoi(match[4]);
  223. std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$");
  224. if (!std::regex_match(nickname, nickname_re)) {
  225. std::cout
  226. << "Nickname is not valid. Must be 4 to 20 alphanumeric characters.\n";
  227. return 0;
  228. }
  229. if (address.empty()) {
  230. std::cout << "Address to room must not be empty.\n";
  231. return 0;
  232. }
  233. break;
  234. }
  235. case 'f':
  236. fullscreen = true;
  237. LOG_INFO(Frontend, "Starting in fullscreen mode...");
  238. break;
  239. case 'h':
  240. PrintHelp(argv[0]);
  241. return 0;
  242. case 'v':
  243. PrintVersion();
  244. return 0;
  245. case 'p':
  246. program_args = argv[optind];
  247. ++optind;
  248. break;
  249. case 'c':
  250. config_path = optarg;
  251. break;
  252. }
  253. } else {
  254. #ifdef _WIN32
  255. filepath = Common::UTF16ToUTF8(argv_w[optind]);
  256. #else
  257. filepath = argv[optind];
  258. #endif
  259. optind++;
  260. }
  261. }
  262. Config config{config_path};
  263. // apply the log_filter setting
  264. // the logger was initialized before and doesn't pick up the filter on its own
  265. Common::Log::Filter filter;
  266. filter.ParseFilterString(Settings::values.log_filter.GetValue());
  267. Common::Log::SetGlobalFilter(filter);
  268. if (!program_args.empty()) {
  269. Settings::values.program_args = program_args;
  270. }
  271. #ifdef _WIN32
  272. LocalFree(argv_w);
  273. #endif
  274. MicroProfileOnThreadCreate("EmuThread");
  275. SCOPE_EXIT({ MicroProfileShutdown(); });
  276. Common::ConfigureNvidiaEnvironmentFlags();
  277. if (filepath.empty()) {
  278. LOG_CRITICAL(Frontend, "Failed to load ROM: No ROM specified");
  279. return -1;
  280. }
  281. Core::System system{};
  282. InputCommon::InputSubsystem input_subsystem{};
  283. // Apply the command line arguments
  284. system.ApplySettings();
  285. std::unique_ptr<EmuWindow_SDL2> emu_window;
  286. switch (Settings::values.renderer_backend.GetValue()) {
  287. case Settings::RendererBackend::OpenGL:
  288. emu_window = std::make_unique<EmuWindow_SDL2_GL>(&input_subsystem, system, fullscreen);
  289. break;
  290. case Settings::RendererBackend::Vulkan:
  291. emu_window = std::make_unique<EmuWindow_SDL2_VK>(&input_subsystem, system, fullscreen);
  292. break;
  293. }
  294. system.SetContentProvider(std::make_unique<FileSys::ContentProviderUnion>());
  295. system.SetFilesystem(std::make_shared<FileSys::RealVfsFilesystem>());
  296. system.GetFileSystemController().CreateFactories(*system.GetFilesystem());
  297. const Core::SystemResultStatus load_result{system.Load(*emu_window, filepath)};
  298. switch (load_result) {
  299. case Core::SystemResultStatus::ErrorGetLoader:
  300. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filepath);
  301. return -1;
  302. case Core::SystemResultStatus::ErrorLoader:
  303. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  304. return -1;
  305. case Core::SystemResultStatus::ErrorNotInitialized:
  306. LOG_CRITICAL(Frontend, "CPUCore not initialized");
  307. return -1;
  308. case Core::SystemResultStatus::ErrorVideoCore:
  309. LOG_CRITICAL(Frontend, "Failed to initialize VideoCore!");
  310. return -1;
  311. case Core::SystemResultStatus::Success:
  312. break; // Expected case
  313. default:
  314. if (static_cast<u32>(load_result) >
  315. static_cast<u32>(Core::SystemResultStatus::ErrorLoader)) {
  316. const u16 loader_id = static_cast<u16>(Core::SystemResultStatus::ErrorLoader);
  317. const u16 error_id = static_cast<u16>(load_result) - loader_id;
  318. LOG_CRITICAL(Frontend,
  319. "While attempting to load the ROM requested, an error occurred. Please "
  320. "refer to the yuzu wiki for more information or the yuzu discord for "
  321. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  322. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id));
  323. }
  324. }
  325. system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL");
  326. if (use_multiplayer) {
  327. if (auto member = system.GetRoomNetwork().GetRoomMember().lock()) {
  328. member->BindOnChatMessageRecieved(OnMessageReceived);
  329. member->BindOnStatusMessageReceived(OnStatusMessageReceived);
  330. member->BindOnStateChanged(OnStateChanged);
  331. member->BindOnError(OnNetworkError);
  332. LOG_DEBUG(Network, "Start connection to {}:{} with nickname {}", address, port,
  333. nickname);
  334. member->Join(nickname, "", address.c_str(), port, 0, Network::NoPreferredMac, password);
  335. } else {
  336. LOG_ERROR(Network, "Could not access RoomMember");
  337. return 0;
  338. }
  339. }
  340. // Core is loaded, start the GPU (makes the GPU contexts current to this thread)
  341. system.GPU().Start();
  342. system.GetCpuManager().OnGpuReady();
  343. if (Settings::values.use_disk_shader_cache.GetValue()) {
  344. system.Renderer().ReadRasterizer()->LoadDiskResources(
  345. system.GetCurrentProcessProgramID(), std::stop_token{},
  346. [](VideoCore::LoadCallbackStage, size_t value, size_t total) {});
  347. }
  348. system.RegisterExitCallback([&] {
  349. // Just exit right away.
  350. exit(0);
  351. });
  352. void(system.Run());
  353. if (system.DebuggerEnabled()) {
  354. system.InitializeDebugger();
  355. }
  356. while (emu_window->IsOpen()) {
  357. emu_window->WaitEvent();
  358. }
  359. system.DetachDebugger();
  360. void(system.Pause());
  361. system.Shutdown();
  362. detached_tasks.WaitForAllTasks();
  363. return 0;
  364. }