Program.cs 23 KB

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