From 9f5b360f01d94efb2ae90536bf125325bb02296e Mon Sep 17 00:00:00 2001 From: David <87927264+Rexicon226@users.noreply.github.com> Date: Mon, 6 Mar 2023 04:58:20 -0800 Subject: [PATCH 01/15] dll autofinder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit read the code 🙄 , auto finds dlls and copies --- external_dlls/autofinder.py | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 external_dlls/autofinder.py diff --git a/external_dlls/autofinder.py b/external_dlls/autofinder.py new file mode 100644 index 00000000..8de79fef --- /dev/null +++ b/external_dlls/autofinder.py @@ -0,0 +1,52 @@ +import os +import re +import platform +import shutil + +def get_steam_dir(): + if platform.system() == "Windows": + return os.path.join(os.getenv("ProgramFiles(x86)"), "Steam") + elif platform.system() == "Darwin": + return os.path.expanduser("~/Library/Application Support/Steam") + else: + return os.path.expanduser("~/.steam/steam") + +def find_game_dir(game_name): + steam_dir = get_steam_dir() + library_folders_path = os.path.join(steam_dir, "steamapps", "libraryfolders.vdf") + app_manifest_pattern = re.compile(r"appmanifest_\d+\.acf") + for library_folder in [steam_dir] + get_library_folders(library_folders_path): + manifest_dir = os.path.join(library_folder, "steamapps") + for manifest_file in os.listdir(manifest_dir): + if app_manifest_pattern.match(manifest_file): + with open(os.path.join(manifest_dir, manifest_file), "r") as f: + manifest_data = f.read() + if game_name in manifest_data: + return os.path.join(library_folder, "steamapps", "common", game_name) + return None + +def get_library_folders(vdf_path): + library_folders = [] + with open(vdf_path, "r") as f: + vdf_data = f.read() + for match in re.finditer(r'"[A-Za-z]:\\[^"]*"', vdf_data): + library_folders.append(match.group(0)[1:-1]) + return library_folders + +print("Searching for game directory") + +game_name = "Kerbal Space Program 2" +game_dir = find_game_dir(game_name) +if game_dir is not None: + print(f"Found {game_name} installed at {game_dir}") + managed_dir = os.path.join(game_dir, "KSP2_x64_Data", "Managed") + if os.path.exists(managed_dir): + for file_name in os.listdir(managed_dir): + file_path = os.path.join(managed_dir, file_name) + if os.path.isfile(file_path): + shutil.copy(file_path, os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)) + print("Files copied successfully!") + else: + print(f"Could not find {game_name} Managed directory") +else: + print(f"{game_name} not found") From ae7e805d10a24126554d41e250b40a22a19aaeac Mon Sep 17 00:00:00 2001 From: David <87927264+Rexicon226@users.noreply.github.com> Date: Mon, 6 Mar 2023 05:20:15 -0800 Subject: [PATCH 02/15] added ebic gamers and pd launcher idk if pd launcher works?? dont use --- external_dlls/autofinder.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/external_dlls/autofinder.py b/external_dlls/autofinder.py index 8de79fef..0cf2eb5c 100644 --- a/external_dlls/autofinder.py +++ b/external_dlls/autofinder.py @@ -1,7 +1,7 @@ import os import re -import platform import shutil +import platform def get_steam_dir(): if platform.system() == "Windows": @@ -23,6 +23,17 @@ def find_game_dir(game_name): manifest_data = f.read() if game_name in manifest_data: return os.path.join(library_folder, "steamapps", "common", game_name) + epic_dir = os.path.join(os.getenv("ProgramData"), "Epic", "EpicGamesLauncher", "Data", "Manifests") + app_info_pattern = re.compile(r"([^/]+)\.item") + for app_info_file in os.listdir(epic_dir): + with open(os.path.join(epic_dir, app_info_file), "r") as f: + app_info_data = f.read() + match = app_info_pattern.search(app_info_data) + if match is not None and match.group(1) == game_name: + return os.path.join(os.path.dirname(epic_dir), "Installation", match.group(0), "KSP2") + private_division_dir = os.path.join(os.getenv("LOCALAPPDATA"), "PrivateDivision", game_name) + if os.path.exists(private_division_dir): + return private_division_dir return None def get_library_folders(vdf_path): @@ -33,8 +44,6 @@ def get_library_folders(vdf_path): library_folders.append(match.group(0)[1:-1]) return library_folders -print("Searching for game directory") - game_name = "Kerbal Space Program 2" game_dir = find_game_dir(game_name) if game_dir is not None: From 1c7f99b7f436447d356327f6775789763c4628eb Mon Sep 17 00:00:00 2001 From: Lexi Date: Tue, 7 Mar 2023 08:16:59 -0500 Subject: [PATCH 03/15] Fixed a typo in a summary, and also added abstractions for setting an app bars indicator --- SpaceWarp/API/Game/Messages/StateChanges.cs | 5 +++-- SpaceWarp/API/UI/Appbar/Appbar.cs | 13 ++++++++++++- SpaceWarp/API/UI/Appbar/AppbarMenu.cs | 2 +- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/SpaceWarp/API/Game/Messages/StateChanges.cs b/SpaceWarp/API/Game/Messages/StateChanges.cs index d4043542..31096995 100644 --- a/SpaceWarp/API/Game/Messages/StateChanges.cs +++ b/SpaceWarp/API/Game/Messages/StateChanges.cs @@ -61,7 +61,8 @@ public static class StateChanges #region State changing /// - /// Action(Message,PreviousState,CurrentState> + /// Invoked when the game state is changed + /// Action(Message,PreviousState,CurrentState) /// public static event System.Action GameStateChanged; @@ -213,7 +214,7 @@ internal static void OnGameStateLeft(MessageCenterMessage message) internal static void OnGameStateChanged(MessageCenterMessage message) { var msg = message as GameStateChangedMessage; - GameStateChanged?.Invoke(msg!,msg!.PreviousState,msg!.CurrentState); + GameStateChanged?.Invoke(msg!, msg!.PreviousState, msg!.CurrentState); } #endregion diff --git a/SpaceWarp/API/UI/Appbar/Appbar.cs b/SpaceWarp/API/UI/Appbar/Appbar.cs index 2176d507..f6c438b3 100644 --- a/SpaceWarp/API/UI/Appbar/Appbar.cs +++ b/SpaceWarp/API/UI/Appbar/Appbar.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using BepInEx.Bootstrap; +using KSP.UI.Binding; using UnityEngine; using SpaceWarp.Backend.UI.Appbar; @@ -96,7 +97,6 @@ public static void RegisterOABAppButton(string text, string id, Texture2D icon, RegisterOABAppButton(text, id, GetAppBarIconFromTexture(icon), func); } - /// /// Convert a Texture2D to a Sprite /// @@ -111,6 +111,17 @@ public static Sprite GetAppBarIconFromTexture(Texture2D texture, int width=0, in return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f)); } + + + /// + /// Sets an app bar buttons indicator (the green sprite to the side of it) + /// + /// The id of the button, what you set when registering the app bar button + /// The state of the indicator, true for on, false for off + public static void SetAppBarButtonIndicator(string id, bool indicator) + { + GameObject.Find(id)?.GetComponent()?.SetValue(indicator); + } internal static void LoadAllButtons() { diff --git a/SpaceWarp/API/UI/Appbar/AppbarMenu.cs b/SpaceWarp/API/UI/Appbar/AppbarMenu.cs index aee7780e..80471f38 100644 --- a/SpaceWarp/API/UI/Appbar/AppbarMenu.cs +++ b/SpaceWarp/API/UI/Appbar/AppbarMenu.cs @@ -74,6 +74,7 @@ public void OnGUI() internal void ToggleGUI(bool drawing) { _drawing = drawing; + Appbar.SetAppBarButtonIndicator(ID, drawing); } public void ToggleGUI() @@ -98,6 +99,5 @@ private void DoDrawing(int windowID) public void CloseWindow() { ToggleGUI(false); - GameObject.Find(ID)?.GetComponent()?.SetValue(false); } } \ No newline at end of file From 21c194a8e3832acce8fe7e38d64acfc96129f501 Mon Sep 17 00:00:00 2001 From: adamsong Date: Tue, 7 Mar 2023 16:54:17 -0500 Subject: [PATCH 04/15] Automatically loads labelled language sources from addressables --- SpaceWarp/Patching/BootstrapPatch.cs | 4 +- .../LoadAddressablesLocalizationsAction.cs | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs diff --git a/SpaceWarp/Patching/BootstrapPatch.cs b/SpaceWarp/Patching/BootstrapPatch.cs index 71dc62f5..7878fb12 100644 --- a/SpaceWarp/Patching/BootstrapPatch.cs +++ b/SpaceWarp/Patching/BootstrapPatch.cs @@ -44,11 +44,13 @@ private static void PatchInitializationsIL(ILContext ilContext, ILLabel endLabel foreach (var plugin in SpaceWarpManager.SpaceWarpPlugins) { - flow.AddAction(new LoadLocalizationAction(plugin)); flow.AddAction(new LoadAddressablesAction(plugin)); + flow.AddAction(new LoadLocalizationAction(plugin)); flow.AddAction(new LoadAssetAction(plugin)); } + flow.AddAction(new LoadAddressablesLocalizationsAction()); + foreach (var plugin in SpaceWarpManager.SpaceWarpPlugins) { flow.AddAction(new InitializeModAction(plugin)); diff --git a/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs b/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs new file mode 100644 index 00000000..f22c2ed4 --- /dev/null +++ b/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.IO; +using I2.Loc; +using KSP.Game; +using KSP.Game.Flow; +using SpaceWarp.API.Mods; +using UnityEngine; +using UnityEngine.AddressableAssets; + +namespace SpaceWarp.Patching.LoadingActions; + +internal sealed class LoadAddressablesLocalizationsAction : FlowAction +{ + public LoadAddressablesLocalizationsAction() : base($"Loading localizations from Addressables") + { + } + + public override void DoAction(Action resolve, Action reject) + { + try + { + GameManager.Instance.Game.Assets.LoadByLabel("language_source", + OnLanguageSourceAssetLoaded, delegate(IList languageAssetLocations) + { + if(languageAssetLocations != null) + { + Addressables.Release(languageAssetLocations); + } + + resolve(); + }); + } + catch (Exception e) + { + Debug.LogError(e.ToString()); + reject(null); + } + } + + private static void OnLanguageSourceAssetLoaded(LanguageSourceAsset asset) + { + if (!asset || LocalizationManager.Sources.Contains(asset.mSource)) return; + asset.mSource.owner = asset; + LocalizationManager.AddSource(asset.mSource); + } +} \ No newline at end of file From 4a60bad879da85d275b1a55d24e6ff8d93459f32 Mon Sep 17 00:00:00 2001 From: Ewy Date: Sat, 11 Mar 2023 16:33:59 +0100 Subject: [PATCH 05/15] Made asset loading asynchronous --- SpaceWarp/API/Assets/AssetManager.cs | 50 ++++++++++--------- .../LoadingActions/LoadAssetAction.cs | 9 ++-- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/SpaceWarp/API/Assets/AssetManager.cs b/SpaceWarp/API/Assets/AssetManager.cs index 820aafa3..c4e8b99c 100644 --- a/SpaceWarp/API/Assets/AssetManager.cs +++ b/SpaceWarp/API/Assets/AssetManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using BepInEx.Logging; using UnityEngine; @@ -9,13 +10,11 @@ public static class AssetManager { private static readonly Dictionary AllAssets = new(); - internal static void RegisterAssetBundle(string modId, string assetBundleName, AssetBundle assetBundle) + internal static async Task RegisterAssetBundle(string modId, string assetBundleName, AssetBundle assetBundle) { assetBundleName = assetBundleName.Replace(".bundle", ""); ManualLogSource logger = BepInEx.Logging.Logger.CreateLogSource($"{modId}/{assetBundleName}"); - // TODO: use async loading instead? - // Object[] bundleObjects = assetBundle.LoadAllAssets(); string[] names = assetBundle.GetAllAssetNames(); foreach (var name in names) @@ -31,34 +30,37 @@ internal static void RegisterAssetBundle(string modId, string assetBundleName, A { assetName = assetName[(assetBundleName.Length + 1)..]; } - + string path = modId + "/" + assetBundleName + "/" + assetName; path = path.ToLower(); - - UnityObject bundleObject = assetBundle.LoadAsset(name); + + await assetBundle.LoadAssetAsync(name); + + UnityObject bundleObject = assetBundle.LoadAssetAsync(name).asset; logger.LogInfo($"registering path \"{path}\""); AllAssets.Add(path, bundleObject); } - - // if (bundleObjects.Length != names.Length) - // { - // logger.Critical("bundle objects length and name lengths do not match"); - // logger.Info("going to dump objects and names"); - // logger.Info("Names"); - // for (int i = 0; i < names.Length; i++) - // { - // logger.Info($"{i} - {names[i]}"); - // } - // - // logger.Info("Objects"); - // for (int i = 0; i < bundleObjects.Length; i++) - // { - // logger.Info($"{i} - {bundleObjects[i]}"); - // } - // throw new System.Exception("bundle objects length and name lengths do not match"); - // } } + + // if (bundleObjects.Length != names.Length) + // { + // logger.Critical("bundle objects length and name lengths do not match"); + // logger.Info("going to dump objects and names"); + // logger.Info("Names"); + // for (int i = 0; i < names.Length; i++) + // { + // logger.Info($"{i} - {names[i]}"); + // } + // + // logger.Info("Objects"); + // for (int i = 0; i < bundleObjects.Length; i++) + // { + // logger.Info($"{i} - {bundleObjects[i]}"); + // } + // throw new System.Exception("bundle objects length and name lengths do not match"); + // } + internal static void RegisterSingleAsset(string modId, string internalAssetPath, T asset) where T : UnityObject { diff --git a/SpaceWarp/Patching/LoadingActions/LoadAssetAction.cs b/SpaceWarp/Patching/LoadingActions/LoadAssetAction.cs index 464cc6e4..984b7141 100644 --- a/SpaceWarp/Patching/LoadingActions/LoadAssetAction.cs +++ b/SpaceWarp/Patching/LoadingActions/LoadAssetAction.cs @@ -18,7 +18,7 @@ public LoadAssetAction(BaseSpaceWarpPlugin plugin) : base($"Loading {plugin.Spac Plugin = plugin; } - public override void DoAction(Action resolve, Action reject) + public override async void DoAction(Action resolve, Action reject) { try { @@ -30,7 +30,6 @@ public override void DoAction(Action resolve, Action reject) string assetBundleName = Path.GetFileNameWithoutExtension(file); if (Path.GetExtension(file) != ".bundle") continue; - AssetBundle assetBundle = AssetBundle.LoadFromFile(file); if (assetBundle == null) @@ -38,7 +37,7 @@ public override void DoAction(Action resolve, Action reject) Logger.LogError($"Failed to load AssetBundle {Plugin.SpaceWarpMetadata.ModID}/{assetBundleName}"); continue; } - AssetManager.RegisterAssetBundle(Plugin.SpaceWarpMetadata.ModID, assetBundleName, assetBundle); + await AssetManager.RegisterAssetBundle(Plugin.SpaceWarpMetadata.ModID, assetBundleName, assetBundle); Logger.LogInfo($"Loaded AssetBundle {Plugin.SpaceWarpMetadata.ModID}/{assetBundleName}"); } } @@ -53,9 +52,10 @@ public override void DoAction(Action resolve, Action reject) var directoryInfo = new DirectoryInfo(imagesPath); foreach (string file in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories).Select(fileInfo => fileInfo.FullName)) { - var assetPathList = PathHelpers.GetRelativePath(imagesPath, file).Split(Path.DirectorySeparatorChar); //We have to make sure it uses '/' as the path separator and toLower() the names + var assetPathList = PathHelpers.GetRelativePath(imagesPath, file).Split(Path.DirectorySeparatorChar); var assetPath = ""; + for (int i = 0; i < assetPathList.Length; i++) { assetPath += assetPathList[i].ToLower(); @@ -71,6 +71,7 @@ public override void DoAction(Action resolve, Action reject) { filterMode = FilterMode.Point }; + try { var fileData = File.ReadAllBytes(file); From 30ca3772f47b2e58614046485314a6742afe862b Mon Sep 17 00:00:00 2001 From: Ewy Date: Sat, 11 Mar 2023 16:48:13 +0100 Subject: [PATCH 06/15] Minor changes & fixes --- SpaceWarp/API/UI/Appbar/AppbarMenu.cs | 1 - SpaceWarp/Backend/UI/Appbar/AppbarBackend.cs | 59 +++++++------------ .../LoadAddressablesLocalizationsAction.cs | 2 - SpaceWarp/SpaceWarpManager.cs | 4 +- 4 files changed, 22 insertions(+), 44 deletions(-) diff --git a/SpaceWarp/API/UI/Appbar/AppbarMenu.cs b/SpaceWarp/API/UI/Appbar/AppbarMenu.cs index 80471f38..d810db6a 100644 --- a/SpaceWarp/API/UI/Appbar/AppbarMenu.cs +++ b/SpaceWarp/API/UI/Appbar/AppbarMenu.cs @@ -1,6 +1,5 @@ using KSP.Game; using KSP.Sim.impl; -using KSP.UI.Binding; using UnityEngine; namespace SpaceWarp.API.UI.Appbar; diff --git a/SpaceWarp/Backend/UI/Appbar/AppbarBackend.cs b/SpaceWarp/Backend/UI/Appbar/AppbarBackend.cs index a9e60215..8de07702 100644 --- a/SpaceWarp/Backend/UI/Appbar/AppbarBackend.cs +++ b/SpaceWarp/Backend/UI/Appbar/AppbarBackend.cs @@ -8,7 +8,6 @@ using HarmonyLib; using I2.Loc; using KSP; -using KSP.Api; using KSP.Api.CoreTypes; using KSP.Game; using KSP.OAB; @@ -40,7 +39,7 @@ public static GameObject AddButton(string buttonText, Sprite buttonIcon, string // Say the magic words... GameObject list = GameObject.Find("GameManager/Default Game Instance(Clone)/UI Manager(Clone)/Popup Canvas/Container/ButtonBar/BTN-App-Tray/appbar-others-group"); - GameObject resourceManger = list?.GetChild("BTN-Resource-Manager"); + GameObject resourceManger = list != null ? list.GetChild("BTN-Resource-Manager") : null; if (list == null || resourceManger == null) { @@ -118,7 +117,7 @@ private static GameObject CreateOABTray() // Say the magic words... GameObject oabAppBar = GameObject.Find("OAB(Clone)/HUDSpawner/HUD/widget_SideBar/widget_sidebarNav"); - GameObject kerbalManager = oabAppBar?.GetChild("button_kerbal-manager"); + GameObject kerbalManager = oabAppBar != null ? oabAppBar.GetChild("button_kerbal-manager") : null; if (oabAppBar == null || kerbalManager == null) { @@ -160,7 +159,7 @@ private static GameObject CreateOABTray() // Create the tooltip itself. tooltip = tooltipObject.AddComponent(); - tooltip.GetType().GetField("tooltipText", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tooltip, "App Tray"); + tooltip.GetType().GetField("tooltipText", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(tooltip, "App Tray"); // Clone the tray from the flight UI. GameObject trayButton = GameManager.Instance.Game.UI.GetPopupCanvas().gameObject.GetChild("BTN-App-Tray"); @@ -179,8 +178,7 @@ private static GameObject CreateOABTray() { var child = oabTray.transform.GetChild(i); - if (child.name.Contains("ELE-border")) - continue; + if (child.name.Contains("ELE-border")) continue; Object.Destroy(child.gameObject); } @@ -196,7 +194,7 @@ public static GameObject AddOABButton(string buttonText, Sprite buttonIcon, stri // Find the resource manager button. GameObject list = GameObject.Find("GameManager/Default Game Instance(Clone)/UI Manager(Clone)/Popup Canvas/Container/ButtonBar/BTN-App-Tray/appbar-others-group"); - GameObject resourceManger = list?.GetChild("BTN-Resource-Manager"); + GameObject resourceManger = list != null ? list.GetChild("BTN-Resource-Manager") : null; if (resourceManger == null) { @@ -213,8 +211,7 @@ public static GameObject AddOABButton(string buttonText, Sprite buttonIcon, stri text.text = buttonText; Localize localizer = text.gameObject.GetComponent(); - if (localizer) - Object.Destroy(localizer); + if (localizer) Object.Destroy(localizer); // Change the icon. GameObject icon = appButton.GetChild("Content").GetChild("GRP-icon"); @@ -240,8 +237,7 @@ public static GameObject AddOABButton(string buttonText, Sprite buttonIcon, stri public static void SetOABTrayState(bool state) { - if (_oabTray == null) - return; + if (_oabTray == null) return; _oabState.SetValue(state); } @@ -258,17 +254,12 @@ internal static void SubscriberSchedulePing(AppbarEvent type) GameObject gameObject = new GameObject(); ToolbarBackendObject waiterObject = gameObject.AddComponent(); - switch (type) + waiterObject.creationEvent = type switch { - case AppbarEvent.Flight: - waiterObject.creationEvent = AppBarInFlightSubscriber; - break; - case AppbarEvent.OAB: - waiterObject.creationEvent = AppBarOABSubscriber; - break; - default: - break; - } + AppbarEvent.Flight => AppBarInFlightSubscriber, + AppbarEvent.OAB => AppBarOABSubscriber, + _ => waiterObject.creationEvent + }; waiterObject.type = type; gameObject.SetActive(true); @@ -288,23 +279,17 @@ internal class ToolbarBackendObject : KerbalBehavior public new void Start() { - StartCoroutine(awaiter()); + StartCoroutine(Awaiter()); } - private IEnumerator awaiter() + private IEnumerator Awaiter() { - switch (type) + yield return type switch { - case AppbarEvent.Flight: - yield return new WaitForSeconds(1); - break; - case AppbarEvent.OAB: - yield return new WaitForFixedUpdate(); - break; - default: - yield return new WaitForSeconds(1); - break; - } + AppbarEvent.Flight => new WaitForSeconds(1), + AppbarEvent.OAB => new WaitForFixedUpdate(), + _ => new WaitForSeconds(1) + }; creationEvent.Invoke(); Destroy(this); @@ -316,14 +301,12 @@ private IEnumerator awaiter() [HarmonyPatch("Start")] internal class ToolbarBackendAppBarPatcher { - public static void Postfix(UIFlightHud __instance) => - AppbarBackend.SubscriberSchedulePing(AppbarBackend.AppbarEvent.Flight); + public static void Postfix(UIFlightHud __instance) => SubscriberSchedulePing(AppbarEvent.Flight); } [HarmonyPatch(typeof(OABSideBar))] [HarmonyPatch("Start")] internal class ToolbarBackendOABSideBarPatcher { - public static void Postfix(OABSideBar __instance) => - AppbarBackend.SubscriberSchedulePing(AppbarBackend.AppbarEvent.OAB); + public static void Postfix(OABSideBar __instance) => SubscriberSchedulePing(AppbarEvent.OAB); } diff --git a/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs b/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs index f22c2ed4..2e453630 100644 --- a/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs +++ b/SpaceWarp/Patching/LoadingActions/LoadAddressablesLocalizationsAction.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; -using System.IO; using I2.Loc; using KSP.Game; using KSP.Game.Flow; -using SpaceWarp.API.Mods; using UnityEngine; using UnityEngine.AddressableAssets; diff --git a/SpaceWarp/SpaceWarpManager.cs b/SpaceWarp/SpaceWarpManager.cs index 532ffed2..fc7ea841 100644 --- a/SpaceWarp/SpaceWarpManager.cs +++ b/SpaceWarp/SpaceWarpManager.cs @@ -1,7 +1,5 @@ -using System; -using System.IO; +using System.IO; using System.Collections.Generic; -using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using Newtonsoft.Json; From f648fe0c56d1493553c24ebf228883723b38aedb Mon Sep 17 00:00:00 2001 From: Ewy Date: Sat, 11 Mar 2023 19:12:55 +0100 Subject: [PATCH 07/15] Improved UI Scaling & auto scroll disables itself upon scrolling up --- ExampleMod/ExampleMod.cs | 1 - SpaceWarp/UI/ModListUI.cs | 18 ++++++++++++----- SpaceWarp/UI/SpaceWarpConsole.cs | 33 +++++++++++++++++++++++--------- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/ExampleMod/ExampleMod.cs b/ExampleMod/ExampleMod.cs index ef19e495..ffce211e 100644 --- a/ExampleMod/ExampleMod.cs +++ b/ExampleMod/ExampleMod.cs @@ -33,7 +33,6 @@ public override void OnInitialized() // Example of using the logger, Were going to log a message to the console, ALT + C to open the console. Logger.LogInfo("Hello World, Im a spacewarp Mod."); - // Register the mod's button in KSP 2s app.bar // This requires an `icon.png` file to exist under [plugin_folder]/assets/images Appbar.RegisterAppButton( diff --git a/SpaceWarp/UI/ModListUI.cs b/SpaceWarp/UI/ModListUI.cs index d2115d69..41105537 100644 --- a/SpaceWarp/UI/ModListUI.cs +++ b/SpaceWarp/UI/ModListUI.cs @@ -34,10 +34,19 @@ public void Start() private void Awake() { - _windowWidth = (int)(Screen.width * 0.85f); - _windowHeight = (int)(Screen.height * 0.85f); - - _windowRect = new Rect(Screen.width * 0.15f, Screen.height * 0.15f, 0, 0); + float minResolution = 1280f / 720f; + float maxResolution = 2048f / 1080f; + float screenRatio = (float) Screen.width / (float) Screen.height; + float scaleFactor = Mathf.Clamp(screenRatio, minResolution, maxResolution); + + _windowWidth = (int) (Screen.width * 0.5f * scaleFactor); + _windowHeight = (int) (Screen.height * 0.5f * scaleFactor); + _windowRect = new Rect( + Screen.width * 0.15f, + Screen.height * 0.15f, + Screen.width * 0.5f * scaleFactor, + Screen.height * 0.5f * scaleFactor + ); } private void OnGUI() @@ -73,7 +82,6 @@ private void Update() CloseWindow(); GUIUtility.ExitGUI(); } - } private void FillWindow(int windowID) diff --git a/SpaceWarp/UI/SpaceWarpConsole.cs b/SpaceWarp/UI/SpaceWarpConsole.cs index 8e5c4bfc..48729ba4 100644 --- a/SpaceWarp/UI/SpaceWarpConsole.cs +++ b/SpaceWarp/UI/SpaceWarpConsole.cs @@ -27,26 +27,36 @@ public sealed class SpaceWarpConsole : KerbalMonoBehaviour private GUIStyle _closeButtonStyle; private SpaceWarpPlugin _spaceWarpPluginInstance; + private static readonly ManualLogSource Logger = BepInEx.Logging.Logger.CreateLogSource("SpaceWarpConsole"); + private void Awake() { - _windowWidth = (int)(Screen.width * 0.5f); - _windowHeight = (int)(Screen.height * 0.5f); - _windowRect = new Rect(Screen.width * 0.15f, Screen.height * 0.15f, 0, 0); + float minResolution = 1280f / 720f; + float maxResolution = 2048f / 1080f; + float screenRatio = (float) Screen.width / (float) Screen.height; + float scaleFactor = Mathf.Clamp(screenRatio, minResolution, maxResolution); + + _windowWidth = (int) (Screen.width * 0.5f * scaleFactor); + _windowHeight = (int) (Screen.height * 0.5f * scaleFactor); + _windowRect = new Rect( + Screen.width * 0.15f, + Screen.height * 0.15f, + Screen.width * 0.5f * scaleFactor, + Screen.height * 0.5f * scaleFactor + ); _scrollPosition = Vector2.zero; _spaceWarpPluginInstance = (Chainloader.PluginInfos[SpaceWarpPlugin.ModGuid].Instance as SpaceWarpPlugin)!; if (_spaceWarpPluginInstance.configShowConsoleButton.Value) + { Appbar.RegisterAppButton( "Console", "BTN-SWConsole", - // Example of using the asset loader, were going to load the apps icon - // Path format [mod_id]/images/filename - // for bundles its [mod_id]/[bundle_name]/[path to file in bundle with out assets/bundle]/filename.extension - // There is also a try get asset function, that returns a bool on whether or not it could grab the asset AssetManager.GetAsset("spacewarp/images/console.png"), ToggleVisible ); + } } private void OnGUI() @@ -67,9 +77,9 @@ private void OnGUI() GUILayoutOption width = GUILayout.Width((float)(_windowWidth * 0.8)); GUILayoutOption height = GUILayout.Height((float)(_windowHeight * 0.8)); - _windowRect = GUILayout.Window(controlID, _windowRect, DrawConsole, ConsoleLockID, width, height); + _windowRect = GUILayout.Window(controlID, _windowRect, DrawConsole, "SPACE WARP - Console", width, height); } - + private void Update() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.C)) @@ -82,6 +92,11 @@ private void Update() CloseWindow(); GUIUtility.ExitGUI(); } + + if (Input.mouseScrollDelta.y + Input.GetAxis("Vertical") > 0) + { + _autoScroll = false; + } } private void DrawConsole(int windowID) From 74a29cdac9ea7515ce79bb2e696bcfc41102e72f Mon Sep 17 00:00:00 2001 From: Lexi Date: Mon, 13 Mar 2023 20:43:54 -0400 Subject: [PATCH 08/15] This *should* check versions, I have nothing to check with --- SpaceWarp/API/Mods/JSON/ModInfo.cs | 5 ++ SpaceWarp/SpaceWarpManager.cs | 1 + SpaceWarp/SpaceWarpPlugin.cs | 98 ++++++++++++++++++++++++++++++ SpaceWarp/UI/ModListUI.cs | 59 ++++++++++++++++-- SpaceWarp/UI/VersionCheckPrompt.cs | 72 ++++++++++++++++++++++ 5 files changed, 231 insertions(+), 4 deletions(-) create mode 100644 SpaceWarp/UI/VersionCheckPrompt.cs diff --git a/SpaceWarp/API/Mods/JSON/ModInfo.cs b/SpaceWarp/API/Mods/JSON/ModInfo.cs index e5130c48..b56188c0 100644 --- a/SpaceWarp/API/Mods/JSON/ModInfo.cs +++ b/SpaceWarp/API/Mods/JSON/ModInfo.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using System.Collections.Generic; +using JetBrains.Annotations; namespace SpaceWarp.API.Mods.JSON; @@ -32,4 +33,8 @@ public sealed class ModInfo [JsonProperty("ksp2_version")] public SupportedVersionsInfo SupportedKsp2Versions { get; internal set; } + + [JsonProperty("version_check", Required = Required.AllowNull)] + [CanBeNull] + public string VersionCheck { get; internal set; } } diff --git a/SpaceWarp/SpaceWarpManager.cs b/SpaceWarp/SpaceWarpManager.cs index fc7ea841..b916729f 100644 --- a/SpaceWarp/SpaceWarpManager.cs +++ b/SpaceWarp/SpaceWarpManager.cs @@ -22,6 +22,7 @@ internal static class SpaceWarpManager internal static string SpaceWarpFolder; internal static IReadOnlyList SpaceWarpPlugins; internal static ConfigurationManager.ConfigurationManager ConfigurationManager; + internal static Dictionary ModsOutdated = new(); internal static void GetSpaceWarpPlugins() { diff --git a/SpaceWarp/SpaceWarpPlugin.cs b/SpaceWarp/SpaceWarpPlugin.cs index 874b48d5..b69a27ab 100644 --- a/SpaceWarp/SpaceWarpPlugin.cs +++ b/SpaceWarp/SpaceWarpPlugin.cs @@ -1,15 +1,21 @@ global using UnityObject = UnityEngine.Object; global using System.Linq; +using System; +using System.Collections; +using System.Collections.Generic; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using KSP.Messages; +using Newtonsoft.Json; using SpaceWarp.API.Game.Messages; using SpaceWarp.API.Mods; +using SpaceWarp.API.Mods.JSON; using SpaceWarp.UI; using UnityEngine; +using UnityEngine.Networking; namespace SpaceWarp; @@ -31,6 +37,9 @@ public sealed class SpaceWarpPlugin : BaseSpaceWarpPlugin internal ConfigEntry configShowTimeStamps; internal ConfigEntry configTimeStampFormat; internal ConfigEntry configDebugMessageLimit; + internal ConfigEntry configFirstLaunch; + internal ConfigEntry configCheckVersions; + internal new ManualLogSource Logger => base.Logger; @@ -56,6 +65,10 @@ public void Awake() "The format for the timestamps in the debug console."); configDebugMessageLimit = Config.Bind("Debug Console", "Message Limit", 1000, "The maximum number of messages to keep in the debug console."); + configFirstLaunch = Config.Bind("Version Checking", "First Launch", true, + "Whether or not this is the first launch of space warp, used to show the version checking prompt to the user."); + configCheckVersions = Config.Bind("Version Checking", "Check Versions", false, + "Whether or not Space Warp should check mod versions using their swinfo.json files"); BepInEx.Logging.Logger.Listeners.Add(new SpaceWarpConsoleLogListener(this)); @@ -76,6 +89,91 @@ public override void OnInitialized() InitializeUI(); } + public override void OnPostInitialized() + { + base.OnPostInitialized(); + if (configFirstLaunch.Value) + { + configFirstLaunch.Value = false; + // Generate a prompt for whether or not space warp should check mod versions + GameObject o = new GameObject(); + VersionCheckPrompt prompt = o.AddComponent(); + prompt.spaceWarpPlugin = this; + } + + if (configCheckVersions.Value) + { + CheckVersions(); + } + else + { + + } + } + + public void ClearVersions() + { + foreach (var plugin in SpaceWarpManager.SpaceWarpPlugins) + { + SpaceWarpManager.ModsOutdated[plugin.SpaceWarpMetadata.ModID] = false; + } + } + public void CheckVersions() + { + ClearVersions(); + foreach (var plugin in SpaceWarpManager.SpaceWarpPlugins) + { + if (plugin.SpaceWarpMetadata.VersionCheck != null) + { + StartCoroutine(CheckVersion(plugin.SpaceWarpMetadata)); + } + } + } + + static bool OlderThan(string currentVersion, string onlineVersion) + { + try + { + var currentList = currentVersion.Split('.'); + var onlineList = onlineVersion.Split('.'); + var minLength = Math.Min(currentList.Length, onlineList.Length); + for (var i = 0; i < minLength; i++) + { + if (int.Parse(currentList[i]) < int.Parse(onlineList[i])) + { + return true; + } + + if (int.Parse(currentList[i]) > int.Parse(onlineList[i])) + { + return false; + } + } + + return onlineList.Length > currentList.Length; + } catch (Exception e) + { + Debug.Log(e); + return false; + } + } + IEnumerator CheckVersion(ModInfo pluginInfo) + { + var www = new UnityWebRequest(pluginInfo.VersionCheck); + yield return www.SendWebRequest(); + + if (www.result != UnityWebRequest.Result.Success) + { + Logger.LogInfo($"Unable to check version for {pluginInfo.ModID} due to error {www.error}"); + } + else + { + var results = www.downloadHandler.text; + var checkInfo = JsonConvert.DeserializeObject(results); + SpaceWarpManager.ModsOutdated[pluginInfo.ModID] = OlderThan(pluginInfo.Version, checkInfo.Version); + } + } + private void InitializeUI() { SpaceWarpManager.ConfigurationManager = (ConfigurationManager.ConfigurationManager)Chainloader.PluginInfos[global::ConfigurationManager.ConfigurationManager.GUID].Instance; diff --git a/SpaceWarp/UI/ModListUI.cs b/SpaceWarp/UI/ModListUI.cs index 41105537..4fce6727 100644 --- a/SpaceWarp/UI/ModListUI.cs +++ b/SpaceWarp/UI/ModListUI.cs @@ -19,6 +19,7 @@ public class ModListUI : KerbalMonoBehaviour private static Vector2 _scrollPositionMods; private static Vector2 _scrollPositionInfo; private static GUIStyle _closeButtonStyle; + private static GUIStyle _outdatedModStyle; private const string ModListHeader = "ModListHeader"; @@ -62,10 +63,48 @@ private void OnGUI() fontSize = 8 }; + if (_outdatedModStyle != null) + { + _outdatedModStyle = new GUIStyle(GUI.skin.button) + { + normal = + { + textColor = Color.yellow + }, + active = + { + textColor = Color.yellow + }, + hover = + { + textColor = Color.yellow + }, + focused = + { + textColor = Color.yellow + }, + onActive = + { + textColor = Color.yellow + }, + onFocused = + { + textColor = Color.yellow + }, + onHover = + { + textColor = Color.yellow + }, + onNormal = + { + textColor = Color.yellow + } + }; + } + int controlID = GUIUtility.GetControlID(FocusType.Passive); GUILayoutOption width = GUILayout.Width((float)(_windowWidth * 0.8)); GUILayoutOption height = GUILayout.Height((float)(_windowHeight * 0.8)); - GUI.skin = SpaceWarpManager.Skin; _windowRect = GUILayout.Window(controlID, _windowRect, FillWindow, ModListHeader, width, height); } @@ -107,9 +146,19 @@ private void FillWindow(int windowID) foreach (var mod in SpaceWarpManager.SpaceWarpPlugins) { - if (GUILayout.Button(mod.SpaceWarpMetadata.Name)) + if (SpaceWarpManager.ModsOutdated[mod.SpaceWarpMetadata.ModID]) + { + if (GUILayout.Button(mod.SpaceWarpMetadata.Name, _outdatedModStyle)) + { + _selectedMetaData = mod.SpaceWarpMetadata; + } + } + else { - _selectedMetaData = mod.SpaceWarpMetadata; + if (GUILayout.Button(mod.SpaceWarpMetadata.Name)) + { + _selectedMetaData = mod.SpaceWarpMetadata; + } } } GUILayout.EndScrollView(); @@ -120,7 +169,9 @@ private void FillWindow(int windowID) _scrollPositionInfo = GUILayout.BeginScrollView(_scrollPositionInfo, false, false); GUILayout.Label($"{_selectedMetaData.Name} (id: {_selectedMetaData.ModID})"); GUILayout.Label($"Author: {_selectedMetaData.Author}"); - GUILayout.Label($"Version: {_selectedMetaData.Version}"); + GUILayout.Label(SpaceWarpManager.ModsOutdated[_selectedMetaData.ModID] + ? $"Version: {_selectedMetaData.Version} (outdated)" + : $"Version: {_selectedMetaData.Version}"); GUILayout.Label($"Source: {_selectedMetaData.Source}"); GUILayout.Label($"Description: {_selectedMetaData.Description}"); GUILayout.Label($"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max}"); diff --git a/SpaceWarp/UI/VersionCheckPrompt.cs b/SpaceWarp/UI/VersionCheckPrompt.cs new file mode 100644 index 00000000..a5da7d44 --- /dev/null +++ b/SpaceWarp/UI/VersionCheckPrompt.cs @@ -0,0 +1,72 @@ +using System; +using UnityEngine; + +namespace SpaceWarp.UI; + +internal class VersionCheckPrompt : MonoBehaviour +{ + public SpaceWarpPlugin spaceWarpPlugin; + private GUIStyle _closeButtonStyle; + private Rect _windowRect; + private float _windowWidth; + private float _windowHeight; + + private void Awake() + { + float minResolution = 1280f / 720f; + float maxResolution = 2048f / 1080f; + float screenRatio = (float) Screen.width / (float) Screen.height; + float scaleFactor = Mathf.Clamp(screenRatio, minResolution, maxResolution); + + _windowWidth = (int) (Screen.width * 0.5f * scaleFactor); + _windowHeight = (int) (Screen.height * 0.5f * scaleFactor); + _windowRect = new Rect( + Screen.width * 0.15f, + Screen.height * 0.15f, + Screen.width * 0.5f * scaleFactor, + Screen.height * 0.5f * scaleFactor + ); + } + public void OnGUI() + { + GUI.skin = SpaceWarp.API.UI.Skins.ConsoleSkin; + + int controlID = GUIUtility.GetControlID(FocusType.Passive); + GUILayoutOption width = GUILayout.Width((float)(_windowWidth * 0.8)); + GUILayoutOption height = GUILayout.Height((float)(_windowHeight * 0.8)); + + _closeButtonStyle ??= new GUIStyle(GUI.skin.button) + { + fontSize = 8 + }; + _windowRect = GUILayout.Window(controlID, _windowRect, FillWindow, "Space Warp", width, height); + } + + private void FillWindow(int windowID) + { + if (GUI.Button(new Rect(_windowRect.width - 18, 2, 16, 16), "x", _closeButtonStyle)) + { + Destroy(this); + GUIUtility.ExitGUI(); + } + + GUILayout.BeginVertical(); + GUILayout.Label("Allow Space Warp to check versions for mods"); + GUILayout.BeginHorizontal(); + if (GUILayout.Button("Yes")) + { + spaceWarpPlugin.CheckVersions(); + spaceWarpPlugin.configCheckVersions.Value = true; + Destroy(this); + } + + if (GUILayout.Button("No")) + { + Destroy(this); + } + + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + GUI.DragWindow(); + } +} \ No newline at end of file From 6aef0e2d1f5fd80947d51ae17b1902adcc88598a Mon Sep 17 00:00:00 2001 From: Lexi Date: Mon, 13 Mar 2023 21:43:40 -0400 Subject: [PATCH 09/15] Working version checking (tested) --- .../API/Mods/JSON/SupportedVersionsInfo.cs | 52 +++++++- SpaceWarp/SpaceWarpManager.cs | 13 ++ SpaceWarp/SpaceWarpPlugin.cs | 12 +- SpaceWarp/UI/ModListUI.cs | 117 ++++++++++++------ SpaceWarp/UI/VersionCheckPrompt.cs | 4 +- SpaceWarpBuildTemplate/swinfo.json | 3 +- 6 files changed, 152 insertions(+), 49 deletions(-) diff --git a/SpaceWarp/API/Mods/JSON/SupportedVersionsInfo.cs b/SpaceWarp/API/Mods/JSON/SupportedVersionsInfo.cs index 5ea1372e..56c540ca 100644 --- a/SpaceWarp/API/Mods/JSON/SupportedVersionsInfo.cs +++ b/SpaceWarp/API/Mods/JSON/SupportedVersionsInfo.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using System; +using Newtonsoft.Json; namespace SpaceWarp.API.Mods.JSON; @@ -13,4 +14,53 @@ public sealed class SupportedVersionsInfo [JsonProperty("max")] public string Max { get; internal set; } = "*"; + + public bool IsSupported(string toCheck) + { + try + { + var minList = Min.Split('.'); + var maxList = Max.Split('.'); + var checkList = toCheck.Split('.'); + var minMin = Math.Min(minList.Length, checkList.Length); + var minMax = Math.Max(maxList.Length, checkList.Length); + for (var i = 0; i < minMin; i++) + { + if (minList[i] == "*") + { + break; + } + if (int.Parse(checkList[i]) < int.Parse(minList[i])) + { + return false; + } + if (int.Parse(checkList[i]) > int.Parse(minList[i])) + { + break; + } + } + + for (var i = 0; i < minMax; i++) + { + if (maxList[i] == "*") + { + break; + } + if (int.Parse(checkList[i]) > int.Parse(minList[i])) + { + return false; + } + if (int.Parse(checkList[i]) < int.Parse(minList[i])) + { + break; + } + } + + return true; + } + catch + { + return true; + } + } } diff --git a/SpaceWarp/SpaceWarpManager.cs b/SpaceWarp/SpaceWarpManager.cs index b916729f..f0d6ac13 100644 --- a/SpaceWarp/SpaceWarpManager.cs +++ b/SpaceWarp/SpaceWarpManager.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using BepInEx.Bootstrap; using BepInEx.Logging; +using KSP.Game; using Newtonsoft.Json; using UnityEngine; using SpaceWarp.API.Assets; @@ -23,6 +24,7 @@ internal static class SpaceWarpManager internal static IReadOnlyList SpaceWarpPlugins; internal static ConfigurationManager.ConfigurationManager ConfigurationManager; internal static Dictionary ModsOutdated = new(); + internal static Dictionary ModsUnsupported = new(); internal static void GetSpaceWarpPlugins() { @@ -79,4 +81,15 @@ public static GUISkin Skin return _skin; } } + + + internal static void CheckKspVersions() + { + const string kspVersion = VersionID.VERSION_TEXT; + foreach (var plugin in SpaceWarpPlugins) + { + ModsUnsupported[plugin.SpaceWarpMetadata.ModID] = + !plugin.SpaceWarpMetadata.SupportedKsp2Versions.IsSupported(kspVersion); + } + } } \ No newline at end of file diff --git a/SpaceWarp/SpaceWarpPlugin.cs b/SpaceWarp/SpaceWarpPlugin.cs index b69a27ab..6ca19956 100644 --- a/SpaceWarp/SpaceWarpPlugin.cs +++ b/SpaceWarp/SpaceWarpPlugin.cs @@ -87,11 +87,6 @@ public override void OnInitialized() Game.Messages.Subscribe(typeof(GameStateChangedMessage), StateChanges.OnGameStateChanged,false,true); InitializeUI(); - } - - public override void OnPostInitialized() - { - base.OnPostInitialized(); if (configFirstLaunch.Value) { configFirstLaunch.Value = false; @@ -107,8 +102,10 @@ public override void OnPostInitialized() } else { - + ClearVersions(); } + + SpaceWarpManager.CheckKspVersions(); } public void ClearVersions() @@ -159,7 +156,7 @@ static bool OlderThan(string currentVersion, string onlineVersion) } IEnumerator CheckVersion(ModInfo pluginInfo) { - var www = new UnityWebRequest(pluginInfo.VersionCheck); + var www = UnityWebRequest.Get(pluginInfo.VersionCheck); yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) @@ -168,6 +165,7 @@ IEnumerator CheckVersion(ModInfo pluginInfo) } else { + var results = www.downloadHandler.text; var checkInfo = JsonConvert.DeserializeObject(results); SpaceWarpManager.ModsOutdated[pluginInfo.ModID] = OlderThan(pluginInfo.Version, checkInfo.Version); diff --git a/SpaceWarp/UI/ModListUI.cs b/SpaceWarp/UI/ModListUI.cs index 4fce6727..f98f99a9 100644 --- a/SpaceWarp/UI/ModListUI.cs +++ b/SpaceWarp/UI/ModListUI.cs @@ -20,6 +20,7 @@ public class ModListUI : KerbalMonoBehaviour private static Vector2 _scrollPositionInfo; private static GUIStyle _closeButtonStyle; private static GUIStyle _outdatedModStyle; + private static GUIStyle _unsupportedModStyle; private const string ModListHeader = "ModListHeader"; @@ -63,44 +64,76 @@ private void OnGUI() fontSize = 8 }; - if (_outdatedModStyle != null) + _outdatedModStyle ??= new GUIStyle(GUI.skin.button) { - _outdatedModStyle = new GUIStyle(GUI.skin.button) + normal = { - normal = - { - textColor = Color.yellow - }, - active = - { - textColor = Color.yellow - }, - hover = - { - textColor = Color.yellow - }, - focused = - { - textColor = Color.yellow - }, - onActive = - { - textColor = Color.yellow - }, - onFocused = - { - textColor = Color.yellow - }, - onHover = - { - textColor = Color.yellow - }, - onNormal = - { - textColor = Color.yellow - } - }; - } + textColor = Color.yellow + }, + active = + { + textColor = Color.yellow + }, + hover = + { + textColor = Color.yellow + }, + focused = + { + textColor = Color.yellow + }, + onActive = + { + textColor = Color.yellow + }, + onFocused = + { + textColor = Color.yellow + }, + onHover = + { + textColor = Color.yellow + }, + onNormal = + { + textColor = Color.yellow + } + }; + _unsupportedModStyle ??= new GUIStyle(GUI.skin.button) + { + normal = + { + textColor = Color.red + }, + active = + { + textColor = Color.red + }, + hover = + { + textColor = Color.red + }, + focused = + { + textColor = Color.red + }, + onActive = + { + textColor = Color.red + }, + onFocused = + { + textColor = Color.red + }, + onHover = + { + textColor = Color.red + }, + onNormal = + { + textColor = Color.red + } + }; int controlID = GUIUtility.GetControlID(FocusType.Passive); GUILayoutOption width = GUILayout.Width((float)(_windowWidth * 0.8)); @@ -146,7 +179,15 @@ private void FillWindow(int windowID) foreach (var mod in SpaceWarpManager.SpaceWarpPlugins) { - if (SpaceWarpManager.ModsOutdated[mod.SpaceWarpMetadata.ModID]) + if (SpaceWarpManager.ModsUnsupported[mod.SpaceWarpMetadata.ModID]) + { + + if (GUILayout.Button(mod.SpaceWarpMetadata.Name, _unsupportedModStyle)) + { + _selectedMetaData = mod.SpaceWarpMetadata; + } + } + else if (SpaceWarpManager.ModsOutdated[mod.SpaceWarpMetadata.ModID]) { if (GUILayout.Button(mod.SpaceWarpMetadata.Name, _outdatedModStyle)) { @@ -174,7 +215,7 @@ private void FillWindow(int windowID) : $"Version: {_selectedMetaData.Version}"); GUILayout.Label($"Source: {_selectedMetaData.Source}"); GUILayout.Label($"Description: {_selectedMetaData.Description}"); - GUILayout.Label($"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max}"); + GUILayout.Label(SpaceWarpManager.ModsUnsupported[_selectedMetaData.ModID] ? $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max} (unsupported)" : $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max}"); GUILayout.Label($"Dependencies"); foreach (DependencyInfo dependency in _selectedMetaData.Dependencies) diff --git a/SpaceWarp/UI/VersionCheckPrompt.cs b/SpaceWarp/UI/VersionCheckPrompt.cs index a5da7d44..dbe6251b 100644 --- a/SpaceWarp/UI/VersionCheckPrompt.cs +++ b/SpaceWarp/UI/VersionCheckPrompt.cs @@ -18,8 +18,8 @@ private void Awake() float screenRatio = (float) Screen.width / (float) Screen.height; float scaleFactor = Mathf.Clamp(screenRatio, minResolution, maxResolution); - _windowWidth = (int) (Screen.width * 0.5f * scaleFactor); - _windowHeight = (int) (Screen.height * 0.5f * scaleFactor); + _windowWidth = (int) (Screen.width * 0.2f * scaleFactor); + _windowHeight = 0; _windowRect = new Rect( Screen.width * 0.15f, Screen.height * 0.15f, diff --git a/SpaceWarpBuildTemplate/swinfo.json b/SpaceWarpBuildTemplate/swinfo.json index 0744b84f..b5a8ad31 100644 --- a/SpaceWarpBuildTemplate/swinfo.json +++ b/SpaceWarpBuildTemplate/swinfo.json @@ -4,7 +4,8 @@ "author": "Space-Warp Team", "description": "Space-Warp is an API for KSP2 mod developers.", "source": "https://github.com/SpaceWarpDev/SpaceWarp", - "version": "0.4.0", + "version_check": "https://raw.githubusercontent.com/SpaceWarpDev/SpaceWarp/main/SpaceWarpBuildTemplate/swinfo.json", + "version": "1.0.0", "dependencies": [], "ksp2_version": { "min": "0", From cb7ed59615e97497ab1e21730aa05569f8a0d881 Mon Sep 17 00:00:00 2001 From: cheese3660 Date: Mon, 13 Mar 2023 21:48:13 -0400 Subject: [PATCH 10/15] Add version checking example to example mod --- ExampleMod/swinfo.json | 1 + 1 file changed, 1 insertion(+) diff --git a/ExampleMod/swinfo.json b/ExampleMod/swinfo.json index cf57cdbd..1c016bb5 100644 --- a/ExampleMod/swinfo.json +++ b/ExampleMod/swinfo.json @@ -4,6 +4,7 @@ "author": "Space-Warp Team", "description": "A Example Mod for Space-Warp", "source": "https://github.com/SpaceWarpDev/SpaceWarp/tree/main/ExampleMod", + "check_version": "https://raw.githubusercontent.com/SpaceWarpDev/SpaceWarp/main/ExampleMod/swinfo.json", "version": "0.4.0", "dependencies": [], "ksp2_version": { From 0f45561c60b73dfb456aa7aa95d05995fe30d1c3 Mon Sep 17 00:00:00 2001 From: Lexi Date: Tue, 14 Mar 2023 09:30:48 -0400 Subject: [PATCH 11/15] Fix KSP version grabbing to use reflection because consts are fun --- SpaceWarp/SpaceWarpManager.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/SpaceWarp/SpaceWarpManager.cs b/SpaceWarp/SpaceWarpManager.cs index f0d6ac13..5620e37f 100644 --- a/SpaceWarp/SpaceWarpManager.cs +++ b/SpaceWarp/SpaceWarpManager.cs @@ -1,5 +1,6 @@ using System.IO; using System.Collections.Generic; +using System.Reflection; using BepInEx.Bootstrap; using BepInEx.Logging; using KSP.Game; @@ -84,8 +85,8 @@ public static GUISkin Skin internal static void CheckKspVersions() - { - const string kspVersion = VersionID.VERSION_TEXT; + { + var kspVersion = typeof(VersionID).GetField("VERSION_TEXT",BindingFlags.Static | BindingFlags.Public)?.GetValue(null) as string; foreach (var plugin in SpaceWarpPlugins) { ModsUnsupported[plugin.SpaceWarpMetadata.ModID] = From 760abe913d032ae2ec8a6dd0406e1611abbc6d2b Mon Sep 17 00:00:00 2001 From: Lexi Date: Tue, 14 Mar 2023 11:32:13 -0400 Subject: [PATCH 12/15] Allow for the showing of non space warp mods in the mod list, and respect non space warp mods swinfo.json if they have any --- SpaceWarp/SpaceWarpManager.cs | 32 ++++++++- SpaceWarp/SpaceWarpPlugin.cs | 13 ++++ SpaceWarp/UI/ModListUI.cs | 124 +++++++++++++++++++++++++--------- 3 files changed, 135 insertions(+), 34 deletions(-) diff --git a/SpaceWarp/SpaceWarpManager.cs b/SpaceWarp/SpaceWarpManager.cs index 5620e37f..071375d9 100644 --- a/SpaceWarp/SpaceWarpManager.cs +++ b/SpaceWarp/SpaceWarpManager.cs @@ -1,8 +1,10 @@ using System.IO; using System.Collections.Generic; using System.Reflection; +using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; +using HarmonyLib; using KSP.Game; using Newtonsoft.Json; using UnityEngine; @@ -23,6 +25,8 @@ internal static class SpaceWarpManager internal static ManualLogSource Logger; internal static string SpaceWarpFolder; internal static IReadOnlyList SpaceWarpPlugins; + internal static IReadOnlyList NonSpaceWarpPlugins; + internal static IReadOnlyList NonSpaceWarpInfos; internal static ConfigurationManager.ConfigurationManager ConfigurationManager; internal static Dictionary ModsOutdated = new(); internal static Dictionary ModsUnsupported = new(); @@ -35,7 +39,6 @@ internal static void GetSpaceWarpPlugins() var spaceWarpPlugins = Chainloader.Plugins.OfType().ToList(); SpaceWarpPlugins = spaceWarpPlugins; - #pragma warning restore CS0618 foreach (var plugin in SpaceWarpPlugins.ToArray()) { var folderPath = Path.GetDirectoryName(plugin.Info.Location); @@ -55,6 +58,28 @@ internal static void GetSpaceWarpPlugins() } plugin.SpaceWarpMetadata = JsonConvert.DeserializeObject(File.ReadAllText(modInfoPath)); } + + var allPlugins = Chainloader.Plugins.ToList(); + List nonSWPlugins = new(); + List nonSWInfos = new(); + foreach (var plugin in allPlugins) + { + if (spaceWarpPlugins.Contains(plugin as BaseSpaceWarpPlugin)) continue; + var folderPath = Path.GetDirectoryName(plugin.Info.Location); + var modInfoPath = Path.Combine(folderPath!, "swinfo.json"); + if (File.Exists(modInfoPath)) + { + var info = JsonConvert.DeserializeObject(File.ReadAllText(modInfoPath)); + nonSWInfos.Add(info); + } + else + { + nonSWPlugins.Add(plugin); + } + } + #pragma warning restore CS0618 + NonSpaceWarpPlugins = nonSWPlugins; + NonSpaceWarpInfos = nonSWInfos; } public static void Initialize(SpaceWarpPlugin spaceWarpPlugin) @@ -92,5 +117,10 @@ internal static void CheckKspVersions() ModsUnsupported[plugin.SpaceWarpMetadata.ModID] = !plugin.SpaceWarpMetadata.SupportedKsp2Versions.IsSupported(kspVersion); } + + foreach (var info in NonSpaceWarpInfos) + { + ModsUnsupported[info.ModID] = !info.SupportedKsp2Versions.IsSupported(kspVersion); + } } } \ No newline at end of file diff --git a/SpaceWarp/SpaceWarpPlugin.cs b/SpaceWarp/SpaceWarpPlugin.cs index 6ca19956..41346aeb 100644 --- a/SpaceWarp/SpaceWarpPlugin.cs +++ b/SpaceWarp/SpaceWarpPlugin.cs @@ -114,6 +114,11 @@ public void ClearVersions() { SpaceWarpManager.ModsOutdated[plugin.SpaceWarpMetadata.ModID] = false; } + + foreach (var info in SpaceWarpManager.NonSpaceWarpInfos) + { + SpaceWarpManager.ModsOutdated[info.ModID] = false; + } } public void CheckVersions() { @@ -125,6 +130,14 @@ public void CheckVersions() StartCoroutine(CheckVersion(plugin.SpaceWarpMetadata)); } } + + foreach (var info in SpaceWarpManager.NonSpaceWarpInfos) + { + if (info.VersionCheck != null) + { + StartCoroutine(CheckVersion(info)); + } + } } static bool OlderThan(string currentVersion, string onlineVersion) diff --git a/SpaceWarp/UI/ModListUI.cs b/SpaceWarp/UI/ModListUI.cs index f98f99a9..ccac222e 100644 --- a/SpaceWarp/UI/ModListUI.cs +++ b/SpaceWarp/UI/ModListUI.cs @@ -1,4 +1,6 @@ -using KSP.Game; +using BepInEx; +using KSP.Game; +using KSP.Modding; using SpaceWarp.API.Mods.JSON; using UnityEngine; @@ -11,6 +13,8 @@ public class ModListUI : KerbalMonoBehaviour private bool _drawUI; private Rect _windowRect; private ModInfo _selectedMetaData; + private BepInPlugin _selectedBepInMetadata; + private bool _selectedBepIn; private int _windowWidth = 350; private int _windowHeight = 700; @@ -21,8 +25,9 @@ public class ModListUI : KerbalMonoBehaviour private static GUIStyle _closeButtonStyle; private static GUIStyle _outdatedModStyle; private static GUIStyle _unsupportedModStyle; + private static GUIStyle _unmanagedHeaderStyle; - private const string ModListHeader = "ModListHeader"; + private const string ModListHeader = "spacewarp.modlist"; public void Start() { @@ -134,7 +139,11 @@ private void OnGUI() textColor = Color.red } }; - + _unmanagedHeaderStyle ??= new GUIStyle(GUI.skin.label) + { + fontStyle = FontStyle.Bold, + alignment = TextAnchor.MiddleCenter + }; int controlID = GUIUtility.GetControlID(FocusType.Passive); GUILayoutOption width = GUILayout.Width((float)(_windowWidth * 0.8)); GUILayoutOption height = GUILayout.Height((float)(_windowHeight * 0.8)); @@ -176,56 +185,105 @@ private void FillWindow(int windowID) GUILayout.Height((float)(_windowHeight * 0.8)), GUILayout.Width(300) ); + + GUILayout.Label("SpaceWarp Mods",_unmanagedHeaderStyle); foreach (var mod in SpaceWarpManager.SpaceWarpPlugins) { if (SpaceWarpManager.ModsUnsupported[mod.SpaceWarpMetadata.ModID]) { - - if (GUILayout.Button(mod.SpaceWarpMetadata.Name, _unsupportedModStyle)) - { - _selectedMetaData = mod.SpaceWarpMetadata; - } + if (!GUILayout.Button(mod.SpaceWarpMetadata.Name, _unsupportedModStyle)) continue; + _selectedBepIn = false; + _selectedMetaData = mod.SpaceWarpMetadata; } else if (SpaceWarpManager.ModsOutdated[mod.SpaceWarpMetadata.ModID]) { - if (GUILayout.Button(mod.SpaceWarpMetadata.Name, _outdatedModStyle)) - { - _selectedMetaData = mod.SpaceWarpMetadata; - } + if (!GUILayout.Button(mod.SpaceWarpMetadata.Name, _outdatedModStyle)) continue; + _selectedBepIn = false; + _selectedMetaData = mod.SpaceWarpMetadata; } else { - if (GUILayout.Button(mod.SpaceWarpMetadata.Name)) + if (!GUILayout.Button(mod.SpaceWarpMetadata.Name)) continue; + _selectedBepIn = false; + _selectedMetaData = mod.SpaceWarpMetadata; + } + } + GUILayout.Label(""); + GUILayout.Label("Unmanaged Mods",_unmanagedHeaderStyle); + + foreach (var info in SpaceWarpManager.NonSpaceWarpInfos) + { + if (SpaceWarpManager.ModsUnsupported[info.ModID]) + { + if (GUILayout.Button(info.Name, _unsupportedModStyle)) { - _selectedMetaData = mod.SpaceWarpMetadata; + _selectedBepIn = false; + _selectedMetaData = info; } } + else if (SpaceWarpManager.ModsOutdated[info.ModID]) + { + if (!GUILayout.Button(info.Name, _outdatedModStyle)) continue; + _selectedBepIn = false; + _selectedMetaData = info; + } + else + { + if (!GUILayout.Button(info.Name)) continue; + _selectedBepIn = false; + _selectedMetaData = info; + } + } + foreach (var mod in SpaceWarpManager.NonSpaceWarpPlugins) + { + if (!GUILayout.Button(mod.Info.Metadata.Name)) continue; + _selectedBepIn = true; + _selectedBepInMetadata = mod.Info.Metadata; } + GUILayout.EndScrollView(); GUILayout.EndVertical(); - if (_selectedMetaData != null) + if (_selectedBepIn) { - GUILayout.BeginVertical(); - _scrollPositionInfo = GUILayout.BeginScrollView(_scrollPositionInfo, false, false); - GUILayout.Label($"{_selectedMetaData.Name} (id: {_selectedMetaData.ModID})"); - GUILayout.Label($"Author: {_selectedMetaData.Author}"); - GUILayout.Label(SpaceWarpManager.ModsOutdated[_selectedMetaData.ModID] - ? $"Version: {_selectedMetaData.Version} (outdated)" - : $"Version: {_selectedMetaData.Version}"); - GUILayout.Label($"Source: {_selectedMetaData.Source}"); - GUILayout.Label($"Description: {_selectedMetaData.Description}"); - GUILayout.Label(SpaceWarpManager.ModsUnsupported[_selectedMetaData.ModID] ? $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max} (unsupported)" : $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max}"); - GUILayout.Label($"Dependencies"); - - foreach (DependencyInfo dependency in _selectedMetaData.Dependencies) - { - GUILayout.Label($"{dependency.ID}: {dependency.Version.Min} - {dependency.Version.Max}"); + if (_selectedBepInMetadata != null) + { + GUILayout.BeginVertical(); + _scrollPositionInfo = GUILayout.BeginScrollView(_scrollPositionInfo, false, false); + GUILayout.Label($"{_selectedBepInMetadata.Name} (guid: {_selectedBepInMetadata.GUID})"); + GUILayout.Label($"Version: {_selectedBepInMetadata.Version}"); + GUILayout.EndScrollView(); + GUILayout.EndVertical(); } - GUILayout.EndScrollView(); - GUILayout.EndVertical(); } - + else + { + if (_selectedMetaData != null) + { + GUILayout.BeginVertical(); + _scrollPositionInfo = GUILayout.BeginScrollView(_scrollPositionInfo, false, false); + GUILayout.Label($"{_selectedMetaData.Name} (id: {_selectedMetaData.ModID})"); + GUILayout.Label($"Author: {_selectedMetaData.Author}"); + GUILayout.Label(SpaceWarpManager.ModsOutdated[_selectedMetaData.ModID] + ? $"Version: {_selectedMetaData.Version} (outdated)" + : $"Version: {_selectedMetaData.Version}"); + GUILayout.Label($"Source: {_selectedMetaData.Source}"); + GUILayout.Label($"Description: {_selectedMetaData.Description}"); + GUILayout.Label(SpaceWarpManager.ModsUnsupported[_selectedMetaData.ModID] + ? $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max} (unsupported)" + : $"KSP2 Version: {_selectedMetaData.SupportedKsp2Versions.Min} - {_selectedMetaData.SupportedKsp2Versions.Max}"); + GUILayout.Label($"Dependencies"); + + foreach (DependencyInfo dependency in _selectedMetaData.Dependencies) + { + GUILayout.Label($"{dependency.ID}: {dependency.Version.Min} - {dependency.Version.Max}"); + } + + GUILayout.EndScrollView(); + GUILayout.EndVertical(); + } + } + GUILayout.EndHorizontal(); if (GUILayout.Button("Open Configuration Manager")) { From ca001f07e62f6a755f52ef9d60bb8af6ffeb3ff5 Mon Sep 17 00:00:00 2001 From: Lexi Date: Tue, 14 Mar 2023 19:49:10 -0400 Subject: [PATCH 13/15] Add extensions for vehicle controls --- .../Extensions/VesselVehicleExtensions.cs | 219 ++++++++++++++++++ SpaceWarp/API/Game/Vehicle.cs | 10 + 2 files changed, 229 insertions(+) create mode 100644 SpaceWarp/API/Game/Extensions/VesselVehicleExtensions.cs create mode 100644 SpaceWarp/API/Game/Vehicle.cs diff --git a/SpaceWarp/API/Game/Extensions/VesselVehicleExtensions.cs b/SpaceWarp/API/Game/Extensions/VesselVehicleExtensions.cs new file mode 100644 index 00000000..d33f56d3 --- /dev/null +++ b/SpaceWarp/API/Game/Extensions/VesselVehicleExtensions.cs @@ -0,0 +1,219 @@ +using KSP.Sim.impl; +using KSP.Sim.State; +using UnityEngine; + +namespace SpaceWarp.API.Game.Extensions; + +public static class VesselVehicleExtensions +{ + public static void SetMainThrottle(this VesselVehicle vehicle, float throttle) + { + var incremental = new FlightCtrlStateIncremental() + { + mainThrottle = throttle + }; + vehicle.AtomicSet(incremental); + } + + public static void SetRoll(this VesselVehicle vehicle, float roll) + { + var incremental = new FlightCtrlStateIncremental() + { + roll = roll + }; + vehicle.AtomicSet(incremental); + } + + public static void SetYaw(this VesselVehicle vehicle, float yaw) + { + var incremental = new FlightCtrlStateIncremental() + { + yaw = yaw + }; + vehicle.AtomicSet(incremental); + } + public static void SetPitch(this VesselVehicle vehicle, float pitch) + { + var incremental = new FlightCtrlStateIncremental() + { + pitch = pitch + }; + vehicle.AtomicSet(incremental); + } + + public static void SetRollYawPitch(this VesselVehicle vehicle, float roll, float yaw, float pitch) + { + var incremental = new FlightCtrlStateIncremental() + { + roll = roll, + yaw = yaw, + pitch = pitch + }; + vehicle.AtomicSet(incremental); + } + + public static void SetRollTrim(this VesselVehicle vehicle, float rollTrim) + { + var incremental = new FlightCtrlStateIncremental() + { + rollTrim=rollTrim + }; + vehicle.AtomicSet(incremental); + } + + public static void SetYawTrim(this VesselVehicle vehicle, float yawTrim) + { + var incremental = new FlightCtrlStateIncremental() + { + yawTrim=yawTrim + }; + vehicle.AtomicSet(incremental); + } + + public static void SetPitchTrim(this VesselVehicle vehicle, float pitchTrim) + { + var incremental = new FlightCtrlStateIncremental() + { + pitchTrim = pitchTrim + }; + vehicle.AtomicSet(incremental); + } + + + public static void SetRollYawPitchTrim(this VesselVehicle vehicle, float rollTrim, float yawTrim, float pitchTrim) + { + var incremental = new FlightCtrlStateIncremental() + { + rollTrim = rollTrim, + yawTrim = yawTrim, + pitchTrim = pitchTrim + }; + vehicle.AtomicSet(incremental); + } + + public static void SetInputRoll(this VesselVehicle vehicle, float roll) + { + var incremental = new FlightCtrlStateIncremental() + { + inputRoll = roll + }; + vehicle.AtomicSet(incremental); + } + + public static void SetInputYaw(this VesselVehicle vehicle, float yaw) + { + var incremental = new FlightCtrlStateIncremental() + { + inputYaw = yaw + }; + vehicle.AtomicSet(incremental); + } + public static void SetInputPitch(this VesselVehicle vehicle, float pitch) + { + var incremental = new FlightCtrlStateIncremental() + { + inputPitch = pitch + }; + vehicle.AtomicSet(incremental); + } + + public static void SetInputRollYawPitch(this VesselVehicle vehicle, float roll, float yaw, float pitch) + { + var incremental = new FlightCtrlStateIncremental() + { + inputRoll = roll, + inputYaw = yaw, + inputPitch = pitch + }; + vehicle.AtomicSet(incremental); + } + + public static void SetWheelSteer(this VesselVehicle vehicle, float wheelSteer, float? wheelSteerTrim=null) + { + var incremental = new FlightCtrlStateIncremental() + { + wheelSteer = wheelSteer, + wheelSteerTrim = wheelSteerTrim + }; + vehicle.AtomicSet(incremental); + } + + public static void SetWheelThrottle(this VesselVehicle vehicle, float wheelThrottle, float? wheelThrottleTrim=null) + { + var incremental = new FlightCtrlStateIncremental() + { + wheelThrottle = wheelThrottle, + wheelThrottleTrim = wheelThrottleTrim + }; + vehicle.AtomicSet(incremental); + } + + public static void SetXYZ(this VesselVehicle vehicle, float? X = null, float? Y = null, float? Z = null) + { + var incremental = new FlightCtrlStateIncremental() + { + X = X, + Y = Y, + Z = Z + }; + vehicle.AtomicSet(incremental); + } + public static void SetXYZ(this VesselVehicle vehicle, Vector3 XYZ) + { + var incremental = new FlightCtrlStateIncremental() + { + X = XYZ.x, + Y = XYZ.y, + Z = XYZ.z + }; + vehicle.AtomicSet(incremental); + } + + public static void SetKillRot(this VesselVehicle vehicle, bool killRot) + { + var incremental = new FlightCtrlStateIncremental() + { + killRot = killRot + }; + vehicle.AtomicSet(incremental); + } + + public static void SetGearState(this VesselVehicle vehicle, bool up) + { + var incremental = new FlightCtrlStateIncremental() + { + gearUp = up, + gearDown = !up + }; + vehicle.AtomicSet(incremental); + } + + + public static void SetHeadlight(this VesselVehicle vehicle, bool on) + { + var incremental = new FlightCtrlStateIncremental() + { + headlight = on + }; + vehicle.AtomicSet(incremental); + } + + + public static void SetBrake(this VesselVehicle vehicle, bool on) + { + var incremental = new FlightCtrlStateIncremental() + { + brakes = on + }; + vehicle.AtomicSet(incremental); + } + + public static void SetStage(this VesselVehicle vehicle, bool stage) + { + var incremental = new FlightCtrlStateIncremental() + { + stage = stage + }; + vehicle.AtomicSet(incremental); + } +} \ No newline at end of file diff --git a/SpaceWarp/API/Game/Vehicle.cs b/SpaceWarp/API/Game/Vehicle.cs new file mode 100644 index 00000000..ba6635a9 --- /dev/null +++ b/SpaceWarp/API/Game/Vehicle.cs @@ -0,0 +1,10 @@ +using KSP.Game; +using KSP.Sim.impl; + +namespace SpaceWarp.API.Game; + +public static class Vehicle +{ + public static VesselVehicle ActiveVesselVehicle => GameManager.Instance.Game.ViewController._activeVesselVehicle; + public static VesselComponent ActiveSimVessel => GameManager.Instance.Game.ViewController.GetActiveSimVessel(); +} \ No newline at end of file From 73b5c2c434c82a22bfb493c47f7d6319bb43c26f Mon Sep 17 00:00:00 2001 From: Lexi Date: Wed, 15 Mar 2023 14:58:17 -0400 Subject: [PATCH 14/15] Start providing extensions for getting parts and such. --- .../Game/Extensions/PartProviderExtensions.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 SpaceWarp/API/Game/Extensions/PartProviderExtensions.cs diff --git a/SpaceWarp/API/Game/Extensions/PartProviderExtensions.cs b/SpaceWarp/API/Game/Extensions/PartProviderExtensions.cs new file mode 100644 index 00000000..f440e162 --- /dev/null +++ b/SpaceWarp/API/Game/Extensions/PartProviderExtensions.cs @@ -0,0 +1,17 @@ +using KSP.Game; +using KSP.Sim.Definitions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SpaceWarp.API.Game.Extensions; + +public static class PartProviderExtensions +{ + public static IEnumerable WithModule(this PartProvider provider) where T : ModuleData + { + return provider._partData.Values.Where(part => part.modules.OfType().Count() > 0); + } +} From afe0e9a443e11bad41becf12c1b27d92d90bff94 Mon Sep 17 00:00:00 2001 From: cheese3660 Date: Wed, 15 Mar 2023 17:44:33 -0400 Subject: [PATCH 15/15] Update swinfo.json --- ExampleMod/swinfo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ExampleMod/swinfo.json b/ExampleMod/swinfo.json index 1c016bb5..6361d5e8 100644 --- a/ExampleMod/swinfo.json +++ b/ExampleMod/swinfo.json @@ -4,7 +4,7 @@ "author": "Space-Warp Team", "description": "A Example Mod for Space-Warp", "source": "https://github.com/SpaceWarpDev/SpaceWarp/tree/main/ExampleMod", - "check_version": "https://raw.githubusercontent.com/SpaceWarpDev/SpaceWarp/main/ExampleMod/swinfo.json", + "version_check": "https://raw.githubusercontent.com/SpaceWarpDev/SpaceWarp/main/ExampleMod/swinfo.json", "version": "0.4.0", "dependencies": [], "ksp2_version": {