suyu.cpp 18 KB

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