Program.cs 24 KB

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