suyu.cpp 15 KB

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