From 6c4d8a3bfcac305f6f93c1a4c0fe56247af1a726 Mon Sep 17 00:00:00 2001 From: Nick Date: Mon, 14 Aug 2023 16:42:33 -0400 Subject: [PATCH 01/18] Make methods for following up on destruction --- .../Handlers/PlanetDestructionHandler.cs | 113 ++++++++++-------- 1 file changed, 63 insertions(+), 50 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index e8377893..06688680 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -82,11 +82,10 @@ namespace NewHorizons.Handlers // force call update here to make it switch to an active star. idk why we didnt have to do this before SunLightEffectsController.Instance.Update(); - // Since we didn't call RemoveBody on the Stranger have to call this here + // Since we didn't call RemoveBody on the all planets there are some we have to call here StrangerRemoved(); - - // Don't forget to fix THE WARP BUG - DisableBody(SearchUtilities.Find("StreamingGroup_TH"), true); + TimberHearthRemoved(); + SunRemoved(); }, 2); // Have to wait or shit goes wild foreach (var streamingAssetBundle in StreamingManager.s_activeBundles) @@ -119,11 +118,6 @@ namespace NewHorizons.Handlers { NHLogger.LogVerbose($"Removing [{ao.name}]"); - if (ao.GetAstroObjectName() == AstroObject.Name.RingWorld) - { - StrangerRemoved(); - } - if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) { NHLogger.LogVerbose($"[{ao.name}] was already removed"); @@ -153,63 +147,31 @@ namespace NewHorizons.Handlers DisableBody(fragment.gameObject, delete); } break; + case AstroObject.Name.CaveTwin: case AstroObject.Name.TowerTwin: DisableBody(SearchUtilities.Find("FocalBody"), delete); DisableBody(SearchUtilities.Find("SandFunnel_Body", false), delete); break; + case AstroObject.Name.GiantsDeep: // Might prevent leftover jellyfish from existing // Might also prevent people from using their own jellyfish however + + // TODO: Make this only affect those on GD? foreach (var jelly in UnityEngine.Object.FindObjectsOfType()) { DisableBody(jelly.gameObject, delete); } - // Else it will re-eanble the pieces - // ao.GetComponent()._realDebrisSectorProxies = null; break; case AstroObject.Name.TimberHearth: - // Always just fucking kill this one to stop THE WARP BUG!!! - DisableBody(SearchUtilities.Find("StreamingGroup_TH"), true); - - foreach (var obj in UnityEngine.Object.FindObjectsOfType()) - { - DisableBody(obj.gameObject, true); - } - foreach (var obj in UnityEngine.Object.FindObjectsOfType()) - { - DisableBody(obj.gameObject, true); - } + TimberHearthRemoved(); break; case AstroObject.Name.Sun: - var starController = ao.gameObject.GetComponent(); - SunLightEffectsController.RemoveStar(starController); - SunLightEffectsController.RemoveStarLight(ao.transform.Find("Sector_SUN/Effects_SUN/SunLight").GetComponent()); - UnityEngine.Object.Destroy(starController); - - var audio = ao.GetComponentInChildren(); - UnityEngine.Object.Destroy(audio); - - foreach (var owAudioSource in ao.GetComponentsInChildren()) - { - owAudioSource.Stop(); - UnityEngine.Object.Destroy(owAudioSource); - } - - foreach (var audioSource in ao.GetComponentsInChildren()) - { - audioSource.Stop(); - UnityEngine.Object.Destroy(audioSource); - } - - foreach (var sunProxy in UnityEngine.Object.FindObjectsOfType()) - { - NHLogger.LogVerbose($"Destroying SunProxy {sunProxy.gameObject.name}"); - UnityEngine.Object.Destroy(sunProxy.gameObject); - } - - // Stop the sun from breaking stuff when the supernova gets triggered - GlobalMessenger.RemoveListener("TriggerSupernova", ao.GetComponent().OnTriggerSupernova); + SunRemoved(); + break; + case AstroObject.Name.RingWorld: + StrangerRemoved(); break; } @@ -244,6 +206,7 @@ namespace NewHorizons.Handlers } // Deal with proxies + // TODO: There has to be a better way of doing this foreach (var p in UnityEngine.Object.FindObjectsOfType()) { if (p._originalBody == ao.gameObject) @@ -265,6 +228,56 @@ namespace NewHorizons.Handlers } } + private static void SunRemoved() + { + var sun = SearchUtilities.Find("Sun_Body").GetComponent(); + + var starController = sun.gameObject.GetComponent(); + SunLightEffectsController.RemoveStar(starController); + SunLightEffectsController.RemoveStarLight(sun.transform.Find("Sector_SUN/Effects_SUN/SunLight").GetComponent()); + UnityEngine.Object.Destroy(starController); + + var audio = sun.GetComponentInChildren(); + UnityEngine.Object.Destroy(audio); + + foreach (var owAudioSource in sun.GetComponentsInChildren()) + { + owAudioSource.Stop(); + UnityEngine.Object.Destroy(owAudioSource); + } + + foreach (var audioSource in sun.GetComponentsInChildren()) + { + audioSource.Stop(); + UnityEngine.Object.Destroy(audioSource); + } + + foreach (var sunProxy in UnityEngine.Object.FindObjectsOfType()) + { + NHLogger.LogVerbose($"Destroying SunProxy {sunProxy.gameObject.name}"); + UnityEngine.Object.Destroy(sunProxy.gameObject); + } + + // Stop the sun from breaking stuff when the supernova gets triggered + GlobalMessenger.RemoveListener("TriggerSupernova", sun.GetComponent().OnTriggerSupernova); + } + + private static void TimberHearthRemoved() + { + // Always just fucking kill this one to stop THE WARP BUG!!! + DisableBody(SearchUtilities.Find("StreamingGroup_TH"), true); + + // TODO: These should only destroy those that are on TH + foreach (var obj in UnityEngine.Object.FindObjectsOfType()) + { + DisableBody(obj.gameObject, true); + } + foreach (var obj in UnityEngine.Object.FindObjectsOfType()) + { + DisableBody(obj.gameObject, true); + } + } + public static void RemoveAllProxies() { UnityEngine.Object.Destroy(UnityEngine.Object.FindObjectOfType().gameObject); From 880dffdfa12ae6c4d9503c07957b28c0cd03856d Mon Sep 17 00:00:00 2001 From: Nick Date: Mon, 14 Aug 2023 16:44:30 -0400 Subject: [PATCH 02/18] Remove RemoveAllProxies method --- NewHorizons/Handlers/PlanetDestructionHandler.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 06688680..9b661d41 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -278,16 +278,6 @@ namespace NewHorizons.Handlers } } - public static void RemoveAllProxies() - { - UnityEngine.Object.Destroy(UnityEngine.Object.FindObjectOfType().gameObject); - - foreach (var name in _solarSystemBodies) - { - RemoveProxy(name.Replace(" ", "").Replace("'", "")); - } - } - private static bool CanSuspend(OWRigidbody rigidbody, string name) { if (rigidbody.transform.name == name) return true; From 68957327671eff69d645bf7444fd3b5b84159f4e Mon Sep 17 00:00:00 2001 From: Nick Date: Mon, 14 Aug 2023 16:51:35 -0400 Subject: [PATCH 03/18] Always update the sun light effects controller to be safe --- NewHorizons/Handlers/PlanetDestructionHandler.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 9b661d41..92ac8577 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -79,9 +79,6 @@ namespace NewHorizons.Handlers } GameObject.FindObjectOfType().gameObject.SetActive(false); - // force call update here to make it switch to an active star. idk why we didnt have to do this before - SunLightEffectsController.Instance.Update(); - // Since we didn't call RemoveBody on the all planets there are some we have to call here StrangerRemoved(); TimberHearthRemoved(); @@ -260,6 +257,9 @@ namespace NewHorizons.Handlers // Stop the sun from breaking stuff when the supernova gets triggered GlobalMessenger.RemoveListener("TriggerSupernova", sun.GetComponent().OnTriggerSupernova); + + // Just to be safe + SunLightEffectsController.Instance.Update(); } private static void TimberHearthRemoved() From eef5323869e02278a2f6099a27f52b5c68189a8d Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 12:45:25 -0400 Subject: [PATCH 04/18] Cache root objects --- NewHorizons/Utility/SearchUtilities.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/NewHorizons/Utility/SearchUtilities.cs b/NewHorizons/Utility/SearchUtilities.cs index 0bbc5990..9ed77826 100644 --- a/NewHorizons/Utility/SearchUtilities.cs +++ b/NewHorizons/Utility/SearchUtilities.cs @@ -10,11 +10,13 @@ namespace NewHorizons.Utility public static class SearchUtilities { private static readonly Dictionary CachedGameObjects = new Dictionary(); + private static readonly Dictionary CachedRootGameObjects = new Dictionary(); public static void ClearCache() { NHLogger.LogVerbose("Clearing search cache"); CachedGameObjects.Clear(); + CachedRootGameObjects.Clear(); } public static List FindObjectsOfTypeAndName(string name) where T : Object @@ -107,8 +109,16 @@ namespace NewHorizons.Utility // 2: find inactive using root + transform.find var names = path.Split('/'); + // Cache the root objects so we don't loop through all of them each time var rootName = names[0]; - var root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName); + if (!CachedRootGameObjects.TryGetValue(rootName, out var root)) + { + root = SceneManager.GetActiveScene().GetRootGameObjects().FirstOrDefault(x => x.name == rootName); + if (root != null) + { + CachedRootGameObjects.Add(rootName, root); + } + } var childPath = string.Join("/", names.Skip(1)); go = root ? root.FindChild(childPath) : null; From 588995bb9b3e23f1d4a7a548bf3cada7c36e3c81 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 13:00:11 -0400 Subject: [PATCH 05/18] Only clear asset bundle cache when changing star system --- .../Builder/Body/SupernovaEffectBuilder.cs | 2 +- NewHorizons/Main.cs | 2 +- .../Utility/Files/AssetBundleUtilities.cs | 35 ++++++++++++++----- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs b/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs index 32086640..9b4c18ec 100644 --- a/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs +++ b/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs @@ -164,7 +164,7 @@ namespace NewHorizons.Builder.Body { if (!string.IsNullOrWhiteSpace(config.ShockEffect.assetBundle) && !string.IsNullOrWhiteSpace(config.ShockEffect.meshPath)) { - var mesh = AssetBundleUtilities.Load(config.ShockEffect.assetBundle, config.ShockEffect.meshPath, mod); + var mesh = AssetBundleUtilities.Load(config.ShockEffect.assetBundle, config.ShockEffect.meshPath, mod, config.starSystem); if (mesh != null) { shockLayer.GetComponent().sharedMesh = mesh; diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index e056b4c3..a3ee3d60 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -262,7 +262,7 @@ namespace NewHorizons SearchUtilities.ClearCache(); ImageUtilities.ClearCache(); AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); + AssetBundleUtilities.OnSceneUnloaded(); EnumUtilities.ClearCache(); IsSystemReady = false; } diff --git a/NewHorizons/Utility/Files/AssetBundleUtilities.cs b/NewHorizons/Utility/Files/AssetBundleUtilities.cs index 60fdce56..678f3bc8 100644 --- a/NewHorizons/Utility/Files/AssetBundleUtilities.cs +++ b/NewHorizons/Utility/Files/AssetBundleUtilities.cs @@ -3,25 +3,42 @@ using OWML.Common; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using UnityEngine; namespace NewHorizons.Utility.Files { public static class AssetBundleUtilities { - public static Dictionary AssetBundles = new Dictionary(); + public static Dictionary AssetBundles = new(); - public static void ClearCache() + public static void OnSceneUnloaded() { - foreach (var pair in AssetBundles) + var bundleKeys = AssetBundles.Keys.ToArray(); + + foreach (var key in bundleKeys) { - if (pair.Value == null) NHLogger.LogError($"The asset bundle for {pair.Key} was null when trying to unload"); - else pair.Value.Unload(true); + var (starSystem, bundle) = AssetBundles[key]; + // If the star system is null/empty keep loaded forever, else only unload when we leave the system + if (!string.IsNullOrEmpty(starSystem) && starSystem != Main.Instance.CurrentStarSystem) + { + if (bundle == null) NHLogger.LogError($"The asset bundle for [{key}] was null when trying to unload"); + else bundle.Unload(true); + + AssetBundles.Remove(key); + } + else + { + NHLogger.LogVerbose($"Not unloading bundle [{key}] because it is still in use for system [{starSystem}]"); + } } - AssetBundles.Clear(); } + // On the off chance this was being called from another mod public static T Load(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod) where T : UnityEngine.Object + => Load(assetBundleRelativeDir, pathInBundle, mod, Main.Instance.CurrentStarSystem); + + public static T Load(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod, string starSystem) where T : UnityEngine.Object { string key = Path.GetFileName(assetBundleRelativeDir); T obj; @@ -32,7 +49,7 @@ namespace NewHorizons.Utility.Files if (AssetBundles.ContainsKey(key)) { - bundle = AssetBundles[key]; + bundle = AssetBundles[key].bundle; } else { @@ -44,7 +61,7 @@ namespace NewHorizons.Utility.Files return null; } - AssetBundles[key] = bundle; + AssetBundles[key] = (starSystem, bundle); } obj = bundle.LoadAsset(pathInBundle); @@ -60,7 +77,7 @@ namespace NewHorizons.Utility.Files public static GameObject LoadPrefab(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod) { - var prefab = Load(assetBundleRelativeDir, pathInBundle, mod); + var prefab = Load(assetBundleRelativeDir, pathInBundle, mod, Main.Instance.CurrentStarSystem); prefab.SetActive(false); From 734f6e1f6ae3b097f4ff5775655445b5f66812ac Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 13:36:04 -0400 Subject: [PATCH 06/18] Clean up destruction, do proxies better --- NewHorizons/Handlers/PlanetCreationHandler.cs | 10 +- .../Handlers/PlanetDestructionHandler.cs | 316 +++++++----------- NewHorizons/Handlers/ProxyHandler.cs | 46 ++- NewHorizons/Main.cs | 1 + .../Patches/ProxyPatches/ProxyBodyPatches.cs | 25 +- .../ProxyPatches/ProxyOrbiterPatches.cs | 15 + 6 files changed, 201 insertions(+), 212 deletions(-) create mode 100644 NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index 2b014cbf..7c33c7b9 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -169,8 +169,14 @@ namespace NewHorizons.Handlers if (body.Config.destroy) { var ao = existingPlanet.GetComponent(); - if (ao != null) Delay.FireInNUpdates(() => PlanetDestructionHandler.RemoveBody(ao), 2); - else Delay.FireInNUpdates(() => PlanetDestructionHandler.DisableBody(existingPlanet, false), 2); + if (ao != null) + { + Delay.FireInNUpdates(() => PlanetDestructionHandler.DisableAstroObject(ao), 2); + } + else + { + Delay.FireInNUpdates(() => PlanetDestructionHandler.DisableGameObject(existingPlanet), 2); + } } else if (body.Config.isQuantumState) { diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 92ac8577..866e48b4 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -11,48 +11,9 @@ namespace NewHorizons.Handlers { public static class PlanetDestructionHandler { - private static readonly string[] _solarSystemBodies = new string[] - { - "Ash Twin", - "Attlerock", - "Brittle Hollow", - "Dark Bramble", - "DreamWorld", - "Ember Twin", - "Giant's Deep", - "Hollow's Lantern", - "Interloper", - "Map Satellite", - "Orbital Probe Cannon", - "Quantum Moon", - "RingWorld", - "Sun", - "Sun Station", - "Timber Hearth", - "White Hole" - }; - - private static readonly string[] _eyeOfTheUniverseBodies = new string[] - { - "Eye Of The Universe", - "Vessel" - }; - - private static readonly string[] _suspendBlacklist = new string[] - { - "Player_Body", - "Ship_Body" - }; + public static readonly string[] _suspendBlacklist = new string[] { "Player_Body", "Probe_Body", "Ship_Body" }; public static void RemoveStockPlanets() - { - if (Main.Instance.CurrentStarSystem == "EyeOfTheUniverse") - RemoveEyeOfTheUniverse(); - else - RemoveSolarSystem(); - } - - public static void RemoveSolarSystem() { // Adapted from EOTS thanks corby var toDisable = new List(); @@ -60,7 +21,7 @@ namespace NewHorizons.Handlers // Collect all rigid bodies and proxies foreach (var rigidbody in CenterOfTheUniverse.s_rigidbodies) { - if (rigidbody.name is not ("Player_Body" or "Probe_Body" or "Ship_Body")) + if (!_suspendBlacklist.Contains(rigidbody.name)) { toDisable.Add(rigidbody.gameObject); } @@ -79,28 +40,18 @@ namespace NewHorizons.Handlers } GameObject.FindObjectOfType().gameObject.SetActive(false); - // Since we didn't call RemoveBody on the all planets there are some we have to call here - StrangerRemoved(); - TimberHearthRemoved(); - SunRemoved(); + if (Main.Instance.CurrentStarSystem != "EyeOfTheUniverse") + { + // Since we didn't call RemoveBody on the all planets there are some we have to call here + StrangerRemoved(); + TimberHearthRemoved(); + SunRemoved(); + } + }, 2); // Have to wait or shit goes wild - - foreach (var streamingAssetBundle in StreamingManager.s_activeBundles) - { - //streamingAssetBundle.Unload(); - } - } - - public static void RemoveEyeOfTheUniverse() - { - foreach (var name in _eyeOfTheUniverseBodies) - { - var ao = AstroObjectLocator.GetAstroObject(name); - if (ao != null) Delay.FireInNUpdates(() => RemoveBody(ao, false), 2); - else NHLogger.LogError($"Couldn't find [{name}]"); - } } + #region Planet specific removals public static void StrangerRemoved() { CloakHandler.FlagStrangerDisabled = true; @@ -111,120 +62,6 @@ namespace NewHorizons.Handlers } } - public static void RemoveBody(AstroObject ao, bool delete = false, List toDestroy = null) - { - NHLogger.LogVerbose($"Removing [{ao.name}]"); - - if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) - { - NHLogger.LogVerbose($"[{ao.name}] was already removed"); - return; - } - - if (toDestroy == null) toDestroy = new List(); - - if (toDestroy.Contains(ao)) - { - NHLogger.LogVerbose($"Possible infinite recursion in RemoveBody: {ao.name} might be it's own primary body?"); - return; - } - - toDestroy.Add(ao); - - try - { - switch(ao._name) - { - case AstroObject.Name.BrittleHollow: - RemoveBody(AstroObjectLocator.GetAstroObject(AstroObject.Name.WhiteHole.ToString()), delete, toDestroy); - // Might prevent leftover fragments from existing - // Might also prevent people from using their own detachable fragments however - foreach(var fragment in UnityEngine.Object.FindObjectsOfType()) - { - DisableBody(fragment.gameObject, delete); - } - break; - - case AstroObject.Name.CaveTwin: - case AstroObject.Name.TowerTwin: - DisableBody(SearchUtilities.Find("FocalBody"), delete); - DisableBody(SearchUtilities.Find("SandFunnel_Body", false), delete); - break; - - case AstroObject.Name.GiantsDeep: - // Might prevent leftover jellyfish from existing - // Might also prevent people from using their own jellyfish however - - // TODO: Make this only affect those on GD? - foreach (var jelly in UnityEngine.Object.FindObjectsOfType()) - { - DisableBody(jelly.gameObject, delete); - } - break; - case AstroObject.Name.TimberHearth: - TimberHearthRemoved(); - break; - case AstroObject.Name.Sun: - SunRemoved(); - break; - case AstroObject.Name.RingWorld: - StrangerRemoved(); - break; - } - - // Always delete the children - NHLogger.LogVerbose($"Removing Children of [{ao._name}], [{ao._customName}]"); - foreach (var child in AstroObjectLocator.GetChildren(ao)) - { - if (child == null) continue; - - NHLogger.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; - - // Some children might be astro objects and as such can have children of their own - var childAO = child.GetComponent(); - if (childAO != null) RemoveBody(childAO, false, toDestroy); - else DisableBody(child, true); - } - - // Always delete moons - foreach (var obj in AstroObjectLocator.GetMoons(ao)) - { - if (obj == null) continue; - - RemoveBody(obj.GetComponent(), false, toDestroy); - } - } - catch (Exception e) - { - NHLogger.LogError($"Exception thrown when trying to delete bodies related to [{ao.name}]:\n{e}"); - } - - // Deal with proxies - // TODO: There has to be a better way of doing this - foreach (var p in UnityEngine.Object.FindObjectsOfType()) - { - if (p._originalBody == ao.gameObject) - { - DisableBody(p.gameObject, true); - break; - } - } - RemoveProxy(ao.name.Replace("_Body", "")); - - Delay.RunWhen(() => Main.IsSystemReady, () => DisableBody(ao.gameObject, delete)); - - foreach (ProxyBody proxy in UnityEngine.Object.FindObjectsOfType()) - { - if (proxy?._realObjectTransform?.gameObject == ao.gameObject) - { - UnityEngine.Object.Destroy(proxy.gameObject); - } - } - } - private static void SunRemoved() { var sun = SearchUtilities.Find("Sun_Body").GetComponent(); @@ -265,18 +102,112 @@ namespace NewHorizons.Handlers private static void TimberHearthRemoved() { // Always just fucking kill this one to stop THE WARP BUG!!! - DisableBody(SearchUtilities.Find("StreamingGroup_TH"), true); + GameObject.Destroy(SearchUtilities.Find("StreamingGroup_TH").gameObject); // TODO: These should only destroy those that are on TH foreach (var obj in UnityEngine.Object.FindObjectsOfType()) { - DisableBody(obj.gameObject, true); + GameObject.Destroy(obj.gameObject); } foreach (var obj in UnityEngine.Object.FindObjectsOfType()) { - DisableBody(obj.gameObject, true); + GameObject.Destroy(obj.gameObject); } } + #endregion + + public static void DisableAstroObject(AstroObject ao, List toDisable = null) + { + NHLogger.LogVerbose($"Removing [{ao.name}]"); + + if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) + { + NHLogger.LogVerbose($"[{ao.name}] was already removed"); + return; + } + + toDisable ??= new List(); + + if (toDisable.Contains(ao)) + { + NHLogger.LogVerbose($"Possible infinite recursion in RemoveBody: {ao.name} might be it's own primary body?"); + return; + } + + toDisable.Add(ao); + + try + { + switch(ao._name) + { + case AstroObject.Name.BrittleHollow: + DisableAstroObject(AstroObjectLocator.GetAstroObject(AstroObject.Name.WhiteHole.ToString()), toDisable); + // Might prevent leftover fragments from existing + // Might also prevent people from using their own detachable fragments however + foreach(var fragment in UnityEngine.Object.FindObjectsOfType()) + { + DisableGameObject(fragment.gameObject); + } + break; + + case AstroObject.Name.CaveTwin: + case AstroObject.Name.TowerTwin: + DisableGameObject(SearchUtilities.Find("FocalBody")); + DisableGameObject(SearchUtilities.Find("SandFunnel_Body", false)); + break; + + case AstroObject.Name.GiantsDeep: + foreach (var jelly in UnityEngine.Object.FindObjectsOfType()) + { + if (jelly.GetSector().GetRootSector().GetName() == Sector.Name.GiantsDeep) + { + DisableGameObject(jelly.gameObject); + } + } + break; + case AstroObject.Name.TimberHearth: + TimberHearthRemoved(); + break; + case AstroObject.Name.Sun: + SunRemoved(); + break; + case AstroObject.Name.RingWorld: + StrangerRemoved(); + break; + } + + // Always delete the children + NHLogger.LogVerbose($"Removing Children of [{ao._name}], [{ao._customName}]"); + foreach (var child in AstroObjectLocator.GetChildren(ao)) + { + if (child == null) continue; + + NHLogger.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; + + // Some children might be astro objects and as such can have children of their own + var childAO = child.GetComponent(); + if (childAO != null) DisableAstroObject(childAO, toDisable); + else DisableGameObject(child); + } + + // Always delete moons + foreach (var obj in AstroObjectLocator.GetMoons(ao)) + { + if (obj == null) continue; + + DisableAstroObject(obj.GetComponent(), toDisable); + } + } + catch (Exception e) + { + NHLogger.LogError($"Exception thrown when trying to delete bodies related to [{ao.name}]:\n{e}"); + } + + RemoveProxy(ao); + } private static bool CanSuspend(OWRigidbody rigidbody, string name) { @@ -285,7 +216,7 @@ namespace NewHorizons.Handlers return CanSuspend(rigidbody._origParentBody, name); } - internal static void DisableBody(GameObject go, bool delete) + internal static void DisableGameObject(GameObject go) { if (go == null) return; @@ -316,33 +247,18 @@ namespace NewHorizons.Handlers } } - if (delete) + go.SetActive(false); + var ol = go.GetComponentInChildren(); + if (ol) { - UnityEngine.Object.Destroy(go); - } - else - { - go.SetActive(false); - var ol = go.GetComponentInChildren(); - if (ol) - { - ol.enabled = false; - } + ol.enabled = false; } } - private static void RemoveProxy(string name) + private static void RemoveProxy(AstroObject ao) { - if (name.Equals("TowerTwin")) name = "AshTwin"; - if (name.Equals("CaveTwin")) name = "EmberTwin"; - var distantProxy = SearchUtilities.Find(name + "_DistantProxy", false); - var distantProxyClone = SearchUtilities.Find(name + "_DistantProxy(Clone)", false); - - if (distantProxy != null) UnityEngine.Object.Destroy(distantProxy.gameObject); - if (distantProxyClone != null) UnityEngine.Object.Destroy(distantProxyClone.gameObject); - - if (distantProxy == null && distantProxyClone == null) - NHLogger.LogVerbose($"Couldn't find proxy for {name}"); + ProxyHandler.GetVanillaProxyBody(ao.transform)?.gameObject?.SetActive(false); + ProxyHandler.GetVanillaProxyOrbiter(ao.transform)?.gameObject?.SetActive(false); } } } diff --git a/NewHorizons/Handlers/ProxyHandler.cs b/NewHorizons/Handlers/ProxyHandler.cs index 090d519d..cb6544ee 100644 --- a/NewHorizons/Handlers/ProxyHandler.cs +++ b/NewHorizons/Handlers/ProxyHandler.cs @@ -1,11 +1,21 @@ using NewHorizons.Components; using System.Collections.Generic; +using UnityEngine; namespace NewHorizons.Handlers { public static class ProxyHandler { - private static List _proxies = new List(); + private static List _proxies = new(); + private static Dictionary _vanillaProxyBody = new(); + private static Dictionary _vanillaProxyOrbiter = new(); + + public static void OnSceneUnloaded() + { + _proxies.Clear(); + _vanillaProxyBody.Clear(); + _vanillaProxyOrbiter.Clear(); + } public static NHProxy GetProxy(string astroName) { @@ -17,6 +27,40 @@ namespace NewHorizons.Handlers return null; } + public static void RegisterVanillaProxyBody(ProxyBody proxy) + { + _vanillaProxyBody.Add(proxy.realObjectTransform, proxy); + } + + public static ProxyBody GetVanillaProxyBody(Transform t) + { + if (_vanillaProxyBody.TryGetValue(t, out ProxyBody proxy)) + { + return proxy; + } + else + { + return null; + } + } + + public static void RegisterVanillaProxyOrbiter(ProxyOrbiter proxy) + { + _vanillaProxyOrbiter.Add(proxy._originalPlanetBody, proxy); + } + + public static ProxyOrbiter GetVanillaProxyOrbiter(Transform t) + { + if (_vanillaProxyOrbiter.TryGetValue(t, out ProxyOrbiter proxy)) + { + return proxy; + } + else + { + return null; + } + } + public static void RegisterProxy(NHProxy proxy) { _proxies.SafeAdd(proxy); diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 2906f9be..74a201f7 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -264,6 +264,7 @@ namespace NewHorizons AudioUtilities.ClearCache(); AssetBundleUtilities.ClearCache(); EnumUtilities.ClearCache(); + ProxyHandler.OnSceneUnloaded(); IsSystemReady = false; } diff --git a/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs b/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs index 5ff71810..b8f648ac 100644 --- a/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs +++ b/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs @@ -1,15 +1,22 @@ using HarmonyLib; +using NewHorizons.Handlers; -namespace NewHorizons.Patches.ProxyPatches +namespace NewHorizons.Patches.ProxyPatches; + +[HarmonyPatch(typeof(ProxyBody))] +public static class ProxyBodyPatches { - [HarmonyPatch(typeof(ProxyBody))] - public static class ProxyBodyPatches + [HarmonyPostfix] + [HarmonyPatch(nameof(ProxyBody.Awake))] + public static void ProxyBody_Awake(ProxyBody __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(ProxyBody.IsObjectInSupernova))] - public static bool ProxyBody_IsObjectInSupernova(ProxyBody __instance) - { - return Locator.GetSunController() != null; - } + ProxyHandler.RegisterVanillaProxyBody(__instance); + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(ProxyBody.IsObjectInSupernova))] + public static bool ProxyBody_IsObjectInSupernova(ProxyBody __instance) + { + return Locator.GetSunController() != null; } } diff --git a/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs b/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs new file mode 100644 index 00000000..c505b5f4 --- /dev/null +++ b/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs @@ -0,0 +1,15 @@ +using HarmonyLib; +using NewHorizons.Handlers; + +namespace NewHorizons.Patches.ProxyPatches; + +[HarmonyPatch(typeof(ProxyOrbiter))] +public static class ProxyOrbiterPatches +{ + [HarmonyPostfix] + [HarmonyPatch(nameof(ProxyOrbiter.Awake))] + public static void ProxyOrbiter_Awake(ProxyOrbiter __instance) + { + ProxyHandler.RegisterVanillaProxyOrbiter(__instance); + } +} From fe8d0888704cdaacd9c98e496557fb3a3f8691f9 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 13:39:38 -0400 Subject: [PATCH 07/18] Giants deep killing method --- .../Handlers/PlanetDestructionHandler.cs | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 866e48b4..79a92b2e 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -45,6 +45,7 @@ namespace NewHorizons.Handlers // Since we didn't call RemoveBody on the all planets there are some we have to call here StrangerRemoved(); TimberHearthRemoved(); + GiantsDeepRemoved(); SunRemoved(); } @@ -114,6 +115,17 @@ namespace NewHorizons.Handlers GameObject.Destroy(obj.gameObject); } } + + private static void GiantsDeepRemoved() + { + foreach (var jelly in UnityEngine.Object.FindObjectsOfType()) + { + if (jelly.GetSector().GetRootSector().GetName() == Sector.Name.GiantsDeep) + { + DisableGameObject(jelly.gameObject); + } + } + } #endregion public static void DisableAstroObject(AstroObject ao, List toDisable = null) @@ -157,13 +169,7 @@ namespace NewHorizons.Handlers break; case AstroObject.Name.GiantsDeep: - foreach (var jelly in UnityEngine.Object.FindObjectsOfType()) - { - if (jelly.GetSector().GetRootSector().GetName() == Sector.Name.GiantsDeep) - { - DisableGameObject(jelly.gameObject); - } - } + GiantsDeepRemoved(); break; case AstroObject.Name.TimberHearth: TimberHearthRemoved(); @@ -189,8 +195,14 @@ namespace NewHorizons.Handlers // Some children might be astro objects and as such can have children of their own var childAO = child.GetComponent(); - if (childAO != null) DisableAstroObject(childAO, toDisable); - else DisableGameObject(child); + if (childAO != null) + { + DisableAstroObject(childAO, toDisable); + } + else + { + DisableGameObject(child); + } } // Always delete moons From 21d7b369d0f618a0815e4a78eb29da0bc572a7bb Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 13:42:35 -0400 Subject: [PATCH 08/18] Only destroy daynight/villagemusic on TH --- NewHorizons/Handlers/PlanetDestructionHandler.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 79a92b2e..9aa9e129 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -105,12 +105,12 @@ namespace NewHorizons.Handlers // Always just fucking kill this one to stop THE WARP BUG!!! GameObject.Destroy(SearchUtilities.Find("StreamingGroup_TH").gameObject); - // TODO: These should only destroy those that are on TH - foreach (var obj in UnityEngine.Object.FindObjectsOfType()) + var timberHearth = SearchUtilities.Find("TimberHearth_Body"); + foreach (var obj in timberHearth.GetComponentsInChildren()) { GameObject.Destroy(obj.gameObject); } - foreach (var obj in UnityEngine.Object.FindObjectsOfType()) + foreach (var obj in timberHearth.GetComponentsInChildren()) { GameObject.Destroy(obj.gameObject); } From 330b1b1675e7e84acdb6b5eeb6ab2281e3b7683f Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 24 Aug 2023 14:38:37 -0400 Subject: [PATCH 09/18] Fix null keys --- NewHorizons/Handlers/ProxyHandler.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/NewHorizons/Handlers/ProxyHandler.cs b/NewHorizons/Handlers/ProxyHandler.cs index cb6544ee..a9c36c4d 100644 --- a/NewHorizons/Handlers/ProxyHandler.cs +++ b/NewHorizons/Handlers/ProxyHandler.cs @@ -29,7 +29,10 @@ namespace NewHorizons.Handlers public static void RegisterVanillaProxyBody(ProxyBody proxy) { - _vanillaProxyBody.Add(proxy.realObjectTransform, proxy); + if (proxy.realObjectTransform != null) + { + _vanillaProxyBody.Add(proxy.realObjectTransform, proxy); + } } public static ProxyBody GetVanillaProxyBody(Transform t) @@ -46,7 +49,10 @@ namespace NewHorizons.Handlers public static void RegisterVanillaProxyOrbiter(ProxyOrbiter proxy) { - _vanillaProxyOrbiter.Add(proxy._originalPlanetBody, proxy); + if (proxy._originalPlanetBody != null) + { + _vanillaProxyOrbiter.Add(proxy._originalPlanetBody, proxy); + } } public static ProxyOrbiter GetVanillaProxyOrbiter(Transform t) From 601acecbb2970f454a63d204b06ba5b1df17f7fd Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 22:30:51 -0400 Subject: [PATCH 10/18] Just call it clear cache sure --- NewHorizons/Main.cs | 2 +- NewHorizons/Utility/Files/AssetBundleUtilities.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index ced1b3f6..70de2b76 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -262,7 +262,7 @@ namespace NewHorizons SearchUtilities.ClearCache(); ImageUtilities.ClearCache(); AudioUtilities.ClearCache(); - AssetBundleUtilities.OnSceneUnloaded(); + AssetBundleUtilities.ClearCache(); EnumUtilities.ClearCache(); ProxyHandler.OnSceneUnloaded(); IsSystemReady = false; diff --git a/NewHorizons/Utility/Files/AssetBundleUtilities.cs b/NewHorizons/Utility/Files/AssetBundleUtilities.cs index 678f3bc8..1f54c2a7 100644 --- a/NewHorizons/Utility/Files/AssetBundleUtilities.cs +++ b/NewHorizons/Utility/Files/AssetBundleUtilities.cs @@ -12,7 +12,7 @@ namespace NewHorizons.Utility.Files { public static Dictionary AssetBundles = new(); - public static void OnSceneUnloaded() + public static void ClearCache() { var bundleKeys = AssetBundles.Keys.ToArray(); From 4c9c35314595edf70551d45d62c1ee3366a89ab2 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 22:36:48 -0400 Subject: [PATCH 11/18] Only clear certain caches on star system changed --- NewHorizons/Main.cs | 57 +++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 18 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 70de2b76..f54d3e47 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -58,7 +58,21 @@ namespace NewHorizons public static bool IsSystemReady { get; private set; } public string DefaultStarSystem => SystemDict.ContainsKey(_defaultSystemOverride) ? _defaultSystemOverride : _defaultStarSystem; - public string CurrentStarSystem => _currentStarSystem; + public string CurrentStarSystem + { + get + { + return _currentStarSystem; + } + private set + { + _previousStarSystem = _currentStarSystem; + _currentStarSystem = value; + } + } + private string _currentStarSystem = "SolarSystem"; + private string _previousStarSystem; + public bool TimeLoopEnabled => SystemDict[CurrentStarSystem]?.Config?.enableTimeLoop ?? true; public bool IsWarpingFromShip { get; private set; } = false; public bool IsWarpingFromVessel { get; private set; } = false; @@ -72,7 +86,7 @@ namespace NewHorizons public static bool HasWarpDrive { get; private set; } = false; private string _defaultStarSystem = "SolarSystem"; - internal string _currentStarSystem = "SolarSystem"; + private bool _firstLoad = true; private bool _playerAwake; @@ -259,12 +273,19 @@ namespace NewHorizons private void OnSceneUnloaded(Scene scene) { + // Caches of GameObjects must always be cleared SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - EnumUtilities.ClearCache(); ProxyHandler.OnSceneUnloaded(); + + // Caches of other assets only have to be cleared if we changed star systems + if (CurrentStarSystem != _previousStarSystem) + { + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + EnumUtilities.ClearCache(); + } + IsSystemReady = false; } @@ -330,7 +351,7 @@ namespace NewHorizons if (isEyeOfTheUniverse) { - _currentStarSystem = "EyeOfTheUniverse"; + CurrentStarSystem = "EyeOfTheUniverse"; } else if (IsWarpingBackToEye) { @@ -341,14 +362,14 @@ namespace NewHorizons return; } - if (!SystemDict.ContainsKey(_currentStarSystem) || !BodyDict.ContainsKey(_currentStarSystem)) + if (!SystemDict.ContainsKey(CurrentStarSystem) || !BodyDict.ContainsKey(CurrentStarSystem)) { - NHLogger.LogError($"System \"{_currentStarSystem}\" does not exist!"); - _currentStarSystem = DefaultStarSystem; + NHLogger.LogError($"System \"{CurrentStarSystem}\" does not exist!"); + CurrentStarSystem = DefaultStarSystem; } // Set time loop stuff if its enabled and if we're warping to a new place - if (IsChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsElapsedInLoop > 0f) + if (IsChangingStarSystem && (SystemDict[CurrentStarSystem].Config.enableTimeLoop || CurrentStarSystem == "SolarSystem") && SecondsElapsedInLoop > 0f) { TimeLoopUtilities.SetSecondsElapsed(SecondsElapsedInLoop); // Prevent the OPC from firing @@ -604,7 +625,7 @@ namespace NewHorizons if (starSystemName != "SolarSystem") { SetDefaultSystem(starSystemName); - _currentStarSystem = DefaultStarSystem; + CurrentStarSystem = DefaultStarSystem; } } @@ -821,7 +842,7 @@ namespace NewHorizons // If we're just on the title screen set the system for later if (LoadManager.GetCurrentScene() == OWScene.TitleScreen) { - _currentStarSystem = newStarSystem; + CurrentStarSystem = newStarSystem; IsWarpingFromShip = warp; IsWarpingFromVessel = vessel; DidWarpFromVessel = false; @@ -865,13 +886,13 @@ namespace NewHorizons { PlayerData.SaveEyeCompletion(); // So that the title screen doesn't keep warping you back to eye - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsElapsedInLoop = TimeLoop.GetSecondsElapsed(); + if (SystemDict[CurrentStarSystem].Config.enableTimeLoop) SecondsElapsedInLoop = TimeLoop.GetSecondsElapsed(); else SecondsElapsedInLoop = -1; sceneToLoad = OWScene.SolarSystem; } - _currentStarSystem = newStarSystem; + CurrentStarSystem = newStarSystem; // Freeze player inputs OWInput.ChangeInputMode(InputMode.None); @@ -891,7 +912,7 @@ namespace NewHorizons // We reset the solar system on death if (!IsChangingStarSystem) { - if (SystemDict[_currentStarSystem].Config.respawnHere) return; + if (SystemDict[CurrentStarSystem].Config.respawnHere) return; ResetCurrentStarSystem(); } @@ -901,7 +922,7 @@ namespace NewHorizons { if (SystemDict.ContainsKey(_defaultSystemOverride)) { - _currentStarSystem = _defaultSystemOverride; + CurrentStarSystem = _defaultSystemOverride; // Sometimes the override will not support spawning regularly, so always warp in IsWarpingFromShip = true; @@ -914,7 +935,7 @@ namespace NewHorizons NHLogger.LogError($"The given default system override {_defaultSystemOverride} is invalid - no system exists with that name"); } - _currentStarSystem = _defaultStarSystem; + CurrentStarSystem = _defaultStarSystem; IsWarpingFromShip = false; } } From 84654724a66473cbb3d8c6037165be180a1d9744 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 22:40:44 -0400 Subject: [PATCH 12/18] Fix goofy stuff --- .../Builder/Body/SupernovaEffectBuilder.cs | 2 +- NewHorizons/Handlers/ProxyHandler.cs | 2 +- NewHorizons/Main.cs | 4 +-- .../EyeScenePatches/LoadManagerPatches.cs | 4 +-- .../VesselWarpControllerPatches.cs | 2 +- .../Utility/Files/AssetBundleUtilities.cs | 33 +++++-------------- 6 files changed, 15 insertions(+), 32 deletions(-) diff --git a/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs b/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs index 9b4c18ec..32086640 100644 --- a/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs +++ b/NewHorizons/Builder/Body/SupernovaEffectBuilder.cs @@ -164,7 +164,7 @@ namespace NewHorizons.Builder.Body { if (!string.IsNullOrWhiteSpace(config.ShockEffect.assetBundle) && !string.IsNullOrWhiteSpace(config.ShockEffect.meshPath)) { - var mesh = AssetBundleUtilities.Load(config.ShockEffect.assetBundle, config.ShockEffect.meshPath, mod, config.starSystem); + var mesh = AssetBundleUtilities.Load(config.ShockEffect.assetBundle, config.ShockEffect.meshPath, mod); if (mesh != null) { shockLayer.GetComponent().sharedMesh = mesh; diff --git a/NewHorizons/Handlers/ProxyHandler.cs b/NewHorizons/Handlers/ProxyHandler.cs index a9c36c4d..42bb51f2 100644 --- a/NewHorizons/Handlers/ProxyHandler.cs +++ b/NewHorizons/Handlers/ProxyHandler.cs @@ -10,7 +10,7 @@ namespace NewHorizons.Handlers private static Dictionary _vanillaProxyBody = new(); private static Dictionary _vanillaProxyOrbiter = new(); - public static void OnSceneUnloaded() + public static void ClearCache() { _proxies.Clear(); _vanillaProxyBody.Clear(); diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index f54d3e47..a78e9eff 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -64,7 +64,7 @@ namespace NewHorizons { return _currentStarSystem; } - private set + internal set { _previousStarSystem = _currentStarSystem; _currentStarSystem = value; @@ -275,7 +275,7 @@ namespace NewHorizons { // Caches of GameObjects must always be cleared SearchUtilities.ClearCache(); - ProxyHandler.OnSceneUnloaded(); + ProxyHandler.ClearCache(); // Caches of other assets only have to be cleared if we changed star systems if (CurrentStarSystem != _previousStarSystem) diff --git a/NewHorizons/Patches/EyeScenePatches/LoadManagerPatches.cs b/NewHorizons/Patches/EyeScenePatches/LoadManagerPatches.cs index 2bf53abf..cf12480a 100644 --- a/NewHorizons/Patches/EyeScenePatches/LoadManagerPatches.cs +++ b/NewHorizons/Patches/EyeScenePatches/LoadManagerPatches.cs @@ -12,10 +12,10 @@ namespace NewHorizons.Patches.EyeScenePatches PlayerData.SaveEyeCompletion(); // Switch to default just in case another mod warps back. - if (Main.Instance.CurrentStarSystem == "EyeOfTheUniverse") Main.Instance._currentStarSystem = Main.Instance.DefaultStarSystem; + if (Main.Instance.CurrentStarSystem == "EyeOfTheUniverse") Main.Instance.CurrentStarSystem = Main.Instance.DefaultStarSystem; } // Switch to eye just in case another mod warps there. - else if (scene == OWScene.EyeOfTheUniverse) Main.Instance._currentStarSystem = "EyeOfTheUniverse"; + else if (scene == OWScene.EyeOfTheUniverse) Main.Instance.CurrentStarSystem = "EyeOfTheUniverse"; } [HarmonyPrefix] diff --git a/NewHorizons/Patches/WarpPatches/VesselWarpControllerPatches.cs b/NewHorizons/Patches/WarpPatches/VesselWarpControllerPatches.cs index 8089ac89..559f43d0 100644 --- a/NewHorizons/Patches/WarpPatches/VesselWarpControllerPatches.cs +++ b/NewHorizons/Patches/WarpPatches/VesselWarpControllerPatches.cs @@ -63,7 +63,7 @@ namespace NewHorizons.Patches.WarpPatches Locator.GetPauseCommandListener().AddPauseCommandLock(); if (canWarpToEye || canWarpToStarSystem && targetSystem == "EyeOfTheUniverse") { - Main.Instance._currentStarSystem = "EyeOfTheUniverse"; + Main.Instance.CurrentStarSystem = "EyeOfTheUniverse"; LoadManager.LoadSceneAsync(OWScene.EyeOfTheUniverse, false, LoadManager.FadeType.ToWhite); } else if (canWarpToStarSystem) diff --git a/NewHorizons/Utility/Files/AssetBundleUtilities.cs b/NewHorizons/Utility/Files/AssetBundleUtilities.cs index 1f54c2a7..60fdce56 100644 --- a/NewHorizons/Utility/Files/AssetBundleUtilities.cs +++ b/NewHorizons/Utility/Files/AssetBundleUtilities.cs @@ -3,42 +3,25 @@ using OWML.Common; using System; using System.Collections.Generic; using System.IO; -using System.Linq; using UnityEngine; namespace NewHorizons.Utility.Files { public static class AssetBundleUtilities { - public static Dictionary AssetBundles = new(); + public static Dictionary AssetBundles = new Dictionary(); public static void ClearCache() { - var bundleKeys = AssetBundles.Keys.ToArray(); - - foreach (var key in bundleKeys) + foreach (var pair in AssetBundles) { - var (starSystem, bundle) = AssetBundles[key]; - // If the star system is null/empty keep loaded forever, else only unload when we leave the system - if (!string.IsNullOrEmpty(starSystem) && starSystem != Main.Instance.CurrentStarSystem) - { - if (bundle == null) NHLogger.LogError($"The asset bundle for [{key}] was null when trying to unload"); - else bundle.Unload(true); - - AssetBundles.Remove(key); - } - else - { - NHLogger.LogVerbose($"Not unloading bundle [{key}] because it is still in use for system [{starSystem}]"); - } + if (pair.Value == null) NHLogger.LogError($"The asset bundle for {pair.Key} was null when trying to unload"); + else pair.Value.Unload(true); } + AssetBundles.Clear(); } - // On the off chance this was being called from another mod public static T Load(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod) where T : UnityEngine.Object - => Load(assetBundleRelativeDir, pathInBundle, mod, Main.Instance.CurrentStarSystem); - - public static T Load(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod, string starSystem) where T : UnityEngine.Object { string key = Path.GetFileName(assetBundleRelativeDir); T obj; @@ -49,7 +32,7 @@ namespace NewHorizons.Utility.Files if (AssetBundles.ContainsKey(key)) { - bundle = AssetBundles[key].bundle; + bundle = AssetBundles[key]; } else { @@ -61,7 +44,7 @@ namespace NewHorizons.Utility.Files return null; } - AssetBundles[key] = (starSystem, bundle); + AssetBundles[key] = bundle; } obj = bundle.LoadAsset(pathInBundle); @@ -77,7 +60,7 @@ namespace NewHorizons.Utility.Files public static GameObject LoadPrefab(string assetBundleRelativeDir, string pathInBundle, IModBehaviour mod) { - var prefab = Load(assetBundleRelativeDir, pathInBundle, mod, Main.Instance.CurrentStarSystem); + var prefab = Load(assetBundleRelativeDir, pathInBundle, mod); prefab.SetActive(false); From 5b2480c8fd772e3004540df4b26c6dcc7c95a7c7 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 23:33:13 -0400 Subject: [PATCH 13/18] Fix guys not being removed, maybe caches are good now --- NewHorizons/Handlers/PlanetCreationHandler.cs | 16 +++++++++++-- .../Handlers/PlanetDestructionHandler.cs | 7 +++--- NewHorizons/Main.cs | 23 +++++++++++-------- 3 files changed, 31 insertions(+), 15 deletions(-) diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index de710065..5817d0ac 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -158,8 +158,20 @@ namespace NewHorizons.Handlers } catch (Exception) { - if (body?.Config?.name == null) NHLogger.LogError($"How is there no name for {body}"); - else existingPlanet = SearchUtilities.Find(body.Config.name.Replace(" ", "") + "_Body", false); + if (body?.Config?.name == null) + { + NHLogger.LogError($"How is there no name for {body}"); + } + else + { + existingPlanet = SearchUtilities.Find(body.Config.name.Replace(" ", "") + "_Body", false); + } + } + + if (existingPlanet == null && body.Config.destroy) + { + NHLogger.LogError($"{body.Config.name} was meant to be destroyed, but was not found"); + return false; } if (existingPlanet != null) diff --git a/NewHorizons/Handlers/PlanetDestructionHandler.cs b/NewHorizons/Handlers/PlanetDestructionHandler.cs index 6b796bac..cc36636c 100644 --- a/NewHorizons/Handlers/PlanetDestructionHandler.cs +++ b/NewHorizons/Handlers/PlanetDestructionHandler.cs @@ -134,14 +134,14 @@ namespace NewHorizons.Handlers public static void DisableAstroObject(AstroObject ao, List toDisable = null) { - NHLogger.LogVerbose($"Removing [{ao.name}]"); - if (ao.gameObject == null || !ao.gameObject.activeInHierarchy) { - NHLogger.LogVerbose($"[{ao.name}] was already removed"); + NHLogger.LogVerbose($"[{ao?.name}] was already removed"); return; } + NHLogger.LogVerbose($"Removing [{ao.name}]"); + toDisable ??= new List(); if (toDisable.Contains(ao)) @@ -222,6 +222,7 @@ namespace NewHorizons.Handlers NHLogger.LogError($"Exception thrown when trying to delete bodies related to [{ao.name}]:\n{e}"); } + DisableGameObject(ao.gameObject); RemoveProxy(ao); } diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index a78e9eff..ab67503e 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -64,16 +64,21 @@ namespace NewHorizons { return _currentStarSystem; } - internal set + set { - _previousStarSystem = _currentStarSystem; + // Prevent invalid values + if (value != "SolarSystem" && value != "EyeOfTheUniverse" && !SystemDict.ContainsKey(value) && !BodyDict.ContainsKey(value)) + { + NHLogger.LogError($"System \"{value}\" does not exist!"); + _currentStarSystem = DefaultStarSystem; + } _currentStarSystem = value; } } - private string _currentStarSystem = "SolarSystem"; + private string _currentStarSystem; private string _previousStarSystem; - public bool TimeLoopEnabled => SystemDict[CurrentStarSystem]?.Config?.enableTimeLoop ?? true; + public bool TimeLoopEnabled => CurrentStarSystem == null || (SystemDict[CurrentStarSystem]?.Config?.enableTimeLoop ?? true); public bool IsWarpingFromShip { get; private set; } = false; public bool IsWarpingFromVessel { get; private set; } = false; public bool IsWarpingBackToEye { get; internal set; } = false; @@ -280,6 +285,7 @@ namespace NewHorizons // Caches of other assets only have to be cleared if we changed star systems if (CurrentStarSystem != _previousStarSystem) { + NHLogger.Log($"Changing star system from {_previousStarSystem} to {CurrentStarSystem} - Clearing system-specific caches!"); ImageUtilities.ClearCache(); AudioUtilities.ClearCache(); AssetBundleUtilities.ClearCache(); @@ -362,12 +368,6 @@ namespace NewHorizons return; } - if (!SystemDict.ContainsKey(CurrentStarSystem) || !BodyDict.ContainsKey(CurrentStarSystem)) - { - NHLogger.LogError($"System \"{CurrentStarSystem}\" does not exist!"); - CurrentStarSystem = DefaultStarSystem; - } - // Set time loop stuff if its enabled and if we're warping to a new place if (IsChangingStarSystem && (SystemDict[CurrentStarSystem].Config.enableTimeLoop || CurrentStarSystem == "SolarSystem") && SecondsElapsedInLoop > 0f) { @@ -576,6 +576,9 @@ namespace NewHorizons { ResetCurrentStarSystem(); } + + // We only check previous when the scene unloads, and at that point current should be updated to the new system + _previousStarSystem = CurrentStarSystem; } // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here From 9f2ff4b6351699616d0947495e184dafbb6454e8 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 23:47:26 -0400 Subject: [PATCH 14/18] Fix proxies but not really --- NewHorizons/Handlers/ProxyHandler.cs | 6 ++++-- NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs | 4 ++-- NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/NewHorizons/Handlers/ProxyHandler.cs b/NewHorizons/Handlers/ProxyHandler.cs index 42bb51f2..811d0837 100644 --- a/NewHorizons/Handlers/ProxyHandler.cs +++ b/NewHorizons/Handlers/ProxyHandler.cs @@ -49,9 +49,11 @@ namespace NewHorizons.Handlers public static void RegisterVanillaProxyOrbiter(ProxyOrbiter proxy) { - if (proxy._originalPlanetBody != null) + // The _originalBody is the moon + // For _originalPlanetBody, that game object will also have a ProxyBody on it so it'd be counted via the other cache + if (proxy._originalBody != null) { - _vanillaProxyOrbiter.Add(proxy._originalPlanetBody, proxy); + _vanillaProxyOrbiter.Add(proxy._originalBody, proxy); } } diff --git a/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs b/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs index b8f648ac..c3d83d83 100644 --- a/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs +++ b/NewHorizons/Patches/ProxyPatches/ProxyBodyPatches.cs @@ -7,8 +7,8 @@ namespace NewHorizons.Patches.ProxyPatches; public static class ProxyBodyPatches { [HarmonyPostfix] - [HarmonyPatch(nameof(ProxyBody.Awake))] - public static void ProxyBody_Awake(ProxyBody __instance) + [HarmonyPatch(nameof(ProxyBody.LateInitialize))] + public static void ProxyBody_LateInitialize(ProxyBody __instance) { ProxyHandler.RegisterVanillaProxyBody(__instance); } diff --git a/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs b/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs index c505b5f4..be099350 100644 --- a/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs +++ b/NewHorizons/Patches/ProxyPatches/ProxyOrbiterPatches.cs @@ -7,8 +7,8 @@ namespace NewHorizons.Patches.ProxyPatches; public static class ProxyOrbiterPatches { [HarmonyPostfix] - [HarmonyPatch(nameof(ProxyOrbiter.Awake))] - public static void ProxyOrbiter_Awake(ProxyOrbiter __instance) + [HarmonyPatch(nameof(ProxyOrbiter.SetOriginalBodies))] + public static void ProxyOrbiter_SetOriginalBodies(ProxyOrbiter __instance) { ProxyHandler.RegisterVanillaProxyOrbiter(__instance); } From 8422066e5f898c87a7970747565fa775fc9d841c Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 25 Aug 2023 23:58:22 -0400 Subject: [PATCH 15/18] Logs --- NewHorizons/Main.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index ab67503e..fbfe94fb 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -384,7 +384,7 @@ namespace NewHorizons launchController.enabled = false; } var nomaiProbe = SearchUtilities.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + nomaiProbe?.gameObject.SetActive(false); } // Reset this @@ -578,6 +578,7 @@ namespace NewHorizons } // We only check previous when the scene unloads, and at that point current should be updated to the new system + NHLogger.LogVerbose($"Set the previous system to {CurrentStarSystem}"); _previousStarSystem = CurrentStarSystem; } From cb12b464545e84d798bd9d1eb4634abbdebb2787 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 26 Aug 2023 00:51:50 -0400 Subject: [PATCH 16/18] Fix distant colour of Bramble nodes. Fixes #372 --- NewHorizons/Builder/Props/BrambleNodeBuilder.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/NewHorizons/Builder/Props/BrambleNodeBuilder.cs b/NewHorizons/Builder/Props/BrambleNodeBuilder.cs index 990b7c18..c02837c8 100644 --- a/NewHorizons/Builder/Props/BrambleNodeBuilder.cs +++ b/NewHorizons/Builder/Props/BrambleNodeBuilder.cs @@ -260,9 +260,17 @@ namespace NewHorizons.Builder.Props // Default size is 70 var fog = brambleNode.FindChild("Effects/InnerWarpFogSphere"); fog.transform.localScale = Vector3.one * config.scale * 70f; - var fogMaterial = fog.GetComponent().material; - fogMaterial.SetFloat("_Radius", fogMaterial.GetFloat("_Radius") * config.scale); - fogMaterial.SetFloat("_Density", fogMaterial.GetFloat("_Density") / config.scale); + + // Copy shared material to not be shared + var fogRenderer = fog.GetComponent(); + fogRenderer.material = new Material(fogRenderer.sharedMaterial); + fogRenderer.material.SetFloat("_Radius", fogRenderer.material.GetFloat("_Radius") * config.scale); + fogRenderer.material.SetFloat("_Density", fogRenderer.material.GetFloat("_Density") / config.scale); + // Fixes bramble nodes being a weird colour until you approach the first time #372 + if (config.fogTint != null) + { + fog.GetComponent().SetColor(config.fogTint.ToColor()); + } } // Set colors @@ -393,7 +401,8 @@ namespace NewHorizons.Builder.Props } } - StreamingHandler.SetUpStreaming(brambleNode, sector); + // If the outer fog warp volume is null we're exposed to the solar system so treat it as a keepLoaded type prop + StreamingHandler.SetUpStreaming(brambleNode, outerFogWarpVolume == null ? null : sector); // Done! brambleNode.SetActive(true); From 553e48e4e9cb75909132d9b8a24bc19f7178f867 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Fri, 25 Aug 2023 22:16:03 -0700 Subject: [PATCH 17/18] teehee --- NewHorizons/Builder/Props/Audio/SignalBuilder.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NewHorizons/Builder/Props/Audio/SignalBuilder.cs b/NewHorizons/Builder/Props/Audio/SignalBuilder.cs index e5e0b885..66a86061 100644 --- a/NewHorizons/Builder/Props/Audio/SignalBuilder.cs +++ b/NewHorizons/Builder/Props/Audio/SignalBuilder.cs @@ -41,7 +41,9 @@ namespace NewHorizons.Builder.Props.Audio Initialized = true; + SceneManager.sceneUnloaded -= OnSceneUnloaded; SceneManager.sceneUnloaded += OnSceneUnloaded; + Main.Instance.OnStarSystemLoaded.RemoveListener(OnStarSystemLoaded); Main.Instance.OnStarSystemLoaded.AddListener(OnStarSystemLoaded); } From 2d452feb87f601f321418e4db36fd841861ff792 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Fri, 25 Aug 2023 22:18:57 -0700 Subject: [PATCH 18/18] this shit has been bothering me for a month lol --- .../Builder/Props/TranslatorText/TranslatorTextBuilder.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/NewHorizons/Builder/Props/TranslatorText/TranslatorTextBuilder.cs b/NewHorizons/Builder/Props/TranslatorText/TranslatorTextBuilder.cs index 48a1cc4e..6ff148ef 100644 --- a/NewHorizons/Builder/Props/TranslatorText/TranslatorTextBuilder.cs +++ b/NewHorizons/Builder/Props/TranslatorText/TranslatorTextBuilder.cs @@ -631,6 +631,12 @@ namespace NewHorizons.Builder.Props.TranslatorText XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xmlPath); XmlNode rootNode = xmlDocument.SelectSingleNode("NomaiObject"); + + if (rootNode == null) + { + NHLogger.LogError($"Couldn't find NomaiObject in [{xmlPath}]"); + return dict; + } foreach (object obj in rootNode.SelectNodes("TextBlock")) {