using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using REPOLib;
using REPOLib.Modules;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Empress")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("TwilightForestCompatPatch")]
[assembly: AssemblyTitle("TwilightForestCompatPatch")]
[assembly: AssemblyVersion("1.0.2.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace TwilightForestCompatPatch
{
[BepInPlugin("empress.repo.twilightforestcompatpatch", "Empress Twilight Forest Compat Patch", "1.0.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class TwilightForestCompatPatchPlugin : BaseUnityPlugin
{
private sealed class TwilightPrefabBuckets
{
public List<GameObject> StartRooms { get; set; } = new List<GameObject>();
public List<GameObject> Normal1 { get; set; } = new List<GameObject>();
public List<GameObject> Passage1 { get; set; } = new List<GameObject>();
public List<GameObject> DeadEnd1 { get; set; } = new List<GameObject>();
public List<GameObject> Extraction1 { get; set; } = new List<GameObject>();
public List<GameObject> Normal2 { get; set; } = new List<GameObject>();
public List<GameObject> Passage2 { get; set; } = new List<GameObject>();
public List<GameObject> DeadEnd2 { get; set; } = new List<GameObject>();
public List<GameObject> Extraction2 { get; set; } = new List<GameObject>();
public List<GameObject> Normal3 { get; set; } = new List<GameObject>();
public List<GameObject> Passage3 { get; set; } = new List<GameObject>();
public List<GameObject> DeadEnd3 { get; set; } = new List<GameObject>();
public List<GameObject> Extraction3 { get; set; } = new List<GameObject>();
public int TotalModuleCount => Normal1.Count + Passage1.Count + DeadEnd1.Count + Extraction1.Count + Normal2.Count + Passage2.Count + DeadEnd2.Count + Extraction2.Count + Normal3.Count + Passage3.Count + DeadEnd3.Count + Extraction3.Count;
}
internal const string PluginGuid = "empress.repo.twilightforestcompatpatch";
internal const string PluginName = "Empress Twilight Forest Compat Patch";
internal const string PluginVersion = "1.0.2";
private const string TwilightBundleFileName = "Minecraft_Twilight_Forest.repobundle";
private const string TwilightLevelName = "Level - Twilightforest";
private const string TwilightLevelResourcePath = "Twilightforest";
private const float TwilightLevelPointCheckRadius = 0.5f;
private const float TwilightLevelPointRepairRadius = 2f;
private const float TwilightLevelPointConnectDistance = 15f;
private const float TwilightLevelPointConnectForwardDot = -0.8f;
private const float TwilightLevelPointConnectApproachDot = 0.8f;
private const float TwilightLevelPointValidationDelay = 0.5f;
private static readonly string[] TwilightStartRoomNames = new string[1] { "Start Room - Twilight - Entrance" };
private static readonly string[] TwilightNormal1Names = new string[8] { "Module - Twilight - Lone Oak", "Module -- Twilight - Hedge Cross", "Module -- Twilight - TreeClimb", "Module -- Twilight - Ruined Portal", "Module -- Twilight - Labyrinth Entrance", "Module -- Twilight - Hedge Intersection", "Module -- Twilight - Hedge Spider Spawner", "Module -- Twilight - Hedge Transformation Tree" };
private static readonly string[] TwilightPassage1Names = new string[2] { "Module -- Twilight - Log Passage", "Module -- Twilight - Naga Skeleton" };
private static readonly string[] TwilightDeadEnd1Names = new string[1] { "Module -- Twilight - Witch Hut Dead End" };
private static readonly string[] TwilightExtraction1Names = new string[1] { "Module -- Twilight - Questing_Grove" };
private static readonly string[] TwilightNormal2Names = new string[2] { "Module -- Twilight - Stone Pit", "Module -- Twilight - Hollow Hill" };
private static readonly string[] TwilightPassage2Names = new string[1] { "Module -- Twilight - Maze Passage" };
private static readonly string[] TwilightDeadEnd2Names = new string[1] { "Module -- Twilight - Lich Tower Dead End1" };
private static readonly string[] TwilightExtraction2Names = new string[1] { "Module -- Twilight - Questing_Grove" };
private static readonly string[] TwilightNormal3Names = new string[2] { "Module -- Twilight - Mangrove Tree", "Module -- Twilight - Castle Forcefields" };
private static readonly string[] TwilightPassage3Names = new string[1] { "Module -- Twilight - Lava Passage" };
private static readonly string[] TwilightDeadEnd3Names = new string[1] { "Module -- Twilight - Dark Tower Dead End" };
private static readonly string[] TwilightExtraction3Names = new string[1] { "Module -- Twilight - Questing_Grove" };
private readonly Harmony _twilightHarmony = new Harmony("empress.repo.twilightforestcompatpatch");
private AssetBundle? _twilightBundle;
private bool _twilightRepairApplied;
private bool _twilightRepairQueued;
private bool _twilightLoggedMissingBundle;
private bool _twilightLoggedMissingPrefabs;
private bool _twilightLoggedDoorMapFallback;
internal static TwilightForestCompatPatchPlugin? Instance { get; private set; }
private void Awake()
{
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
Instance = this;
GameObject gameObject = ((Component)this).gameObject;
((Object)gameObject).hideFlags = (HideFlags)(((Object)gameObject).hideFlags | 0x23);
BundleLoader.OnAllBundlesLoaded += TwilightHandleBundlesLoaded;
_twilightHarmony.PatchAll();
if ((Object)(object)RunManager.instance != (Object)null)
{
((MonoBehaviour)this).StartCoroutine(TwilightRepairWhenReady());
}
}
private void OnDestroy()
{
BundleLoader.OnAllBundlesLoaded -= TwilightHandleBundlesLoaded;
_twilightHarmony.UnpatchSelf();
if (Instance == this)
{
Instance = null;
}
}
private void TwilightHandleBundlesLoaded()
{
if (!_twilightRepairQueued && !_twilightRepairApplied)
{
_twilightRepairQueued = true;
((MonoBehaviour)this).StartCoroutine(TwilightRepairWhenReady());
}
}
private IEnumerator TwilightRepairWhenReady()
{
yield return null;
for (int attempt = 0; attempt < 120; attempt++)
{
if (_twilightRepairApplied)
{
break;
}
if (TwilightTryRepairLevel())
{
break;
}
yield return null;
}
_twilightRepairQueued = false;
}
internal bool TwilightTryRepairCurrentLevel()
{
List<Level> list = new List<Level>();
if ((Object)(object)LevelGenerator.Instance != (Object)null && (Object)(object)LevelGenerator.Instance.Level != (Object)null)
{
list.Add(LevelGenerator.Instance.Level);
}
if ((Object)(object)RunManager.instance != (Object)null && (Object)(object)RunManager.instance.levelCurrent != (Object)null)
{
list.Add(RunManager.instance.levelCurrent);
}
return TwilightTryRepairLevel(list);
}
private bool TwilightTryRepairLevel(IEnumerable<Level>? candidates = null)
{
if (_twilightRepairApplied)
{
return true;
}
Level val = TwilightFindLevel(candidates) ?? TwilightFindLevel(Levels.AllLevels);
if ((Object)(object)val == (Object)null)
{
return false;
}
AssetBundle val2 = TwilightGetBundle();
if ((Object)(object)val2 == (Object)null)
{
if (!_twilightLoggedMissingBundle)
{
_twilightLoggedMissingBundle = true;
((BaseUnityPlugin)this).Logger.LogWarning((object)"Empress Twilight Forest Compat Patch could not locate the Twilight Forest bundle.");
}
return false;
}
_twilightLoggedMissingBundle = false;
TwilightPrefabBuckets twilightPrefabBuckets = TwilightCollectPrefabs(val2);
if (twilightPrefabBuckets.StartRooms.Count == 0 || twilightPrefabBuckets.TotalModuleCount == 0)
{
if (!_twilightLoggedMissingPrefabs)
{
_twilightLoggedMissingPrefabs = true;
((BaseUnityPlugin)this).Logger.LogError((object)"Empress Twilight Forest Compat Patch could not rebuild the Twilight Forest prefab lists from the original bundle.");
}
return false;
}
_twilightLoggedMissingPrefabs = false;
TwilightApplyHideFlags((Object)(object)val2);
TwilightApplyHideFlags((Object)(object)val);
TwilightEnsureLevelFallbackData(val);
TwilightRegisterLevelObjects(val);
val.StartRooms = TwilightRegisterPrefabs(val, "StartRoom", twilightPrefabBuckets.StartRooms);
val.ModulesNormal1 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal1);
val.ModulesPassage1 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage1);
val.ModulesDeadEnd1 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd1);
val.ModulesExtraction1 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction1);
val.ModulesNormal2 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal2);
val.ModulesPassage2 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage2);
val.ModulesDeadEnd2 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd2);
val.ModulesExtraction2 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction2);
val.ModulesNormal3 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal3);
val.ModulesPassage3 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage3);
val.ModulesDeadEnd3 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd3);
val.ModulesExtraction3 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction3);
_twilightRepairApplied = val.StartRooms.Count > 0 && TwilightCountModules(val) > 0;
if (_twilightRepairApplied)
{
((BaseUnityPlugin)this).Logger.LogInfo((object)$"Empress Twilight Forest Compat Patch repaired {((Object)val).name} with {val.StartRooms.Count} start rooms and {TwilightCountModules(val)} modules.");
}
return _twilightRepairApplied;
}
private static Level? TwilightFindLevel(IEnumerable<Level>? candidates)
{
if (candidates == null)
{
return null;
}
foreach (Level candidate in candidates)
{
if (TwilightIsTwilightLevel(candidate))
{
return candidate;
}
}
return null;
}
private AssetBundle? TwilightGetBundle()
{
if ((Object)(object)_twilightBundle != (Object)null)
{
return _twilightBundle;
}
foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles())
{
try
{
if (allLoadedAssetBundle.GetAllAssetNames().Any((string assetName) => assetName.EndsWith("level - twilightforest.asset", StringComparison.OrdinalIgnoreCase) || assetName.EndsWith("tfassettestmod.asset", StringComparison.OrdinalIgnoreCase)))
{
_twilightBundle = allLoadedAssetBundle;
return _twilightBundle;
}
}
catch
{
}
}
string text = Directory.GetFiles(Paths.PluginPath, "Minecraft_Twilight_Forest.repobundle", SearchOption.AllDirectories).FirstOrDefault();
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
_twilightBundle = AssetBundle.LoadFromFile(text);
return _twilightBundle;
}
private static TwilightPrefabBuckets TwilightCollectPrefabs(AssetBundle bundle)
{
//IL_0113: Unknown result type (might be due to invalid IL or missing references)
//IL_0118: Unknown result type (might be due to invalid IL or missing references)
//IL_015c: Unknown result type (might be due to invalid IL or missing references)
//IL_0161: Unknown result type (might be due to invalid IL or missing references)
//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase);
StartRoom[] array = bundle.LoadAllAssets<StartRoom>();
foreach (StartRoom val in array)
{
TwilightAddAssetByName(dictionary, ((Object)(object)val != (Object)null) ? ((Component)val).gameObject : null);
}
Module[] array2 = bundle.LoadAllAssets<Module>();
foreach (Module val2 in array2)
{
TwilightAddAssetByName(dictionary, ((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject : null);
}
GameObject[] array3 = bundle.LoadAllAssets<GameObject>();
foreach (GameObject prefab in array3)
{
TwilightAddAssetByName(dictionary, prefab);
}
if (!dictionary.Keys.Any((string name) => name.StartsWith("Start Room - Twilight -", StringComparison.OrdinalIgnoreCase)) || !dictionary.Keys.Any((string name) => name.Contains("Twilight", StringComparison.OrdinalIgnoreCase) && name.StartsWith("Module", StringComparison.OrdinalIgnoreCase)))
{
array = Resources.FindObjectsOfTypeAll<StartRoom>();
Scene scene;
foreach (StartRoom val3 in array)
{
if (!((Object)(object)val3 == (Object)null))
{
scene = ((Component)val3).gameObject.scene;
if (!((Scene)(ref scene)).IsValid())
{
TwilightAddAssetByName(dictionary, ((Component)val3).gameObject);
}
}
}
array2 = Resources.FindObjectsOfTypeAll<Module>();
foreach (Module val4 in array2)
{
if (!((Object)(object)val4 == (Object)null))
{
scene = ((Component)val4).gameObject.scene;
if (!((Scene)(ref scene)).IsValid())
{
TwilightAddAssetByName(dictionary, ((Component)val4).gameObject);
}
}
}
array3 = Resources.FindObjectsOfTypeAll<GameObject>();
foreach (GameObject val5 in array3)
{
if (!((Object)(object)val5 == (Object)null))
{
scene = val5.scene;
if (!((Scene)(ref scene)).IsValid())
{
TwilightAddAssetByName(dictionary, val5);
}
}
}
}
return new TwilightPrefabBuckets
{
StartRooms = TwilightResolvePrefabs(dictionary, TwilightStartRoomNames),
Normal1 = TwilightResolvePrefabs(dictionary, TwilightNormal1Names),
Passage1 = TwilightResolvePrefabs(dictionary, TwilightPassage1Names),
DeadEnd1 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd1Names),
Extraction1 = TwilightResolvePrefabs(dictionary, TwilightExtraction1Names),
Normal2 = TwilightResolvePrefabs(dictionary, TwilightNormal2Names),
Passage2 = TwilightResolvePrefabs(dictionary, TwilightPassage2Names),
DeadEnd2 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd2Names),
Extraction2 = TwilightResolvePrefabs(dictionary, TwilightExtraction2Names),
Normal3 = TwilightResolvePrefabs(dictionary, TwilightNormal3Names),
Passage3 = TwilightResolvePrefabs(dictionary, TwilightPassage3Names),
DeadEnd3 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd3Names),
Extraction3 = TwilightResolvePrefabs(dictionary, TwilightExtraction3Names)
};
}
private static void TwilightAddAssetByName(IDictionary<string, GameObject> prefabsByName, GameObject? prefab)
{
if (!((Object)(object)prefab == (Object)null) && !string.IsNullOrWhiteSpace(((Object)prefab).name) && !prefabsByName.ContainsKey(((Object)prefab).name))
{
prefabsByName[((Object)prefab).name] = prefab;
}
}
private static List<GameObject> TwilightResolvePrefabs(IReadOnlyDictionary<string, GameObject> prefabsByName, IEnumerable<string> names)
{
List<GameObject> list = new List<GameObject>();
foreach (string name in names)
{
if (prefabsByName.TryGetValue(name, out GameObject value))
{
list.Add(value);
}
}
return list;
}
private static void TwilightRegisterLevelObjects(Level level)
{
if ((Object)(object)level.ConnectObject != (Object)null)
{
TwilightRegisterNetworkPrefab("Level/" + (level.ResourcePath ?? "Twilightforest") + "/Other/" + ((Object)level.ConnectObject).name, level.ConnectObject);
}
if ((Object)(object)level.BlockObject != (Object)null)
{
TwilightRegisterNetworkPrefab("Level/" + (level.ResourcePath ?? "Twilightforest") + "/Other/" + ((Object)level.BlockObject).name, level.BlockObject);
}
}
private static List<PrefabRef> TwilightRegisterPrefabs(Level level, string moduleTypeName, IEnumerable<GameObject> prefabs)
{
List<PrefabRef> list = new List<PrefabRef>();
foreach (GameObject item in prefabs.OrderBy<GameObject, string>((GameObject gameObject) => ((Object)gameObject).name, StringComparer.OrdinalIgnoreCase))
{
PrefabRef val = TwilightRegisterNetworkPrefab("Level/" + ((Object)level).name + "/" + moduleTypeName + "/" + ((Object)item).name, item);
if (val != null)
{
list.Add(val);
}
}
return list;
}
private static PrefabRef? TwilightRegisterNetworkPrefab(string prefabId, GameObject prefab)
{
PrefabRef val = TwilightGetRegisteredPrefabRef(prefabId, prefab);
if (val != null)
{
return val;
}
TwilightPreparePrefab(prefab);
Utilities.FixAudioMixerGroups(prefab);
return NetworkPrefabs.RegisterNetworkPrefab(prefabId, prefab);
}
private static PrefabRef? TwilightGetRegisteredPrefabRef(string prefabId, GameObject prefab)
{
if (!NetworkPrefabs.PrefabRefs.TryGetValue(prefabId, out var value) || value == null)
{
return null;
}
if ((Object)(object)value.Prefab == (Object)null || (Object)(object)value.Prefab == (Object)(object)prefab)
{
return value;
}
return null;
}
private static void TwilightPreparePrefab(GameObject prefab)
{
TwilightApplyHideFlags((Object)(object)prefab);
TwilightAssignFallbackAudioMixerGroups(prefab);
TwilightAssignFallbackPhysAttributes(prefab);
}
private static void TwilightAssignFallbackAudioMixerGroups(GameObject prefab)
{
AudioMixerGroup val = TwilightGetFallbackAudioMixerGroup();
if ((Object)(object)prefab == (Object)null || (Object)(object)val == (Object)null)
{
return;
}
AudioSource[] componentsInChildren = prefab.GetComponentsInChildren<AudioSource>(true);
foreach (AudioSource val2 in componentsInChildren)
{
if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.outputAudioMixerGroup != (Object)null))
{
val2.outputAudioMixerGroup = val;
}
}
}
private static void TwilightAssignFallbackPhysAttributes(GameObject prefab)
{
if ((Object)(object)prefab == (Object)null)
{
return;
}
NotValuableObject[] componentsInChildren = prefab.GetComponentsInChildren<NotValuableObject>(true);
foreach (NotValuableObject val in componentsInChildren)
{
if (!((Object)(object)val == (Object)null) && !((Object)(object)val.physAttributePreset != (Object)null))
{
Rigidbody component = ((Component)val).GetComponent<Rigidbody>();
float mass = (((Object)(object)component != (Object)null && component.mass > 0f) ? component.mass : 1f);
val.physAttributePreset = TwilightCreateFallbackPhysAttribute(mass);
}
}
}
private static PhysAttribute TwilightCreateFallbackPhysAttribute(float mass)
{
PhysAttribute obj = ScriptableObject.CreateInstance<PhysAttribute>();
obj.mass = Mathf.Max(0.01f, mass);
TwilightApplyHideFlags((Object)(object)obj);
return obj;
}
private static AudioMixerGroup? TwilightGetFallbackAudioMixerGroup()
{
if ((Object)(object)AudioManager.instance == (Object)null)
{
return null;
}
return AudioManager.instance.SoundMasterGroup ?? AudioManager.instance.PersistentSoundGroup ?? AudioManager.instance.MusicMasterGroup ?? AudioManager.instance.MicrophoneSoundGroup ?? AudioManager.instance.MicrophoneSpectateGroup ?? AudioManager.instance.TTSSoundGroup ?? AudioManager.instance.TTSSpectateGroup;
}
private static int TwilightCountModules(Level level)
{
return (level.ModulesNormal1?.Count ?? 0) + (level.ModulesPassage1?.Count ?? 0) + (level.ModulesDeadEnd1?.Count ?? 0) + (level.ModulesExtraction1?.Count ?? 0) + (level.ModulesNormal2?.Count ?? 0) + (level.ModulesPassage2?.Count ?? 0) + (level.ModulesDeadEnd2?.Count ?? 0) + (level.ModulesExtraction2?.Count ?? 0) + (level.ModulesNormal3?.Count ?? 0) + (level.ModulesPassage3?.Count ?? 0) + (level.ModulesDeadEnd3?.Count ?? 0) + (level.ModulesExtraction3?.Count ?? 0);
}
internal static bool TwilightIsCurrentLevel()
{
if (!TwilightIsTwilightLevel(((Object)(object)LevelGenerator.Instance != (Object)null) ? LevelGenerator.Instance.Level : null))
{
return TwilightIsTwilightLevel(((Object)(object)RunManager.instance != (Object)null) ? RunManager.instance.levelCurrent : null);
}
return true;
}
private static bool TwilightIsTwilightLevel(Level? level)
{
if ((Object)(object)level == (Object)null)
{
return false;
}
if (!string.Equals(((Object)level).name, "Level - Twilightforest", StringComparison.OrdinalIgnoreCase))
{
return string.Equals(level.ResourcePath, "Twilightforest", StringComparison.OrdinalIgnoreCase);
}
return true;
}
internal static void TwilightEnsureLevelFallbackData(Level? level)
{
if (TwilightIsTwilightLevel(level))
{
Level val = level;
if (val.ValuablePresets == null)
{
val.ValuablePresets = new List<LevelValuables>();
}
val = level;
if (val.AmbiencePresets == null)
{
val.AmbiencePresets = new List<LevelAmbience>();
}
if (level.ValuablePresets.Count == 0 && (Object)(object)ValuablePresets.GenericValuablePreset != (Object)null)
{
level.ValuablePresets.Add(ValuablePresets.GenericValuablePreset);
}
if (level.AmbiencePresets.Count == 0 && TwilightTryGetFallbackAmbience(out LevelAmbience ambience))
{
level.AmbiencePresets.Add(ambience);
}
}
}
private static bool TwilightTryGetFallbackAmbience(out LevelAmbience ambience)
{
ambience = null;
if ((Object)(object)AudioManager.instance != (Object)null && AudioManager.instance.levelAmbiences != null)
{
foreach (LevelAmbience levelAmbience in AudioManager.instance.levelAmbiences)
{
if (!((Object)(object)levelAmbience == (Object)null))
{
ambience = levelAmbience;
return true;
}
}
}
if ((Object)(object)RunManager.instance != (Object)null && RunManager.instance.levels != null)
{
foreach (Level level in RunManager.instance.levels)
{
if (level?.AmbiencePresets == null)
{
continue;
}
foreach (LevelAmbience ambiencePreset in level.AmbiencePresets)
{
if (!((Object)(object)ambiencePreset == (Object)null))
{
ambience = ambiencePreset;
return true;
}
}
}
}
return false;
}
internal static void TwilightEnsureExtractionPointCompatibility(ExtractionPoint extractionPoint)
{
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
//IL_006c: Unknown result type (might be due to invalid IL or missing references)
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
//IL_00da: Expected O, but got Unknown
if ((Object)(object)extractionPoint == (Object)null || !TwilightIsCurrentLevel())
{
return;
}
if ((Object)(object)extractionPoint.extractionArea == (Object)null)
{
GameObject val = GameObject.CreatePrimitive((PrimitiveType)2);
((Object)val).name = "Twilight Patch Extraction Area";
val.transform.SetParent(((Component)extractionPoint).transform, false);
val.transform.localPosition = Vector3.zero;
val.transform.localRotation = Quaternion.identity;
val.transform.localScale = Vector3.one * 0.1f;
MeshRenderer component = val.GetComponent<MeshRenderer>();
if ((Object)(object)component != (Object)null)
{
((Renderer)component).enabled = false;
}
Collider component2 = val.GetComponent<Collider>();
if ((Object)(object)component2 != (Object)null)
{
Object.Destroy((Object)(object)component2);
}
val.SetActive(false);
TwilightApplyHideFlags((Object)(object)val);
extractionPoint.extractionArea = val;
}
if ((Object)(object)extractionPoint.grossUp == (Object)null)
{
GameObject val2 = new GameObject("Twilight Patch GrossUp");
val2.transform.SetParent(((Component)extractionPoint).transform, false);
val2.SetActive(false);
TwilightApplyHideFlags((Object)(object)val2);
extractionPoint.grossUp = val2;
}
}
internal void TwilightRepairLevelPoints(LevelGenerator levelGenerator)
{
if ((Object)(object)levelGenerator == (Object)null || !TwilightIsTwilightLevel(levelGenerator.Level) || levelGenerator.LevelPathPoints == null)
{
return;
}
int num = 0;
int num2 = 0;
foreach (LevelPoint levelPathPoint in levelGenerator.LevelPathPoints)
{
if (TwilightRepairLevelPoint(levelPathPoint))
{
num++;
}
if (TwilightRepairLevelPointRoom(levelPathPoint))
{
num2++;
}
}
if (num > 0 || num2 > 0)
{
((BaseUnityPlugin)this).Logger.LogInfo((object)$"Empress Twilight Forest Compat Patch repaired {num} Twilight Forest level points onto the navmesh and restored {num2} room links.");
}
}
private static bool TwilightRepairLevelPoint(LevelPoint? levelPoint)
{
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_0043: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)levelPoint == (Object)null)
{
return false;
}
Vector3 position = ((Component)levelPoint).transform.position;
NavMeshHit val = default(NavMeshHit);
if (NavMesh.SamplePosition(position, ref val, 0.5f, -1))
{
return false;
}
NavMeshHit val2 = default(NavMeshHit);
if (!NavMesh.SamplePosition(position, ref val2, 2f, -1))
{
return false;
}
((Component)levelPoint).transform.position = ((NavMeshHit)(ref val2)).position;
TwilightRepairLevelPointRoom(levelPoint);
return true;
}
private static bool TwilightRepairLevelPointRoom(LevelPoint? levelPoint)
{
//IL_001f: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)levelPoint == (Object)null || (Object)(object)levelPoint.Room != (Object)null)
{
return false;
}
RoomVolume room = default(RoomVolume);
Vector3 val = default(Vector3);
if (!SemiFunc.GetRoomVolumeAtPosition(((Component)levelPoint).transform.position, ref room, ref val))
{
return false;
}
levelPoint.Room = room;
return true;
}
internal IEnumerator TwilightSilentLevelPointCheck(LevelPoint levelPoint)
{
if (!((Object)(object)levelPoint == (Object)null))
{
while ((Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated)
{
yield return (object)new WaitForSeconds(0.1f);
}
yield return (object)new WaitForSeconds(0.5f);
if (TwilightIsCurrentLevel())
{
TwilightRepairLevelPoint(levelPoint);
TwilightRepairLevelPointRoom(levelPoint);
TwilightRepairLevelPointConnections(levelPoint, LevelGenerator.Instance?.LevelPathPoints);
}
}
}
private static void TwilightRepairLevelPointConnections(LevelPoint? levelPoint, IList<LevelPoint>? allLevelPoints)
{
if ((Object)(object)levelPoint == (Object)null)
{
return;
}
if (levelPoint.ConnectedPoints == null)
{
levelPoint.ConnectedPoints = new List<LevelPoint>();
}
levelPoint.ConnectedPoints.RemoveAll((LevelPoint connectedPoint) => (Object)(object)connectedPoint == (Object)null);
LevelPoint[] array = levelPoint.ConnectedPoints.ToArray();
for (int i = 0; i < array.Length; i++)
{
TwilightAddLevelPointConnection(array[i], levelPoint);
}
if (!levelPoint.ModuleConnect || allLevelPoints == null || levelPoint.ConnectedPoints.Count > 0)
{
return;
}
LevelPoint val = null;
float currentBestDistance = float.MaxValue;
foreach (LevelPoint allLevelPoint in allLevelPoints)
{
if (TwilightCanConnectLevelPoints(levelPoint, allLevelPoint, currentBestDistance, out var distance))
{
val = allLevelPoint;
currentBestDistance = distance;
}
}
TwilightAddLevelPointConnection(levelPoint, val);
TwilightAddLevelPointConnection(val, levelPoint);
}
private static bool TwilightCanConnectLevelPoints(LevelPoint source, LevelPoint? candidate, float currentBestDistance, out float distance)
{
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_003d: Unknown result type (might be due to invalid IL or missing references)
//IL_0042: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_0082: Unknown result type (might be due to invalid IL or missing references)
//IL_009b: Unknown result type (might be due to invalid IL or missing references)
//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
distance = 0f;
if ((Object)(object)source == (Object)null || (Object)(object)candidate == (Object)null || (Object)(object)source == (Object)(object)candidate || !candidate.ModuleConnect)
{
return false;
}
Vector3 val = ((Component)source).transform.position - ((Component)candidate).transform.position;
if (((Vector3)(ref val)).sqrMagnitude <= Mathf.Epsilon)
{
return false;
}
distance = ((Vector3)(ref val)).magnitude;
if (distance >= 15f || distance >= currentBestDistance)
{
return false;
}
if (Vector3.Dot(((Component)candidate).transform.forward, ((Component)source).transform.forward) > -0.8f)
{
return false;
}
return Vector3.Dot(((Component)candidate).transform.forward, ((Vector3)(ref val)).normalized) > 0.8f;
}
private static void TwilightAddLevelPointConnection(LevelPoint? source, LevelPoint? target)
{
if (!((Object)(object)source == (Object)null) && !((Object)(object)target == (Object)null))
{
if (source.ConnectedPoints == null)
{
source.ConnectedPoints = new List<LevelPoint>();
}
if (!source.ConnectedPoints.Contains(target))
{
source.ConnectedPoints.Add(target);
}
}
}
internal GameObject TwilightCreateFallbackDoorMapObject(Map map, DirtFinderMapDoor door)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
MapLayer layerParent = map.GetLayerParent(((Component)door).transform.position.y);
GameObject val = TwilightInstantiateFallbackDoorMapObject(map, ((Component)layerParent).transform);
((Object)val).name = ((Object)((Component)door).gameObject).name;
door.Target = val.transform;
DirtFinderMapDoorTarget val2 = val.GetComponent<DirtFinderMapDoorTarget>() ?? val.AddComponent<DirtFinderMapDoorTarget>();
val2.Target = ((Component)door).transform;
val2.Layer = layerParent;
DirtFinderMapDoorTarget val3 = val2;
if (val3.HingeTransform == null)
{
val3.HingeTransform = val.transform;
}
map.DoorUpdate(val2.HingeTransform, ((Component)door).transform, layerParent);
if (!_twilightLoggedDoorMapFallback)
{
_twilightLoggedDoorMapFallback = true;
((BaseUnityPlugin)this).Logger.LogWarning((object)"Empress Twilight Forest Compat Patch injected fallback minimap door markers for missing Twilight Forest door prefabs.");
}
return val;
}
private static GameObject TwilightInstantiateFallbackDoorMapObject(Map map, Transform parent)
{
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
//IL_008a: Unknown result type (might be due to invalid IL or missing references)
//IL_009a: Unknown result type (might be due to invalid IL or missing references)
GameObject val;
if ((Object)(object)map.Door1x1Object != (Object)null)
{
val = Object.Instantiate<GameObject>(map.Door1x1Object, parent);
Collider[] componentsInChildren = val.GetComponentsInChildren<Collider>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
{
Object.Destroy((Object)(object)componentsInChildren[i]);
}
}
else
{
val = GameObject.CreatePrimitive((PrimitiveType)3);
val.transform.SetParent(parent, false);
val.transform.localScale = new Vector3(0.12f, 0.12f, 0.3f);
Collider component = val.GetComponent<Collider>();
if ((Object)(object)component != (Object)null)
{
Object.Destroy((Object)(object)component);
}
}
val.transform.localPosition = Vector3.zero;
val.transform.localRotation = Quaternion.identity;
DirtFinderMapDoorTarget val2 = val.GetComponent<DirtFinderMapDoorTarget>() ?? val.AddComponent<DirtFinderMapDoorTarget>();
if (val2.HingeTransform == null)
{
val2.HingeTransform = val.transform;
}
TwilightApplyHideFlags((Object)(object)val);
return val;
}
private static void TwilightApplyHideFlags(Object obj)
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0013: Unknown result type (might be due to invalid IL or missing references)
//IL_0035: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_0050: Unknown result type (might be due to invalid IL or missing references)
//IL_0074: Unknown result type (might be due to invalid IL or missing references)
//IL_007b: Unknown result type (might be due to invalid IL or missing references)
if (obj == (Object)null)
{
return;
}
obj.hideFlags = (HideFlags)(obj.hideFlags | 0x23);
GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
if (val == null)
{
return;
}
Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(true);
foreach (Transform obj2 in componentsInChildren)
{
((Object)obj2).hideFlags = (HideFlags)(((Object)obj2).hideFlags | 0x23);
GameObject gameObject = ((Component)obj2).gameObject;
((Object)gameObject).hideFlags = (HideFlags)(((Object)gameObject).hideFlags | 0x23);
Component[] components = ((Component)obj2).GetComponents<Component>();
foreach (Component val2 in components)
{
if ((Object)(object)val2 != (Object)null)
{
((Object)val2).hideFlags = (HideFlags)(((Object)val2).hideFlags | 0x23);
}
}
}
}
}
[HarmonyPatch(typeof(LevelGenerator), "StartRoomGeneration")]
internal static class TwilightForestCompatPatchStartRoomGenerationPatch
{
[HarmonyPrefix]
private static void TwilightPrefix()
{
TwilightForestCompatPatchPlugin.Instance?.TwilightTryRepairCurrentLevel();
}
}
[HarmonyPatch(typeof(ExtractionPoint), "Start")]
internal static class TwilightForestCompatPatchExtractionPointStartPatch
{
[HarmonyPostfix]
private static void TwilightPostfix(ExtractionPoint __instance)
{
TwilightForestCompatPatchPlugin.TwilightEnsureExtractionPointCompatibility(__instance);
}
}
[HarmonyPatch(typeof(Levels), "RegisterLevelWithGame")]
internal static class TwilightForestCompatPatchRegisterLevelPatch
{
[HarmonyPrefix]
private static void TwilightPrefix(Level level)
{
TwilightForestCompatPatchPlugin.TwilightEnsureLevelFallbackData(level);
}
}
[HarmonyPatch(typeof(Map), "AddDoor")]
internal static class TwilightForestCompatPatchMapAddDoorPatch
{
[HarmonyPrefix]
private static bool TwilightPrefix(Map __instance, DirtFinderMapDoor door, GameObject doorPrefab, ref GameObject __result)
{
if (!TwilightForestCompatPatchPlugin.TwilightIsCurrentLevel() || (Object)(object)door == (Object)null || (Object)(object)doorPrefab != (Object)null)
{
return true;
}
TwilightForestCompatPatchPlugin instance = TwilightForestCompatPatchPlugin.Instance;
if ((Object)(object)instance == (Object)null)
{
return true;
}
__result = instance.TwilightCreateFallbackDoorMapObject(__instance, door);
return false;
}
}
[HarmonyPatch(typeof(LevelGenerator), "NavMeshSetupRPC")]
internal static class TwilightForestCompatPatchNavMeshSetupPatch
{
[HarmonyPostfix]
private static void TwilightPostfix(LevelGenerator __instance)
{
TwilightForestCompatPatchPlugin.Instance?.TwilightRepairLevelPoints(__instance);
}
}
[HarmonyPatch(typeof(LevelPoint), "NavMeshCheck")]
internal static class TwilightForestCompatPatchLevelPointNavMeshCheckPatch
{
[HarmonyPrefix]
private static bool TwilightPrefix(LevelPoint __instance, ref IEnumerator __result)
{
if (!TwilightForestCompatPatchPlugin.TwilightIsCurrentLevel())
{
return true;
}
TwilightForestCompatPatchPlugin instance = TwilightForestCompatPatchPlugin.Instance;
if ((Object)(object)instance == (Object)null)
{
return true;
}
__result = instance.TwilightSilentLevelPointCheck(__instance);
return false;
}
}
}