Program.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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.Configuration;
  7. using Ryujinx.Common.Configuration.Hid;
  8. using Ryujinx.Common.Configuration.Hid.Controller;
  9. using Ryujinx.Common.Configuration.Hid.Controller.Motion;
  10. using Ryujinx.Common.Configuration.Hid.Keyboard;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.Common.System;
  13. using Ryujinx.Common.Utilities;
  14. using Ryujinx.Graphics.GAL;
  15. using Ryujinx.Graphics.GAL.Multithreading;
  16. using Ryujinx.Graphics.Gpu;
  17. using Ryujinx.Graphics.Gpu.Shader;
  18. using Ryujinx.Graphics.OpenGL;
  19. using Ryujinx.Headless.SDL2.OpenGL;
  20. using Ryujinx.HLE;
  21. using Ryujinx.HLE.FileSystem;
  22. using Ryujinx.HLE.FileSystem.Content;
  23. using Ryujinx.HLE.HOS;
  24. using Ryujinx.HLE.HOS.Services.Account.Acc;
  25. using Ryujinx.Input;
  26. using Ryujinx.Input.HLE;
  27. using Ryujinx.Input.SDL2;
  28. using System;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Reflection;
  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. RangeLeft = 1.0f,
  171. RangeRight = 1.0f,
  172. TriggerThreshold = 0.5f,
  173. LeftJoycon = new LeftJoyconCommonConfig<ConfigGamepadInputId>
  174. {
  175. DpadUp = ConfigGamepadInputId.DpadUp,
  176. DpadDown = ConfigGamepadInputId.DpadDown,
  177. DpadLeft = ConfigGamepadInputId.DpadLeft,
  178. DpadRight = ConfigGamepadInputId.DpadRight,
  179. ButtonMinus = ConfigGamepadInputId.Minus,
  180. ButtonL = ConfigGamepadInputId.LeftShoulder,
  181. ButtonZl = ConfigGamepadInputId.LeftTrigger,
  182. ButtonSl = ConfigGamepadInputId.Unbound,
  183. ButtonSr = ConfigGamepadInputId.Unbound,
  184. },
  185. LeftJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  186. {
  187. Joystick = ConfigStickInputId.Left,
  188. StickButton = ConfigGamepadInputId.LeftStick,
  189. InvertStickX = false,
  190. InvertStickY = false,
  191. },
  192. RightJoycon = new RightJoyconCommonConfig<ConfigGamepadInputId>
  193. {
  194. ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B,
  195. ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A,
  196. ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y,
  197. ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X,
  198. ButtonPlus = ConfigGamepadInputId.Plus,
  199. ButtonR = ConfigGamepadInputId.RightShoulder,
  200. ButtonZr = ConfigGamepadInputId.RightTrigger,
  201. ButtonSl = ConfigGamepadInputId.Unbound,
  202. ButtonSr = ConfigGamepadInputId.Unbound,
  203. },
  204. RightJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  205. {
  206. Joystick = ConfigStickInputId.Right,
  207. StickButton = ConfigGamepadInputId.RightStick,
  208. InvertStickX = false,
  209. InvertStickY = false,
  210. },
  211. Motion = new StandardMotionConfigController
  212. {
  213. MotionBackend = MotionInputBackendType.GamepadDriver,
  214. EnableMotion = true,
  215. Sensitivity = 100,
  216. GyroDeadzone = 1,
  217. },
  218. Rumble = new RumbleConfigController
  219. {
  220. StrongRumble = 1f,
  221. WeakRumble = 1f,
  222. EnableRumble = false
  223. }
  224. };
  225. }
  226. }
  227. else
  228. {
  229. string profileBasePath;
  230. if (isKeyboard)
  231. {
  232. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "keyboard");
  233. }
  234. else
  235. {
  236. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "controller");
  237. }
  238. string path = Path.Combine(profileBasePath, inputProfileName + ".json");
  239. if (!File.Exists(path))
  240. {
  241. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" not found for \"{inputId}\"");
  242. return null;
  243. }
  244. try
  245. {
  246. using (Stream stream = File.OpenRead(path))
  247. {
  248. config = JsonHelper.Deserialize<InputConfig>(stream);
  249. }
  250. }
  251. catch (JsonException)
  252. {
  253. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" parsing failed for \"{inputId}\"");
  254. return null;
  255. }
  256. }
  257. config.Id = inputId;
  258. config.PlayerIndex = index;
  259. string inputTypeName = isKeyboard ? "Keyboard" : "Gamepad";
  260. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} configured with {inputTypeName} \"{config.Id}\"");
  261. // If both stick ranges are 0 (usually indicative of an outdated profile load) then both sticks will be set to 1.0.
  262. if (config is StandardControllerInputConfig controllerConfig)
  263. {
  264. if (controllerConfig.RangeLeft <= 0.0f && controllerConfig.RangeRight <= 0.0f)
  265. {
  266. controllerConfig.RangeLeft = 1.0f;
  267. controllerConfig.RangeRight = 1.0f;
  268. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} stick range reset. Save the profile now to update your configuration");
  269. }
  270. }
  271. return config;
  272. }
  273. static void Load(Options option)
  274. {
  275. IGamepad gamepad;
  276. if (option.ListInputIds)
  277. {
  278. Logger.Info?.Print(LogClass.Application, "Input Ids:");
  279. foreach (string id in _inputManager.KeyboardDriver.GamepadsIds)
  280. {
  281. gamepad = _inputManager.KeyboardDriver.GetGamepad(id);
  282. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  283. gamepad.Dispose();
  284. }
  285. foreach (string id in _inputManager.GamepadDriver.GamepadsIds)
  286. {
  287. gamepad = _inputManager.GamepadDriver.GetGamepad(id);
  288. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  289. gamepad.Dispose();
  290. }
  291. return;
  292. }
  293. if (option.InputPath == null)
  294. {
  295. Logger.Error?.Print(LogClass.Application, "Please provide a file to load");
  296. return;
  297. }
  298. _inputConfiguration = new List<InputConfig>();
  299. _enableKeyboard = (bool)option.EnableKeyboard;
  300. _enableMouse = (bool)option.EnableMouse;
  301. void LoadPlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  302. {
  303. InputConfig inputConfig = HandlePlayerConfiguration(inputProfileName, inputId, index);
  304. if (inputConfig != null)
  305. {
  306. _inputConfiguration.Add(inputConfig);
  307. }
  308. }
  309. LoadPlayerConfiguration(option.InputProfile1Name, option.InputId1, PlayerIndex.Player1);
  310. LoadPlayerConfiguration(option.InputProfile2Name, option.InputId2, PlayerIndex.Player2);
  311. LoadPlayerConfiguration(option.InputProfile3Name, option.InputId3, PlayerIndex.Player3);
  312. LoadPlayerConfiguration(option.InputProfile4Name, option.InputId4, PlayerIndex.Player4);
  313. LoadPlayerConfiguration(option.InputProfile5Name, option.InputId5, PlayerIndex.Player5);
  314. LoadPlayerConfiguration(option.InputProfile6Name, option.InputId6, PlayerIndex.Player6);
  315. LoadPlayerConfiguration(option.InputProfile7Name, option.InputId7, PlayerIndex.Player7);
  316. LoadPlayerConfiguration(option.InputProfile8Name, option.InputId8, PlayerIndex.Player8);
  317. LoadPlayerConfiguration(option.InputProfileHandheldName, option.InputIdHandheld, PlayerIndex.Handheld);
  318. if (_inputConfiguration.Count == 0)
  319. {
  320. return;
  321. }
  322. // Setup logging level
  323. Logger.SetEnable(LogLevel.Debug, (bool)option.LoggingEnableDebug);
  324. Logger.SetEnable(LogLevel.Stub, (bool)option.LoggingEnableStub);
  325. Logger.SetEnable(LogLevel.Info, (bool)option.LoggingEnableInfo);
  326. Logger.SetEnable(LogLevel.Warning, (bool)option.LoggingEnableWarning);
  327. Logger.SetEnable(LogLevel.Error, (bool)option.LoggingEnableError);
  328. Logger.SetEnable(LogLevel.Guest, (bool)option.LoggingEnableGuest);
  329. Logger.SetEnable(LogLevel.AccessLog, (bool)option.LoggingEnableFsAccessLog);
  330. if ((bool)option.EnableFileLog)
  331. {
  332. Logger.AddTarget(new AsyncLogTargetWrapper(
  333. new FileLogTarget(AppDomain.CurrentDomain.BaseDirectory, "file"),
  334. 1000,
  335. AsyncLogTargetOverflowAction.Block
  336. ));
  337. }
  338. // Setup graphics configuration
  339. GraphicsConfig.EnableShaderCache = (bool)option.EnableShaderCache;
  340. GraphicsConfig.ResScale = option.ResScale;
  341. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  342. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  343. while (true)
  344. {
  345. LoadApplication(option);
  346. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  347. {
  348. break;
  349. }
  350. _userChannelPersistence.ShouldRestart = false;
  351. }
  352. }
  353. private static void SetupProgressHandler()
  354. {
  355. Ptc.PtcStateChanged -= ProgressHandler;
  356. Ptc.PtcStateChanged += ProgressHandler;
  357. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  358. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  359. }
  360. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  361. {
  362. string label;
  363. switch (state)
  364. {
  365. case PtcLoadingState ptcState:
  366. label = $"PTC : {current}/{total}";
  367. break;
  368. case ShaderCacheState shaderCacheState:
  369. label = $"Shaders : {current}/{total}";
  370. break;
  371. default:
  372. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  373. }
  374. Logger.Info?.Print(LogClass.Application, label);
  375. }
  376. private static Switch InitializeEmulationContext(WindowBase window, Options options)
  377. {
  378. IRenderer renderer = new Renderer();
  379. BackendThreading threadingMode = options.BackendThreading;
  380. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  381. if (threadedGAL)
  382. {
  383. renderer = new ThreadedRenderer(renderer);
  384. }
  385. HLEConfiguration configuration = new HLEConfiguration(_virtualFileSystem,
  386. _libHacHorizonManager,
  387. _contentManager,
  388. _accountManager,
  389. _userChannelPersistence,
  390. renderer,
  391. new SDL2HardwareDeviceDriver(),
  392. (bool)options.ExpandRam ? MemoryConfiguration.MemoryConfiguration6GB : MemoryConfiguration.MemoryConfiguration4GB,
  393. window,
  394. options.SystemLanguage,
  395. options.SystemRegion,
  396. (bool)options.EnableVsync,
  397. (bool)options.EnableDockedMode,
  398. (bool)options.EnablePtc,
  399. (bool)options.EnableInternetAccess,
  400. (bool)options.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  401. options.FsGlobalAccessLogMode,
  402. options.SystemTimeOffset,
  403. options.SystemTimeZone,
  404. options.MemoryManagerMode,
  405. (bool)options.IgnoreMissingServices,
  406. options.AspectRatio,
  407. options.AudioVolume);
  408. return new Switch(configuration);
  409. }
  410. private static void ExecutionEntrypoint()
  411. {
  412. if (OperatingSystem.IsWindows())
  413. {
  414. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  415. }
  416. DisplaySleep.Prevent();
  417. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  418. _window.Execute();
  419. Ptc.Close();
  420. PtcProfiler.Stop();
  421. _emulationContext.Dispose();
  422. _window.Dispose();
  423. if (OperatingSystem.IsWindows())
  424. {
  425. _windowsMultimediaTimerResolution?.Dispose();
  426. _windowsMultimediaTimerResolution = null;
  427. }
  428. }
  429. private static bool LoadApplication(Options options)
  430. {
  431. string path = options.InputPath;
  432. Logger.RestartTime();
  433. _window = new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, (bool)options.EnableMouse);
  434. _emulationContext = InitializeEmulationContext(_window, options);
  435. SetupProgressHandler();
  436. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  437. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  438. if (Directory.Exists(path))
  439. {
  440. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  441. if (romFsFiles.Length == 0)
  442. {
  443. romFsFiles = Directory.GetFiles(path, "*.romfs");
  444. }
  445. if (romFsFiles.Length > 0)
  446. {
  447. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  448. _emulationContext.LoadCart(path, romFsFiles[0]);
  449. }
  450. else
  451. {
  452. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  453. _emulationContext.LoadCart(path);
  454. }
  455. }
  456. else if (File.Exists(path))
  457. {
  458. switch (Path.GetExtension(path).ToLowerInvariant())
  459. {
  460. case ".xci":
  461. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  462. _emulationContext.LoadXci(path);
  463. break;
  464. case ".nca":
  465. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  466. _emulationContext.LoadNca(path);
  467. break;
  468. case ".nsp":
  469. case ".pfs0":
  470. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  471. _emulationContext.LoadNsp(path);
  472. break;
  473. default:
  474. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  475. try
  476. {
  477. _emulationContext.LoadProgram(path);
  478. }
  479. catch (ArgumentOutOfRangeException)
  480. {
  481. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  482. return false;
  483. }
  484. break;
  485. }
  486. }
  487. else
  488. {
  489. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  490. _emulationContext.Dispose();
  491. return false;
  492. }
  493. Translator.IsReadyForTranslation.Reset();
  494. Thread windowThread = new Thread(() =>
  495. {
  496. ExecutionEntrypoint();
  497. })
  498. {
  499. Name = "GUI.WindowThread"
  500. };
  501. windowThread.Start();
  502. windowThread.Join();
  503. return true;
  504. }
  505. }
  506. }