Program.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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.Guest, (bool)option.LoggingEnableGuest);
  330. Logger.SetEnable(LogLevel.AccessLog, (bool)option.LoggingEnableFsAccessLog);
  331. if ((bool)option.EnableFileLog)
  332. {
  333. Logger.AddTarget(new AsyncLogTargetWrapper(
  334. new FileLogTarget(AppDomain.CurrentDomain.BaseDirectory, "file"),
  335. 1000,
  336. AsyncLogTargetOverflowAction.Block
  337. ));
  338. }
  339. // Setup graphics configuration
  340. GraphicsConfig.EnableShaderCache = (bool)option.EnableShaderCache;
  341. GraphicsConfig.ResScale = option.ResScale;
  342. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  343. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  344. while (true)
  345. {
  346. LoadApplication(option);
  347. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  348. {
  349. break;
  350. }
  351. _userChannelPersistence.ShouldRestart = false;
  352. }
  353. }
  354. private static void SetupProgressHandler()
  355. {
  356. Ptc.PtcStateChanged -= ProgressHandler;
  357. Ptc.PtcStateChanged += ProgressHandler;
  358. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  359. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  360. }
  361. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  362. {
  363. string label;
  364. switch (state)
  365. {
  366. case PtcLoadingState ptcState:
  367. label = $"PTC : {current}/{total}";
  368. break;
  369. case ShaderCacheState shaderCacheState:
  370. label = $"Shaders : {current}/{total}";
  371. break;
  372. default:
  373. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  374. }
  375. Logger.Info?.Print(LogClass.Application, label);
  376. }
  377. private static Switch InitializeEmulationContext(WindowBase window, Options options)
  378. {
  379. IRenderer renderer = new Renderer();
  380. BackendThreading threadingMode = options.BackendThreading;
  381. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  382. if (threadedGAL)
  383. {
  384. renderer = new ThreadedRenderer(renderer);
  385. }
  386. HLEConfiguration configuration = new HLEConfiguration(_virtualFileSystem,
  387. _libHacHorizonManager,
  388. _contentManager,
  389. _accountManager,
  390. _userChannelPersistence,
  391. renderer,
  392. new SDL2HardwareDeviceDriver(),
  393. (bool)options.ExpandRam ? MemoryConfiguration.MemoryConfiguration6GB : MemoryConfiguration.MemoryConfiguration4GB,
  394. window,
  395. options.SystemLanguage,
  396. options.SystemRegion,
  397. (bool)options.EnableVsync,
  398. (bool)options.EnableDockedMode,
  399. (bool)options.EnablePtc,
  400. (bool)options.EnableInternetAccess,
  401. (bool)options.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  402. options.FsGlobalAccessLogMode,
  403. options.SystemTimeOffset,
  404. options.SystemTimeZone,
  405. options.MemoryManagerMode,
  406. (bool)options.IgnoreMissingServices,
  407. options.AspectRatio,
  408. options.AudioVolume);
  409. return new Switch(configuration);
  410. }
  411. private static void ExecutionEntrypoint()
  412. {
  413. if (OperatingSystem.IsWindows())
  414. {
  415. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  416. }
  417. DisplaySleep.Prevent();
  418. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  419. _window.Execute();
  420. Ptc.Close();
  421. PtcProfiler.Stop();
  422. _emulationContext.Dispose();
  423. _window.Dispose();
  424. if (OperatingSystem.IsWindows())
  425. {
  426. _windowsMultimediaTimerResolution?.Dispose();
  427. _windowsMultimediaTimerResolution = null;
  428. }
  429. }
  430. private static bool LoadApplication(Options options)
  431. {
  432. string path = options.InputPath;
  433. Logger.RestartTime();
  434. _window = new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, (bool)options.EnableMouse);
  435. _emulationContext = InitializeEmulationContext(_window, options);
  436. SetupProgressHandler();
  437. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  438. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  439. if (Directory.Exists(path))
  440. {
  441. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  442. if (romFsFiles.Length == 0)
  443. {
  444. romFsFiles = Directory.GetFiles(path, "*.romfs");
  445. }
  446. if (romFsFiles.Length > 0)
  447. {
  448. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  449. _emulationContext.LoadCart(path, romFsFiles[0]);
  450. }
  451. else
  452. {
  453. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  454. _emulationContext.LoadCart(path);
  455. }
  456. }
  457. else if (File.Exists(path))
  458. {
  459. switch (Path.GetExtension(path).ToLowerInvariant())
  460. {
  461. case ".xci":
  462. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  463. _emulationContext.LoadXci(path);
  464. break;
  465. case ".nca":
  466. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  467. _emulationContext.LoadNca(path);
  468. break;
  469. case ".nsp":
  470. case ".pfs0":
  471. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  472. _emulationContext.LoadNsp(path);
  473. break;
  474. default:
  475. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  476. try
  477. {
  478. _emulationContext.LoadProgram(path);
  479. }
  480. catch (ArgumentOutOfRangeException)
  481. {
  482. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  483. return false;
  484. }
  485. break;
  486. }
  487. }
  488. else
  489. {
  490. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  491. _emulationContext.Dispose();
  492. return false;
  493. }
  494. Translator.IsReadyForTranslation.Reset();
  495. Thread windowThread = new Thread(() =>
  496. {
  497. ExecutionEntrypoint();
  498. })
  499. {
  500. Name = "GUI.WindowThread"
  501. };
  502. windowThread.Start();
  503. windowThread.Join();
  504. return true;
  505. }
  506. }
  507. }