From 85a9c5ce66a22b6ff3cf697a7f53dc2545a2d45f Mon Sep 17 00:00:00 2001 From: Noah Pilarski Date: Tue, 5 Jul 2022 08:01:15 -0400 Subject: [PATCH 01/18] Make cloaks also turn off tessellated renderers. Stops water, sand, inner clouds, and any other tessellated renderer from showing even when player is not inside cloak. --- NewHorizons/Components/CloakSectorController.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/NewHorizons/Components/CloakSectorController.cs b/NewHorizons/Components/CloakSectorController.cs index 09f50776..ae4ebdcd 100644 --- a/NewHorizons/Components/CloakSectorController.cs +++ b/NewHorizons/Components/CloakSectorController.cs @@ -11,6 +11,7 @@ namespace NewHorizons.Components private bool _isInitialized; private List _renderers = null; + private List _tessellatedRenderers = null; public static bool isPlayerInside = false; public static bool isProbeInside = false; @@ -51,6 +52,7 @@ namespace NewHorizons.Components private void SetUpList() { _renderers = _root.GetComponentsInChildren().ToList(); + _tessellatedRenderers = _root.GetComponentsInChildren().ToList(); } public void OnPlayerEnter() @@ -62,6 +64,11 @@ namespace NewHorizons.Components renderer.forceRenderingOff = false; } + foreach (var tessellatedRenderer in _tessellatedRenderers) + { + tessellatedRenderer.enabled = false; + } + isPlayerInside = true; GlobalMessenger.FireEvent("PlayerEnterCloakField"); } @@ -75,6 +82,11 @@ namespace NewHorizons.Components renderer.forceRenderingOff = true; } + foreach (var tessellatedRenderer in _tessellatedRenderers) + { + tessellatedRenderer.enabled = true; + } + isPlayerInside = false; GlobalMessenger.FireEvent("PlayerExitCloakField"); } From eff1cc72354770d5003566c548681ca1b28ff081 Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Tue, 5 Jul 2022 17:45:56 -0400 Subject: [PATCH 02/18] added a fallback for when the desired removechild is part of an inactive object that the user believes will later become active --- NewHorizons/Builder/Props/DetailBuilder.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index fdbe5256..9471e2eb 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -45,8 +45,14 @@ namespace NewHorizons.Builder.Props // We purposefully use GameObject.Find here because we don't want to find inactive things. // If you were to try and disable two children with the same name, if we were finding inactive then we'd disable the first one twice var childObj = GameObject.Find($"{detailPath}/{childPath}"); + if (childObj == null) + { + Logger.LogWarning($"Couldn't find \"{childPath}\". Including disabled game objects in search.", true); + childObj = SearchUtilities.Find($"{detailPath}/{childPath}"); + } + if (childObj != null) childObj.gameObject.SetActive(false); - else Logger.LogWarning($"Couldn't find {childPath}"); + else Logger.LogWarning($"Couldn't find \"{childPath}\"."); } } From e0239393467418c541c2c96b905735d0e2ac3c6c Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Tue, 5 Jul 2022 17:46:13 -0400 Subject: [PATCH 03/18] added a Verbose level for logs that print way too much --- NewHorizons/Handlers/PlanetDestructionHandler.cs | 4 ++-- NewHorizons/Main.cs | 12 ++++++++---- NewHorizons/Patches/ShipLogPatches.cs | 6 +++--- NewHorizons/Utility/DebugUtilities/DebugReload.cs | 2 +- NewHorizons/Utility/Logger.cs | 15 ++++++++++----- NewHorizons/default-config.json | 3 ++- 6 files changed, 26 insertions(+), 16 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 82c0454a..14cbdbfa 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -49,7 +49,7 @@ namespace NewHorizons.Handlers public static void RemoveBody(AstroObject ao, bool delete = false, List toDestroy = null) { - Logger.Log($"Removing [{ao.name}]"); + Logger.LogVerbose($"Removing [{ao.name}]"); if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) { @@ -208,7 +208,7 @@ namespace NewHorizons.Handlers { if (go == null) return; - Logger.Log($"Removing [{go.name}]"); + Logger.LogVerbose($"Removing [{go.name}]"); if (delete) { diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 955b7cd5..1f7e52a0 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -30,7 +30,8 @@ namespace NewHorizons public static Main Instance { get; private set; } // Settings - public static bool Debug { get; private set; } + public static bool Debug { get; private set; } + public static bool VerboseLogs { get; private set; } private static bool _useCustomTitleScreen; private static bool _wasConfigured = false; private static string _defaultSystemOverride; @@ -79,7 +80,8 @@ namespace NewHorizons var currentScene = SceneManager.GetActiveScene().name; - Debug = config.GetSettingsValue("Debug"); + Debug = config.GetSettingsValue("Debug"); + VerboseLogs = config.GetSettingsValue("Verbose Logs"); if (currentScene == "SolarSystem") { @@ -87,7 +89,9 @@ namespace NewHorizons DebugMenu.UpdatePauseMenuButton(); } - Logger.UpdateLogLevel(Debug ? Logger.LogType.Log : Logger.LogType.Error); + if (Debug && VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); + else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); + else Logger.UpdateLogLevel(Logger.LogType.Error); _defaultSystemOverride = config.GetSettingsValue("Default System Override"); @@ -168,7 +172,7 @@ namespace NewHorizons ResetConfigs(resetTranslation: false); - Logger.Log("Begin load of config files...", Logger.LogType.Log); + Logger.Log("Begin load of config files..."); try { diff --git a/NewHorizons/Patches/ShipLogPatches.cs b/NewHorizons/Patches/ShipLogPatches.cs index e61263be..3190b2f3 100644 --- a/NewHorizons/Patches/ShipLogPatches.cs +++ b/NewHorizons/Patches/ShipLogPatches.cs @@ -21,7 +21,7 @@ namespace NewHorizons.Patches { RumorModeBuilder.Init(); ShipLogHandler.Init(); - Logger.Log("Beginning Ship Log Generation For: " + Main.Instance.CurrentStarSystem, Logger.LogType.Log); + Logger.Log("Beginning Ship Log Generation For: " + Main.Instance.CurrentStarSystem); if (Main.Instance.CurrentStarSystem != "SolarSystem") { __instance._shipLogXmlAssets = new TextAsset[] { }; @@ -58,7 +58,7 @@ namespace NewHorizons.Patches RumorModeBuilder.UpdateEntryCuriosity(ref logEntry); } - Logger.Log("Ship Log Generation Complete For: " + Main.Instance.CurrentStarSystem, Logger.LogType.Log); + Logger.Log("Ship Log Generation Complete For: " + Main.Instance.CurrentStarSystem); } [HarmonyPrefix] @@ -157,7 +157,7 @@ namespace NewHorizons.Patches } } - Logger.Log("Map Mode Construction Complete", Logger.LogType.Log); + Logger.Log("Map Mode Construction Complete"); } [HarmonyPrefix] diff --git a/NewHorizons/Utility/DebugUtilities/DebugReload.cs b/NewHorizons/Utility/DebugUtilities/DebugReload.cs index ac48c7ad..eaa09373 100644 --- a/NewHorizons/Utility/DebugUtilities/DebugReload.cs +++ b/NewHorizons/Utility/DebugUtilities/DebugReload.cs @@ -29,7 +29,7 @@ namespace NewHorizons.Utility.DebugUtilities private static void ReloadConfigs() { - Logger.Log("Begin reload of config files...", Logger.LogType.Log); + Logger.Log("Begin reload of config files..."); Main.ResetConfigs(); diff --git a/NewHorizons/Utility/Logger.cs b/NewHorizons/Utility/Logger.cs index 5935b269..e204107b 100644 --- a/NewHorizons/Utility/Logger.cs +++ b/NewHorizons/Utility/Logger.cs @@ -1,4 +1,4 @@ -using OWML.Common; +using OWML.Common; using System; using System.ComponentModel; using UnityEngine; @@ -7,7 +7,7 @@ namespace NewHorizons.Utility public static class Logger { - private static LogType _logLevel = LogType.Error; + private static LogType _logLevel = LogType.Error; public static void UpdateLogLevel(LogType newLevel) { @@ -44,7 +44,11 @@ namespace NewHorizons.Utility if ((int)type < (int)_logLevel) return; Main.Instance.ModHelper.Console.WriteLine(Enum.GetName(typeof(LogType), type) + " : " + text, LogTypeToMessageType(type)); } - + + public static void LogVerbose(string text) + { + Log(text, LogType.Verbose); + } public static void Log(string text) { Log(text, LogType.Log); @@ -53,13 +57,14 @@ namespace NewHorizons.Utility { Log(text, LogType.Error); } - public static void LogWarning(string text) + public static void LogWarning(string text, bool isVerbose=false) { Log(text, LogType.Warning); } public enum LogType { - Todo, + Todo, + Verbose, Log, Warning, Error, diff --git a/NewHorizons/default-config.json b/NewHorizons/default-config.json index f5200a8d..146eb9fe 100644 --- a/NewHorizons/default-config.json +++ b/NewHorizons/default-config.json @@ -3,6 +3,7 @@ "settings": { "Debug": false, "Custom title screen": true, - "Default System Override": "" + "Default System Override": "", + "Verbose Logs": false } } \ No newline at end of file From f01f156569a133d13438651421b8431f73aa3254 Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Tue, 5 Jul 2022 17:51:35 -0400 Subject: [PATCH 04/18] fixed line endings --- .../Components/CloakSectorController.cs | 306 +++++++++--------- 1 file changed, 153 insertions(+), 153 deletions(-) diff --git a/NewHorizons/Components/CloakSectorController.cs b/NewHorizons/Components/CloakSectorController.cs index ac2dd46c..7d0bbf7b 100644 --- a/NewHorizons/Components/CloakSectorController.cs +++ b/NewHorizons/Components/CloakSectorController.cs @@ -1,153 +1,153 @@ -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -namespace NewHorizons.Components -{ - public class CloakSectorController : MonoBehaviour - { - private CloakFieldController _cloak; - private GameObject _root; - - private bool _isInitialized; - - private List _renderers = null; - private List _tessellatedRenderers = null; - private List _tessSphereToggles = null; - - public static bool isPlayerInside = false; - public static bool isProbeInside = false; - public static bool isShipInside = false; - - public void Init(CloakFieldController cloak, GameObject root) - { - _cloak = cloak; - _root = root; - - // Lets just clear these off idc - _cloak.OnPlayerEnter = new OWEvent(); - _cloak.OnPlayerExit = new OWEvent(); - _cloak.OnProbeEnter = new OWEvent(); - _cloak.OnProbeExit = new OWEvent(); - _cloak.OnShipEnter = new OWEvent(); - _cloak.OnShipExit = new OWEvent(); - - _cloak.OnPlayerEnter += OnPlayerEnter; - _cloak.OnPlayerExit += OnPlayerExit; - _cloak.OnProbeEnter += OnProbeEnter; - _cloak.OnProbeExit += OnProbeExit; - _cloak.OnShipEnter += OnShipEnter; - _cloak.OnShipExit += OnShipExit; - - _isInitialized = true; - } - - void OnDestroy() - { - if (_isInitialized) - { - _cloak.OnPlayerEnter -= OnPlayerEnter; - _cloak.OnPlayerExit -= OnPlayerExit; - } - } - - private void SetUpList() - { - _renderers = _root.GetComponentsInChildren().ToList(); - _tessellatedRenderers = _root.GetComponentsInChildren().ToList(); - _tessSphereToggles = _root.GetComponentsInChildren().ToList(); - } - - public void OnPlayerEnter() - { - SetUpList(); - - foreach (var renderer in _renderers) - { - renderer.forceRenderingOff = false; - } - - foreach (var tessellatedRenderer in _tessellatedRenderers) - { - tessellatedRenderer.enabled = true; - } - - foreach (var tessSphereSectorToggle in _tessSphereToggles) - { - tessSphereSectorToggle.OnEnterCloakField(); - } - - isPlayerInside = true; - GlobalMessenger.FireEvent("PlayerEnterCloakField"); - } - - public void OnPlayerExit() - { - SetUpList(); - - foreach (var renderer in _renderers) - { - renderer.forceRenderingOff = true; - } - - foreach (var tessellatedRenderer in _tessellatedRenderers) - { - tessellatedRenderer.enabled = false; - } - - foreach (var tessSphereSectorToggle in _tessSphereToggles) - { - tessSphereSectorToggle.OnExitCloakField(); - } - - isPlayerInside = false; - GlobalMessenger.FireEvent("PlayerExitCloakField"); - } - - public void OnProbeEnter() - { - isProbeInside = true; - GlobalMessenger.FireEvent("ProbeEnterCloakField"); - } - - public void OnProbeExit() - { - isProbeInside = false; - GlobalMessenger.FireEvent("ProbeExitCloakField"); - } - - public void OnShipEnter() - { - isShipInside = true; - GlobalMessenger.FireEvent("ShipEnterCloakField"); - } - - public void OnShipExit() - { - isShipInside = false; - GlobalMessenger.FireEvent("ShipExitCloakField"); - } - - public void EnableCloak() - { - SunLightController.RegisterSunOverrider(_cloak, 900); - _cloak._cloakSphereRenderer.SetActivation(true); - Shader.EnableKeyword("_CLOAKINGFIELDENABLED"); - _cloak._cloakVisualsEnabled = true; - } - - public void DisableCloak() - { - SunLightController.UnregisterSunOverrider(_cloak); - _cloak._cloakSphereRenderer.SetActivation(false); - Shader.DisableKeyword("_CLOAKINGFIELDENABLED"); - _cloak._cloakVisualsEnabled = false; - } - - public void SetReferenceFrameVolumeActive(bool active) => _cloak._referenceFrameVolume?.gameObject.SetActive(active); - public void EnableReferenceFrameVolume() => SetReferenceFrameVolumeActive(true); - public void DisableReferenceFrameVolume() => SetReferenceFrameVolumeActive(false); - - public void TurnOnMusic() => _cloak._hasTriggeredMusic = false; - public void TurnOffMusic() => _cloak._hasTriggeredMusic = true; - } -} +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace NewHorizons.Components +{ + public class CloakSectorController : MonoBehaviour + { + private CloakFieldController _cloak; + private GameObject _root; + + private bool _isInitialized; + + private List _renderers = null; + private List _tessellatedRenderers = null; + private List _tessSphereToggles = null; + + public static bool isPlayerInside = false; + public static bool isProbeInside = false; + public static bool isShipInside = false; + + public void Init(CloakFieldController cloak, GameObject root) + { + _cloak = cloak; + _root = root; + + // Lets just clear these off idc + _cloak.OnPlayerEnter = new OWEvent(); + _cloak.OnPlayerExit = new OWEvent(); + _cloak.OnProbeEnter = new OWEvent(); + _cloak.OnProbeExit = new OWEvent(); + _cloak.OnShipEnter = new OWEvent(); + _cloak.OnShipExit = new OWEvent(); + + _cloak.OnPlayerEnter += OnPlayerEnter; + _cloak.OnPlayerExit += OnPlayerExit; + _cloak.OnProbeEnter += OnProbeEnter; + _cloak.OnProbeExit += OnProbeExit; + _cloak.OnShipEnter += OnShipEnter; + _cloak.OnShipExit += OnShipExit; + + _isInitialized = true; + } + + void OnDestroy() + { + if (_isInitialized) + { + _cloak.OnPlayerEnter -= OnPlayerEnter; + _cloak.OnPlayerExit -= OnPlayerExit; + } + } + + private void SetUpList() + { + _renderers = _root.GetComponentsInChildren().ToList(); + _tessellatedRenderers = _root.GetComponentsInChildren().ToList(); + _tessSphereToggles = _root.GetComponentsInChildren().ToList(); + } + + public void OnPlayerEnter() + { + SetUpList(); + + foreach (var renderer in _renderers) + { + renderer.forceRenderingOff = false; + } + + foreach (var tessellatedRenderer in _tessellatedRenderers) + { + tessellatedRenderer.enabled = true; + } + + foreach (var tessSphereSectorToggle in _tessSphereToggles) + { + tessSphereSectorToggle.OnEnterCloakField(); + } + + isPlayerInside = true; + GlobalMessenger.FireEvent("PlayerEnterCloakField"); + } + + public void OnPlayerExit() + { + SetUpList(); + + foreach (var renderer in _renderers) + { + renderer.forceRenderingOff = true; + } + + foreach (var tessellatedRenderer in _tessellatedRenderers) + { + tessellatedRenderer.enabled = false; + } + + foreach (var tessSphereSectorToggle in _tessSphereToggles) + { + tessSphereSectorToggle.OnExitCloakField(); + } + + isPlayerInside = false; + GlobalMessenger.FireEvent("PlayerExitCloakField"); + } + + public void OnProbeEnter() + { + isProbeInside = true; + GlobalMessenger.FireEvent("ProbeEnterCloakField"); + } + + public void OnProbeExit() + { + isProbeInside = false; + GlobalMessenger.FireEvent("ProbeExitCloakField"); + } + + public void OnShipEnter() + { + isShipInside = true; + GlobalMessenger.FireEvent("ShipEnterCloakField"); + } + + public void OnShipExit() + { + isShipInside = false; + GlobalMessenger.FireEvent("ShipExitCloakField"); + } + + public void EnableCloak() + { + SunLightController.RegisterSunOverrider(_cloak, 900); + _cloak._cloakSphereRenderer.SetActivation(true); + Shader.EnableKeyword("_CLOAKINGFIELDENABLED"); + _cloak._cloakVisualsEnabled = true; + } + + public void DisableCloak() + { + SunLightController.UnregisterSunOverrider(_cloak); + _cloak._cloakSphereRenderer.SetActivation(false); + Shader.DisableKeyword("_CLOAKINGFIELDENABLED"); + _cloak._cloakVisualsEnabled = false; + } + + public void SetReferenceFrameVolumeActive(bool active) => _cloak._referenceFrameVolume?.gameObject.SetActive(active); + public void EnableReferenceFrameVolume() => SetReferenceFrameVolumeActive(true); + public void DisableReferenceFrameVolume() => SetReferenceFrameVolumeActive(false); + + public void TurnOnMusic() => _cloak._hasTriggeredMusic = false; + public void TurnOffMusic() => _cloak._hasTriggeredMusic = true; + } +} From 1be956004573aa90dde3d5eeb97a954071e3ad90 Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Tue, 5 Jul 2022 17:52:17 -0400 Subject: [PATCH 05/18] removed unneeded param --- NewHorizons/Utility/Logger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NewHorizons/Utility/Logger.cs b/NewHorizons/Utility/Logger.cs index e204107b..4fb24358 100644 --- a/NewHorizons/Utility/Logger.cs +++ b/NewHorizons/Utility/Logger.cs @@ -57,7 +57,7 @@ namespace NewHorizons.Utility { Log(text, LogType.Error); } - public static void LogWarning(string text, bool isVerbose=false) + public static void LogWarning(string text) { Log(text, LogType.Warning); } From 2e14d2a419a769e10d68f34d5f2def58e1ddad64 Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Tue, 5 Jul 2022 17:57:14 -0400 Subject: [PATCH 06/18] fixed outdated LogWarning call --- NewHorizons/Builder/Props/DetailBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index 9471e2eb..655bf4d8 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -47,7 +47,7 @@ namespace NewHorizons.Builder.Props var childObj = GameObject.Find($"{detailPath}/{childPath}"); if (childObj == null) { - Logger.LogWarning($"Couldn't find \"{childPath}\". Including disabled game objects in search.", true); + Logger.LogWarning($"Couldn't find \"{childPath}\". Including disabled game objects in search."); childObj = SearchUtilities.Find($"{detailPath}/{childPath}"); } From 44f6dfa0705af64a84e50a6aa2d89733590b1e02 Mon Sep 17 00:00:00 2001 From: Will Corby Date: Tue, 5 Jul 2022 15:24:22 -0700 Subject: [PATCH 07/18] do da hokey pokey make it so verbose logs can still happen even if debug mode is off --- NewHorizons/Main.cs | 1132 +++++++++++++++++++++---------------------- 1 file changed, 566 insertions(+), 566 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 1f7e52a0..09578576 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -1,570 +1,570 @@ -using HarmonyLib; -using NewHorizons.AchievementsPlus; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External; -using NewHorizons.External.Configs; -using NewHorizons.Handlers; -using NewHorizons.Utility; -using NewHorizons.Utility.DebugMenu; -using NewHorizons.Utility.DebugUtilities; -using NewHorizons.VoiceActing; -using OWML.Common; -using OWML.ModHelper; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons -{ - - public class Main : ModBehaviour - { - public static AssetBundle NHAssetBundle { get; private set; } - public static Main Instance { get; private set; } - - // Settings +using HarmonyLib; +using NewHorizons.AchievementsPlus; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.External.Configs; +using NewHorizons.Handlers; +using NewHorizons.Utility; +using NewHorizons.Utility.DebugMenu; +using NewHorizons.Utility.DebugUtilities; +using NewHorizons.VoiceActing; +using OWML.Common; +using OWML.ModHelper; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons +{ + + public class Main : ModBehaviour + { + public static AssetBundle NHAssetBundle { get; private set; } + public static Main Instance { get; private set; } + + // Settings public static bool Debug { get; private set; } - public static bool VerboseLogs { get; private set; } - private static bool _useCustomTitleScreen; - private static bool _wasConfigured = false; - private static string _defaultSystemOverride; - - public static Dictionary SystemDict = new Dictionary(); - public static Dictionary> BodyDict = new Dictionary>(); - public static List MountedAddons = new List(); - - public static float SecondsLeftInLoop = -1; - - public static bool IsSystemReady { get; private set; } - public static float FurthestOrbit { get; set; } = 50000f; - - public string CurrentStarSystem { get { return Instance._currentStarSystem; } } - public bool IsWarpingFromShip { get; private set; } = false; - public bool IsWarpingFromVessel { get; private set; } = false; - public bool WearingSuit { get; private set; } = false; - - public bool IsChangingStarSystem { get; private set; } = false; - - public static bool HasWarpDrive { get; private set; } = false; - - private string _defaultStarSystem = "SolarSystem"; - private string _currentStarSystem = "SolarSystem"; - private bool _firstLoad = true; - private ShipWarpController _shipWarpController; - - // API events - public class StarSystemEvent : UnityEvent { } - public StarSystemEvent OnChangeStarSystem; - public StarSystemEvent OnStarSystemLoaded; - - // For warping to the eye system - private GameObject _ship; - - public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } - - public override object GetApi() - { - return new NewHorizonsApi(); - } - - public override void Configure(IModConfig config) - { - Logger.Log("Settings changed"); - - var currentScene = SceneManager.GetActiveScene().name; - + public static bool VerboseLogs { get; private set; } + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; + private static string _defaultSystemOverride; + + public static Dictionary SystemDict = new Dictionary(); + public static Dictionary> BodyDict = new Dictionary>(); + public static List MountedAddons = new List(); + + public static float SecondsLeftInLoop = -1; + + public static bool IsSystemReady { get; private set; } + public static float FurthestOrbit { get; set; } = 50000f; + + public string CurrentStarSystem { get { return Instance._currentStarSystem; } } + public bool IsWarpingFromShip { get; private set; } = false; + public bool IsWarpingFromVessel { get; private set; } = false; + public bool WearingSuit { get; private set; } = false; + + public bool IsChangingStarSystem { get; private set; } = false; + + public static bool HasWarpDrive { get; private set; } = false; + + private string _defaultStarSystem = "SolarSystem"; + private string _currentStarSystem = "SolarSystem"; + private bool _firstLoad = true; + private ShipWarpController _shipWarpController; + + // API events + public class StarSystemEvent : UnityEvent { } + public StarSystemEvent OnChangeStarSystem; + public StarSystemEvent OnStarSystemLoaded; + + // For warping to the eye system + private GameObject _ship; + + public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } + + public override object GetApi() + { + return new NewHorizonsApi(); + } + + public override void Configure(IModConfig config) + { + Logger.Log("Settings changed"); + + var currentScene = SceneManager.GetActiveScene().name; + Debug = config.GetSettingsValue("Debug"); - VerboseLogs = config.GetSettingsValue("Verbose Logs"); - - if (currentScene == "SolarSystem") - { - DebugReload.UpdateReloadButton(); - DebugMenu.UpdatePauseMenuButton(); - } - - if (Debug && VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); + VerboseLogs = config.GetSettingsValue("Verbose Logs"); + + if (currentScene == "SolarSystem") + { + DebugReload.UpdateReloadButton(); + DebugMenu.UpdatePauseMenuButton(); + } + + if (VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); else Logger.UpdateLogLevel(Logger.LogType.Error); - - _defaultSystemOverride = config.GetSettingsValue("Default System Override"); - - // Else it doesn't get set idk - if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - } - - var wasUsingCustomTitleScreen = _useCustomTitleScreen; - _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); - // Reload the title screen if this was updated on it - // Don't reload if we haven't configured yet (called on game start) - if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) - { - Logger.Log("Reloading"); - SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); - } - - _wasConfigured = true; - } - - public static void ResetConfigs(bool resetTranslation = true) - { - BodyDict.Clear(); - SystemDict.Clear(); - - BodyDict["SolarSystem"] = new List(); - BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr - SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) - { - Config = - { - destroyStockPlanets = false, - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[5]{ 0,3,2,1,5 }, - y = new int[5]{ 4,5,3,2,1 }, - z = new int[5]{ 4,1,2,5,0 } - } - } - }; - SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) - { - Config = - { - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[3]{ 1,5,4 }, - y = new int[4]{ 3,0,1,4 }, - z = new int[6]{ 1,2,3,0,5,4 } - } - } - }; - - if (!resetTranslation) return; - TranslationHandler.ClearTables(); - TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); - } - - public void Start() - { - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - OnChangeStarSystem = new StarSystemEvent(); - OnStarSystemLoaded = new StarSystemEvent(); - - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - - Instance = this; - GlobalMessenger.AddListener("PlayerDeath", OnDeath); - - GlobalMessenger.AddListener("WakeUp", OnWakeUp); - NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); - VesselWarpHandler.Initialize(); - - ResetConfigs(resetTranslation: false); - - Logger.Log("Begin load of config files..."); - - try - { - LoadConfigs(this); - } - catch (Exception) - { - Logger.LogWarning("Couldn't find planets folder"); - } - - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); - Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; - - AchievementHandler.Init(); - VoiceHandler.Init(); - } - - public void OnDestroy() - { - Logger.Log($"Destroying NewHorizons"); - SceneManager.sceneLoaded -= OnSceneLoaded; - GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); - GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); - - AchievementHandler.OnDestroy(); - } - - private static void OnWakeUp() - { - IsSystemReady = true; - } - - private void OnSceneUnloaded(Scene scene) - { - SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - IsSystemReady = false; - } - - private void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); - - // Set time loop stuff if its enabled and if we're warping to a new place - if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) - { - TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); - // Prevent the OPC from firing - var launchController = GameObject.FindObjectOfType(); - if (launchController != null) - { - GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); - foreach (var fakeDebris in launchController._fakeDebrisBodies) - { - fakeDebris.gameObject.SetActive(false); - } - launchController.enabled = false; - } - var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); - } - - // Reset this - SecondsLeftInLoop = -1; - - IsChangingStarSystem = false; - - if (scene.name == "TitleScreen" && _useCustomTitleScreen) - { - TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); - TitleSceneHandler.InitSubtitles(); - } - - if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) - { - if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); - _ship.transform.position = new Vector3(50, 0, 0); - _ship.SetActive(true); - } - - if (scene.name == "SolarSystem") - { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - - if (_ship != null) - { - _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); - DontDestroyOnLoad(_ship); - } - - IsSystemReady = false; - - NewHorizonsData.Load(); - SignalBuilder.Init(); - AstroObjectLocator.Init(); - OWAssetHandler.Init(); - PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); - VesselWarpHandler.LoadVessel(); - SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); - LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); - - // Warp drive - StarChartHandler.Init(SystemDict.Values.ToArray()); - HasWarpDrive = StarChartHandler.CanWarp(); - _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); - _shipWarpController.Init(); - if (HasWarpDrive == true) EnableWarpDrive(); - - var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; - var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; - Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); - - IsWarpingFromShip = false; - IsWarpingFromVessel = false; - - var map = GameObject.FindObjectOfType(); - if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; - - // Fix the map satellite - SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); - - try - { - Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); - Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); - } - catch (Exception e) - { - Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); - } - } - else - { - // Reset back to original solar system after going to main menu. - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - } - } - - // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here - private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) - { - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. - - if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); - else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); - else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); - - VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); - } - - public void EnableWarpDrive() - { - Logger.Log("Setting up warp drive"); - PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); - HasWarpDrive = true; - } - - - #region Load - public void LoadConfigs(IModBehaviour mod) - { - try - { - if (_firstLoad) - { - MountedAddons.Add(mod); - } - var folder = mod.ModHelper.Manifest.ModFolderPath; - - // Load systems first so that when we load bodies later we can check for missing ones - if (Directory.Exists(folder + @"systems\")) - { - foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) - { - var name = Path.GetFileNameWithoutExtension(file); - - Logger.Log($"Loading system {name}"); - - var relativePath = file.Replace(folder, ""); - var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); - starSystemConfig.FixCoordinates(); - - if (starSystemConfig.startHere) - { - // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around - if (name != "SolarSystem") - { - SetDefaultSystem(name); - _currentStarSystem = name; - } - } - - if (SystemDict.ContainsKey(name)) - { - SystemDict[name].Config.Merge(starSystemConfig); - } - else - { - SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); - } - } - } - if (Directory.Exists(folder + "planets")) - { - foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) - { - var relativeDirectory = file.Replace(folder, ""); - var body = LoadConfig(mod, relativeDirectory); - - if (body != null) - { - // Wanna track the spawn point of each system - if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; - - // Add the new planet to the planet dictionary - if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); - BodyDict[body.Config.starSystem].Add(body); - } - } - } - // Has to go before translations for achievements - if (File.Exists(folder + "addon-manifest.json")) - { - var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); - - AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); - } - if (Directory.Exists(folder + @"translations\")) - { - LoadTranslations(folder, mod); - } - - } - catch (Exception ex) - { - Logger.LogError($"{ex.Message}, {ex.StackTrace}"); - } - } - - private void LoadTranslations(string folder, IModBehaviour mod) - { - var foundFile = false; - foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) - { - if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; - - var relativeFile = $"translations/{language.ToString().ToLower()}.json"; - - if (File.Exists($"{folder}{relativeFile}")) - { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); - - var config = new TranslationConfig($"{folder}{relativeFile}"); - - foundFile = true; - - TranslationHandler.RegisterTranslation(language, config); - - if (AchievementHandler.Enabled) - { - AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); - } - } - } - if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); - } - - public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) - { - NewHorizonsBody body = null; - try - { - var config = mod.ModHelper.Storage.Load(relativePath); - if (config == null) - { - Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); - return null; - } - - Logger.Log($"Loaded {config.name}"); - - if (!SystemDict.ContainsKey(config.starSystem)) - { - // Since we didn't load it earlier there shouldn't be a star system config - var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); - if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); - else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); - - starSystemConfig.FixCoordinates(); - - var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); - - SystemDict.Add(config.starSystem, system); - - BodyDict.Add(config.starSystem, new List()); - } - - // Has to happen after we make sure theres a system config - config.MigrateAndValidate(); - - body = new NewHorizonsBody(config, mod, relativePath); - } - catch (Exception e) - { - Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); - } - - return body; - } - - public void SetDefaultSystem(string defaultSystem) - { - _defaultStarSystem = defaultSystem; - } - - #endregion Load - - #region Change star system - public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) - { - if (IsChangingStarSystem) return; - - IsWarpingFromShip = warp; - IsWarpingFromVessel = vessel; - OnChangeStarSystem?.Invoke(newStarSystem); - - Logger.Log($"Warping to {newStarSystem}"); - if (warp && _shipWarpController) _shipWarpController.WarpOut(); - IsChangingStarSystem = true; - WearingSuit = PlayerState.IsWearingSuit(); - - // We kill them so they don't move as much - Locator.GetDeathManager().KillPlayer(DeathType.Meditation); - - OWScene sceneToLoad; - - if (newStarSystem == "EyeOfTheUniverse") - { - PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); - sceneToLoad = OWScene.EyeOfTheUniverse; - } - else - { - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); - else SecondsLeftInLoop = -1; - - sceneToLoad = OWScene.SolarSystem; - } - - _currentStarSystem = newStarSystem; - - LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); - } - - void OnDeath(DeathType _) - { - // We reset the solar system on death (unless we just killed the player) - if (!IsChangingStarSystem) - { - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - - IsWarpingFromShip = false; - } - } - #endregion Change star system - } -} + + _defaultSystemOverride = config.GetSettingsValue("Default System Override"); + + // Else it doesn't get set idk + if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + } + + var wasUsingCustomTitleScreen = _useCustomTitleScreen; + _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); + // Reload the title screen if this was updated on it + // Don't reload if we haven't configured yet (called on game start) + if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) + { + Logger.Log("Reloading"); + SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); + } + + _wasConfigured = true; + } + + public static void ResetConfigs(bool resetTranslation = true) + { + BodyDict.Clear(); + SystemDict.Clear(); + + BodyDict["SolarSystem"] = new List(); + BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) + { + Config = + { + destroyStockPlanets = false, + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[5]{ 0,3,2,1,5 }, + y = new int[5]{ 4,5,3,2,1 }, + z = new int[5]{ 4,1,2,5,0 } + } + } + }; + SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) + { + Config = + { + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[3]{ 1,5,4 }, + y = new int[4]{ 3,0,1,4 }, + z = new int[6]{ 1,2,3,0,5,4 } + } + } + }; + + if (!resetTranslation) return; + TranslationHandler.ClearTables(); + TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); + } + + public void Start() + { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + + OnChangeStarSystem = new StarSystemEvent(); + OnStarSystemLoaded = new StarSystemEvent(); + + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; + + Instance = this; + GlobalMessenger.AddListener("PlayerDeath", OnDeath); + + GlobalMessenger.AddListener("WakeUp", OnWakeUp); + NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); + VesselWarpHandler.Initialize(); + + ResetConfigs(resetTranslation: false); + + Logger.Log("Begin load of config files..."); + + try + { + LoadConfigs(this); + } + catch (Exception) + { + Logger.LogWarning("Couldn't find planets folder"); + } + + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); + Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; + + AchievementHandler.Init(); + VoiceHandler.Init(); + } + + public void OnDestroy() + { + Logger.Log($"Destroying NewHorizons"); + SceneManager.sceneLoaded -= OnSceneLoaded; + GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); + GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); + + AchievementHandler.OnDestroy(); + } + + private static void OnWakeUp() + { + IsSystemReady = true; + } + + private void OnSceneUnloaded(Scene scene) + { + SearchUtilities.ClearCache(); + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + IsSystemReady = false; + } + + private void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + Logger.Log($"Scene Loaded: {scene.name} {mode}"); + + // Set time loop stuff if its enabled and if we're warping to a new place + if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) + { + TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); + // Prevent the OPC from firing + var launchController = GameObject.FindObjectOfType(); + if (launchController != null) + { + GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); + foreach (var fakeDebris in launchController._fakeDebrisBodies) + { + fakeDebris.gameObject.SetActive(false); + } + launchController.enabled = false; + } + var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); + if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + } + + // Reset this + SecondsLeftInLoop = -1; + + IsChangingStarSystem = false; + + if (scene.name == "TitleScreen" && _useCustomTitleScreen) + { + TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); + TitleSceneHandler.InitSubtitles(); + } + + if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) + { + if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); + _ship.transform.position = new Vector3(50, 0, 0); + _ship.SetActive(true); + } + + if (scene.name == "SolarSystem") + { + foreach (var body in GameObject.FindObjectsOfType()) + { + Logger.Log($"{body.name}, {body.transform.rotation}"); + } + + if (_ship != null) + { + _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); + DontDestroyOnLoad(_ship); + } + + IsSystemReady = false; + + NewHorizonsData.Load(); + SignalBuilder.Init(); + AstroObjectLocator.Init(); + OWAssetHandler.Init(); + PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); + VesselWarpHandler.LoadVessel(); + SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); + LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); + + // Warp drive + StarChartHandler.Init(SystemDict.Values.ToArray()); + HasWarpDrive = StarChartHandler.CanWarp(); + _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); + _shipWarpController.Init(); + if (HasWarpDrive == true) EnableWarpDrive(); + + var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; + var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; + Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); + + IsWarpingFromShip = false; + IsWarpingFromVessel = false; + + var map = GameObject.FindObjectOfType(); + if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; + + // Fix the map satellite + SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); + + try + { + Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); + Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); + } + catch (Exception e) + { + Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); + } + } + else + { + // Reset back to original solar system after going to main menu. + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + } + } + + // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here + private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) + { + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. + + if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); + else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); + else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); + + VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); + } + + public void EnableWarpDrive() + { + Logger.Log("Setting up warp drive"); + PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); + HasWarpDrive = true; + } + + + #region Load + public void LoadConfigs(IModBehaviour mod) + { + try + { + if (_firstLoad) + { + MountedAddons.Add(mod); + } + var folder = mod.ModHelper.Manifest.ModFolderPath; + + // Load systems first so that when we load bodies later we can check for missing ones + if (Directory.Exists(folder + @"systems\")) + { + foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) + { + var name = Path.GetFileNameWithoutExtension(file); + + Logger.Log($"Loading system {name}"); + + var relativePath = file.Replace(folder, ""); + var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); + starSystemConfig.FixCoordinates(); + + if (starSystemConfig.startHere) + { + // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around + if (name != "SolarSystem") + { + SetDefaultSystem(name); + _currentStarSystem = name; + } + } + + if (SystemDict.ContainsKey(name)) + { + SystemDict[name].Config.Merge(starSystemConfig); + } + else + { + SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); + } + } + } + if (Directory.Exists(folder + "planets")) + { + foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) + { + var relativeDirectory = file.Replace(folder, ""); + var body = LoadConfig(mod, relativeDirectory); + + if (body != null) + { + // Wanna track the spawn point of each system + if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; + + // Add the new planet to the planet dictionary + if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); + BodyDict[body.Config.starSystem].Add(body); + } + } + } + // Has to go before translations for achievements + if (File.Exists(folder + "addon-manifest.json")) + { + var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); + + AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); + } + if (Directory.Exists(folder + @"translations\")) + { + LoadTranslations(folder, mod); + } + + } + catch (Exception ex) + { + Logger.LogError($"{ex.Message}, {ex.StackTrace}"); + } + } + + private void LoadTranslations(string folder, IModBehaviour mod) + { + var foundFile = false; + foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) + { + if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; + + var relativeFile = $"translations/{language.ToString().ToLower()}.json"; + + if (File.Exists($"{folder}{relativeFile}")) + { + Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + + var config = new TranslationConfig($"{folder}{relativeFile}"); + + foundFile = true; + + TranslationHandler.RegisterTranslation(language, config); + + if (AchievementHandler.Enabled) + { + AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); + } + } + } + if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); + } + + public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) + { + NewHorizonsBody body = null; + try + { + var config = mod.ModHelper.Storage.Load(relativePath); + if (config == null) + { + Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); + return null; + } + + Logger.Log($"Loaded {config.name}"); + + if (!SystemDict.ContainsKey(config.starSystem)) + { + // Since we didn't load it earlier there shouldn't be a star system config + var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); + if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); + else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); + + starSystemConfig.FixCoordinates(); + + var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); + + SystemDict.Add(config.starSystem, system); + + BodyDict.Add(config.starSystem, new List()); + } + + // Has to happen after we make sure theres a system config + config.MigrateAndValidate(); + + body = new NewHorizonsBody(config, mod, relativePath); + } + catch (Exception e) + { + Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); + } + + return body; + } + + public void SetDefaultSystem(string defaultSystem) + { + _defaultStarSystem = defaultSystem; + } + + #endregion Load + + #region Change star system + public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) + { + if (IsChangingStarSystem) return; + + IsWarpingFromShip = warp; + IsWarpingFromVessel = vessel; + OnChangeStarSystem?.Invoke(newStarSystem); + + Logger.Log($"Warping to {newStarSystem}"); + if (warp && _shipWarpController) _shipWarpController.WarpOut(); + IsChangingStarSystem = true; + WearingSuit = PlayerState.IsWearingSuit(); + + // We kill them so they don't move as much + Locator.GetDeathManager().KillPlayer(DeathType.Meditation); + + OWScene sceneToLoad; + + if (newStarSystem == "EyeOfTheUniverse") + { + PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); + sceneToLoad = OWScene.EyeOfTheUniverse; + } + else + { + if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); + else SecondsLeftInLoop = -1; + + sceneToLoad = OWScene.SolarSystem; + } + + _currentStarSystem = newStarSystem; + + LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); + } + + void OnDeath(DeathType _) + { + // We reset the solar system on death (unless we just killed the player) + if (!IsChangingStarSystem) + { + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + + IsWarpingFromShip = false; + } + } + #endregion Change star system + } +} From be31f42b8e0704f75cc7f9f9aea7faa9fdc6a2d0 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 15:35:00 -0700 Subject: [PATCH 08/18] Revert "do da hokey pokey" This reverts commit 44f6dfa0705af64a84e50a6aa2d89733590b1e02. --- NewHorizons/Main.cs | 1132 +++++++++++++++++++++---------------------- 1 file changed, 566 insertions(+), 566 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 09578576..1f7e52a0 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -1,570 +1,570 @@ -using HarmonyLib; -using NewHorizons.AchievementsPlus; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External; -using NewHorizons.External.Configs; -using NewHorizons.Handlers; -using NewHorizons.Utility; -using NewHorizons.Utility.DebugMenu; -using NewHorizons.Utility.DebugUtilities; -using NewHorizons.VoiceActing; -using OWML.Common; -using OWML.ModHelper; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons -{ - - public class Main : ModBehaviour - { - public static AssetBundle NHAssetBundle { get; private set; } - public static Main Instance { get; private set; } - - // Settings +using HarmonyLib; +using NewHorizons.AchievementsPlus; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.External.Configs; +using NewHorizons.Handlers; +using NewHorizons.Utility; +using NewHorizons.Utility.DebugMenu; +using NewHorizons.Utility.DebugUtilities; +using NewHorizons.VoiceActing; +using OWML.Common; +using OWML.ModHelper; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons +{ + + public class Main : ModBehaviour + { + public static AssetBundle NHAssetBundle { get; private set; } + public static Main Instance { get; private set; } + + // Settings public static bool Debug { get; private set; } - public static bool VerboseLogs { get; private set; } - private static bool _useCustomTitleScreen; - private static bool _wasConfigured = false; - private static string _defaultSystemOverride; - - public static Dictionary SystemDict = new Dictionary(); - public static Dictionary> BodyDict = new Dictionary>(); - public static List MountedAddons = new List(); - - public static float SecondsLeftInLoop = -1; - - public static bool IsSystemReady { get; private set; } - public static float FurthestOrbit { get; set; } = 50000f; - - public string CurrentStarSystem { get { return Instance._currentStarSystem; } } - public bool IsWarpingFromShip { get; private set; } = false; - public bool IsWarpingFromVessel { get; private set; } = false; - public bool WearingSuit { get; private set; } = false; - - public bool IsChangingStarSystem { get; private set; } = false; - - public static bool HasWarpDrive { get; private set; } = false; - - private string _defaultStarSystem = "SolarSystem"; - private string _currentStarSystem = "SolarSystem"; - private bool _firstLoad = true; - private ShipWarpController _shipWarpController; - - // API events - public class StarSystemEvent : UnityEvent { } - public StarSystemEvent OnChangeStarSystem; - public StarSystemEvent OnStarSystemLoaded; - - // For warping to the eye system - private GameObject _ship; - - public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } - - public override object GetApi() - { - return new NewHorizonsApi(); - } - - public override void Configure(IModConfig config) - { - Logger.Log("Settings changed"); - - var currentScene = SceneManager.GetActiveScene().name; - + public static bool VerboseLogs { get; private set; } + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; + private static string _defaultSystemOverride; + + public static Dictionary SystemDict = new Dictionary(); + public static Dictionary> BodyDict = new Dictionary>(); + public static List MountedAddons = new List(); + + public static float SecondsLeftInLoop = -1; + + public static bool IsSystemReady { get; private set; } + public static float FurthestOrbit { get; set; } = 50000f; + + public string CurrentStarSystem { get { return Instance._currentStarSystem; } } + public bool IsWarpingFromShip { get; private set; } = false; + public bool IsWarpingFromVessel { get; private set; } = false; + public bool WearingSuit { get; private set; } = false; + + public bool IsChangingStarSystem { get; private set; } = false; + + public static bool HasWarpDrive { get; private set; } = false; + + private string _defaultStarSystem = "SolarSystem"; + private string _currentStarSystem = "SolarSystem"; + private bool _firstLoad = true; + private ShipWarpController _shipWarpController; + + // API events + public class StarSystemEvent : UnityEvent { } + public StarSystemEvent OnChangeStarSystem; + public StarSystemEvent OnStarSystemLoaded; + + // For warping to the eye system + private GameObject _ship; + + public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } + + public override object GetApi() + { + return new NewHorizonsApi(); + } + + public override void Configure(IModConfig config) + { + Logger.Log("Settings changed"); + + var currentScene = SceneManager.GetActiveScene().name; + Debug = config.GetSettingsValue("Debug"); - VerboseLogs = config.GetSettingsValue("Verbose Logs"); - - if (currentScene == "SolarSystem") - { - DebugReload.UpdateReloadButton(); - DebugMenu.UpdatePauseMenuButton(); - } - - if (VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); + VerboseLogs = config.GetSettingsValue("Verbose Logs"); + + if (currentScene == "SolarSystem") + { + DebugReload.UpdateReloadButton(); + DebugMenu.UpdatePauseMenuButton(); + } + + if (Debug && VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); else Logger.UpdateLogLevel(Logger.LogType.Error); - - _defaultSystemOverride = config.GetSettingsValue("Default System Override"); - - // Else it doesn't get set idk - if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - } - - var wasUsingCustomTitleScreen = _useCustomTitleScreen; - _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); - // Reload the title screen if this was updated on it - // Don't reload if we haven't configured yet (called on game start) - if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) - { - Logger.Log("Reloading"); - SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); - } - - _wasConfigured = true; - } - - public static void ResetConfigs(bool resetTranslation = true) - { - BodyDict.Clear(); - SystemDict.Clear(); - - BodyDict["SolarSystem"] = new List(); - BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr - SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) - { - Config = - { - destroyStockPlanets = false, - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[5]{ 0,3,2,1,5 }, - y = new int[5]{ 4,5,3,2,1 }, - z = new int[5]{ 4,1,2,5,0 } - } - } - }; - SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) - { - Config = - { - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[3]{ 1,5,4 }, - y = new int[4]{ 3,0,1,4 }, - z = new int[6]{ 1,2,3,0,5,4 } - } - } - }; - - if (!resetTranslation) return; - TranslationHandler.ClearTables(); - TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); - } - - public void Start() - { - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - OnChangeStarSystem = new StarSystemEvent(); - OnStarSystemLoaded = new StarSystemEvent(); - - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - - Instance = this; - GlobalMessenger.AddListener("PlayerDeath", OnDeath); - - GlobalMessenger.AddListener("WakeUp", OnWakeUp); - NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); - VesselWarpHandler.Initialize(); - - ResetConfigs(resetTranslation: false); - - Logger.Log("Begin load of config files..."); - - try - { - LoadConfigs(this); - } - catch (Exception) - { - Logger.LogWarning("Couldn't find planets folder"); - } - - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); - Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; - - AchievementHandler.Init(); - VoiceHandler.Init(); - } - - public void OnDestroy() - { - Logger.Log($"Destroying NewHorizons"); - SceneManager.sceneLoaded -= OnSceneLoaded; - GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); - GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); - - AchievementHandler.OnDestroy(); - } - - private static void OnWakeUp() - { - IsSystemReady = true; - } - - private void OnSceneUnloaded(Scene scene) - { - SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - IsSystemReady = false; - } - - private void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); - - // Set time loop stuff if its enabled and if we're warping to a new place - if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) - { - TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); - // Prevent the OPC from firing - var launchController = GameObject.FindObjectOfType(); - if (launchController != null) - { - GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); - foreach (var fakeDebris in launchController._fakeDebrisBodies) - { - fakeDebris.gameObject.SetActive(false); - } - launchController.enabled = false; - } - var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); - } - - // Reset this - SecondsLeftInLoop = -1; - - IsChangingStarSystem = false; - - if (scene.name == "TitleScreen" && _useCustomTitleScreen) - { - TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); - TitleSceneHandler.InitSubtitles(); - } - - if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) - { - if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); - _ship.transform.position = new Vector3(50, 0, 0); - _ship.SetActive(true); - } - - if (scene.name == "SolarSystem") - { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - - if (_ship != null) - { - _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); - DontDestroyOnLoad(_ship); - } - - IsSystemReady = false; - - NewHorizonsData.Load(); - SignalBuilder.Init(); - AstroObjectLocator.Init(); - OWAssetHandler.Init(); - PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); - VesselWarpHandler.LoadVessel(); - SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); - LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); - - // Warp drive - StarChartHandler.Init(SystemDict.Values.ToArray()); - HasWarpDrive = StarChartHandler.CanWarp(); - _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); - _shipWarpController.Init(); - if (HasWarpDrive == true) EnableWarpDrive(); - - var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; - var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; - Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); - - IsWarpingFromShip = false; - IsWarpingFromVessel = false; - - var map = GameObject.FindObjectOfType(); - if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; - - // Fix the map satellite - SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); - - try - { - Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); - Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); - } - catch (Exception e) - { - Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); - } - } - else - { - // Reset back to original solar system after going to main menu. - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - } - } - - // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here - private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) - { - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. - - if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); - else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); - else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); - - VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); - } - - public void EnableWarpDrive() - { - Logger.Log("Setting up warp drive"); - PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); - HasWarpDrive = true; - } - - - #region Load - public void LoadConfigs(IModBehaviour mod) - { - try - { - if (_firstLoad) - { - MountedAddons.Add(mod); - } - var folder = mod.ModHelper.Manifest.ModFolderPath; - - // Load systems first so that when we load bodies later we can check for missing ones - if (Directory.Exists(folder + @"systems\")) - { - foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) - { - var name = Path.GetFileNameWithoutExtension(file); - - Logger.Log($"Loading system {name}"); - - var relativePath = file.Replace(folder, ""); - var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); - starSystemConfig.FixCoordinates(); - - if (starSystemConfig.startHere) - { - // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around - if (name != "SolarSystem") - { - SetDefaultSystem(name); - _currentStarSystem = name; - } - } - - if (SystemDict.ContainsKey(name)) - { - SystemDict[name].Config.Merge(starSystemConfig); - } - else - { - SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); - } - } - } - if (Directory.Exists(folder + "planets")) - { - foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) - { - var relativeDirectory = file.Replace(folder, ""); - var body = LoadConfig(mod, relativeDirectory); - - if (body != null) - { - // Wanna track the spawn point of each system - if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; - - // Add the new planet to the planet dictionary - if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); - BodyDict[body.Config.starSystem].Add(body); - } - } - } - // Has to go before translations for achievements - if (File.Exists(folder + "addon-manifest.json")) - { - var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); - - AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); - } - if (Directory.Exists(folder + @"translations\")) - { - LoadTranslations(folder, mod); - } - - } - catch (Exception ex) - { - Logger.LogError($"{ex.Message}, {ex.StackTrace}"); - } - } - - private void LoadTranslations(string folder, IModBehaviour mod) - { - var foundFile = false; - foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) - { - if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; - - var relativeFile = $"translations/{language.ToString().ToLower()}.json"; - - if (File.Exists($"{folder}{relativeFile}")) - { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); - - var config = new TranslationConfig($"{folder}{relativeFile}"); - - foundFile = true; - - TranslationHandler.RegisterTranslation(language, config); - - if (AchievementHandler.Enabled) - { - AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); - } - } - } - if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); - } - - public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) - { - NewHorizonsBody body = null; - try - { - var config = mod.ModHelper.Storage.Load(relativePath); - if (config == null) - { - Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); - return null; - } - - Logger.Log($"Loaded {config.name}"); - - if (!SystemDict.ContainsKey(config.starSystem)) - { - // Since we didn't load it earlier there shouldn't be a star system config - var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); - if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); - else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); - - starSystemConfig.FixCoordinates(); - - var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); - - SystemDict.Add(config.starSystem, system); - - BodyDict.Add(config.starSystem, new List()); - } - - // Has to happen after we make sure theres a system config - config.MigrateAndValidate(); - - body = new NewHorizonsBody(config, mod, relativePath); - } - catch (Exception e) - { - Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); - } - - return body; - } - - public void SetDefaultSystem(string defaultSystem) - { - _defaultStarSystem = defaultSystem; - } - - #endregion Load - - #region Change star system - public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) - { - if (IsChangingStarSystem) return; - - IsWarpingFromShip = warp; - IsWarpingFromVessel = vessel; - OnChangeStarSystem?.Invoke(newStarSystem); - - Logger.Log($"Warping to {newStarSystem}"); - if (warp && _shipWarpController) _shipWarpController.WarpOut(); - IsChangingStarSystem = true; - WearingSuit = PlayerState.IsWearingSuit(); - - // We kill them so they don't move as much - Locator.GetDeathManager().KillPlayer(DeathType.Meditation); - - OWScene sceneToLoad; - - if (newStarSystem == "EyeOfTheUniverse") - { - PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); - sceneToLoad = OWScene.EyeOfTheUniverse; - } - else - { - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); - else SecondsLeftInLoop = -1; - - sceneToLoad = OWScene.SolarSystem; - } - - _currentStarSystem = newStarSystem; - - LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); - } - - void OnDeath(DeathType _) - { - // We reset the solar system on death (unless we just killed the player) - if (!IsChangingStarSystem) - { - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - - IsWarpingFromShip = false; - } - } - #endregion Change star system - } -} + + _defaultSystemOverride = config.GetSettingsValue("Default System Override"); + + // Else it doesn't get set idk + if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + } + + var wasUsingCustomTitleScreen = _useCustomTitleScreen; + _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); + // Reload the title screen if this was updated on it + // Don't reload if we haven't configured yet (called on game start) + if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) + { + Logger.Log("Reloading"); + SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); + } + + _wasConfigured = true; + } + + public static void ResetConfigs(bool resetTranslation = true) + { + BodyDict.Clear(); + SystemDict.Clear(); + + BodyDict["SolarSystem"] = new List(); + BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) + { + Config = + { + destroyStockPlanets = false, + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[5]{ 0,3,2,1,5 }, + y = new int[5]{ 4,5,3,2,1 }, + z = new int[5]{ 4,1,2,5,0 } + } + } + }; + SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) + { + Config = + { + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[3]{ 1,5,4 }, + y = new int[4]{ 3,0,1,4 }, + z = new int[6]{ 1,2,3,0,5,4 } + } + } + }; + + if (!resetTranslation) return; + TranslationHandler.ClearTables(); + TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); + } + + public void Start() + { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + + OnChangeStarSystem = new StarSystemEvent(); + OnStarSystemLoaded = new StarSystemEvent(); + + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; + + Instance = this; + GlobalMessenger.AddListener("PlayerDeath", OnDeath); + + GlobalMessenger.AddListener("WakeUp", OnWakeUp); + NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); + VesselWarpHandler.Initialize(); + + ResetConfigs(resetTranslation: false); + + Logger.Log("Begin load of config files..."); + + try + { + LoadConfigs(this); + } + catch (Exception) + { + Logger.LogWarning("Couldn't find planets folder"); + } + + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); + Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; + + AchievementHandler.Init(); + VoiceHandler.Init(); + } + + public void OnDestroy() + { + Logger.Log($"Destroying NewHorizons"); + SceneManager.sceneLoaded -= OnSceneLoaded; + GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); + GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); + + AchievementHandler.OnDestroy(); + } + + private static void OnWakeUp() + { + IsSystemReady = true; + } + + private void OnSceneUnloaded(Scene scene) + { + SearchUtilities.ClearCache(); + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + IsSystemReady = false; + } + + private void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + Logger.Log($"Scene Loaded: {scene.name} {mode}"); + + // Set time loop stuff if its enabled and if we're warping to a new place + if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) + { + TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); + // Prevent the OPC from firing + var launchController = GameObject.FindObjectOfType(); + if (launchController != null) + { + GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); + foreach (var fakeDebris in launchController._fakeDebrisBodies) + { + fakeDebris.gameObject.SetActive(false); + } + launchController.enabled = false; + } + var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); + if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + } + + // Reset this + SecondsLeftInLoop = -1; + + IsChangingStarSystem = false; + + if (scene.name == "TitleScreen" && _useCustomTitleScreen) + { + TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); + TitleSceneHandler.InitSubtitles(); + } + + if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) + { + if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); + _ship.transform.position = new Vector3(50, 0, 0); + _ship.SetActive(true); + } + + if (scene.name == "SolarSystem") + { + foreach (var body in GameObject.FindObjectsOfType()) + { + Logger.Log($"{body.name}, {body.transform.rotation}"); + } + + if (_ship != null) + { + _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); + DontDestroyOnLoad(_ship); + } + + IsSystemReady = false; + + NewHorizonsData.Load(); + SignalBuilder.Init(); + AstroObjectLocator.Init(); + OWAssetHandler.Init(); + PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); + VesselWarpHandler.LoadVessel(); + SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); + LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); + + // Warp drive + StarChartHandler.Init(SystemDict.Values.ToArray()); + HasWarpDrive = StarChartHandler.CanWarp(); + _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); + _shipWarpController.Init(); + if (HasWarpDrive == true) EnableWarpDrive(); + + var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; + var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; + Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); + + IsWarpingFromShip = false; + IsWarpingFromVessel = false; + + var map = GameObject.FindObjectOfType(); + if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; + + // Fix the map satellite + SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); + + try + { + Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); + Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); + } + catch (Exception e) + { + Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); + } + } + else + { + // Reset back to original solar system after going to main menu. + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + } + } + + // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here + private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) + { + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. + + if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); + else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); + else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); + + VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); + } + + public void EnableWarpDrive() + { + Logger.Log("Setting up warp drive"); + PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); + HasWarpDrive = true; + } + + + #region Load + public void LoadConfigs(IModBehaviour mod) + { + try + { + if (_firstLoad) + { + MountedAddons.Add(mod); + } + var folder = mod.ModHelper.Manifest.ModFolderPath; + + // Load systems first so that when we load bodies later we can check for missing ones + if (Directory.Exists(folder + @"systems\")) + { + foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) + { + var name = Path.GetFileNameWithoutExtension(file); + + Logger.Log($"Loading system {name}"); + + var relativePath = file.Replace(folder, ""); + var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); + starSystemConfig.FixCoordinates(); + + if (starSystemConfig.startHere) + { + // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around + if (name != "SolarSystem") + { + SetDefaultSystem(name); + _currentStarSystem = name; + } + } + + if (SystemDict.ContainsKey(name)) + { + SystemDict[name].Config.Merge(starSystemConfig); + } + else + { + SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); + } + } + } + if (Directory.Exists(folder + "planets")) + { + foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) + { + var relativeDirectory = file.Replace(folder, ""); + var body = LoadConfig(mod, relativeDirectory); + + if (body != null) + { + // Wanna track the spawn point of each system + if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; + + // Add the new planet to the planet dictionary + if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); + BodyDict[body.Config.starSystem].Add(body); + } + } + } + // Has to go before translations for achievements + if (File.Exists(folder + "addon-manifest.json")) + { + var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); + + AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); + } + if (Directory.Exists(folder + @"translations\")) + { + LoadTranslations(folder, mod); + } + + } + catch (Exception ex) + { + Logger.LogError($"{ex.Message}, {ex.StackTrace}"); + } + } + + private void LoadTranslations(string folder, IModBehaviour mod) + { + var foundFile = false; + foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) + { + if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; + + var relativeFile = $"translations/{language.ToString().ToLower()}.json"; + + if (File.Exists($"{folder}{relativeFile}")) + { + Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + + var config = new TranslationConfig($"{folder}{relativeFile}"); + + foundFile = true; + + TranslationHandler.RegisterTranslation(language, config); + + if (AchievementHandler.Enabled) + { + AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); + } + } + } + if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); + } + + public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) + { + NewHorizonsBody body = null; + try + { + var config = mod.ModHelper.Storage.Load(relativePath); + if (config == null) + { + Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); + return null; + } + + Logger.Log($"Loaded {config.name}"); + + if (!SystemDict.ContainsKey(config.starSystem)) + { + // Since we didn't load it earlier there shouldn't be a star system config + var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); + if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); + else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); + + starSystemConfig.FixCoordinates(); + + var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); + + SystemDict.Add(config.starSystem, system); + + BodyDict.Add(config.starSystem, new List()); + } + + // Has to happen after we make sure theres a system config + config.MigrateAndValidate(); + + body = new NewHorizonsBody(config, mod, relativePath); + } + catch (Exception e) + { + Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); + } + + return body; + } + + public void SetDefaultSystem(string defaultSystem) + { + _defaultStarSystem = defaultSystem; + } + + #endregion Load + + #region Change star system + public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) + { + if (IsChangingStarSystem) return; + + IsWarpingFromShip = warp; + IsWarpingFromVessel = vessel; + OnChangeStarSystem?.Invoke(newStarSystem); + + Logger.Log($"Warping to {newStarSystem}"); + if (warp && _shipWarpController) _shipWarpController.WarpOut(); + IsChangingStarSystem = true; + WearingSuit = PlayerState.IsWearingSuit(); + + // We kill them so they don't move as much + Locator.GetDeathManager().KillPlayer(DeathType.Meditation); + + OWScene sceneToLoad; + + if (newStarSystem == "EyeOfTheUniverse") + { + PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); + sceneToLoad = OWScene.EyeOfTheUniverse; + } + else + { + if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); + else SecondsLeftInLoop = -1; + + sceneToLoad = OWScene.SolarSystem; + } + + _currentStarSystem = newStarSystem; + + LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); + } + + void OnDeath(DeathType _) + { + // We reset the solar system on death (unless we just killed the player) + if (!IsChangingStarSystem) + { + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + + IsWarpingFromShip = false; + } + } + #endregion Change star system + } +} From 08a0a6023059b71e75f487083595a5c592096729 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 15:35:32 -0700 Subject: [PATCH 09/18] okay do it for real --- NewHorizons/Main.cs | 1132 +++++++++++++++++++++---------------------- 1 file changed, 566 insertions(+), 566 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 1f7e52a0..09578576 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -1,570 +1,570 @@ -using HarmonyLib; -using NewHorizons.AchievementsPlus; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External; -using NewHorizons.External.Configs; -using NewHorizons.Handlers; -using NewHorizons.Utility; -using NewHorizons.Utility.DebugMenu; -using NewHorizons.Utility.DebugUtilities; -using NewHorizons.VoiceActing; -using OWML.Common; -using OWML.ModHelper; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons -{ - - public class Main : ModBehaviour - { - public static AssetBundle NHAssetBundle { get; private set; } - public static Main Instance { get; private set; } - - // Settings +using HarmonyLib; +using NewHorizons.AchievementsPlus; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.External.Configs; +using NewHorizons.Handlers; +using NewHorizons.Utility; +using NewHorizons.Utility.DebugMenu; +using NewHorizons.Utility.DebugUtilities; +using NewHorizons.VoiceActing; +using OWML.Common; +using OWML.ModHelper; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons +{ + + public class Main : ModBehaviour + { + public static AssetBundle NHAssetBundle { get; private set; } + public static Main Instance { get; private set; } + + // Settings public static bool Debug { get; private set; } - public static bool VerboseLogs { get; private set; } - private static bool _useCustomTitleScreen; - private static bool _wasConfigured = false; - private static string _defaultSystemOverride; - - public static Dictionary SystemDict = new Dictionary(); - public static Dictionary> BodyDict = new Dictionary>(); - public static List MountedAddons = new List(); - - public static float SecondsLeftInLoop = -1; - - public static bool IsSystemReady { get; private set; } - public static float FurthestOrbit { get; set; } = 50000f; - - public string CurrentStarSystem { get { return Instance._currentStarSystem; } } - public bool IsWarpingFromShip { get; private set; } = false; - public bool IsWarpingFromVessel { get; private set; } = false; - public bool WearingSuit { get; private set; } = false; - - public bool IsChangingStarSystem { get; private set; } = false; - - public static bool HasWarpDrive { get; private set; } = false; - - private string _defaultStarSystem = "SolarSystem"; - private string _currentStarSystem = "SolarSystem"; - private bool _firstLoad = true; - private ShipWarpController _shipWarpController; - - // API events - public class StarSystemEvent : UnityEvent { } - public StarSystemEvent OnChangeStarSystem; - public StarSystemEvent OnStarSystemLoaded; - - // For warping to the eye system - private GameObject _ship; - - public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } - - public override object GetApi() - { - return new NewHorizonsApi(); - } - - public override void Configure(IModConfig config) - { - Logger.Log("Settings changed"); - - var currentScene = SceneManager.GetActiveScene().name; - + public static bool VerboseLogs { get; private set; } + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; + private static string _defaultSystemOverride; + + public static Dictionary SystemDict = new Dictionary(); + public static Dictionary> BodyDict = new Dictionary>(); + public static List MountedAddons = new List(); + + public static float SecondsLeftInLoop = -1; + + public static bool IsSystemReady { get; private set; } + public static float FurthestOrbit { get; set; } = 50000f; + + public string CurrentStarSystem { get { return Instance._currentStarSystem; } } + public bool IsWarpingFromShip { get; private set; } = false; + public bool IsWarpingFromVessel { get; private set; } = false; + public bool WearingSuit { get; private set; } = false; + + public bool IsChangingStarSystem { get; private set; } = false; + + public static bool HasWarpDrive { get; private set; } = false; + + private string _defaultStarSystem = "SolarSystem"; + private string _currentStarSystem = "SolarSystem"; + private bool _firstLoad = true; + private ShipWarpController _shipWarpController; + + // API events + public class StarSystemEvent : UnityEvent { } + public StarSystemEvent OnChangeStarSystem; + public StarSystemEvent OnStarSystemLoaded; + + // For warping to the eye system + private GameObject _ship; + + public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } + + public override object GetApi() + { + return new NewHorizonsApi(); + } + + public override void Configure(IModConfig config) + { + Logger.Log("Settings changed"); + + var currentScene = SceneManager.GetActiveScene().name; + Debug = config.GetSettingsValue("Debug"); - VerboseLogs = config.GetSettingsValue("Verbose Logs"); - - if (currentScene == "SolarSystem") - { - DebugReload.UpdateReloadButton(); - DebugMenu.UpdatePauseMenuButton(); - } - - if (Debug && VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); + VerboseLogs = config.GetSettingsValue("Verbose Logs"); + + if (currentScene == "SolarSystem") + { + DebugReload.UpdateReloadButton(); + DebugMenu.UpdatePauseMenuButton(); + } + + if (VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); else Logger.UpdateLogLevel(Logger.LogType.Error); - - _defaultSystemOverride = config.GetSettingsValue("Default System Override"); - - // Else it doesn't get set idk - if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - } - - var wasUsingCustomTitleScreen = _useCustomTitleScreen; - _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); - // Reload the title screen if this was updated on it - // Don't reload if we haven't configured yet (called on game start) - if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) - { - Logger.Log("Reloading"); - SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); - } - - _wasConfigured = true; - } - - public static void ResetConfigs(bool resetTranslation = true) - { - BodyDict.Clear(); - SystemDict.Clear(); - - BodyDict["SolarSystem"] = new List(); - BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr - SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) - { - Config = - { - destroyStockPlanets = false, - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[5]{ 0,3,2,1,5 }, - y = new int[5]{ 4,5,3,2,1 }, - z = new int[5]{ 4,1,2,5,0 } - } - } - }; - SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) - { - Config = - { - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[3]{ 1,5,4 }, - y = new int[4]{ 3,0,1,4 }, - z = new int[6]{ 1,2,3,0,5,4 } - } - } - }; - - if (!resetTranslation) return; - TranslationHandler.ClearTables(); - TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); - } - - public void Start() - { - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - OnChangeStarSystem = new StarSystemEvent(); - OnStarSystemLoaded = new StarSystemEvent(); - - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - - Instance = this; - GlobalMessenger.AddListener("PlayerDeath", OnDeath); - - GlobalMessenger.AddListener("WakeUp", OnWakeUp); - NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); - VesselWarpHandler.Initialize(); - - ResetConfigs(resetTranslation: false); - - Logger.Log("Begin load of config files..."); - - try - { - LoadConfigs(this); - } - catch (Exception) - { - Logger.LogWarning("Couldn't find planets folder"); - } - - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); - Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; - - AchievementHandler.Init(); - VoiceHandler.Init(); - } - - public void OnDestroy() - { - Logger.Log($"Destroying NewHorizons"); - SceneManager.sceneLoaded -= OnSceneLoaded; - GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); - GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); - - AchievementHandler.OnDestroy(); - } - - private static void OnWakeUp() - { - IsSystemReady = true; - } - - private void OnSceneUnloaded(Scene scene) - { - SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - IsSystemReady = false; - } - - private void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); - - // Set time loop stuff if its enabled and if we're warping to a new place - if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) - { - TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); - // Prevent the OPC from firing - var launchController = GameObject.FindObjectOfType(); - if (launchController != null) - { - GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); - foreach (var fakeDebris in launchController._fakeDebrisBodies) - { - fakeDebris.gameObject.SetActive(false); - } - launchController.enabled = false; - } - var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); - } - - // Reset this - SecondsLeftInLoop = -1; - - IsChangingStarSystem = false; - - if (scene.name == "TitleScreen" && _useCustomTitleScreen) - { - TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); - TitleSceneHandler.InitSubtitles(); - } - - if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) - { - if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); - _ship.transform.position = new Vector3(50, 0, 0); - _ship.SetActive(true); - } - - if (scene.name == "SolarSystem") - { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - - if (_ship != null) - { - _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); - DontDestroyOnLoad(_ship); - } - - IsSystemReady = false; - - NewHorizonsData.Load(); - SignalBuilder.Init(); - AstroObjectLocator.Init(); - OWAssetHandler.Init(); - PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); - VesselWarpHandler.LoadVessel(); - SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); - LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); - - // Warp drive - StarChartHandler.Init(SystemDict.Values.ToArray()); - HasWarpDrive = StarChartHandler.CanWarp(); - _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); - _shipWarpController.Init(); - if (HasWarpDrive == true) EnableWarpDrive(); - - var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; - var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; - Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); - - IsWarpingFromShip = false; - IsWarpingFromVessel = false; - - var map = GameObject.FindObjectOfType(); - if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; - - // Fix the map satellite - SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); - - try - { - Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); - Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); - } - catch (Exception e) - { - Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); - } - } - else - { - // Reset back to original solar system after going to main menu. - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - } - } - - // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here - private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) - { - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. - - if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); - else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); - else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); - - VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); - } - - public void EnableWarpDrive() - { - Logger.Log("Setting up warp drive"); - PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); - HasWarpDrive = true; - } - - - #region Load - public void LoadConfigs(IModBehaviour mod) - { - try - { - if (_firstLoad) - { - MountedAddons.Add(mod); - } - var folder = mod.ModHelper.Manifest.ModFolderPath; - - // Load systems first so that when we load bodies later we can check for missing ones - if (Directory.Exists(folder + @"systems\")) - { - foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) - { - var name = Path.GetFileNameWithoutExtension(file); - - Logger.Log($"Loading system {name}"); - - var relativePath = file.Replace(folder, ""); - var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); - starSystemConfig.FixCoordinates(); - - if (starSystemConfig.startHere) - { - // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around - if (name != "SolarSystem") - { - SetDefaultSystem(name); - _currentStarSystem = name; - } - } - - if (SystemDict.ContainsKey(name)) - { - SystemDict[name].Config.Merge(starSystemConfig); - } - else - { - SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); - } - } - } - if (Directory.Exists(folder + "planets")) - { - foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) - { - var relativeDirectory = file.Replace(folder, ""); - var body = LoadConfig(mod, relativeDirectory); - - if (body != null) - { - // Wanna track the spawn point of each system - if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; - - // Add the new planet to the planet dictionary - if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); - BodyDict[body.Config.starSystem].Add(body); - } - } - } - // Has to go before translations for achievements - if (File.Exists(folder + "addon-manifest.json")) - { - var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); - - AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); - } - if (Directory.Exists(folder + @"translations\")) - { - LoadTranslations(folder, mod); - } - - } - catch (Exception ex) - { - Logger.LogError($"{ex.Message}, {ex.StackTrace}"); - } - } - - private void LoadTranslations(string folder, IModBehaviour mod) - { - var foundFile = false; - foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) - { - if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; - - var relativeFile = $"translations/{language.ToString().ToLower()}.json"; - - if (File.Exists($"{folder}{relativeFile}")) - { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); - - var config = new TranslationConfig($"{folder}{relativeFile}"); - - foundFile = true; - - TranslationHandler.RegisterTranslation(language, config); - - if (AchievementHandler.Enabled) - { - AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); - } - } - } - if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); - } - - public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) - { - NewHorizonsBody body = null; - try - { - var config = mod.ModHelper.Storage.Load(relativePath); - if (config == null) - { - Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); - return null; - } - - Logger.Log($"Loaded {config.name}"); - - if (!SystemDict.ContainsKey(config.starSystem)) - { - // Since we didn't load it earlier there shouldn't be a star system config - var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); - if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); - else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); - - starSystemConfig.FixCoordinates(); - - var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); - - SystemDict.Add(config.starSystem, system); - - BodyDict.Add(config.starSystem, new List()); - } - - // Has to happen after we make sure theres a system config - config.MigrateAndValidate(); - - body = new NewHorizonsBody(config, mod, relativePath); - } - catch (Exception e) - { - Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); - } - - return body; - } - - public void SetDefaultSystem(string defaultSystem) - { - _defaultStarSystem = defaultSystem; - } - - #endregion Load - - #region Change star system - public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) - { - if (IsChangingStarSystem) return; - - IsWarpingFromShip = warp; - IsWarpingFromVessel = vessel; - OnChangeStarSystem?.Invoke(newStarSystem); - - Logger.Log($"Warping to {newStarSystem}"); - if (warp && _shipWarpController) _shipWarpController.WarpOut(); - IsChangingStarSystem = true; - WearingSuit = PlayerState.IsWearingSuit(); - - // We kill them so they don't move as much - Locator.GetDeathManager().KillPlayer(DeathType.Meditation); - - OWScene sceneToLoad; - - if (newStarSystem == "EyeOfTheUniverse") - { - PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); - sceneToLoad = OWScene.EyeOfTheUniverse; - } - else - { - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); - else SecondsLeftInLoop = -1; - - sceneToLoad = OWScene.SolarSystem; - } - - _currentStarSystem = newStarSystem; - - LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); - } - - void OnDeath(DeathType _) - { - // We reset the solar system on death (unless we just killed the player) - if (!IsChangingStarSystem) - { - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - - IsWarpingFromShip = false; - } - } - #endregion Change star system - } -} + + _defaultSystemOverride = config.GetSettingsValue("Default System Override"); + + // Else it doesn't get set idk + if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + } + + var wasUsingCustomTitleScreen = _useCustomTitleScreen; + _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); + // Reload the title screen if this was updated on it + // Don't reload if we haven't configured yet (called on game start) + if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) + { + Logger.Log("Reloading"); + SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); + } + + _wasConfigured = true; + } + + public static void ResetConfigs(bool resetTranslation = true) + { + BodyDict.Clear(); + SystemDict.Clear(); + + BodyDict["SolarSystem"] = new List(); + BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) + { + Config = + { + destroyStockPlanets = false, + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[5]{ 0,3,2,1,5 }, + y = new int[5]{ 4,5,3,2,1 }, + z = new int[5]{ 4,1,2,5,0 } + } + } + }; + SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) + { + Config = + { + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[3]{ 1,5,4 }, + y = new int[4]{ 3,0,1,4 }, + z = new int[6]{ 1,2,3,0,5,4 } + } + } + }; + + if (!resetTranslation) return; + TranslationHandler.ClearTables(); + TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); + } + + public void Start() + { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + + OnChangeStarSystem = new StarSystemEvent(); + OnStarSystemLoaded = new StarSystemEvent(); + + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; + + Instance = this; + GlobalMessenger.AddListener("PlayerDeath", OnDeath); + + GlobalMessenger.AddListener("WakeUp", OnWakeUp); + NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); + VesselWarpHandler.Initialize(); + + ResetConfigs(resetTranslation: false); + + Logger.Log("Begin load of config files..."); + + try + { + LoadConfigs(this); + } + catch (Exception) + { + Logger.LogWarning("Couldn't find planets folder"); + } + + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); + Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; + + AchievementHandler.Init(); + VoiceHandler.Init(); + } + + public void OnDestroy() + { + Logger.Log($"Destroying NewHorizons"); + SceneManager.sceneLoaded -= OnSceneLoaded; + GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); + GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); + + AchievementHandler.OnDestroy(); + } + + private static void OnWakeUp() + { + IsSystemReady = true; + } + + private void OnSceneUnloaded(Scene scene) + { + SearchUtilities.ClearCache(); + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + IsSystemReady = false; + } + + private void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + Logger.Log($"Scene Loaded: {scene.name} {mode}"); + + // Set time loop stuff if its enabled and if we're warping to a new place + if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) + { + TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); + // Prevent the OPC from firing + var launchController = GameObject.FindObjectOfType(); + if (launchController != null) + { + GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); + foreach (var fakeDebris in launchController._fakeDebrisBodies) + { + fakeDebris.gameObject.SetActive(false); + } + launchController.enabled = false; + } + var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); + if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + } + + // Reset this + SecondsLeftInLoop = -1; + + IsChangingStarSystem = false; + + if (scene.name == "TitleScreen" && _useCustomTitleScreen) + { + TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); + TitleSceneHandler.InitSubtitles(); + } + + if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) + { + if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); + _ship.transform.position = new Vector3(50, 0, 0); + _ship.SetActive(true); + } + + if (scene.name == "SolarSystem") + { + foreach (var body in GameObject.FindObjectsOfType()) + { + Logger.Log($"{body.name}, {body.transform.rotation}"); + } + + if (_ship != null) + { + _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); + DontDestroyOnLoad(_ship); + } + + IsSystemReady = false; + + NewHorizonsData.Load(); + SignalBuilder.Init(); + AstroObjectLocator.Init(); + OWAssetHandler.Init(); + PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); + VesselWarpHandler.LoadVessel(); + SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); + LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); + + // Warp drive + StarChartHandler.Init(SystemDict.Values.ToArray()); + HasWarpDrive = StarChartHandler.CanWarp(); + _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); + _shipWarpController.Init(); + if (HasWarpDrive == true) EnableWarpDrive(); + + var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; + var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; + Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); + + IsWarpingFromShip = false; + IsWarpingFromVessel = false; + + var map = GameObject.FindObjectOfType(); + if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; + + // Fix the map satellite + SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); + + try + { + Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); + Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); + } + catch (Exception e) + { + Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); + } + } + else + { + // Reset back to original solar system after going to main menu. + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + } + } + + // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here + private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) + { + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. + + if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); + else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); + else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); + + VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); + } + + public void EnableWarpDrive() + { + Logger.Log("Setting up warp drive"); + PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); + HasWarpDrive = true; + } + + + #region Load + public void LoadConfigs(IModBehaviour mod) + { + try + { + if (_firstLoad) + { + MountedAddons.Add(mod); + } + var folder = mod.ModHelper.Manifest.ModFolderPath; + + // Load systems first so that when we load bodies later we can check for missing ones + if (Directory.Exists(folder + @"systems\")) + { + foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) + { + var name = Path.GetFileNameWithoutExtension(file); + + Logger.Log($"Loading system {name}"); + + var relativePath = file.Replace(folder, ""); + var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); + starSystemConfig.FixCoordinates(); + + if (starSystemConfig.startHere) + { + // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around + if (name != "SolarSystem") + { + SetDefaultSystem(name); + _currentStarSystem = name; + } + } + + if (SystemDict.ContainsKey(name)) + { + SystemDict[name].Config.Merge(starSystemConfig); + } + else + { + SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); + } + } + } + if (Directory.Exists(folder + "planets")) + { + foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) + { + var relativeDirectory = file.Replace(folder, ""); + var body = LoadConfig(mod, relativeDirectory); + + if (body != null) + { + // Wanna track the spawn point of each system + if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; + + // Add the new planet to the planet dictionary + if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); + BodyDict[body.Config.starSystem].Add(body); + } + } + } + // Has to go before translations for achievements + if (File.Exists(folder + "addon-manifest.json")) + { + var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); + + AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); + } + if (Directory.Exists(folder + @"translations\")) + { + LoadTranslations(folder, mod); + } + + } + catch (Exception ex) + { + Logger.LogError($"{ex.Message}, {ex.StackTrace}"); + } + } + + private void LoadTranslations(string folder, IModBehaviour mod) + { + var foundFile = false; + foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) + { + if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; + + var relativeFile = $"translations/{language.ToString().ToLower()}.json"; + + if (File.Exists($"{folder}{relativeFile}")) + { + Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + + var config = new TranslationConfig($"{folder}{relativeFile}"); + + foundFile = true; + + TranslationHandler.RegisterTranslation(language, config); + + if (AchievementHandler.Enabled) + { + AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); + } + } + } + if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); + } + + public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) + { + NewHorizonsBody body = null; + try + { + var config = mod.ModHelper.Storage.Load(relativePath); + if (config == null) + { + Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); + return null; + } + + Logger.Log($"Loaded {config.name}"); + + if (!SystemDict.ContainsKey(config.starSystem)) + { + // Since we didn't load it earlier there shouldn't be a star system config + var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); + if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); + else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); + + starSystemConfig.FixCoordinates(); + + var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); + + SystemDict.Add(config.starSystem, system); + + BodyDict.Add(config.starSystem, new List()); + } + + // Has to happen after we make sure theres a system config + config.MigrateAndValidate(); + + body = new NewHorizonsBody(config, mod, relativePath); + } + catch (Exception e) + { + Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); + } + + return body; + } + + public void SetDefaultSystem(string defaultSystem) + { + _defaultStarSystem = defaultSystem; + } + + #endregion Load + + #region Change star system + public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) + { + if (IsChangingStarSystem) return; + + IsWarpingFromShip = warp; + IsWarpingFromVessel = vessel; + OnChangeStarSystem?.Invoke(newStarSystem); + + Logger.Log($"Warping to {newStarSystem}"); + if (warp && _shipWarpController) _shipWarpController.WarpOut(); + IsChangingStarSystem = true; + WearingSuit = PlayerState.IsWearingSuit(); + + // We kill them so they don't move as much + Locator.GetDeathManager().KillPlayer(DeathType.Meditation); + + OWScene sceneToLoad; + + if (newStarSystem == "EyeOfTheUniverse") + { + PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); + sceneToLoad = OWScene.EyeOfTheUniverse; + } + else + { + if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); + else SecondsLeftInLoop = -1; + + sceneToLoad = OWScene.SolarSystem; + } + + _currentStarSystem = newStarSystem; + + LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); + } + + void OnDeath(DeathType _) + { + // We reset the solar system on death (unless we just killed the player) + if (!IsChangingStarSystem) + { + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + + IsWarpingFromShip = false; + } + } + #endregion Change star system + } +} From 0b915b3da99cde54709cec2d8680977024f66950 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 15:36:45 -0700 Subject: [PATCH 10/18] change the lines? --- NewHorizons/Main.cs | 1140 +++++++++++++++++++++---------------------- 1 file changed, 570 insertions(+), 570 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 09578576..a1f70357 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -1,570 +1,570 @@ -using HarmonyLib; -using NewHorizons.AchievementsPlus; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External; -using NewHorizons.External.Configs; -using NewHorizons.Handlers; -using NewHorizons.Utility; -using NewHorizons.Utility.DebugMenu; -using NewHorizons.Utility.DebugUtilities; -using NewHorizons.VoiceActing; -using OWML.Common; -using OWML.ModHelper; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons -{ - - public class Main : ModBehaviour - { - public static AssetBundle NHAssetBundle { get; private set; } - public static Main Instance { get; private set; } - - // Settings - public static bool Debug { get; private set; } - public static bool VerboseLogs { get; private set; } - private static bool _useCustomTitleScreen; - private static bool _wasConfigured = false; - private static string _defaultSystemOverride; - - public static Dictionary SystemDict = new Dictionary(); - public static Dictionary> BodyDict = new Dictionary>(); - public static List MountedAddons = new List(); - - public static float SecondsLeftInLoop = -1; - - public static bool IsSystemReady { get; private set; } - public static float FurthestOrbit { get; set; } = 50000f; - - public string CurrentStarSystem { get { return Instance._currentStarSystem; } } - public bool IsWarpingFromShip { get; private set; } = false; - public bool IsWarpingFromVessel { get; private set; } = false; - public bool WearingSuit { get; private set; } = false; - - public bool IsChangingStarSystem { get; private set; } = false; - - public static bool HasWarpDrive { get; private set; } = false; - - private string _defaultStarSystem = "SolarSystem"; - private string _currentStarSystem = "SolarSystem"; - private bool _firstLoad = true; - private ShipWarpController _shipWarpController; - - // API events - public class StarSystemEvent : UnityEvent { } - public StarSystemEvent OnChangeStarSystem; - public StarSystemEvent OnStarSystemLoaded; - - // For warping to the eye system - private GameObject _ship; - - public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } - - public override object GetApi() - { - return new NewHorizonsApi(); - } - - public override void Configure(IModConfig config) - { - Logger.Log("Settings changed"); - - var currentScene = SceneManager.GetActiveScene().name; - - Debug = config.GetSettingsValue("Debug"); - VerboseLogs = config.GetSettingsValue("Verbose Logs"); - - if (currentScene == "SolarSystem") - { - DebugReload.UpdateReloadButton(); - DebugMenu.UpdatePauseMenuButton(); - } - - if (VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); - else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); - else Logger.UpdateLogLevel(Logger.LogType.Error); - - _defaultSystemOverride = config.GetSettingsValue("Default System Override"); - - // Else it doesn't get set idk - if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - } - - var wasUsingCustomTitleScreen = _useCustomTitleScreen; - _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); - // Reload the title screen if this was updated on it - // Don't reload if we haven't configured yet (called on game start) - if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) - { - Logger.Log("Reloading"); - SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); - } - - _wasConfigured = true; - } - - public static void ResetConfigs(bool resetTranslation = true) - { - BodyDict.Clear(); - SystemDict.Clear(); - - BodyDict["SolarSystem"] = new List(); - BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr - SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) - { - Config = - { - destroyStockPlanets = false, - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[5]{ 0,3,2,1,5 }, - y = new int[5]{ 4,5,3,2,1 }, - z = new int[5]{ 4,1,2,5,0 } - } - } - }; - SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) - { - Config = - { - coords = new StarSystemConfig.NomaiCoordinates - { - x = new int[3]{ 1,5,4 }, - y = new int[4]{ 3,0,1,4 }, - z = new int[6]{ 1,2,3,0,5,4 } - } - } - }; - - if (!resetTranslation) return; - TranslationHandler.ClearTables(); - TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); - } - - public void Start() - { - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - OnChangeStarSystem = new StarSystemEvent(); - OnStarSystemLoaded = new StarSystemEvent(); - - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - - Instance = this; - GlobalMessenger.AddListener("PlayerDeath", OnDeath); - - GlobalMessenger.AddListener("WakeUp", OnWakeUp); - NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); - VesselWarpHandler.Initialize(); - - ResetConfigs(resetTranslation: false); - - Logger.Log("Begin load of config files..."); - - try - { - LoadConfigs(this); - } - catch (Exception) - { - Logger.LogWarning("Couldn't find planets folder"); - } - - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); - Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; - - AchievementHandler.Init(); - VoiceHandler.Init(); - } - - public void OnDestroy() - { - Logger.Log($"Destroying NewHorizons"); - SceneManager.sceneLoaded -= OnSceneLoaded; - GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); - GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); - - AchievementHandler.OnDestroy(); - } - - private static void OnWakeUp() - { - IsSystemReady = true; - } - - private void OnSceneUnloaded(Scene scene) - { - SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - IsSystemReady = false; - } - - private void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); - - // Set time loop stuff if its enabled and if we're warping to a new place - if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) - { - TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); - // Prevent the OPC from firing - var launchController = GameObject.FindObjectOfType(); - if (launchController != null) - { - GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); - foreach (var fakeDebris in launchController._fakeDebrisBodies) - { - fakeDebris.gameObject.SetActive(false); - } - launchController.enabled = false; - } - var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); - } - - // Reset this - SecondsLeftInLoop = -1; - - IsChangingStarSystem = false; - - if (scene.name == "TitleScreen" && _useCustomTitleScreen) - { - TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); - TitleSceneHandler.InitSubtitles(); - } - - if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) - { - if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); - _ship.transform.position = new Vector3(50, 0, 0); - _ship.SetActive(true); - } - - if (scene.name == "SolarSystem") - { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - - if (_ship != null) - { - _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); - DontDestroyOnLoad(_ship); - } - - IsSystemReady = false; - - NewHorizonsData.Load(); - SignalBuilder.Init(); - AstroObjectLocator.Init(); - OWAssetHandler.Init(); - PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); - VesselWarpHandler.LoadVessel(); - SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); - LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); - - // Warp drive - StarChartHandler.Init(SystemDict.Values.ToArray()); - HasWarpDrive = StarChartHandler.CanWarp(); - _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); - _shipWarpController.Init(); - if (HasWarpDrive == true) EnableWarpDrive(); - - var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; - var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; - Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); - - IsWarpingFromShip = false; - IsWarpingFromVessel = false; - - var map = GameObject.FindObjectOfType(); - if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; - - // Fix the map satellite - SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); - - try - { - Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); - Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); - } - catch (Exception e) - { - Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); - } - } - else - { - // Reset back to original solar system after going to main menu. - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - } - } - - // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here - private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) - { - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. - - if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); - else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); - else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); - - VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); - } - - public void EnableWarpDrive() - { - Logger.Log("Setting up warp drive"); - PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); - HasWarpDrive = true; - } - - - #region Load - public void LoadConfigs(IModBehaviour mod) - { - try - { - if (_firstLoad) - { - MountedAddons.Add(mod); - } - var folder = mod.ModHelper.Manifest.ModFolderPath; - - // Load systems first so that when we load bodies later we can check for missing ones - if (Directory.Exists(folder + @"systems\")) - { - foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) - { - var name = Path.GetFileNameWithoutExtension(file); - - Logger.Log($"Loading system {name}"); - - var relativePath = file.Replace(folder, ""); - var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); - starSystemConfig.FixCoordinates(); - - if (starSystemConfig.startHere) - { - // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around - if (name != "SolarSystem") - { - SetDefaultSystem(name); - _currentStarSystem = name; - } - } - - if (SystemDict.ContainsKey(name)) - { - SystemDict[name].Config.Merge(starSystemConfig); - } - else - { - SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); - } - } - } - if (Directory.Exists(folder + "planets")) - { - foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) - { - var relativeDirectory = file.Replace(folder, ""); - var body = LoadConfig(mod, relativeDirectory); - - if (body != null) - { - // Wanna track the spawn point of each system - if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; - - // Add the new planet to the planet dictionary - if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); - BodyDict[body.Config.starSystem].Add(body); - } - } - } - // Has to go before translations for achievements - if (File.Exists(folder + "addon-manifest.json")) - { - var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); - - AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); - } - if (Directory.Exists(folder + @"translations\")) - { - LoadTranslations(folder, mod); - } - - } - catch (Exception ex) - { - Logger.LogError($"{ex.Message}, {ex.StackTrace}"); - } - } - - private void LoadTranslations(string folder, IModBehaviour mod) - { - var foundFile = false; - foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) - { - if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; - - var relativeFile = $"translations/{language.ToString().ToLower()}.json"; - - if (File.Exists($"{folder}{relativeFile}")) - { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); - - var config = new TranslationConfig($"{folder}{relativeFile}"); - - foundFile = true; - - TranslationHandler.RegisterTranslation(language, config); - - if (AchievementHandler.Enabled) - { - AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); - } - } - } - if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); - } - - public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) - { - NewHorizonsBody body = null; - try - { - var config = mod.ModHelper.Storage.Load(relativePath); - if (config == null) - { - Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); - return null; - } - - Logger.Log($"Loaded {config.name}"); - - if (!SystemDict.ContainsKey(config.starSystem)) - { - // Since we didn't load it earlier there shouldn't be a star system config - var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); - if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); - else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); - - starSystemConfig.FixCoordinates(); - - var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); - - SystemDict.Add(config.starSystem, system); - - BodyDict.Add(config.starSystem, new List()); - } - - // Has to happen after we make sure theres a system config - config.MigrateAndValidate(); - - body = new NewHorizonsBody(config, mod, relativePath); - } - catch (Exception e) - { - Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); - } - - return body; - } - - public void SetDefaultSystem(string defaultSystem) - { - _defaultStarSystem = defaultSystem; - } - - #endregion Load - - #region Change star system - public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) - { - if (IsChangingStarSystem) return; - - IsWarpingFromShip = warp; - IsWarpingFromVessel = vessel; - OnChangeStarSystem?.Invoke(newStarSystem); - - Logger.Log($"Warping to {newStarSystem}"); - if (warp && _shipWarpController) _shipWarpController.WarpOut(); - IsChangingStarSystem = true; - WearingSuit = PlayerState.IsWearingSuit(); - - // We kill them so they don't move as much - Locator.GetDeathManager().KillPlayer(DeathType.Meditation); - - OWScene sceneToLoad; - - if (newStarSystem == "EyeOfTheUniverse") - { - PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); - sceneToLoad = OWScene.EyeOfTheUniverse; - } - else - { - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); - else SecondsLeftInLoop = -1; - - sceneToLoad = OWScene.SolarSystem; - } - - _currentStarSystem = newStarSystem; - - LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); - } - - void OnDeath(DeathType _) - { - // We reset the solar system on death (unless we just killed the player) - if (!IsChangingStarSystem) - { - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - - IsWarpingFromShip = false; - } - } - #endregion Change star system - } -} +using HarmonyLib; +using NewHorizons.AchievementsPlus; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.External.Configs; +using NewHorizons.Handlers; +using NewHorizons.Utility; +using NewHorizons.Utility.DebugMenu; +using NewHorizons.Utility.DebugUtilities; +using NewHorizons.VoiceActing; +using OWML.Common; +using OWML.ModHelper; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons +{ + + public class Main : ModBehaviour + { + public static AssetBundle NHAssetBundle { get; private set; } + public static Main Instance { get; private set; } + + // Settings + public static bool Debug { get; private set; } + public static bool VerboseLogs { get; private set; } + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; + private static string _defaultSystemOverride; + + public static Dictionary SystemDict = new Dictionary(); + public static Dictionary> BodyDict = new Dictionary>(); + public static List MountedAddons = new List(); + + public static float SecondsLeftInLoop = -1; + + public static bool IsSystemReady { get; private set; } + public static float FurthestOrbit { get; set; } = 50000f; + + public string CurrentStarSystem { get { return Instance._currentStarSystem; } } + public bool IsWarpingFromShip { get; private set; } = false; + public bool IsWarpingFromVessel { get; private set; } = false; + public bool WearingSuit { get; private set; } = false; + + public bool IsChangingStarSystem { get; private set; } = false; + + public static bool HasWarpDrive { get; private set; } = false; + + private string _defaultStarSystem = "SolarSystem"; + private string _currentStarSystem = "SolarSystem"; + private bool _firstLoad = true; + private ShipWarpController _shipWarpController; + + // API events + public class StarSystemEvent : UnityEvent { } + public StarSystemEvent OnChangeStarSystem; + public StarSystemEvent OnStarSystemLoaded; + + // For warping to the eye system + private GameObject _ship; + + public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } + + public override object GetApi() + { + return new NewHorizonsApi(); + } + + public override void Configure(IModConfig config) + { + Logger.Log("Settings changed"); + + var currentScene = SceneManager.GetActiveScene().name; + + Debug = config.GetSettingsValue("Debug"); + VerboseLogs = config.GetSettingsValue("Verbose Logs"); + + if (currentScene == "SolarSystem") + { + DebugReload.UpdateReloadButton(); + DebugMenu.UpdatePauseMenuButton(); + } + + if (VerboseLogs) Logger.UpdateLogLevel(Logger.LogType.Verbose); + else if (Debug) Logger.UpdateLogLevel(Logger.LogType.Log); + else Logger.UpdateLogLevel(Logger.LogType.Error); + + _defaultSystemOverride = config.GetSettingsValue("Default System Override"); + + // Else it doesn't get set idk + if (currentScene == "TitleScreen" && SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + } + + var wasUsingCustomTitleScreen = _useCustomTitleScreen; + _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); + // Reload the title screen if this was updated on it + // Don't reload if we haven't configured yet (called on game start) + if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) + { + Logger.Log("Reloading"); + SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); + } + + _wasConfigured = true; + } + + public static void ResetConfigs(bool resetTranslation = true) + { + BodyDict.Clear(); + SystemDict.Clear(); + + BodyDict["SolarSystem"] = new List(); + BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) + { + Config = + { + destroyStockPlanets = false, + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[5]{ 0,3,2,1,5 }, + y = new int[5]{ 4,5,3,2,1 }, + z = new int[5]{ 4,1,2,5,0 } + } + } + }; + SystemDict["EyeOfTheUniverse"] = new NewHorizonsSystem("EyeOfTheUniverse", new StarSystemConfig(), Instance) + { + Config = + { + coords = new StarSystemConfig.NomaiCoordinates + { + x = new int[3]{ 1,5,4 }, + y = new int[4]{ 3,0,1,4 }, + z = new int[6]{ 1,2,3,0,5,4 } + } + } + }; + + if (!resetTranslation) return; + TranslationHandler.ClearTables(); + TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); + } + + public void Start() + { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + + OnChangeStarSystem = new StarSystemEvent(); + OnStarSystemLoaded = new StarSystemEvent(); + + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; + + Instance = this; + GlobalMessenger.AddListener("PlayerDeath", OnDeath); + + GlobalMessenger.AddListener("WakeUp", OnWakeUp); + NHAssetBundle = ModHelper.Assets.LoadBundle("Assets/xen.newhorizons"); + VesselWarpHandler.Initialize(); + + ResetConfigs(resetTranslation: false); + + Logger.Log("Begin load of config files..."); + + try + { + LoadConfigs(this); + } + catch (Exception) + { + Logger.LogWarning("Couldn't find planets folder"); + } + + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); + Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; + + AchievementHandler.Init(); + VoiceHandler.Init(); + } + + public void OnDestroy() + { + Logger.Log($"Destroying NewHorizons"); + SceneManager.sceneLoaded -= OnSceneLoaded; + GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); + GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); + + AchievementHandler.OnDestroy(); + } + + private static void OnWakeUp() + { + IsSystemReady = true; + } + + private void OnSceneUnloaded(Scene scene) + { + SearchUtilities.ClearCache(); + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + IsSystemReady = false; + } + + private void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + Logger.Log($"Scene Loaded: {scene.name} {mode}"); + + // Set time loop stuff if its enabled and if we're warping to a new place + if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) + { + TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); + // Prevent the OPC from firing + var launchController = GameObject.FindObjectOfType(); + if (launchController != null) + { + GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); + foreach (var fakeDebris in launchController._fakeDebrisBodies) + { + fakeDebris.gameObject.SetActive(false); + } + launchController.enabled = false; + } + var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); + if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + } + + // Reset this + SecondsLeftInLoop = -1; + + IsChangingStarSystem = false; + + if (scene.name == "TitleScreen" && _useCustomTitleScreen) + { + TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); + TitleSceneHandler.InitSubtitles(); + } + + if (scene.name == "EyeOfTheUniverse" && IsWarpingFromShip) + { + if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); + _ship.transform.position = new Vector3(50, 0, 0); + _ship.SetActive(true); + } + + if (scene.name == "SolarSystem") + { + foreach (var body in GameObject.FindObjectsOfType()) + { + Logger.Log($"{body.name}, {body.transform.rotation}"); + } + + if (_ship != null) + { + _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); + DontDestroyOnLoad(_ship); + } + + IsSystemReady = false; + + NewHorizonsData.Load(); + SignalBuilder.Init(); + AstroObjectLocator.Init(); + OWAssetHandler.Init(); + PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); + VesselWarpHandler.LoadVessel(); + SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); + LoadTranslations(ModHelper.Manifest.ModFolderPath + "Assets/", this); + + // Warp drive + StarChartHandler.Init(SystemDict.Values.ToArray()); + HasWarpDrive = StarChartHandler.CanWarp(); + _shipWarpController = SearchUtilities.Find("Ship_Body").AddComponent(); + _shipWarpController.Init(); + if (HasWarpDrive == true) EnableWarpDrive(); + + var shouldWarpInFromShip = IsWarpingFromShip && _shipWarpController != null; + var shouldWarpInFromVessel = IsWarpingFromVessel && VesselWarpHandler.VesselSpawnPoint != null; + Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpInFromShip, shouldWarpInFromVessel)); + + IsWarpingFromShip = false; + IsWarpingFromVessel = false; + + var map = GameObject.FindObjectOfType(); + if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; + + // Fix the map satellite + SearchUtilities.Find("HearthianMapSatellite_Body", false).AddComponent(); + + try + { + Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); + Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); + } + catch (Exception e) + { + Logger.LogError($"Exception thrown when invoking star system loaded event with parameter [{Instance.CurrentStarSystem}] : {e.GetType().FullName} {e.Message} {e.StackTrace}"); + } + } + else + { + // Reset back to original solar system after going to main menu. + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + } + } + + // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here + private void OnSystemReady(bool shouldWarpInFromShip, bool shouldWarpInFromVessel) + { + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + // DebugArrow.CreateArrow(Locator.GetPlayerBody().gameObject); // This is for NH devs mostly. It shouldn't be active in debug mode for now. Someone should make a dev tools submenu for it though. + + if (shouldWarpInFromShip) _shipWarpController.WarpIn(WearingSuit); + else if (shouldWarpInFromVessel) VesselWarpHandler.TeleportToVessel(); + else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); + + VesselCoordinatePromptHandler.RegisterPrompts(SystemDict.Where(system => system.Value.Config.coords != null).Select(x => x.Value).ToList()); + } + + public void EnableWarpDrive() + { + Logger.Log("Setting up warp drive"); + PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); + HasWarpDrive = true; + } + + + #region Load + public void LoadConfigs(IModBehaviour mod) + { + try + { + if (_firstLoad) + { + MountedAddons.Add(mod); + } + var folder = mod.ModHelper.Manifest.ModFolderPath; + + // Load systems first so that when we load bodies later we can check for missing ones + if (Directory.Exists(folder + @"systems\")) + { + foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json?", SearchOption.AllDirectories)) + { + var name = Path.GetFileNameWithoutExtension(file); + + Logger.Log($"Loading system {name}"); + + var relativePath = file.Replace(folder, ""); + var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); + starSystemConfig.FixCoordinates(); + + if (starSystemConfig.startHere) + { + // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around + if (name != "SolarSystem") + { + SetDefaultSystem(name); + _currentStarSystem = name; + } + } + + if (SystemDict.ContainsKey(name)) + { + SystemDict[name].Config.Merge(starSystemConfig); + } + else + { + SystemDict[name] = new NewHorizonsSystem(name, starSystemConfig, mod); + } + } + } + if (Directory.Exists(folder + "planets")) + { + foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json?", SearchOption.AllDirectories)) + { + var relativeDirectory = file.Replace(folder, ""); + var body = LoadConfig(mod, relativeDirectory); + + if (body != null) + { + // Wanna track the spawn point of each system + if (body.Config.Spawn != null) SystemDict[body.Config.starSystem].Spawn = body.Config.Spawn; + + // Add the new planet to the planet dictionary + if (!BodyDict.ContainsKey(body.Config.starSystem)) BodyDict[body.Config.starSystem] = new List(); + BodyDict[body.Config.starSystem].Add(body); + } + } + } + // Has to go before translations for achievements + if (File.Exists(folder + "addon-manifest.json")) + { + var addonConfig = mod.ModHelper.Storage.Load("addon-manifest.json"); + + AchievementHandler.RegisterAddon(addonConfig, mod as ModBehaviour); + } + if (Directory.Exists(folder + @"translations\")) + { + LoadTranslations(folder, mod); + } + + } + catch (Exception ex) + { + Logger.LogError($"{ex.Message}, {ex.StackTrace}"); + } + } + + private void LoadTranslations(string folder, IModBehaviour mod) + { + var foundFile = false; + foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) + { + if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; + + var relativeFile = $"translations/{language.ToString().ToLower()}.json"; + + if (File.Exists($"{folder}{relativeFile}")) + { + Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + + var config = new TranslationConfig($"{folder}{relativeFile}"); + + foundFile = true; + + TranslationHandler.RegisterTranslation(language, config); + + if (AchievementHandler.Enabled) + { + AchievementHandler.RegisterTranslationsFromFiles(mod as ModBehaviour, "translations"); + } + } + } + if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); + } + + public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativePath) + { + NewHorizonsBody body = null; + try + { + var config = mod.ModHelper.Storage.Load(relativePath); + if (config == null) + { + Logger.LogError($"Couldn't load {relativePath}. Is your Json formatted correctly?"); + return null; + } + + Logger.Log($"Loaded {config.name}"); + + if (!SystemDict.ContainsKey(config.starSystem)) + { + // Since we didn't load it earlier there shouldn't be a star system config + var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.starSystem}.json"); + if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); + else Logger.LogWarning($"Loaded system config for {config.starSystem}. Why wasn't this loaded earlier?"); + + starSystemConfig.FixCoordinates(); + + var system = new NewHorizonsSystem(config.starSystem, starSystemConfig, mod); + + SystemDict.Add(config.starSystem, system); + + BodyDict.Add(config.starSystem, new List()); + } + + // Has to happen after we make sure theres a system config + config.MigrateAndValidate(); + + body = new NewHorizonsBody(config, mod, relativePath); + } + catch (Exception e) + { + Logger.LogError($"Error encounter when loading {relativePath}: {e.Message} {e.StackTrace}"); + } + + return body; + } + + public void SetDefaultSystem(string defaultSystem) + { + _defaultStarSystem = defaultSystem; + } + + #endregion Load + + #region Change star system + public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false, bool vessel = false) + { + if (IsChangingStarSystem) return; + + IsWarpingFromShip = warp; + IsWarpingFromVessel = vessel; + OnChangeStarSystem?.Invoke(newStarSystem); + + Logger.Log($"Warping to {newStarSystem}"); + if (warp && _shipWarpController) _shipWarpController.WarpOut(); + IsChangingStarSystem = true; + WearingSuit = PlayerState.IsWearingSuit(); + + // We kill them so they don't move as much + Locator.GetDeathManager().KillPlayer(DeathType.Meditation); + + OWScene sceneToLoad; + + if (newStarSystem == "EyeOfTheUniverse") + { + PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); + sceneToLoad = OWScene.EyeOfTheUniverse; + } + else + { + if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); + else SecondsLeftInLoop = -1; + + sceneToLoad = OWScene.SolarSystem; + } + + _currentStarSystem = newStarSystem; + + LoadManager.LoadSceneAsync(sceneToLoad, !vessel, LoadManager.FadeType.ToBlack, 0.1f, true); + } + + void OnDeath(DeathType _) + { + // We reset the solar system on death (unless we just killed the player) + if (!IsChangingStarSystem) + { + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarpingFromShip = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + + IsWarpingFromShip = false; + } + } + #endregion Change star system + } +} From 2e47d170f9973474d16ad6bf6437ba12390e2713 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 5 Jul 2022 19:28:38 -0400 Subject: [PATCH 11/18] Change fifty gorillion logs to be verbose --- .../AchievementsPlus/AchievementHandler.cs | 2 +- .../Builder/Body/AsteroidBeltBuilder.cs | 2 +- .../Builder/Body/SingularityBuilder.cs | 4 +- .../Builder/General/AstroObjectBuilder.cs | 2 +- .../Builder/General/SpawnPointBuilder.cs | 4 +- .../Builder/Orbital/InitialMotionBuilder.cs | 6 +- NewHorizons/Builder/Props/DetailBuilder.cs | 2 +- NewHorizons/Builder/Props/NomaiTextBuilder.cs | 5 +- NewHorizons/Builder/Props/QuantumBuilder.cs | 2 +- NewHorizons/Builder/Props/SignalBuilder.cs | 2 +- NewHorizons/Builder/ShipLog/MapModeBuilder.cs | 2 +- .../Builder/StarSystem/SkyboxBuilder.cs | 2 +- .../Components/NHMultiStateQuantumObject.cs | 2 +- NewHorizons/Components/QuantumPlanet.cs | 2 +- .../Components/ShipLogStarChartMode.cs | 2 +- NewHorizons/Components/ShipWarpController.cs | 10 +- NewHorizons/Components/StarLightController.cs | 6 +- NewHorizons/External/NewHorizonsData.cs | 8 +- NewHorizons/Handlers/PlanetCreationHandler.cs | 10 +- .../Handlers/PlanetDestructionHandler.cs | 12 +- NewHorizons/Handlers/PlanetGraphHandler.cs | 2 +- NewHorizons/Handlers/StarChartHandler.cs | 4 +- NewHorizons/Handlers/TitleSceneHandler.cs | 4 +- NewHorizons/Handlers/VesselWarpHandler.cs | 6 +- NewHorizons/Main.cs | 21 ++- NewHorizons/Patches/PlayerSpawnerPatches.cs | 2 +- NewHorizons/Patches/ShipLogPatches.cs | 4 +- NewHorizons/Utility/AstroObjectLocator.cs | 2 +- NewHorizons/Utility/AudioUtilities.cs | 6 +- NewHorizons/Utility/DebugMenu/DebugMenu.cs | 4 +- .../Utility/DebugMenu/DebugMenuNomaiText.cs | 25 ++-- .../Utility/DebugMenu/DebugMenuPropPlacer.cs | 8 +- .../Utility/DebugUtilities/DebugPropPlacer.cs | 8 +- .../Utility/DebugUtilities/DebugRaycaster.cs | 4 +- NewHorizons/Utility/ImageUtilities.cs | 10 +- NewHorizons/Utility/Logger.cs | 129 +++++++----------- NewHorizons/Utility/NewHorizonExtensions.cs | 2 +- NewHorizons/Utility/SearchUtilities.cs | 2 +- NewHorizons/VoiceActing/VoiceHandler.cs | 4 +- 39 files changed, 144 insertions(+), 190 deletions(-) diff --git a/NewHorizons/AchievementsPlus/AchievementHandler.cs b/NewHorizons/AchievementsPlus/AchievementHandler.cs index da9014f8..b7ea6a48 100644 --- a/NewHorizons/AchievementsPlus/AchievementHandler.cs +++ b/NewHorizons/AchievementsPlus/AchievementHandler.cs @@ -20,7 +20,7 @@ namespace NewHorizons.AchievementsPlus if (API == null) { - Logger.Log("Achievements+ isn't installed"); + Logger.LogVerbose("Achievements+ isn't installed"); Enabled = false; return; } diff --git a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs index 5e71238f..03705a11 100644 --- a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs +++ b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs @@ -69,7 +69,7 @@ namespace NewHorizons.Builder.Body } var asteroid = new NewHorizonsBody(config, mod); - PlanetCreationHandler.NextPassBodies.Add(asteroid); + PlanetCreationHandler.GenerateBody(asteroid); } } } diff --git a/NewHorizons/Builder/Body/SingularityBuilder.cs b/NewHorizons/Builder/Body/SingularityBuilder.cs index ef261d82..286780c3 100644 --- a/NewHorizons/Builder/Body/SingularityBuilder.cs +++ b/NewHorizons/Builder/Body/SingularityBuilder.cs @@ -76,14 +76,14 @@ namespace NewHorizons.Builder.Body { if (blackHole == null || whiteHole == null) return; - Logger.Log($"Pairing singularities [{blackHoleID}], [{whiteHoleID}]"); + Logger.LogVerbose($"Pairing singularities [{blackHoleID}], [{whiteHoleID}]"); var whiteHoleVolume = whiteHole.GetComponentInChildren(); var blackHoleVolume = blackHole.GetComponentInChildren(); if (whiteHoleVolume == null || blackHoleVolume == null) { - Logger.Log($"[{blackHoleID}] and [{whiteHoleID}] do not have compatible polarities"); + Logger.LogWarning($"[{blackHoleID}] and [{whiteHoleID}] do not have compatible polarities"); return; } diff --git a/NewHorizons/Builder/General/AstroObjectBuilder.cs b/NewHorizons/Builder/General/AstroObjectBuilder.cs index a2fecf27..0e17e777 100644 --- a/NewHorizons/Builder/General/AstroObjectBuilder.cs +++ b/NewHorizons/Builder/General/AstroObjectBuilder.cs @@ -1,4 +1,4 @@ -using NewHorizons.Components.Orbital; +using NewHorizons.Components.Orbital; using NewHorizons.External.Configs; using UnityEngine; using Logger = NewHorizons.Utility.Logger; diff --git a/NewHorizons/Builder/General/SpawnPointBuilder.cs b/NewHorizons/Builder/General/SpawnPointBuilder.cs index a2ec2b99..0311374f 100644 --- a/NewHorizons/Builder/General/SpawnPointBuilder.cs +++ b/NewHorizons/Builder/General/SpawnPointBuilder.cs @@ -62,7 +62,7 @@ namespace NewHorizons.Builder.General if (Main.Instance.IsWarpingFromShip) { - Logger.Log("Overriding player spawn to be inside ship"); + Logger.LogVerbose("Overriding player spawn to be inside ship"); GameObject playerSpawnGO = new GameObject("PlayerSpawnPoint"); playerSpawnGO.transform.parent = ship.transform; playerSpawnGO.layer = 8; @@ -81,7 +81,7 @@ namespace NewHorizons.Builder.General Main.Instance.ModHelper.Events.Unity.RunWhen(() => Main.IsSystemReady, () => SuitUp()); } - Logger.Log("Made spawnpoint on [" + planetGO.name + "]"); + Logger.Log($"Made spawnpoint on [{planetGO.name}]"); return playerSpawn; } diff --git a/NewHorizons/Builder/Orbital/InitialMotionBuilder.cs b/NewHorizons/Builder/Orbital/InitialMotionBuilder.cs index 36ece316..8caa1d8f 100644 --- a/NewHorizons/Builder/Orbital/InitialMotionBuilder.cs +++ b/NewHorizons/Builder/Orbital/InitialMotionBuilder.cs @@ -80,7 +80,7 @@ namespace NewHorizons.Builder.Orbital } else { - Logger.Log($"No primary gravity or focal point for {primaryBody}"); + Logger.LogError($"No primary gravity or focal point for {primaryBody}"); } } @@ -99,7 +99,7 @@ namespace NewHorizons.Builder.Orbital private static void SetBinaryInitialMotion(AstroObject baryCenter, NHAstroObject primaryBody, NHAstroObject secondaryBody) { - Logger.Log($"Setting binary initial motion [{primaryBody.name}] [{secondaryBody.name}]"); + Logger.LogVerbose($"Setting binary initial motion [{primaryBody.name}] [{secondaryBody.name}]"); var primaryGravity = new Gravity(primaryBody._gravityVolume); var secondaryGravity = new Gravity(secondaryBody._gravityVolume); @@ -172,7 +172,7 @@ namespace NewHorizons.Builder.Orbital secondaryInitialMotion._cachedInitVelocity = baryCenterVelocity + secondaryVelocity; secondaryInitialMotion._isInitVelocityDirty = false; - Logger.Log($"Binary Initial Motion: {m1}, {m2}, {r1}, {r2}, {primaryVelocity}, {secondaryVelocity}"); + Logger.LogVerbose($"Binary Initial Motion: {m1}, {m2}, {r1}, {r2}, {primaryVelocity}, {secondaryVelocity}"); } } } diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index 655bf4d8..089affe8 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -233,7 +233,7 @@ namespace NewHorizons.Builder.Props // If it's not a moving anglerfish make sure the anim controller is regular else if (component is AnglerfishAnimController angler && angler.GetComponentInParent() == null) { - Logger.Log("Enabling anglerfish animation"); + Logger.LogVerbose("Enabling anglerfish animation"); // Remove any reference to its angler if (angler._anglerfishController) { diff --git a/NewHorizons/Builder/Props/NomaiTextBuilder.cs b/NewHorizons/Builder/Props/NomaiTextBuilder.cs index 6ade077e..0fa1fd58 100644 --- a/NewHorizons/Builder/Props/NomaiTextBuilder.cs +++ b/NewHorizons/Builder/Props/NomaiTextBuilder.cs @@ -30,9 +30,10 @@ namespace NewHorizons.Builder.Props } private static Dictionary conversationInfoToCorrespondingSpawnedGameObject = new Dictionary(); + public static GameObject GetSpawnedGameObjectByNomaiTextInfo(PropModule.NomaiTextInfo convo) { - Logger.Log("retrieving wall text obj for " + convo); + Logger.LogVerbose("Retrieving wall text obj for " + convo); if (!conversationInfoToCorrespondingSpawnedGameObject.ContainsKey(convo)) return null; return conversationInfoToCorrespondingSpawnedGameObject[convo]; } @@ -168,7 +169,7 @@ namespace NewHorizons.Builder.Props () => Main.IsSystemReady, () => { - Logger.Log("Fixing scroll!"); + Logger.LogVerbose("Fixing scroll!"); scrollItem._nomaiWallText = nomaiWallText; scrollItem.SetSector(sector); customScroll.transform.Find("Props_NOM_Scroll/Props_NOM_Scroll_Geo").GetComponent().enabled = true; diff --git a/NewHorizons/Builder/Props/QuantumBuilder.cs b/NewHorizons/Builder/Props/QuantumBuilder.cs index 52311c93..06bfe4f1 100644 --- a/NewHorizons/Builder/Props/QuantumBuilder.cs +++ b/NewHorizons/Builder/Props/QuantumBuilder.cs @@ -216,7 +216,7 @@ namespace NewHorizons.Builder.Props void Update() { - if (meshFilter == null && skinnedMeshRenderer == null) { Logger.Log("Useless BoxShapeFixer, destroying"); GameObject.DestroyImmediate(this); } + if (meshFilter == null && skinnedMeshRenderer == null) { Logger.LogVerbose("Useless BoxShapeFixer, destroying"); GameObject.DestroyImmediate(this); } Mesh sharedMesh = null; if (meshFilter != null) sharedMesh = meshFilter.sharedMesh; diff --git a/NewHorizons/Builder/Props/SignalBuilder.cs b/NewHorizons/Builder/Props/SignalBuilder.cs index 24da4772..a245958b 100644 --- a/NewHorizons/Builder/Props/SignalBuilder.cs +++ b/NewHorizons/Builder/Props/SignalBuilder.cs @@ -24,7 +24,7 @@ namespace NewHorizons.Builder.Props public static void Init() { - Logger.Log($"Initializing SignalBuilder"); + Logger.LogVerbose($"Initializing SignalBuilder"); _customSignalNames = new Dictionary(); _availableSignalNames = new Stack(new SignalName[] { diff --git a/NewHorizons/Builder/ShipLog/MapModeBuilder.cs b/NewHorizons/Builder/ShipLog/MapModeBuilder.cs index c87438b0..b377bf51 100644 --- a/NewHorizons/Builder/ShipLog/MapModeBuilder.cs +++ b/NewHorizons/Builder/ShipLog/MapModeBuilder.cs @@ -99,7 +99,7 @@ namespace NewHorizons.Builder.ShipLog { const float unviewedIconOffset = 15; - Logger.Log($"Adding ship log astro object for {body.Config.name}"); + Logger.LogVerbose($"Adding ship log astro object for {body.Config.name}"); GameObject unviewedReference = SearchUtilities.Find(ShipLogHandler.PAN_ROOT_PATH + "/TimberHearth/UnviewedIcon"); diff --git a/NewHorizons/Builder/StarSystem/SkyboxBuilder.cs b/NewHorizons/Builder/StarSystem/SkyboxBuilder.cs index 02437a83..44d27945 100644 --- a/NewHorizons/Builder/StarSystem/SkyboxBuilder.cs +++ b/NewHorizons/Builder/StarSystem/SkyboxBuilder.cs @@ -1,4 +1,4 @@ -using NewHorizons.External.Configs; +using NewHorizons.External.Configs; using NewHorizons.Utility; using OWML.Common; using UnityEngine; diff --git a/NewHorizons/Components/NHMultiStateQuantumObject.cs b/NewHorizons/Components/NHMultiStateQuantumObject.cs index 502d5996..5838c70d 100644 --- a/NewHorizons/Components/NHMultiStateQuantumObject.cs +++ b/NewHorizons/Components/NHMultiStateQuantumObject.cs @@ -70,7 +70,7 @@ namespace NewHorizons.Components if (previousIndex >= 0 && previousIndex < _states.Length) _states[previousIndex].SetVisible(visible: false); _states[_stateIndex].SetVisible(visible: true); - Logger.Log("trying state " + _stateIndex); + Logger.LogVerbose($"MultiStateQuantumObject - Trying to change state {_stateIndex}"); indices.Remove(_stateIndex); } while (!CurrentStateIsValid() && indices.Count > 0); diff --git a/NewHorizons/Components/QuantumPlanet.cs b/NewHorizons/Components/QuantumPlanet.cs index 796bddd5..32eaa09d 100644 --- a/NewHorizons/Components/QuantumPlanet.cs +++ b/NewHorizons/Components/QuantumPlanet.cs @@ -52,7 +52,7 @@ namespace NewHorizons.Components public override bool ChangeQuantumState(bool skipInstantVisibilityCheck) { - Logger.Log($"Trying to change quantum state"); + Logger.LogVerbose($"QuantumPlanet - Trying to change quantum state"); if (states.Count <= 1) return false; diff --git a/NewHorizons/Components/ShipLogStarChartMode.cs b/NewHorizons/Components/ShipLogStarChartMode.cs index 314985b3..83035ab7 100644 --- a/NewHorizons/Components/ShipLogStarChartMode.cs +++ b/NewHorizons/Components/ShipLogStarChartMode.cs @@ -133,7 +133,7 @@ namespace NewHorizons.Components else { var path = $"planets/{uniqueID}.png"; - Logger.Log($"Trying to load {path}"); + Logger.LogVerbose($"ShipLogStarChartManager - Trying to load {path}"); texture = ImageUtilities.GetTexture(Main.SystemDict[uniqueID].Mod, path); } } diff --git a/NewHorizons/Components/ShipWarpController.cs b/NewHorizons/Components/ShipWarpController.cs index b79a60d9..e34f9626 100644 --- a/NewHorizons/Components/ShipWarpController.cs +++ b/NewHorizons/Components/ShipWarpController.cs @@ -99,7 +99,7 @@ namespace NewHorizons.Components public void WarpIn(bool wearingSuit) { - Logger.Log("Starting warp-in"); + Logger.LogVerbose("Starting warp-in"); // Trying really hard to stop the player from dying while warping in _impactDeathSpeed = Locator.GetDeathManager()._impactDeathSpeed; Locator.GetDeathManager()._impactDeathSpeed = Mathf.Infinity; @@ -112,7 +112,7 @@ namespace NewHorizons.Components public void WarpOut() { - Logger.Log("Starting warp-out"); + Logger.LogVerbose("Starting warp-out"); _oneShotSource.PlayOneShot(global::AudioType.VesselSingularityCreate, 1f); _blackhole.Create(); } @@ -129,7 +129,7 @@ namespace NewHorizons.Components { if (Locator.GetPlayerTransform().TryGetComponent(out var resources) && resources._currentHealth < 100f) { - Logger.Log("Player died in a warp drive accident, reviving them"); + Logger.LogVerbose("Player died in a warp drive accident, reviving them"); // Means the player was killed meaning they weren't teleported in resources._currentHealth = 100f; if (!PlayerState.AtFlightConsole()) TeleportToShip(); @@ -151,7 +151,7 @@ namespace NewHorizons.Components private void StartWarpInEffect() { - Logger.Log("Starting warp-in effect"); + Logger.LogVerbose("Starting warp-in effect"); _oneShotSource.PlayOneShot(global::AudioType.VesselSingularityCollapse, 1f); Locator.GetDeathManager()._invincible = true; if (Main.Instance.CurrentStarSystem.Equals("SolarSystem")) TeleportToShip(); @@ -171,7 +171,7 @@ namespace NewHorizons.Components public void FinishWarpIn() { - Logger.Log("Finishing warp"); + Logger.LogVerbose("Finishing warp"); Locator.GetShipBody().GetComponentInChildren().OnPressInteract(); _waitingToBeSeated = false; Main.Instance.ModHelper.Events.Unity.FireInNUpdates(() => _whitehole.Collapse(), 30); diff --git a/NewHorizons/Components/StarLightController.cs b/NewHorizons/Components/StarLightController.cs index 7e46459d..310616e1 100644 --- a/NewHorizons/Components/StarLightController.cs +++ b/NewHorizons/Components/StarLightController.cs @@ -28,13 +28,13 @@ namespace NewHorizons.Components { if (star == null) return; - Logger.Log($"Adding new star to list: {star.gameObject.name}"); + Logger.LogVerbose($"Adding new star to list: {star.gameObject.name}"); Instance._stars.Add(star); } public static void RemoveStar(StarController star) { - Logger.Log($"Removing star from list: {star?.gameObject?.name}"); + Logger.LogVerbose($"Removing star from list: {star?.gameObject?.name}"); if (Instance._stars.Contains(star)) { if (Instance._activeStar != null && Instance._activeStar.Equals(star)) @@ -85,7 +85,7 @@ namespace NewHorizons.Components if (_activeStar != null) _activeStar.Disable(); - Logger.Log($"Switching active star: {star.gameObject.name}"); + Logger.LogVerbose($"Switching active star: {star.gameObject.name}"); _activeStar = star; diff --git a/NewHorizons/External/NewHorizonsData.cs b/NewHorizons/External/NewHorizonsData.cs index 2a1a3e63..afda8857 100644 --- a/NewHorizons/External/NewHorizonsData.cs +++ b/NewHorizons/External/NewHorizonsData.cs @@ -26,18 +26,18 @@ namespace NewHorizons.External if (!_saveFile.Profiles.ContainsKey(_activeProfileName)) _saveFile.Profiles.Add(_activeProfileName, new NewHorizonsProfile()); _activeProfile = _saveFile.Profiles[_activeProfileName]; - Logger.Log($"Loaded save data for {_activeProfileName}"); + Logger.LogVerbose($"Loaded save data for {_activeProfileName}"); } catch (Exception) { try { - Logger.Log($"Couldn't load save data from {FileName}, creating a new file"); + Logger.LogVerbose($"Couldn't load save data from {FileName}, creating a new file"); _saveFile = new NewHorizonsSaveFile(); _saveFile.Profiles.Add(_activeProfileName, new NewHorizonsProfile()); _activeProfile = _saveFile.Profiles[_activeProfileName]; Main.Instance.ModHelper.Storage.Save(_saveFile, FileName); - Logger.Log($"Loaded save data for {_activeProfileName}"); + Logger.LogVerbose($"Loaded save data for {_activeProfileName}"); } catch (Exception e) { @@ -55,7 +55,7 @@ namespace NewHorizons.External public static void Reset() { if (_saveFile == null || _activeProfile == null) Load(); - Logger.Log($"Resetting save data for {_activeProfileName}"); + Logger.LogVerbose($"Resetting save data for {_activeProfileName}"); _activeProfile = new NewHorizonsProfile(); _saveFile.Profiles[_activeProfileName] = _activeProfile; diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index f0ff27b9..a9a801d4 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -278,8 +278,8 @@ namespace NewHorizons.Handlers { if (defaultPrimaryToSun) { - Logger.Log($"Couldn't find {body.Config.Orbit.primaryBody}, defaulting to Sun"); - primaryBody = AstroObjectLocator.GetAstroObject("Sun"); + Logger.LogError($"Couldn't find {body.Config.Orbit.primaryBody}, defaulting to center of solar system"); + primaryBody = Locator.GetCenterOfTheUniverse().GetAttachedOWRigidbody().GetComponent(); } else { @@ -293,8 +293,6 @@ namespace NewHorizons.Handlers primaryBody = null; } - Logger.Log($"Begin generation sequence of [{body.Config.name}]"); - var go = new GameObject(body.Config.name.Replace(" ", "").Replace("'", "") + "_Body"); go.SetActive(false); @@ -339,7 +337,7 @@ namespace NewHorizons.Handlers // Spawning on other planets is a bit hacky so we do it last if (body.Config.Spawn != null) { - Logger.Log("Doing spawn point thing"); + Logger.LogVerbose("Making spawn point"); Main.SystemDict[body.Config.starSystem].SpawnPoint = SpawnPointBuilder.Make(go, body.Config.Spawn, owRigidBody); } @@ -606,7 +604,7 @@ namespace NewHorizons.Handlers public static void UpdatePosition(GameObject go, IOrbitalParameters orbit, AstroObject primaryBody, AstroObject secondaryBody) { - Logger.Log($"Placing [{secondaryBody?.name}] around [{primaryBody?.name}]"); + Logger.LogVerbose($"Placing [{secondaryBody?.name}] around [{primaryBody?.name}]"); go.transform.parent = Locator.GetRootTransform(); diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 14cbdbfa..33ffbb39 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -53,7 +53,7 @@ namespace NewHorizons.Handlers if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) { - Logger.Log($"[{ao.name}] was already removed"); + Logger.LogVerbose($"[{ao.name}] was already removed"); return; } @@ -61,7 +61,7 @@ namespace NewHorizons.Handlers if (toDestroy.Contains(ao)) { - Logger.LogError($"Possible infinite recursion in RemoveBody: {ao.name} might be it's own primary body?"); + Logger.LogVerbose($"Possible infinite recursion in RemoveBody: {ao.name} might be it's own primary body?"); return; } @@ -133,7 +133,7 @@ namespace NewHorizons.Handlers foreach (var sunProxy in GameObject.FindObjectsOfType()) { - Logger.Log($"Destroying SunProxy {sunProxy.gameObject.name}"); + Logger.LogVerbose($"Destroying SunProxy {sunProxy.gameObject.name}"); GameObject.Destroy(sunProxy.gameObject); } @@ -143,12 +143,12 @@ namespace NewHorizons.Handlers } // Always delete the children - Logger.Log($"Removing Children of [{ao._name}], [{ao._customName}]"); + Logger.LogVerbose($"Removing Children of [{ao._name}], [{ao._customName}]"); foreach (var child in AstroObjectLocator.GetChildren(ao)) { if (child == null) continue; - Logger.Log($"Removing child [{child.name}] of [{ao._name}]"); + Logger.LogVerbose($"Removing child [{child.name}] of [{ao._name}]"); // Ship starts as a child of TH but obvious we want to keep that if (child.name == "Ship_Body") continue; @@ -236,7 +236,7 @@ namespace NewHorizons.Handlers if (distantProxyClone != null) GameObject.Destroy(distantProxyClone.gameObject); if (distantProxy == null && distantProxyClone == null) - Logger.Log($"Couldn't find proxy for {name}"); + Logger.LogVerbose($"Couldn't find proxy for {name}"); } } } diff --git a/NewHorizons/Handlers/PlanetGraphHandler.cs b/NewHorizons/Handlers/PlanetGraphHandler.cs index da99907d..20b87cb4 100644 --- a/NewHorizons/Handlers/PlanetGraphHandler.cs +++ b/NewHorizons/Handlers/PlanetGraphHandler.cs @@ -109,7 +109,7 @@ namespace NewHorizons.Handlers foreach (var node in nodeDict.Values.ToList()) { var childrenString = String.Join(", ", node.children.Select(x => x?.body?.Config?.name).ToList()); - Logger.Log($"NODE: [{node?.body?.Config?.name}], [{node?.parent?.body?.Config?.name}], [{childrenString}]"); + Logger.LogVerbose($"NODE: [{node?.body?.Config?.name}], [{node?.parent?.body?.Config?.name}], [{childrenString}]"); } // Return all tree roots (no parents) diff --git a/NewHorizons/Handlers/StarChartHandler.cs b/NewHorizons/Handlers/StarChartHandler.cs index 4b1844e6..a6a3aa1c 100644 --- a/NewHorizons/Handlers/StarChartHandler.cs +++ b/NewHorizons/Handlers/StarChartHandler.cs @@ -97,7 +97,7 @@ namespace NewHorizons.Handlers { if (_factIDToStarSystem.TryGetValue(factID, out var systemUnlocked)) { - Logger.Log($"Just learned [{factID}] and unlocked [{systemUnlocked}]"); + Logger.LogVerbose($"Just learned [{factID}] and unlocked [{systemUnlocked}]"); if (!Main.HasWarpDrive) Main.Instance.EnableWarpDrive(); ShipLogStarChartMode.AddSystemCard(systemUnlocked); } @@ -105,7 +105,7 @@ namespace NewHorizons.Handlers public static void RegisterFactForSystem(string factID, string system) { - Logger.Log($"Need to know [{factID}] to unlock [{system}]"); + Logger.LogVerbose($"Need to know [{factID}] to unlock [{system}]"); _starSystemToFactID.Add(system, factID); _factIDToStarSystem.Add(factID, system); } diff --git a/NewHorizons/Handlers/TitleSceneHandler.cs b/NewHorizons/Handlers/TitleSceneHandler.cs index 242590a4..38d6321d 100644 --- a/NewHorizons/Handlers/TitleSceneHandler.cs +++ b/NewHorizons/Handlers/TitleSceneHandler.cs @@ -36,7 +36,7 @@ namespace NewHorizons.Handlers var selectionCount = Mathf.Min(eligibleCount, 3); var indices = RandomUtility.GetUniqueRandomArray(0, eligible.Count(), selectionCount); - Logger.Log($"Displaying {selectionCount} bodies on the title screen"); + Logger.LogVerbose($"Displaying {selectionCount} bodies on the title screen"); GameObject body1, body2, body3; @@ -74,7 +74,7 @@ namespace NewHorizons.Handlers private static GameObject LoadTitleScreenBody(NewHorizonsBody body) { - Logger.Log($"Displaying {body.Config.name} on the title screen"); + Logger.LogVerbose($"Displaying {body.Config.name} on the title screen"); GameObject titleScreenGO = new GameObject(body.Config.name + "_TitleScreen"); HeightMapModule heightMap = new HeightMapModule(); var minSize = 15; diff --git a/NewHorizons/Handlers/VesselWarpHandler.cs b/NewHorizons/Handlers/VesselWarpHandler.cs index f124096a..308713fe 100644 --- a/NewHorizons/Handlers/VesselWarpHandler.cs +++ b/NewHorizons/Handlers/VesselWarpHandler.cs @@ -75,10 +75,10 @@ namespace NewHorizons.Handlers { var system = SystemDict[Instance.CurrentStarSystem]; - Logger.Log("Checking for Vessel Prefab"); + Logger.LogVerbose("Checking for Vessel Prefab"); if (VesselPrefab == null) return null; - Logger.Log("Creating Vessel"); + Logger.LogVerbose("Creating Vessel"); var vesselObject = GameObject.Instantiate(VesselPrefab); VesselObject = vesselObject; vesselObject.name = VesselPrefab.name; @@ -159,7 +159,7 @@ namespace NewHorizons.Handlers { var system = SystemDict[Instance.CurrentStarSystem]; - Logger.Log("Updating DB Vessel"); + Logger.LogVerbose("Updating DB Vessel"); var vectorSector = SearchUtilities.Find("DB_VesselDimension_Body/Sector_VesselDimension"); VesselObject = vectorSector; diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index a1f70357..e0d67abf 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -76,7 +76,7 @@ namespace NewHorizons public override void Configure(IModConfig config) { - Logger.Log("Settings changed"); + Logger.LogVerbose("Settings changed"); var currentScene = SceneManager.GetActiveScene().name; @@ -107,7 +107,7 @@ namespace NewHorizons // Don't reload if we haven't configured yet (called on game start) if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) { - Logger.Log("Reloading"); + Logger.LogVerbose("Reloading"); SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); } @@ -217,7 +217,7 @@ namespace NewHorizons private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); + Logger.LogVerbose($"Scene Loaded: {scene.name} {mode}"); // Set time loop stuff if its enabled and if we're warping to a new place if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) @@ -258,11 +258,6 @@ namespace NewHorizons if (scene.name == "SolarSystem") { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - if (_ship != null) { _ship = SearchUtilities.Find("Ship_Body").InstantiateInactive(); @@ -302,7 +297,7 @@ namespace NewHorizons try { - Logger.Log($"Star system loaded [{Instance.CurrentStarSystem}]"); + Logger.Log($"Star system finished loading [{Instance.CurrentStarSystem}]"); Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); } catch (Exception e) @@ -344,7 +339,7 @@ namespace NewHorizons public void EnableWarpDrive() { - Logger.Log("Setting up warp drive"); + Logger.LogVerbose("Setting up warp drive"); PlanetCreationHandler.LoadBody(LoadConfig(this, "Assets/WarpDriveConfig.json")); HasWarpDrive = true; } @@ -368,7 +363,7 @@ namespace NewHorizons { var name = Path.GetFileNameWithoutExtension(file); - Logger.Log($"Loading system {name}"); + Logger.LogVerbose($"Loading system {name}"); var relativePath = file.Replace(folder, ""); var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); @@ -442,7 +437,7 @@ namespace NewHorizons if (File.Exists($"{folder}{relativeFile}")) { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + Logger.LogVerbose($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); var config = new TranslationConfig($"{folder}{relativeFile}"); @@ -471,7 +466,7 @@ namespace NewHorizons return null; } - Logger.Log($"Loaded {config.name}"); + Logger.LogVerbose($"Loaded {config.name}"); if (!SystemDict.ContainsKey(config.starSystem)) { diff --git a/NewHorizons/Patches/PlayerSpawnerPatches.cs b/NewHorizons/Patches/PlayerSpawnerPatches.cs index 09e9ff0a..327a70ad 100644 --- a/NewHorizons/Patches/PlayerSpawnerPatches.cs +++ b/NewHorizons/Patches/PlayerSpawnerPatches.cs @@ -9,7 +9,7 @@ namespace NewHorizons.Patches [HarmonyPatch(typeof(PlayerSpawner), nameof(PlayerSpawner.SpawnPlayer))] public static void PlayerSpawner_SpawnPlayer(PlayerSpawner __instance) { - Logger.Log("Player spawning"); + Logger.LogVerbose("Player spawning"); __instance.SetInitialSpawnPoint(Main.SystemDict[Main.Instance.CurrentStarSystem].SpawnPoint); } } diff --git a/NewHorizons/Patches/ShipLogPatches.cs b/NewHorizons/Patches/ShipLogPatches.cs index 3190b2f3..306b53a9 100644 --- a/NewHorizons/Patches/ShipLogPatches.cs +++ b/NewHorizons/Patches/ShipLogPatches.cs @@ -21,7 +21,7 @@ namespace NewHorizons.Patches { RumorModeBuilder.Init(); ShipLogHandler.Init(); - Logger.Log("Beginning Ship Log Generation For: " + Main.Instance.CurrentStarSystem); + Logger.Log($"Beginning Ship Log Generation For: {Main.Instance.CurrentStarSystem}"); if (Main.Instance.CurrentStarSystem != "SolarSystem") { __instance._shipLogXmlAssets = new TextAsset[] { }; @@ -58,7 +58,7 @@ namespace NewHorizons.Patches RumorModeBuilder.UpdateEntryCuriosity(ref logEntry); } - Logger.Log("Ship Log Generation Complete For: " + Main.Instance.CurrentStarSystem); + Logger.Log($"Ship Log Generation Complete For: {Main.Instance.CurrentStarSystem}"); } [HarmonyPrefix] diff --git a/NewHorizons/Utility/AstroObjectLocator.cs b/NewHorizons/Utility/AstroObjectLocator.cs index c03449b3..ad8ab0ae 100644 --- a/NewHorizons/Utility/AstroObjectLocator.cs +++ b/NewHorizons/Utility/AstroObjectLocator.cs @@ -68,7 +68,7 @@ namespace NewHorizons.Utility } else { - Logger.Log($"Registering [{ao.name}] as [{key}]"); + Logger.LogVerbose($"Registering [{ao.name}] as [{key}]"); _customAstroObjectDictionary.Add(key, ao); } } diff --git a/NewHorizons/Utility/AudioUtilities.cs b/NewHorizons/Utility/AudioUtilities.cs index 45b68261..b5e04bf1 100644 --- a/NewHorizons/Utility/AudioUtilities.cs +++ b/NewHorizons/Utility/AudioUtilities.cs @@ -13,10 +13,10 @@ namespace NewHorizons.Utility { if (_loadedAudioClips.ContainsKey(path)) { - Logger.Log($"Already loaded audio at path: {path}"); + Logger.LogVerbose($"Already loaded audio at path: {path}"); return _loadedAudioClips[path]; } - Logger.Log($"Loading audio at path: {path}"); + Logger.LogVerbose($"Loading audio at path: {path}"); var task = Task.Run(async () => await GetAudioClip(path)); task.Wait(); _loadedAudioClips.Add(path, task.Result); @@ -25,7 +25,7 @@ namespace NewHorizons.Utility public static void ClearCache() { - Logger.Log("Clearing audio cache"); + Logger.LogVerbose("Clearing audio cache"); foreach (var audioClip in _loadedAudioClips.Values) { diff --git a/NewHorizons/Utility/DebugMenu/DebugMenu.cs b/NewHorizons/Utility/DebugMenu/DebugMenu.cs index c33e77f5..0c5b35ae 100644 --- a/NewHorizons/Utility/DebugMenu/DebugMenu.cs +++ b/NewHorizons/Utility/DebugMenu/DebugMenu.cs @@ -200,7 +200,7 @@ namespace NewHorizons.Utility.DebugMenu { if (body.RelativePath == null) { - Logger.Log($"Error loading config for {body.Config.name} in {body.Config.starSystem}"); + Logger.LogWarning($"Error loading config for {body.Config.name} in {body.Config.starSystem}"); continue; } @@ -219,7 +219,7 @@ namespace NewHorizons.Utility.DebugMenu foreach (var filePath in loadedConfigFiles.Keys) { - Logger.Log($"Possibly Saving... {loadedConfigFiles[filePath].name} @ {filePath}"); + Logger.LogVerbose($"Possibly Saving... {loadedConfigFiles[filePath].name} @ {filePath}"); if (loadedConfigFiles[filePath].starSystem != Main.Instance.CurrentStarSystem) continue; diff --git a/NewHorizons/Utility/DebugMenu/DebugMenuNomaiText.cs b/NewHorizons/Utility/DebugMenu/DebugMenuNomaiText.cs index c8d82122..30903469 100644 --- a/NewHorizons/Utility/DebugMenu/DebugMenuNomaiText.cs +++ b/NewHorizons/Utility/DebugMenu/DebugMenuNomaiText.cs @@ -101,7 +101,7 @@ namespace NewHorizons.Utility.DebugMenu collapsed = true }; - Logger.Log("adding go " + conversationMetadata.conversationGo); + Logger.LogVerbose("Adding conversation Game Object " + conversationMetadata.conversationGo); conversations.Add(conversationMetadata); @@ -128,7 +128,7 @@ namespace NewHorizons.Utility.DebugMenu var parentID = (new Regex(regex)).Matches(metadata.spiralGo.name)[0].Groups[1].Value; metadata.parentID = parentID == "" ? -1 : int.Parse(parentID); - Logger.Log("Parent id for '" + metadata.spiralGo.name + "' : " + parentID); + Logger.LogVerbose("Parent id for '" + metadata.spiralGo.name + "' : " + parentID); } conversationMetadata.spirals.Add(metadata); @@ -190,7 +190,7 @@ namespace NewHorizons.Utility.DebugMenu if (GUILayout.Button(arrow + conversationMeta.planetConfig.name + " - " + i, menu._submenuStyle)) { conversationMeta.collapsed = !conversationMeta.collapsed; - Logger.Log("BUTTON " + i); + Logger.LogVerbose("BUTTON " + i); } if (!conversationMeta.collapsed) @@ -204,7 +204,7 @@ namespace NewHorizons.Utility.DebugMenu //conversationMeta.conversation.type == PropModule.NomaiTextInfo.NomaiTextType.Wall && GUILayout.Button("Place conversation with G") ) { - Logger.Log(conversationMeta.conversationGo+" 0"); + Logger.LogVerbose(conversationMeta.conversationGo+" 0"); DebugNomaiTextPlacer.active = true; _dnp.onRaycast = (DebugRaycastData data) => { @@ -423,7 +423,7 @@ namespace NewHorizons.Utility.DebugMenu SpiralMetadata parentSpiralMeta = GetParent(spiralMetadata); var parentPoints = parentSpiralMeta.spiralGo.GetComponent()._points; - Logger.Log("got parent and parent points"); + Logger.Log("Got parent and parent points"); var prevPointOnParent = parentPoints[Mathf.Max(0, spiralMetadata.pointOnParent-1)]; var nextPointOnParent = parentPoints[Mathf.Min(parentPoints.Count()-1, spiralMetadata.pointOnParent+1)]; @@ -432,14 +432,14 @@ namespace NewHorizons.Utility.DebugMenu var newRotationRelativeToParent = parentTangent + 90; spiralMetadata.spiral.zRotation = parentSpiralMeta.spiral.zRotation + newRotationRelativeToParent; - Logger.Log("got zRotation: " + newRotationRelativeToParent + " -=- " + spiralMetadata.spiral.zRotation); + Logger.Log("Got zRotation: " + newRotationRelativeToParent + " -=- " + spiralMetadata.spiral.zRotation); var pointOnParent = parentPoints[spiralMetadata.pointOnParent]; var selfBasePoint = spiralMetadata.spiralGo.GetComponent()._points[0]; var newPointRelativeToParent = -selfBasePoint + pointOnParent; spiralMetadata.spiral.position = parentSpiralMeta.spiral.position + new Vector2(newPointRelativeToParent.x, newPointRelativeToParent.y); - Logger.Log("got position " + newPointRelativeToParent + " -=- " + spiralMetadata.spiral.position); + Logger.Log("Got position " + newPointRelativeToParent + " -=- " + spiralMetadata.spiral.position); spiralMetadata.spiralGo.transform.localPosition = new Vector3(spiralMetadata.spiral.position.x, spiralMetadata.spiral.position.y, 0); spiralMetadata.spiralGo.transform.localEulerAngles = new Vector3(0, 0, spiralMetadata.spiral.zRotation); @@ -450,9 +450,9 @@ namespace NewHorizons.Utility.DebugMenu private void UpdateChildrenLocations(SpiralMetadata parentSprialMetadata) { - Logger.Log("updating children"); + Logger.Log("Updating children"); ConversationMetadata convoMeta = conversations.Where(m => m.conversation == parentSprialMetadata.conversation).First(); - Logger.Log("got convo meta"); + Logger.Log("Got conversation metadata"); convoMeta.spirals .Where(spiralMeta => spiralMeta.parentID == parentSprialMetadata.id && spiralMeta.id != parentSprialMetadata.id) @@ -482,15 +482,10 @@ namespace NewHorizons.Utility.DebugMenu { var nomaiWallTextObj = conversationMetadata.conversationGo; if (nomaiWallTextObj == null) return; + var planetGO = sectorParent; var info = conversationMetadata.conversation; - Logger.Log(nomaiWallTextObj + " 1"); - Logger.Log(nomaiWallTextObj?.transform + " 2"); - Logger.Log(planetGO + " 3"); - Logger.Log(planetGO?.transform + " 4"); - Logger.Log(info + " 5"); - Logger.Log(info?.position + " 6"); nomaiWallTextObj.transform.position = planetGO.transform.TransformPoint(info.position); if (info.normal != null) { diff --git a/NewHorizons/Utility/DebugMenu/DebugMenuPropPlacer.cs b/NewHorizons/Utility/DebugMenu/DebugMenuPropPlacer.cs index 9d61f2f1..76d3462d 100644 --- a/NewHorizons/Utility/DebugMenu/DebugMenuPropPlacer.cs +++ b/NewHorizons/Utility/DebugMenu/DebugMenuPropPlacer.cs @@ -311,14 +311,14 @@ namespace NewHorizons.Utility.DebugMenu // Get all configs foreach (var filePath in menu.loadedConfigFiles.Keys) { - Logger.Log($"Potentially updating copy of config at {filePath}"); - Logger.Log($"{menu.loadedConfigFiles[filePath].name} {AstroObjectLocator.GetAstroObject(menu.loadedConfigFiles[filePath].name)?.name}"); - Logger.Log($"{menu.loadedConfigFiles[filePath].name}"); + Logger.LogVerbose($"Potentially updating copy of config at {filePath}"); + Logger.LogVerbose($"{menu.loadedConfigFiles[filePath].name} {AstroObjectLocator.GetAstroObject(menu.loadedConfigFiles[filePath].name)?.name}"); + Logger.LogVerbose($"{menu.loadedConfigFiles[filePath].name}"); if (menu.loadedConfigFiles[filePath].starSystem != Main.Instance.CurrentStarSystem) return; if (menu.loadedConfigFiles[filePath].name == null || AstroObjectLocator.GetAstroObject(menu.loadedConfigFiles[filePath].name) == null) { - Logger.Log("Failed to update copy of config at " + filePath); + Logger.LogWarning("Failed to update copy of config at " + filePath); continue; } diff --git a/NewHorizons/Utility/DebugUtilities/DebugPropPlacer.cs b/NewHorizons/Utility/DebugUtilities/DebugPropPlacer.cs index e482d84f..9a5812a7 100644 --- a/NewHorizons/Utility/DebugUtilities/DebugPropPlacer.cs +++ b/NewHorizons/Utility/DebugUtilities/DebugPropPlacer.cs @@ -98,7 +98,7 @@ namespace NewHorizons.Utility.DebugUtilities if (!data.hitBodyGameObject.name.EndsWith("_Body")) { - Logger.Log("Cannot place object on non-body object: " + data.hitBodyGameObject.name); + Logger.LogWarning("Cannot place object on non-body object: " + data.hitBodyGameObject.name); } try @@ -115,7 +115,7 @@ namespace NewHorizons.Utility.DebugUtilities } catch { - Logger.Log($"Failed to place object {currentObject} on body ${data.hitBodyGameObject} at location ${data.pos}."); + Logger.LogError($"Failed to place object {currentObject} on body ${data.hitBodyGameObject} at location ${data.pos}."); } } @@ -198,7 +198,7 @@ namespace NewHorizons.Utility.DebugUtilities //var body = AstroObjectLocator.GetAstroObject(bodyGameObjectName); - Logger.Log($"Adding prop to {Main.Instance.CurrentStarSystem}::{body.name}"); + Logger.LogVerbose($"Adding prop to {Main.Instance.CurrentStarSystem}::{body.name}"); detailInfo = detailInfo == null ? new DetailInfo() : detailInfo; @@ -230,7 +230,7 @@ namespace NewHorizons.Utility.DebugUtilities if (bodyProps == null || bodyProps.Count == 0) continue; if (bodyProps[0].body == null) continue; var body = bodyProps[0].body; - Logger.Log("getting prop group for body " + body.name); + Logger.LogVerbose("getting prop group for body " + body.name); //string bodyName = GetAstroObjectName(bodyProps[0].body); DetailInfo[] infoArray = new DetailInfo[bodyProps.Count]; diff --git a/NewHorizons/Utility/DebugUtilities/DebugRaycaster.cs b/NewHorizons/Utility/DebugUtilities/DebugRaycaster.cs index 6d5890f1..d7930ad1 100644 --- a/NewHorizons/Utility/DebugUtilities/DebugRaycaster.cs +++ b/NewHorizons/Utility/DebugUtilities/DebugRaycaster.cs @@ -43,7 +43,7 @@ namespace NewHorizons.Utility.DebugUtilities if (!data.hit) { - Logger.Log("Debug Raycast Didn't Hit Anything! (Try moving closer)"); + Logger.LogWarning("Debug Raycast Didn't Hit Anything! (Try moving closer)"); return; } @@ -120,7 +120,7 @@ namespace NewHorizons.Utility.DebugUtilities if (Vector3.Cross(U, N) == Vector3.zero) U = new Vector3(0, 0, 1); if (Vector3.Cross(U, N) == Vector3.zero) U = new Vector3(0, 1, 0); // if 0,0,1 was actually the same vector U already was (lol), try (0,1,0) instead - Logger.Log("Up vector is " + U.ToString()); + Logger.LogVerbose("Up vector is " + U.ToString()); // stackoverflow.com/a/9605695 // I don't know exactly how this works, but I'm projecting a point that is located above the plane's origin, relative to the planet, onto the plane. this gets us our v vector diff --git a/NewHorizons/Utility/ImageUtilities.cs b/NewHorizons/Utility/ImageUtilities.cs index b65ea0e9..ea4abafa 100644 --- a/NewHorizons/Utility/ImageUtilities.cs +++ b/NewHorizons/Utility/ImageUtilities.cs @@ -31,11 +31,11 @@ namespace NewHorizons.Utility var path = mod.ModHelper.Manifest.ModFolderPath + filename; if (_loadedTextures.ContainsKey(path)) { - Logger.Log($"Already loaded image at path: {path}"); + Logger.LogVerbose($"Already loaded image at path: {path}"); return _loadedTextures[path]; } - Logger.Log($"Loading image at path: {path}"); + Logger.LogVerbose($"Loading image at path: {path}"); try { var data = File.ReadAllBytes(path); @@ -70,7 +70,7 @@ namespace NewHorizons.Utility public static void ClearCache() { - Logger.Log("Clearing image cache"); + Logger.LogVerbose("Clearing image cache"); foreach (var texture in _loadedTextures.Values) { @@ -368,7 +368,7 @@ namespace NewHorizons.Utility { if (_loadedTextures.ContainsKey(url)) { - Logger.Log($"Already loaded image at path: {url}"); + Logger.LogVerbose($"Already loaded image at path: {url}"); var texture = _loadedTextures[url]; imageLoadedEvent.Invoke(texture, index); yield break; @@ -390,7 +390,7 @@ namespace NewHorizons.Utility if (_loadedTextures.ContainsKey(url)) { - Logger.Log($"Already loaded image at path: {url}"); + Logger.LogVerbose($"Already loaded image at path: {url}"); Destroy(texture); texture = _loadedTextures[url]; } diff --git a/NewHorizons/Utility/Logger.cs b/NewHorizons/Utility/Logger.cs index 4fb24358..1ef08544 100644 --- a/NewHorizons/Utility/Logger.cs +++ b/NewHorizons/Utility/Logger.cs @@ -1,85 +1,50 @@ -using OWML.Common; -using System; -using System.ComponentModel; -using UnityEngine; -namespace NewHorizons.Utility -{ - public static class Logger - { - - private static LogType _logLevel = LogType.Error; - - public static void UpdateLogLevel(LogType newLevel) - { - _logLevel = newLevel; - } - - public static void LogProperties(UnityEngine.Object obj) - { - foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj)) - { - string name = descriptor?.Name; - object value; - try - { - value = descriptor.GetValue(obj); - } - catch (Exception) - { - value = null; - } - - Log($"{obj.name} {name}={value}"); - } - } - - public static void LogPath(GameObject go) - { - if (go == null) Log("Can't print path: GameObject is null"); - else Log($"{go.transform.GetPath()}"); - } - - public static void Log(string text, LogType type) - { - if ((int)type < (int)_logLevel) return; - Main.Instance.ModHelper.Console.WriteLine(Enum.GetName(typeof(LogType), type) + " : " + text, LogTypeToMessageType(type)); - } +using OWML.Common; +using System; +using System.ComponentModel; +using UnityEngine; +namespace NewHorizons.Utility +{ + public static class Logger + { - public static void LogVerbose(string text) + private static LogType _logLevel = LogType.Error; + + public static void UpdateLogLevel(LogType newLevel) + { + _logLevel = newLevel; + } + + public static void Log(string text, LogType type) + { + if ((int)type < (int)_logLevel) return; + Main.Instance.ModHelper.Console.WriteLine($"{Enum.GetName(typeof(LogType), type)} : {text}", LogTypeToMessageType(type)); + } + + public static void Log(string text) => Log(text, LogType.Log); + public static void LogVerbose(string text) => Log(text, LogType.Verbose); + public static void LogError(string text) => Log(text, LogType.Error); + public static void LogWarning(string text) => Log(text, LogType.Warning); + + public enum LogType { - Log(text, LogType.Verbose); - } - public static void Log(string text) - { - Log(text, LogType.Log); - } - public static void LogError(string text) - { - Log(text, LogType.Error); - } - public static void LogWarning(string text) - { - Log(text, LogType.Warning); - } - public enum LogType - { Todo, - Verbose, - Log, - Warning, - Error, - } - private static MessageType LogTypeToMessageType(LogType t) - { - switch (t) - { - case LogType.Error: - return MessageType.Error; - case LogType.Warning: - return MessageType.Warning; - default: - return MessageType.Info; - } - } - } -} + Verbose, + Log, + Warning, + Error, + } + + private static MessageType LogTypeToMessageType(LogType t) + { + switch (t) + { + case LogType.Error: + return MessageType.Error; + case LogType.Warning: + return MessageType.Warning; + default: + return MessageType.Info; + } + } + } +} diff --git a/NewHorizons/Utility/NewHorizonExtensions.cs b/NewHorizons/Utility/NewHorizonExtensions.cs index 9c04d33d..2776a671 100644 --- a/NewHorizons/Utility/NewHorizonExtensions.cs +++ b/NewHorizons/Utility/NewHorizonExtensions.cs @@ -146,7 +146,7 @@ namespace NewHorizons.Utility bool xCorrect = nomaiCoordinateInterface._nodeControllers[0].CheckCoordinate(coordinates.x); bool yCorrect = nomaiCoordinateInterface._nodeControllers[1].CheckCoordinate(coordinates.y); bool zCorrect = nomaiCoordinateInterface._nodeControllers[2].CheckCoordinate(coordinates.z); - Utility.Logger.Log($"Coordinate Check for {system}: {xCorrect}, {yCorrect}, {zCorrect} [{string.Join("-", coordinates.x)}, {string.Join("-", coordinates.y)}, {string.Join("-", coordinates.z)}]"); + Utility.Logger.LogVerbose($"Coordinate Check for {system}: {xCorrect}, {yCorrect}, {zCorrect} [{string.Join("-", coordinates.x)}, {string.Join("-", coordinates.y)}, {string.Join("-", coordinates.z)}]"); return xCorrect && yCorrect && zCorrect; } } diff --git a/NewHorizons/Utility/SearchUtilities.cs b/NewHorizons/Utility/SearchUtilities.cs index d31310e6..18f3299e 100644 --- a/NewHorizons/Utility/SearchUtilities.cs +++ b/NewHorizons/Utility/SearchUtilities.cs @@ -13,7 +13,7 @@ namespace NewHorizons.Utility public static void ClearCache() { - Logger.Log("Clearing search cache"); + Logger.LogVerbose("Clearing search cache"); CachedGameObjects.Clear(); } diff --git a/NewHorizons/VoiceActing/VoiceHandler.cs b/NewHorizons/VoiceActing/VoiceHandler.cs index 4718d5a3..de24099e 100644 --- a/NewHorizons/VoiceActing/VoiceHandler.cs +++ b/NewHorizons/VoiceActing/VoiceHandler.cs @@ -16,7 +16,7 @@ namespace NewHorizons.VoiceActing if (API == null) { - Logger.Log("VoiceMod isn't installed"); + Logger.LogVerbose("VoiceMod isn't installed"); Enabled = false; return; } @@ -33,7 +33,7 @@ namespace NewHorizons.VoiceActing } else { - Logger.Log($"Didn't find VoiceMod audio for {mod.ModHelper.Manifest.Name} at {folder}"); + Logger.LogVerbose($"Didn't find VoiceMod audio for {mod.ModHelper.Manifest.Name} at {folder}"); } } } From 01b42f1aced294465155b9d820e3aa74dba036e8 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 5 Jul 2022 19:39:59 -0400 Subject: [PATCH 12/18] Log stuff --- NewHorizons/Builder/Body/AsteroidBeltBuilder.cs | 3 +++ NewHorizons/Handlers/PlanetCreationHandler.cs | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs index 03705a11..367930cc 100644 --- a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs +++ b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs @@ -5,6 +5,7 @@ using NewHorizons.Utility; using OWML.Common; using UnityEngine; using Random = UnityEngine.Random; +using Logger = NewHorizons.Utility.Logger; namespace NewHorizons.Builder.Body { public static class AsteroidBeltBuilder @@ -19,6 +20,8 @@ namespace NewHorizons.Builder.Body if (belt.amount >= 0) count = belt.amount; if (count > 200) count = 200; + Logger.Log($"Generating {count} asteroid belt around {bodyName}"); + Random.InitState(belt.randomSeed); for (int i = 0; i < count; i++) diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index a9a801d4..a2a36aab 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -219,7 +219,8 @@ namespace NewHorizons.Handlers { try { - GameObject planetObject = GenerateBody(body, defaultPrimaryToSun); + Logger.Log($"Creating [{body.Config.name}]"); + var planetObject = GenerateBody(body, defaultPrimaryToSun); if (planetObject == null) return false; planetObject.SetActive(true); _dict.Add(planetObject.GetComponent(), body); @@ -361,6 +362,8 @@ namespace NewHorizons.Handlers ProxyBuilder.Make(go, body); }); + Logger.LogVerbose($"Finished creating [{body.Config.name}]"); + return go; } From 708f26111efac51c6615ed1f3befe600430762d3 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 5 Jul 2022 19:40:50 -0400 Subject: [PATCH 13/18] Use var --- NewHorizons/Builder/Body/AsteroidBeltBuilder.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs index 367930cc..b106ebb4 100644 --- a/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs +++ b/NewHorizons/Builder/Body/AsteroidBeltBuilder.cs @@ -14,9 +14,9 @@ namespace NewHorizons.Builder.Body { var belt = parentConfig.AsteroidBelt; - float minSize = belt.minSize; - float maxSize = belt.maxSize; - int count = (int)(2f * Mathf.PI * belt.innerRadius / (10f * maxSize)); + var minSize = belt.minSize; + var maxSize = belt.maxSize; + var count = (int)(2f * Mathf.PI * belt.innerRadius / (10f * maxSize)); if (belt.amount >= 0) count = belt.amount; if (count > 200) count = 200; From f4ece2ab5e84505d85fc1346072fb8c7b3e0b9b4 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 5 Jul 2022 19:56:11 -0400 Subject: [PATCH 14/18] Just remove all children --- NewHorizons/Builder/Props/DetailBuilder.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index 089affe8..f21db4d4 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -42,17 +42,17 @@ namespace NewHorizons.Builder.Props var detailPath = detailGO.transform.GetPath(); foreach (var childPath in detail.removeChildren) { - // We purposefully use GameObject.Find here because we don't want to find inactive things. - // If you were to try and disable two children with the same name, if we were finding inactive then we'd disable the first one twice - var childObj = GameObject.Find($"{detailPath}/{childPath}"); - if (childObj == null) + // Multiple children can have the same path so we delete all that match + var path = $"{detailPath}/{childPath}"; + + var flag = true; + foreach (var childObj in detailGO.GetComponentsInChildren().Where(x => x.GetPath() == path)) { - Logger.LogWarning($"Couldn't find \"{childPath}\". Including disabled game objects in search."); - childObj = SearchUtilities.Find($"{detailPath}/{childPath}"); + flag = false; + childObj.gameObject.SetActive(false); } - if (childObj != null) childObj.gameObject.SetActive(false); - else Logger.LogWarning($"Couldn't find \"{childPath}\"."); + if (flag) Logger.LogWarning($"Couldn't find \"{childPath}\"."); } } From 768aa5fd27f8f4743797caf2c0f7b92b38c25663 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 5 Jul 2022 19:57:00 -0400 Subject: [PATCH 15/18] True --- NewHorizons/Builder/Props/DetailBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index f21db4d4..4331f200 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -46,7 +46,7 @@ namespace NewHorizons.Builder.Props var path = $"{detailPath}/{childPath}"; var flag = true; - foreach (var childObj in detailGO.GetComponentsInChildren().Where(x => x.GetPath() == path)) + foreach (var childObj in detailGO.GetComponentsInChildren(true).Where(x => x.GetPath() == path)) { flag = false; childObj.gameObject.SetActive(false); From a6cdea44acf075e187f72a39044fa9262fa93f9c Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 17:04:15 -0700 Subject: [PATCH 16/18] cache transforms when removing children --- NewHorizons/Builder/Props/DetailBuilder.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index 4331f200..0d1c8c7a 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -40,13 +40,14 @@ namespace NewHorizons.Builder.Props if (detail.removeChildren != null) { var detailPath = detailGO.transform.GetPath(); + var transforms = detailGO.GetComponentsInChildren(true); foreach (var childPath in detail.removeChildren) { // Multiple children can have the same path so we delete all that match var path = $"{detailPath}/{childPath}"; - + var flag = true; - foreach (var childObj in detailGO.GetComponentsInChildren(true).Where(x => x.GetPath() == path)) + foreach (var childObj in transforms.Where(x => x.GetPath() == path)) { flag = false; childObj.gameObject.SetActive(false); From 75478bc5a1a3d398287f27d66fdaad2a7f255681 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 17:06:34 -0700 Subject: [PATCH 17/18] reorder log functions to be in the same order as the enum --- NewHorizons/Utility/Logger.cs | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/NewHorizons/Utility/Logger.cs b/NewHorizons/Utility/Logger.cs index 1ef08544..8731c5da 100644 --- a/NewHorizons/Utility/Logger.cs +++ b/NewHorizons/Utility/Logger.cs @@ -14,37 +14,31 @@ namespace NewHorizons.Utility _logLevel = newLevel; } - public static void Log(string text, LogType type) + private static void Log(string text, LogType type) { if ((int)type < (int)_logLevel) return; Main.Instance.ModHelper.Console.WriteLine($"{Enum.GetName(typeof(LogType), type)} : {text}", LogTypeToMessageType(type)); } - public static void Log(string text) => Log(text, LogType.Log); public static void LogVerbose(string text) => Log(text, LogType.Verbose); - public static void LogError(string text) => Log(text, LogType.Error); + public static void Log(string text) => Log(text, LogType.Log); public static void LogWarning(string text) => Log(text, LogType.Warning); + public static void LogError(string text) => Log(text, LogType.Error); public enum LogType { - Todo, Verbose, Log, Warning, Error, } - private static MessageType LogTypeToMessageType(LogType t) - { - switch (t) + private static MessageType LogTypeToMessageType(LogType t) => + t switch { - case LogType.Error: - return MessageType.Error; - case LogType.Warning: - return MessageType.Warning; - default: - return MessageType.Info; - } - } + LogType.Error => MessageType.Error, + LogType.Warning => MessageType.Warning, + _ => MessageType.Info + }; } } From e1c76cfa9e598dc8f9d2302510024eb1a3a7fcd7 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Tue, 5 Jul 2022 17:07:18 -0700 Subject: [PATCH 18/18] no need to cast --- NewHorizons/Utility/Logger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NewHorizons/Utility/Logger.cs b/NewHorizons/Utility/Logger.cs index 8731c5da..4716a37e 100644 --- a/NewHorizons/Utility/Logger.cs +++ b/NewHorizons/Utility/Logger.cs @@ -16,7 +16,7 @@ namespace NewHorizons.Utility private static void Log(string text, LogType type) { - if ((int)type < (int)_logLevel) return; + if (type < _logLevel) return; Main.Instance.ModHelper.Console.WriteLine($"{Enum.GetName(typeof(LogType), type)} : {text}", LogTypeToMessageType(type)); }