Program.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using CommandLine;
  4. using LibHac.Tools.FsSystem;
  5. using Ryujinx.Audio.Backends.SDL2;
  6. using Ryujinx.Common;
  7. using Ryujinx.Common.Configuration;
  8. using Ryujinx.Common.Configuration.Hid;
  9. using Ryujinx.Common.Configuration.Hid.Controller;
  10. using Ryujinx.Common.Configuration.Hid.Controller.Motion;
  11. using Ryujinx.Common.Configuration.Hid.Keyboard;
  12. using Ryujinx.Common.Logging;
  13. using Ryujinx.Common.System;
  14. using Ryujinx.Common.Utilities;
  15. using Ryujinx.Graphics.GAL;
  16. using Ryujinx.Graphics.GAL.Multithreading;
  17. using Ryujinx.Graphics.Gpu;
  18. using Ryujinx.Graphics.Gpu.Shader;
  19. using Ryujinx.Graphics.OpenGL;
  20. using Ryujinx.Headless.SDL2.OpenGL;
  21. using Ryujinx.HLE;
  22. using Ryujinx.HLE.FileSystem;
  23. using Ryujinx.HLE.FileSystem.Content;
  24. using Ryujinx.HLE.HOS;
  25. using Ryujinx.HLE.HOS.Services.Account.Acc;
  26. using Ryujinx.Input;
  27. using Ryujinx.Input.HLE;
  28. using Ryujinx.Input.SDL2;
  29. using System;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Text.Json;
  34. using System.Threading;
  35. using ConfigGamepadInputId = Ryujinx.Common.Configuration.Hid.Controller.GamepadInputId;
  36. using ConfigStickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId;
  37. using Key = Ryujinx.Common.Configuration.Hid.Key;
  38. namespace Ryujinx.Headless.SDL2
  39. {
  40. class Program
  41. {
  42. public static string Version { get; private set; }
  43. private static VirtualFileSystem _virtualFileSystem;
  44. private static ContentManager _contentManager;
  45. private static AccountManager _accountManager;
  46. private static LibHacHorizonManager _libHacHorizonManager;
  47. private static UserChannelPersistence _userChannelPersistence;
  48. private static InputManager _inputManager;
  49. private static Switch _emulationContext;
  50. private static WindowBase _window;
  51. private static WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  52. private static List<InputConfig> _inputConfiguration;
  53. private static bool _enableKeyboard;
  54. private static bool _enableMouse;
  55. static void Main(string[] args)
  56. {
  57. Version = ReleaseInformations.GetVersion();
  58. Console.Title = $"Ryujinx Console {Version} (Headless SDL2)";
  59. AppDataManager.Initialize(null);
  60. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  61. _libHacHorizonManager = new LibHacHorizonManager();
  62. _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
  63. _libHacHorizonManager.InitializeArpServer();
  64. _libHacHorizonManager.InitializeBcatServer();
  65. _libHacHorizonManager.InitializeSystemClients();
  66. _contentManager = new ContentManager(_virtualFileSystem);
  67. _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient);
  68. _userChannelPersistence = new UserChannelPersistence();
  69. _inputManager = new InputManager(new SDL2KeyboardDriver(), new SDL2GamepadDriver());
  70. GraphicsConfig.EnableShaderCache = true;
  71. Parser.Default.ParseArguments<Options>(args)
  72. .WithParsed(options => Load(options))
  73. .WithNotParsed(errors => errors.Output());
  74. _inputManager.Dispose();
  75. }
  76. private static InputConfig HandlePlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  77. {
  78. if (inputId == null)
  79. {
  80. if (index == PlayerIndex.Player1)
  81. {
  82. Logger.Info?.Print(LogClass.Application, $"{index} not configured, defaulting to default keyboard.");
  83. // Default to keyboard
  84. inputId = "0";
  85. }
  86. else
  87. {
  88. Logger.Info?.Print(LogClass.Application, $"{index} not configured");
  89. return null;
  90. }
  91. }
  92. IGamepad gamepad;
  93. bool isKeyboard = true;
  94. gamepad = _inputManager.KeyboardDriver.GetGamepad(inputId);
  95. if (gamepad == null)
  96. {
  97. gamepad = _inputManager.GamepadDriver.GetGamepad(inputId);
  98. isKeyboard = false;
  99. if (gamepad == null)
  100. {
  101. Logger.Error?.Print(LogClass.Application, $"{index} gamepad not found (\"{inputId}\")");
  102. return null;
  103. }
  104. }
  105. string gamepadName = gamepad.Name;
  106. gamepad.Dispose();
  107. InputConfig config;
  108. if (inputProfileName == null || inputProfileName.Equals("default"))
  109. {
  110. if (isKeyboard)
  111. {
  112. config = new StandardKeyboardInputConfig
  113. {
  114. Version = InputConfig.CurrentVersion,
  115. Backend = InputBackendType.WindowKeyboard,
  116. Id = null,
  117. ControllerType = ControllerType.JoyconPair,
  118. LeftJoycon = new LeftJoyconCommonConfig<Key>
  119. {
  120. DpadUp = Key.Up,
  121. DpadDown = Key.Down,
  122. DpadLeft = Key.Left,
  123. DpadRight = Key.Right,
  124. ButtonMinus = Key.Minus,
  125. ButtonL = Key.E,
  126. ButtonZl = Key.Q,
  127. ButtonSl = Key.Unbound,
  128. ButtonSr = Key.Unbound
  129. },
  130. LeftJoyconStick = new JoyconConfigKeyboardStick<Key>
  131. {
  132. StickUp = Key.W,
  133. StickDown = Key.S,
  134. StickLeft = Key.A,
  135. StickRight = Key.D,
  136. StickButton = Key.F,
  137. },
  138. RightJoycon = new RightJoyconCommonConfig<Key>
  139. {
  140. ButtonA = Key.Z,
  141. ButtonB = Key.X,
  142. ButtonX = Key.C,
  143. ButtonY = Key.V,
  144. ButtonPlus = Key.Plus,
  145. ButtonR = Key.U,
  146. ButtonZr = Key.O,
  147. ButtonSl = Key.Unbound,
  148. ButtonSr = Key.Unbound
  149. },
  150. RightJoyconStick = new JoyconConfigKeyboardStick<Key>
  151. {
  152. StickUp = Key.I,
  153. StickDown = Key.K,
  154. StickLeft = Key.J,
  155. StickRight = Key.L,
  156. StickButton = Key.H,
  157. }
  158. };
  159. }
  160. else
  161. {
  162. bool isNintendoStyle = gamepadName.Contains("Nintendo");
  163. config = new StandardControllerInputConfig
  164. {
  165. Version = InputConfig.CurrentVersion,
  166. Backend = InputBackendType.GamepadSDL2,
  167. Id = null,
  168. ControllerType = ControllerType.JoyconPair,
  169. DeadzoneLeft = 0.1f,
  170. DeadzoneRight = 0.1f,
  171. RangeLeft = 1.0f,
  172. RangeRight = 1.0f,
  173. TriggerThreshold = 0.5f,
  174. LeftJoycon = new LeftJoyconCommonConfig<ConfigGamepadInputId>
  175. {
  176. DpadUp = ConfigGamepadInputId.DpadUp,
  177. DpadDown = ConfigGamepadInputId.DpadDown,
  178. DpadLeft = ConfigGamepadInputId.DpadLeft,
  179. DpadRight = ConfigGamepadInputId.DpadRight,
  180. ButtonMinus = ConfigGamepadInputId.Minus,
  181. ButtonL = ConfigGamepadInputId.LeftShoulder,
  182. ButtonZl = ConfigGamepadInputId.LeftTrigger,
  183. ButtonSl = ConfigGamepadInputId.Unbound,
  184. ButtonSr = ConfigGamepadInputId.Unbound,
  185. },
  186. LeftJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  187. {
  188. Joystick = ConfigStickInputId.Left,
  189. StickButton = ConfigGamepadInputId.LeftStick,
  190. InvertStickX = false,
  191. InvertStickY = false,
  192. },
  193. RightJoycon = new RightJoyconCommonConfig<ConfigGamepadInputId>
  194. {
  195. ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B,
  196. ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A,
  197. ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y,
  198. ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X,
  199. ButtonPlus = ConfigGamepadInputId.Plus,
  200. ButtonR = ConfigGamepadInputId.RightShoulder,
  201. ButtonZr = ConfigGamepadInputId.RightTrigger,
  202. ButtonSl = ConfigGamepadInputId.Unbound,
  203. ButtonSr = ConfigGamepadInputId.Unbound,
  204. },
  205. RightJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  206. {
  207. Joystick = ConfigStickInputId.Right,
  208. StickButton = ConfigGamepadInputId.RightStick,
  209. InvertStickX = false,
  210. InvertStickY = false,
  211. },
  212. Motion = new StandardMotionConfigController
  213. {
  214. MotionBackend = MotionInputBackendType.GamepadDriver,
  215. EnableMotion = true,
  216. Sensitivity = 100,
  217. GyroDeadzone = 1,
  218. },
  219. Rumble = new RumbleConfigController
  220. {
  221. StrongRumble = 1f,
  222. WeakRumble = 1f,
  223. EnableRumble = false
  224. }
  225. };
  226. }
  227. }
  228. else
  229. {
  230. string profileBasePath;
  231. if (isKeyboard)
  232. {
  233. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "keyboard");
  234. }
  235. else
  236. {
  237. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "controller");
  238. }
  239. string path = Path.Combine(profileBasePath, inputProfileName + ".json");
  240. if (!File.Exists(path))
  241. {
  242. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" not found for \"{inputId}\"");
  243. return null;
  244. }
  245. try
  246. {
  247. using (Stream stream = File.OpenRead(path))
  248. {
  249. config = JsonHelper.Deserialize<InputConfig>(stream);
  250. }
  251. }
  252. catch (JsonException)
  253. {
  254. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" parsing failed for \"{inputId}\"");
  255. return null;
  256. }
  257. }
  258. config.Id = inputId;
  259. config.PlayerIndex = index;
  260. string inputTypeName = isKeyboard ? "Keyboard" : "Gamepad";
  261. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} configured with {inputTypeName} \"{config.Id}\"");
  262. // If both stick ranges are 0 (usually indicative of an outdated profile load) then both sticks will be set to 1.0.
  263. if (config is StandardControllerInputConfig controllerConfig)
  264. {
  265. if (controllerConfig.RangeLeft <= 0.0f && controllerConfig.RangeRight <= 0.0f)
  266. {
  267. controllerConfig.RangeLeft = 1.0f;
  268. controllerConfig.RangeRight = 1.0f;
  269. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} stick range reset. Save the profile now to update your configuration");
  270. }
  271. }
  272. return config;
  273. }
  274. static void Load(Options option)
  275. {
  276. IGamepad gamepad;
  277. if (option.ListInputIds)
  278. {
  279. Logger.Info?.Print(LogClass.Application, "Input Ids:");
  280. foreach (string id in _inputManager.KeyboardDriver.GamepadsIds)
  281. {
  282. gamepad = _inputManager.KeyboardDriver.GetGamepad(id);
  283. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  284. gamepad.Dispose();
  285. }
  286. foreach (string id in _inputManager.GamepadDriver.GamepadsIds)
  287. {
  288. gamepad = _inputManager.GamepadDriver.GetGamepad(id);
  289. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  290. gamepad.Dispose();
  291. }
  292. return;
  293. }
  294. if (option.InputPath == null)
  295. {
  296. Logger.Error?.Print(LogClass.Application, "Please provide a file to load");
  297. return;
  298. }
  299. _inputConfiguration = new List<InputConfig>();
  300. _enableKeyboard = (bool)option.EnableKeyboard;
  301. _enableMouse = (bool)option.EnableMouse;
  302. void LoadPlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  303. {
  304. InputConfig inputConfig = HandlePlayerConfiguration(inputProfileName, inputId, index);
  305. if (inputConfig != null)
  306. {
  307. _inputConfiguration.Add(inputConfig);
  308. }
  309. }
  310. LoadPlayerConfiguration(option.InputProfile1Name, option.InputId1, PlayerIndex.Player1);
  311. LoadPlayerConfiguration(option.InputProfile2Name, option.InputId2, PlayerIndex.Player2);
  312. LoadPlayerConfiguration(option.InputProfile3Name, option.InputId3, PlayerIndex.Player3);
  313. LoadPlayerConfiguration(option.InputProfile4Name, option.InputId4, PlayerIndex.Player4);
  314. LoadPlayerConfiguration(option.InputProfile5Name, option.InputId5, PlayerIndex.Player5);
  315. LoadPlayerConfiguration(option.InputProfile6Name, option.InputId6, PlayerIndex.Player6);
  316. LoadPlayerConfiguration(option.InputProfile7Name, option.InputId7, PlayerIndex.Player7);
  317. LoadPlayerConfiguration(option.InputProfile8Name, option.InputId8, PlayerIndex.Player8);
  318. LoadPlayerConfiguration(option.InputProfileHandheldName, option.InputIdHandheld, PlayerIndex.Handheld);
  319. if (_inputConfiguration.Count == 0)
  320. {
  321. return;
  322. }
  323. // Setup logging level
  324. Logger.SetEnable(LogLevel.Debug, (bool)option.LoggingEnableDebug);
  325. Logger.SetEnable(LogLevel.Stub, (bool)option.LoggingEnableStub);
  326. Logger.SetEnable(LogLevel.Info, (bool)option.LoggingEnableInfo);
  327. Logger.SetEnable(LogLevel.Warning, (bool)option.LoggingEnableWarning);
  328. Logger.SetEnable(LogLevel.Error, (bool)option.LoggingEnableError);
  329. Logger.SetEnable(LogLevel.Trace, (bool)option.LoggingEnableTrace);
  330. Logger.SetEnable(LogLevel.Guest, (bool)option.LoggingEnableGuest);
  331. Logger.SetEnable(LogLevel.AccessLog, (bool)option.LoggingEnableFsAccessLog);
  332. if ((bool)option.EnableFileLog)
  333. {
  334. Logger.AddTarget(new AsyncLogTargetWrapper(
  335. new FileLogTarget(AppDomain.CurrentDomain.BaseDirectory, "file"),
  336. 1000,
  337. AsyncLogTargetOverflowAction.Block
  338. ));
  339. }
  340. // Setup graphics configuration
  341. GraphicsConfig.EnableShaderCache = (bool)option.EnableShaderCache;
  342. GraphicsConfig.ResScale = option.ResScale;
  343. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  344. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  345. while (true)
  346. {
  347. LoadApplication(option);
  348. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  349. {
  350. break;
  351. }
  352. _userChannelPersistence.ShouldRestart = false;
  353. }
  354. }
  355. private static void SetupProgressHandler()
  356. {
  357. Ptc.PtcStateChanged -= ProgressHandler;
  358. Ptc.PtcStateChanged += ProgressHandler;
  359. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  360. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  361. }
  362. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  363. {
  364. string label;
  365. switch (state)
  366. {
  367. case PtcLoadingState ptcState:
  368. label = $"PTC : {current}/{total}";
  369. break;
  370. case ShaderCacheState shaderCacheState:
  371. label = $"Shaders : {current}/{total}";
  372. break;
  373. default:
  374. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  375. }
  376. Logger.Info?.Print(LogClass.Application, label);
  377. }
  378. private static Switch InitializeEmulationContext(WindowBase window, Options options)
  379. {
  380. IRenderer renderer = new Renderer();
  381. BackendThreading threadingMode = options.BackendThreading;
  382. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  383. if (threadedGAL)
  384. {
  385. renderer = new ThreadedRenderer(renderer);
  386. }
  387. HLEConfiguration configuration = new HLEConfiguration(_virtualFileSystem,
  388. _libHacHorizonManager,
  389. _contentManager,
  390. _accountManager,
  391. _userChannelPersistence,
  392. renderer,
  393. new SDL2HardwareDeviceDriver(),
  394. (bool)options.ExpandRam ? MemoryConfiguration.MemoryConfiguration6GB : MemoryConfiguration.MemoryConfiguration4GB,
  395. window,
  396. options.SystemLanguage,
  397. options.SystemRegion,
  398. (bool)options.EnableVsync,
  399. (bool)options.EnableDockedMode,
  400. (bool)options.EnablePtc,
  401. (bool)options.EnableInternetAccess,
  402. (bool)options.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  403. options.FsGlobalAccessLogMode,
  404. options.SystemTimeOffset,
  405. options.SystemTimeZone,
  406. options.MemoryManagerMode,
  407. (bool)options.IgnoreMissingServices,
  408. options.AspectRatio,
  409. options.AudioVolume);
  410. return new Switch(configuration);
  411. }
  412. private static void ExecutionEntrypoint()
  413. {
  414. if (OperatingSystem.IsWindows())
  415. {
  416. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  417. }
  418. DisplaySleep.Prevent();
  419. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  420. _window.Execute();
  421. Ptc.Close();
  422. PtcProfiler.Stop();
  423. _emulationContext.Dispose();
  424. _window.Dispose();
  425. if (OperatingSystem.IsWindows())
  426. {
  427. _windowsMultimediaTimerResolution?.Dispose();
  428. _windowsMultimediaTimerResolution = null;
  429. }
  430. }
  431. private static bool LoadApplication(Options options)
  432. {
  433. string path = options.InputPath;
  434. Logger.RestartTime();
  435. _window = new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, (bool)options.EnableMouse);
  436. _emulationContext = InitializeEmulationContext(_window, options);
  437. SetupProgressHandler();
  438. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  439. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  440. if (Directory.Exists(path))
  441. {
  442. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  443. if (romFsFiles.Length == 0)
  444. {
  445. romFsFiles = Directory.GetFiles(path, "*.romfs");
  446. }
  447. if (romFsFiles.Length > 0)
  448. {
  449. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  450. _emulationContext.LoadCart(path, romFsFiles[0]);
  451. }
  452. else
  453. {
  454. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  455. _emulationContext.LoadCart(path);
  456. }
  457. }
  458. else if (File.Exists(path))
  459. {
  460. switch (Path.GetExtension(path).ToLowerInvariant())
  461. {
  462. case ".xci":
  463. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  464. _emulationContext.LoadXci(path);
  465. break;
  466. case ".nca":
  467. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  468. _emulationContext.LoadNca(path);
  469. break;
  470. case ".nsp":
  471. case ".pfs0":
  472. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  473. _emulationContext.LoadNsp(path);
  474. break;
  475. default:
  476. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  477. try
  478. {
  479. _emulationContext.LoadProgram(path);
  480. }
  481. catch (ArgumentOutOfRangeException)
  482. {
  483. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  484. return false;
  485. }
  486. break;
  487. }
  488. }
  489. else
  490. {
  491. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  492. _emulationContext.Dispose();
  493. return false;
  494. }
  495. Translator.IsReadyForTranslation.Reset();
  496. Thread windowThread = new Thread(() =>
  497. {
  498. ExecutionEntrypoint();
  499. })
  500. {
  501. Name = "GUI.WindowThread"
  502. };
  503. windowThread.Start();
  504. windowThread.Join();
  505. return true;
  506. }
  507. }
  508. }