Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of TeoUpgrades v1.0.0
plugins/TeoUpgrades.dll
Decompiled 9 hours agousing 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.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using TeoUpgrades.Core; using UnityEngine; 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("Teo")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Teo upgrade box artwork for R.E.P.O.")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("TeoUpgrades")] [assembly: AssemblyTitle("TeoUpgrades")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [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] [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] [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 TeoUpgrades { [BepInPlugin("teo.upgrades", "Teo Upgrades", "0.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { private sealed class AppliedMaterial { public MeshRenderer Renderer { get; } public Material Original { get; } public Material Replacement { get; } public AppliedMaterial(MeshRenderer renderer, Material original, Material replacement) { Renderer = renderer; Original = original; Replacement = replacement; } } public const string Guid = "teo.upgrades"; public const string Version = "0.1.0"; private static Plugin? _instance; private Harmony? _harmony; private Type? _itemUpgradeType; private TextureCatalog? _catalog; private UpgradeMatcher? _matcher; private string _textureDirectory = ""; private string _diagnosticPath = ""; private ConfigEntry<bool> _enabled; private ConfigEntry<int> _textureSize; private ConfigEntry<bool> _atlasConversion; private ConfigEntry<bool> _diagnostics; private readonly Dictionary<string, Texture2D> _textures = new Dictionary<string, Texture2D>(StringComparer.Ordinal); private readonly HashSet<string> _failedTextures = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<string, Material> _materials = new Dictionary<string, Material>(StringComparer.Ordinal); private readonly HashSet<int> _queued = new HashSet<int>(); private readonly HashSet<string> _reported = new HashSet<string>(StringComparer.Ordinal); private readonly List<AppliedMaterial> _applied = new List<AppliedMaterial>(); private readonly List<TeoBoxMarker> _markers = new List<TeoBoxMarker>(); private bool _ready; private void Awake() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Expected O, but got Unknown _instance = this; _enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable Teo box artwork. Restart the game after changing settings."); _textureSize = ((BaseUnityPlugin)this).Config.Bind<int>("Graphics", "TextureSize", 1024, new ConfigDescription("Baked atlas size. 2048 improves close-up detail and uses about four times the texture memory.", (AcceptableValueBase)(object)new AcceptableValueList<int>(new int[2] { 1024, 2048 }), Array.Empty<object>())); _atlasConversion = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics", "ConvertAtlasLayout", true, "Fit the supplied art panels to the actual Upgrade Pack UV layout. Keep enabled for the included images."); _diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "WriteReport", true, "Write observed upgrade identities and renderer details to BepInEx/TeoUpgrades-diagnostics.txt. No network upload."); _diagnosticPath = Path.Combine(Paths.BepInExRootPath, "TeoUpgrades-diagnostics.txt"); InitializeReport(); if (!_enabled.Value) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Teo artwork is disabled in config."); return; } try { string path = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? throw new InvalidOperationException("Plugin location is unavailable."); _textureDirectory = Path.Combine(path, "Textures"); _catalog = TextureCatalog.FromJson(File.ReadAllText(Path.Combine(path, "textures.json"), Encoding.UTF8)); _matcher = new UpgradeMatcher(_catalog); TextureEntry[] entries = _catalog.Entries; foreach (TextureEntry textureEntry in entries) { string text = Path.Combine(_textureDirectory, textureEntry.File); if (!File.Exists(text)) { throw new FileNotFoundException("Missing selected artwork: " + textureEntry.File, text); } if (textureEntry.Enabled) { ValidatePngFile(text); } } _itemUpgradeType = AccessTools.TypeByName("ItemUpgrade"); if (_itemUpgradeType == null || !typeof(Component).IsAssignableFrom(_itemUpgradeType)) { throw new InvalidOperationException("The R.E.P.O. ItemUpgrade component was not found. This is a R.E.P.O. plugin."); } _harmony = new Harmony("teo.upgrades"); int num = InstallStartHook(_itemUpgradeType); Type type = AccessTools.TypeByName("ItemAttributes"); if (type != null && typeof(Component).IsAssignableFrom(type)) { num += InstallStartHook(type); } if (num == 0) { throw new InvalidOperationException("No supported upgrade initialization hook was found."); } _ready = true; SceneManager.sceneLoaded += OnSceneLoaded; ((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + _catalog.Entries.Length + " selected images; " + _catalog.Entries.Count((TextureEntry x) => x.Enabled) + " supported upgrade mappings. Atlas conversion: " + _atlasConversion.Value + ".")); Report("CATALOG: 12 vanilla + 9 MoreUpgrades mappings; Fall Damage Reduction artwork is included but unassigned."); entries = _catalog.Entries; foreach (TextureEntry textureEntry2 in entries) { Report("ART: " + textureEntry2.Key + " -> " + textureEntry2.File + (textureEntry2.Enabled ? " [enabled]" : " [unassigned]")); } } catch (Exception ex) { _ready = false; Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Teo Upgrades could not initialize; original boxes remain active. " + ex)); Report("INITIALIZATION ERROR: " + ex); } } private void Start() { if (_ready) { ((MonoBehaviour)this).StartCoroutine(ScanAfterSceneLoad()); } } private int InstallStartHook(Type type) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "Start", Type.EmptyTypes, (Type[])null); if (methodInfo == null) { Report("HOOK MISSING: " + type.FullName + ".Start"); return 0; } HarmonyMethod val = new HarmonyMethod(typeof(Plugin).GetMethod("OnItemStarted", BindingFlags.Static | BindingFlags.NonPublic)) { priority = 0 }; _harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Report("HOOK: " + type.FullName + ".Start postfix"); return 1; } catch (Exception ex) { Report("HOOK ERROR: " + type.FullName + ".Start " + ex.Message); ((BaseUnityPlugin)this).Logger.LogWarning((object)("Optional initialization hook unavailable: " + type.FullName + ".Start. " + ex.Message)); return 0; } } private static void OnItemStarted(Component __instance) { try { if ((Object)(object)_instance != (Object)null && _instance._ready) { _instance.Queue(__instance); } } catch (Exception ex) { Plugin? instance = _instance; if (instance != null) { ((BaseUnityPlugin)instance).Logger.LogWarning((object)("Could not queue an upgrade texture: " + ex.Message)); } } } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (_ready) { ((MonoBehaviour)this).StartCoroutine(ScanAfterSceneLoad()); } } private IEnumerator ScanAfterSceneLoad() { yield return null; yield return null; if (_ready && !(_itemUpgradeType == null)) { Component[] array; try { array = Object.FindObjectsOfType(_itemUpgradeType, true).OfType<Component>().ToArray(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Upgrade scan failed: " + ex.Message)); yield break; } Component[] array2 = array; foreach (Component component in array2) { Queue(component); } PruneUnusedMaterials(); } } private void Queue(Component component) { if (!_ready || (Object)(object)component == (Object)null || _itemUpgradeType == null) { return; } Component component2 = component.GetComponent(_itemUpgradeType); if ((Object)(object)component2 == (Object)null) { return; } TeoBoxMarker component3 = component2.GetComponent<TeoBoxMarker>(); if (!((Object)(object)component3 != (Object)null) || !component3.Applied) { int instanceID = ((Object)component2).GetInstanceID(); if (_queued.Add(instanceID)) { ((MonoBehaviour)this).StartCoroutine(ApplyAfterInitialization(component2, instanceID)); } } } private IEnumerator ApplyAfterInitialization(Component upgrade, int instanceId) { yield return null; try { if ((Object)(object)upgrade != (Object)null && _ready) { ApplyToUpgrade(upgrade); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("A box could not be reskinned; its original material remains available. " + ex.Message)); ReportOnce("error:" + (((Object)(object)upgrade != (Object)null) ? ((Object)upgrade).name : "destroyed"), "BOX ERROR: " + ex); } finally { _queued.Remove(instanceId); } } private void ApplyToUpgrade(Component upgrade) { //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Expected O, but got Unknown //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) if (_matcher == null) { return; } TeoBoxMarker component = upgrade.GetComponent<TeoBoxMarker>(); if ((Object)(object)component != (Object)null && component.Applied) { return; } UpgradeIdentity upgradeIdentity = ReadIdentity(upgrade); MatchResult matchResult = _matcher.Match(upgradeIdentity); string text = string.Join("|", upgradeIdentity.ComponentNames) + ":" + string.Join("|", upgradeIdentity.UpgradeIds) + ":" + string.Join("|", upgradeIdentity.ObjectNames); if (matchResult.Entry == null) { ReportOnce("unmapped:" + text, "UNMAPPED: " + DescribeIdentity(upgradeIdentity) + "\nReason: " + matchResult.Reason + "\n" + DescribeRenderers(upgrade.transform)); return; } TextureEntry entry = matchResult.Entry; MeshRenderer val = FindBoxRenderer(upgrade.transform); if ((Object)(object)val == (Object)null) { ReportOnce("missing-renderer:" + text, "NO SAFE BOX RENDERER: " + entry.Title + "\n" + DescribeIdentity(upgradeIdentity) + "\n" + DescribeRenderers(upgrade.transform)); ((BaseUnityPlugin)this).Logger.LogWarning((object)("Matched " + entry.Title + " but did not find its expected Upgrade Pack/Mesh renderer. See diagnostics.")); return; } Material[] sharedMaterials = ((Renderer)val).sharedMaterials; if (sharedMaterials.Length != 1 || (Object)(object)sharedMaterials[0] == (Object)null) { ReportOnce("materials:" + text, "UNSUPPORTED BOX MATERIAL SLOTS: " + entry.Title + "\n" + DescribeRenderers(upgrade.transform)); return; } Material val2 = sharedMaterials[0]; string text2 = (val2.HasProperty("_MainTex") ? "_MainTex" : (val2.HasProperty("_BaseMap") ? "_BaseMap" : null)); if (text2 == null) { ReportOnce("shader:" + text, "UNSUPPORTED BOX SHADER: " + entry.Title + " " + ((Object)val2.shader).name); return; } ReportOnce("before:" + text, "MATCH: " + entry.Title + " <- " + DescribeIdentity(upgradeIdentity) + "\n" + DescribeRenderers(upgrade.transform)); Texture2D texture = GetTexture(entry); if (!((Object)(object)texture == (Object)null)) { string key = ((Object)val2).GetInstanceID() + ":" + entry.Key; if (!_materials.TryGetValue(key, out Material value) || (Object)(object)value == (Object)null) { value = new Material(val2) { name = "TeoUpgrades/" + entry.Key }; value.SetTexture(text2, (Texture)(object)texture); value.SetTextureScale(text2, Vector2.one); value.SetTextureOffset(text2, Vector2.zero); _materials[key] = value; } ((Renderer)val).sharedMaterial = value; _applied.Add(new AppliedMaterial(val, val2, value)); component = component ?? upgrade.gameObject.AddComponent<TeoBoxMarker>(); component.Applied = true; _markers.Add(component); if (_applied.Count % 64 == 0) { PruneUnusedMaterials(); } ReportOnce("applied:" + entry.Key, "APPLIED: " + entry.Title + " | " + ((Texture)texture).width + "x" + ((Texture)texture).height + " | original shader retained | runtime atlas converted=" + _atlasConversion.Value); if (_reported.Add("console:" + entry.Key)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Applied Teo artwork: " + entry.Title)); } } } private static MeshRenderer? FindBoxRenderer(Transform root) { Transform val = root.Find("Mesh"); if ((Object)(object)val != (Object)null) { MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>(); if (IsExpectedBox(component)) { return component; } } MeshRenderer[] array = ((Component)root).GetComponentsInChildren<MeshRenderer>(true).Where(IsExpectedBox).ToArray(); if (array.Length != 1) { return null; } return array[0]; } private static bool IsExpectedBox(MeshRenderer? renderer) { if ((Object)(object)renderer == (Object)null) { return false; } MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>(); Mesh val = (((Object)(object)component != (Object)null) ? component.sharedMesh : null); if ((Object)(object)val == (Object)null || val.vertexCount != 24 || val.subMeshCount != 1) { return false; } return string.Equals(((Object)val).name.Replace(" (Instance)", "").Replace("(Clone)", "").Trim(), "Upgrade Pack", StringComparison.OrdinalIgnoreCase); } private Texture2D? GetTexture(TextureEntry entry) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Expected O, but got Unknown if (_textures.TryGetValue(entry.Key, out Texture2D value) && (Object)(object)value != (Object)null) { return value; } if (_failedTextures.Contains(entry.Key) || _catalog == null) { return null; } Texture2D val = null; Texture2D val2 = null; try { byte[] array = File.ReadAllBytes(Path.Combine(_textureDirectory, entry.File)); val = new Texture2D(2, 2, (TextureFormat)4, false, false); if (!ImageConversion.LoadImage(val, array, false)) { throw new InvalidDataException("Unity could not decode " + entry.File); } if (_atlasConversion.Value) { Color32[] pixels = val.GetPixels32(); uint[] array2 = new uint[pixels.Length]; for (int i = 0; i < pixels.Length; i++) { array2[i] = (uint)(pixels[i].r | (pixels[i].g << 8) | (pixels[i].b << 16) | (pixels[i].a << 24)); } int value2 = _textureSize.Value; uint[] array3 = AtlasMapper.Bake(array2, ((Texture)val).width, ((Texture)val).height, value2, value2, entry.SourceRegions, _catalog.TargetRegions); Color32[] array4 = (Color32[])(object)new Color32[array3.Length]; for (int j = 0; j < array3.Length; j++) { array4[j] = new Color32((byte)array3[j], (byte)(array3[j] >> 8), (byte)(array3[j] >> 16), (byte)(array3[j] >> 24)); } val2 = new Texture2D(value2, value2, (TextureFormat)4, true, false); val2.SetPixels32(array4); val2.Apply(true, true); Object.Destroy((Object)(object)val); val = null; } else { val2 = val; val = null; val2.Apply(false, true); } ((Object)val2).name = "TeoUpgrades/" + entry.Key; ((Texture)val2).wrapMode = (TextureWrapMode)1; ((Texture)val2).filterMode = (FilterMode)2; ((Texture)val2).anisoLevel = 2; _textures[entry.Key] = val2; return val2; } catch (Exception ex) { if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } if ((Object)(object)val2 != (Object)null) { Object.Destroy((Object)(object)val2); } _failedTextures.Add(entry.Key); ((BaseUnityPlugin)this).Logger.LogError((object)("Cannot load " + entry.File + ": " + ex.Message)); Report("TEXTURE ERROR: " + entry.Key + " " + ex); return null; } } private static UpgradeIdentity ReadIdentity(Component upgrade) { MonoBehaviour[] array = (from x in upgrade.GetComponentsInChildren<MonoBehaviour>(true) where (Object)(object)x != (Object)null select x).ToArray(); HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HashSet<string> hashSet2 = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ((Object)upgrade.gameObject).name }; MonoBehaviour[] array2 = array; foreach (MonoBehaviour val in array2) { if (((object)val).GetType().Name == "REPOLibItemUpgrade" && (ReadMember(val, "UpgradeId") ?? ReadMember(val, "_upgradeId")) is string text && !string.IsNullOrWhiteSpace(text)) { hashSet.Add(text); } if (((object)val).GetType().Name == "ItemAttributes") { object? obj = ReadMember(val, "item"); Object val2 = (Object)((obj is Object) ? obj : null); if (val2 != null && val2 != (Object)null) { hashSet2.Add(val2.name); } } } return new UpgradeIdentity { ComponentNames = array.Select((MonoBehaviour x) => ((object)x).GetType().Name).Distinct().OrderBy<string, string>((string x) => x, StringComparer.Ordinal) .ToArray(), UpgradeIds = hashSet.OrderBy<string, string>((string x) => x, StringComparer.Ordinal).ToArray(), ObjectNames = hashSet2.OrderBy<string, string>((string x) => x, StringComparer.Ordinal).ToArray() }; } private static object? ReadMember(object instance, string name) { try { FieldInfo fieldInfo = AccessTools.Field(instance.GetType(), name); if (fieldInfo != null) { return fieldInfo.GetValue(instance); } PropertyInfo propertyInfo = AccessTools.Property(instance.GetType(), name); if (propertyInfo != null && propertyInfo.GetIndexParameters().Length == 0) { return propertyInfo.GetValue(instance, null); } } catch { } return null; } private static string DescribeIdentity(UpgradeIdentity identity) { return "objects=[" + string.Join(", ", identity.ObjectNames) + "] upgradeIds=[" + string.Join(", ", identity.UpgradeIds) + "] components=[" + string.Join(", ", identity.ComponentNames) + "]"; } private static string DescribeRenderers(Transform root) { StringBuilder stringBuilder = new StringBuilder(); MeshRenderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<MeshRenderer>(true); foreach (MeshRenderer val in componentsInChildren) { MeshFilter component = ((Component)val).GetComponent<MeshFilter>(); Mesh val2 = (((Object)(object)component != (Object)null) ? component.sharedMesh : null); string text = ((Object)val).name; Transform parent = ((Component)val).transform.parent; while ((Object)(object)parent != (Object)null && (Object)(object)parent != (Object)(object)root) { text = ((Object)parent).name + "/" + text; parent = parent.parent; } stringBuilder.Append(" RENDERER ").Append(text).Append(" mesh=") .Append(((Object)(object)val2 != (Object)null) ? ((Object)val2).name : "none"); if ((Object)(object)val2 != (Object)null) { stringBuilder.Append(" vertices=").Append(val2.vertexCount).Append(" readable=") .Append(val2.isReadable); } stringBuilder.AppendLine(); Material[] sharedMaterials = ((Renderer)val).sharedMaterials; foreach (Material val3 in sharedMaterials) { if ((Object)(object)val3 == (Object)null) { continue; } stringBuilder.Append(" MATERIAL ").Append(((Object)val3).name).Append(" shader=") .Append(((Object)(object)val3.shader != (Object)null) ? ((Object)val3.shader).name : "none"); string[] array = new string[2] { "_MainTex", "_BaseMap" }; foreach (string text2 in array) { if (val3.HasProperty(text2)) { Texture texture = val3.GetTexture(text2); stringBuilder.Append(' ').Append(text2).Append('=') .Append(((Object)(object)texture != (Object)null) ? (((Object)texture).name + "(" + texture.width + "x" + texture.height + ")") : "none"); } } stringBuilder.AppendLine(); } } return stringBuilder.ToString().TrimEnd(); } private static void ValidatePngFile(string path) { FileInfo fileInfo = new FileInfo(path); if (fileInfo.Length < 24 || fileInfo.Length > 52428800) { throw new InvalidDataException("Unexpected PNG size: " + fileInfo.Name); } byte[] array = new byte[24]; using (FileStream fileStream = File.OpenRead(path)) { if (fileStream.Read(array, 0, array.Length) != array.Length) { throw new InvalidDataException("Truncated PNG: " + fileInfo.Name); } } byte[] array2 = new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }; for (int i = 0; i < array2.Length; i++) { if (array[i] != array2[i]) { throw new InvalidDataException("Invalid PNG: " + fileInfo.Name); } } uint num = (uint)((array[16] << 24) | (array[17] << 16) | (array[18] << 8) | array[19]); uint num2 = (uint)((array[20] << 24) | (array[21] << 16) | (array[22] << 8) | array[23]); if (num < 32 || num2 < 32 || num > 4096 || num2 > 4096) { throw new InvalidDataException("Unsupported PNG dimensions: " + fileInfo.Name); } } private void InitializeReport() { if (!_diagnostics.Value) { return; } try { File.WriteAllText(_diagnosticPath, "Teo Upgrades 0.1.0 diagnostic report\nUTC: " + DateTime.UtcNow.ToString("O") + "\nGame version: " + Application.version + "\nUnity: " + Application.unityVersion + "\nOnly observed items are recorded. An upgrade absent from the shop is not necessarily a failure.\n\n", Encoding.UTF8); foreach (PluginInfo item in Chainloader.PluginInfos.Values.OrderBy<PluginInfo, string>((PluginInfo x) => x.Metadata.GUID, StringComparer.Ordinal)) { Report("PLUGIN: " + item.Metadata.GUID + " " + item.Metadata.Version); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not create diagnostic report: " + ex.Message)); } } private void ReportOnce(string key, string text) { if (_reported.Add(key)) { Report(text); } } private void Report(string text) { if (!_diagnostics.Value) { return; } try { File.AppendAllText(_diagnosticPath, text + Environment.NewLine, Encoding.UTF8); } catch { } } private void PruneUnusedMaterials() { _applied.RemoveAll((AppliedMaterial x) => (Object)(object)x.Renderer == (Object)null || (Object)(object)((Renderer)x.Renderer).sharedMaterial != (Object)(object)x.Replacement); _markers.RemoveAll((TeoBoxMarker x) => (Object)(object)x == (Object)null); HashSet<Material> hashSet = new HashSet<Material>(_applied.Select((AppliedMaterial x) => x.Replacement)); string[] array = _materials.Keys.ToArray(); foreach (string key in array) { Material val = _materials[key]; if (!((Object)(object)val != (Object)null) || !hashSet.Contains(val)) { if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } _materials.Remove(key); } } } private void OnDestroy() { _ready = false; SceneManager.sceneLoaded -= OnSceneLoaded; ((MonoBehaviour)this).StopAllCoroutines(); Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } foreach (AppliedMaterial item in _applied) { if ((Object)(object)item.Renderer != (Object)null && (Object)(object)((Renderer)item.Renderer).sharedMaterial == (Object)(object)item.Replacement) { ((Renderer)item.Renderer).sharedMaterial = item.Original; } } foreach (Material value in _materials.Values) { if ((Object)(object)value != (Object)null) { Object.Destroy((Object)(object)value); } } foreach (Texture2D value2 in _textures.Values) { if ((Object)(object)value2 != (Object)null) { Object.Destroy((Object)(object)value2); } } foreach (TeoBoxMarker marker in _markers) { if ((Object)(object)marker != (Object)null) { marker.Applied = false; Object.Destroy((Object)(object)marker); } } if ((Object)(object)_instance == (Object)(object)this) { _instance = null; } } } public sealed class TeoBoxMarker : MonoBehaviour { public bool Applied; } } namespace TeoUpgrades.Core { [DataContract] public sealed class AtlasRect { [DataMember(Name = "left", IsRequired = true)] public float Left { get; set; } [DataMember(Name = "top", IsRequired = true)] public float Top { get; set; } [DataMember(Name = "right", IsRequired = true)] public float Right { get; set; } [DataMember(Name = "bottom", IsRequired = true)] public float Bottom { get; set; } public AtlasRect() { } public AtlasRect(float left, float top, float right, float bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } public void Validate() { if (!Finite(Left) || !Finite(Top) || !Finite(Right) || !Finite(Bottom) || Left < 0f || Top < 0f || Right > 1f || Bottom > 1f || Right <= Left || Bottom <= Top) { throw new InvalidDataException("Invalid normalized atlas rectangle."); } } private static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } } public static class AtlasMapper { public static uint[] Bake(uint[] source, int sourceWidth, int sourceHeight, int outputWidth, int outputHeight, IReadOnlyList<AtlasRect> sourceRegions, IReadOnlyList<AtlasRect> targetRegions) { if (sourceWidth < 1 || sourceHeight < 1 || outputWidth < 1 || outputHeight < 1 || sourceWidth > 8192 || sourceHeight > 8192 || outputWidth > 4096 || outputHeight > 4096) { throw new ArgumentOutOfRangeException("Invalid atlas dimensions."); } if (source == null || source.Length != sourceWidth * sourceHeight) { throw new ArgumentException("Source pixel count does not match dimensions."); } if (sourceRegions == null || targetRegions == null || sourceRegions.Count != targetRegions.Count || sourceRegions.Count == 0) { throw new ArgumentException("Source and target region counts must match."); } uint[] array = new uint[outputWidth * outputHeight]; for (int i = 0; i < array.Length; i++) { array[i] = 4278190080u; } for (int j = 0; j < sourceRegions.Count; j++) { AtlasRect atlasRect = sourceRegions[j]; AtlasRect atlasRect2 = targetRegions[j]; atlasRect.Validate(); atlasRect2.Validate(); int num = Math.Max(0, (int)Math.Floor(atlasRect2.Left * (float)outputWidth)); int num2 = Math.Min(outputWidth - 1, (int)Math.Ceiling(atlasRect2.Right * (float)outputWidth) - 1); int num3 = Math.Max(0, (int)Math.Floor(atlasRect2.Top * (float)outputHeight)); int num4 = Math.Min(outputHeight - 1, (int)Math.Ceiling(atlasRect2.Bottom * (float)outputHeight) - 1); int num5 = Math.Max(0, (int)Math.Floor(atlasRect.Left * (float)sourceWidth)); int num6 = Math.Min(sourceWidth - 1, (int)Math.Ceiling(atlasRect.Right * (float)sourceWidth) - 1); int num7 = Math.Max(0, (int)Math.Floor(atlasRect.Top * (float)sourceHeight)); int num8 = Math.Min(sourceHeight - 1, (int)Math.Ceiling(atlasRect.Bottom * (float)sourceHeight) - 1); for (int k = num3; k <= num4; k++) { float num9 = Clamp01((((float)k + 0.5f) / (float)outputHeight - atlasRect2.Top) / (atlasRect2.Bottom - atlasRect2.Top)); float num10 = Clamp((atlasRect.Top + num9 * (atlasRect.Bottom - atlasRect.Top)) * (float)sourceHeight - 0.5f, num7, num8); int num11 = (int)Math.Floor(num10); int num12 = Math.Min(num8, num11 + 1); float fy = num10 - (float)num11; for (int l = num; l <= num2; l++) { float num13 = Clamp01((((float)l + 0.5f) / (float)outputWidth - atlasRect2.Left) / (atlasRect2.Right - atlasRect2.Left)); float num14 = Clamp((atlasRect.Left + num13 * (atlasRect.Right - atlasRect.Left)) * (float)sourceWidth - 0.5f, num5, num6); int num15 = (int)Math.Floor(num14); int num16 = Math.Min(num6, num15 + 1); float fx = num14 - (float)num15; uint a = source[(sourceHeight - 1 - num11) * sourceWidth + num15]; uint b = source[(sourceHeight - 1 - num11) * sourceWidth + num16]; uint c = source[(sourceHeight - 1 - num12) * sourceWidth + num15]; uint d = source[(sourceHeight - 1 - num12) * sourceWidth + num16]; array[(outputHeight - 1 - k) * outputWidth + l] = Interpolate(a, b, c, d, fx, fy); } } } return array; } public static (float X, float Y) MapPoint(float x, float y, AtlasRect source, AtlasRect target) { source.Validate(); target.Validate(); return (X: source.Left + Clamp01((x - target.Left) / (target.Right - target.Left)) * (source.Right - source.Left), Y: source.Top + Clamp01((y - target.Top) / (target.Bottom - target.Top)) * (source.Bottom - source.Top)); } private static uint Interpolate(uint a, uint b, uint c, uint d, float fx, float fy) { uint num = 0u; for (int i = 0; i <= 24; i += 8) { float num2 = (float)((a >> i) & 0xFF) * (1f - fx) + (float)((b >> i) & 0xFF) * fx; float num3 = (float)((c >> i) & 0xFF) * (1f - fx) + (float)((d >> i) & 0xFF) * fx; num |= (uint)Math.Round(num2 * (1f - fy) + num3 * fy) << i; } return num; } private static float Clamp01(float x) { return Clamp(x, 0f, 1f); } private static float Clamp(float x, float min, float max) { return Math.Max(min, Math.Min(max, x)); } } [DataContract] public sealed class TextureCatalog { [DataMember(Name = "formatVersion", IsRequired = true)] public int FormatVersion { get; set; } [DataMember(Name = "targetRegions", IsRequired = true)] public AtlasRect[] TargetRegions { get; set; } = Array.Empty<AtlasRect>(); [DataMember(Name = "entries", IsRequired = true)] public TextureEntry[] Entries { get; set; } = Array.Empty<TextureEntry>(); public static TextureCatalog FromJson(string json) { using MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); TextureCatalog obj = (new DataContractJsonSerializer(typeof(TextureCatalog)).ReadObject(stream) as TextureCatalog) ?? throw new InvalidDataException("Texture catalog is empty."); obj.Validate(); return obj; } public void Validate() { if (FormatVersion != 1) { throw new InvalidDataException("Unsupported texture catalog format."); } if (TargetRegions == null || TargetRegions.Length != 6) { throw new InvalidDataException("The upgrade atlas must have exactly six target regions."); } AtlasRect[] targetRegions = TargetRegions; for (int i = 0; i < targetRegions.Length; i++) { targetRegions[i].Validate(); } if (Entries == null || Entries.Length == 0) { throw new InvalidDataException("No texture entries."); } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HashSet<string> hashSet2 = new HashSet<string>(StringComparer.OrdinalIgnoreCase); Dictionary<string, string> table = new Dictionary<string, string>(StringComparer.Ordinal); Dictionary<string, string> table2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); Dictionary<string, string> table3 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); TextureEntry[] entries = Entries; foreach (TextureEntry textureEntry in entries) { if (textureEntry == null || string.IsNullOrWhiteSpace(textureEntry.Key) || !hashSet.Add(textureEntry.Key)) { throw new InvalidDataException("Texture keys must be nonempty and unique."); } if (!IsSafeTextureFile(textureEntry.File) || !hashSet2.Add(textureEntry.File)) { throw new InvalidDataException("Unsafe or duplicate texture filename: " + textureEntry.File); } if (string.IsNullOrWhiteSpace(textureEntry.Title)) { throw new InvalidDataException("Missing title: " + textureEntry.Key); } if (textureEntry.SourceRegions == null || textureEntry.SourceRegions.Length != 6) { throw new InvalidDataException("Exactly six source panels are required: " + textureEntry.Key); } targetRegions = textureEntry.SourceRegions; for (int j = 0; j < targetRegions.Length; j++) { targetRegions[j].Validate(); } if (textureEntry.Enabled) { string[] componentNames = textureEntry.ComponentNames; int num = ((componentNames != null) ? componentNames.Length : 0); string[] upgradeIds = textureEntry.UpgradeIds; int num2 = num + ((upgradeIds != null) ? upgradeIds.Length : 0); string[] objectNames = textureEntry.ObjectNames; if (num2 + ((objectNames != null) ? objectNames.Length : 0) == 0) { throw new InvalidDataException("Enabled texture has no explicit item identities: " + textureEntry.Key); } AddAliases(table, textureEntry.ComponentNames, textureEntry.Key); AddAliases(table2, textureEntry.UpgradeIds, textureEntry.Key); AddAliases(table3, textureEntry.ObjectNames, textureEntry.Key); } } } public static bool IsSafeTextureFile(string? file) { if (string.IsNullOrEmpty(file) || file.Length > 120 || !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) { return false; } foreach (char c in file) { if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_' && c != '-' && c != '.') { return false; } } if (!file.Contains("..")) { return file[0] != '.'; } return false; } private static void AddAliases(Dictionary<string, string> table, string[]? aliases, string key) { string[] array = aliases ?? Array.Empty<string>(); foreach (string text in array) { if (string.IsNullOrWhiteSpace(text) || text != text.Trim()) { throw new InvalidDataException("Empty or padded item alias: " + key); } if (table.TryGetValue(text, out string value) && value != key) { throw new InvalidDataException("Ambiguous item alias '" + text + "'."); } table[text] = key; } } } [DataContract] public sealed class TextureEntry { [DataMember(Name = "key", IsRequired = true)] public string Key { get; set; } = ""; [DataMember(Name = "title", IsRequired = true)] public string Title { get; set; } = ""; [DataMember(Name = "file", IsRequired = true)] public string File { get; set; } = ""; [DataMember(Name = "enabled", IsRequired = true)] public bool Enabled { get; set; } [DataMember(Name = "componentNames")] public string[] ComponentNames { get; set; } = Array.Empty<string>(); [DataMember(Name = "upgradeIds")] public string[] UpgradeIds { get; set; } = Array.Empty<string>(); [DataMember(Name = "objectNames")] public string[] ObjectNames { get; set; } = Array.Empty<string>(); [DataMember(Name = "sourceRegions", IsRequired = true)] public AtlasRect[] SourceRegions { get; set; } = Array.Empty<AtlasRect>(); [DataMember(Name = "note")] public string Note { get; set; } = ""; } public sealed class UpgradeIdentity { public string[] ComponentNames { get; set; } = Array.Empty<string>(); public string[] UpgradeIds { get; set; } = Array.Empty<string>(); public string[] ObjectNames { get; set; } = Array.Empty<string>(); } public sealed class MatchResult { public TextureEntry? Entry { get; } public string Reason { get; } public bool Ambiguous { get; } public MatchResult(TextureEntry? entry, string reason, bool ambiguous = false) { Entry = entry; Reason = reason; Ambiguous = ambiguous; } } public sealed class UpgradeMatcher { private readonly TextureEntry[] _entries; public UpgradeMatcher(TextureCatalog catalog) { catalog.Validate(); _entries = catalog.Entries.Where((TextureEntry x) => x.Enabled).ToArray(); } public MatchResult Match(UpgradeIdentity identity) { Dictionary<string, TextureEntry> dictionary = new Dictionary<string, TextureEntry>(StringComparer.Ordinal); TextureEntry[] entries = _entries; foreach (TextureEntry textureEntry in entries) { bool num = (textureEntry.ComponentNames ?? Array.Empty<string>()).Any((string alias) => (identity.ComponentNames ?? Array.Empty<string>()).Contains<string>(alias, StringComparer.Ordinal)); bool flag = (textureEntry.UpgradeIds ?? Array.Empty<string>()).Any((string alias) => (identity.UpgradeIds ?? Array.Empty<string>()).Contains<string>(alias, StringComparer.OrdinalIgnoreCase)); bool flag2 = (textureEntry.ObjectNames ?? Array.Empty<string>()).Any((string alias) => (identity.ObjectNames ?? Array.Empty<string>()).Any((string name) => string.Equals(alias, NormalizeObjectName(name), StringComparison.OrdinalIgnoreCase))); if (num || flag || flag2) { dictionary[textureEntry.Key] = textureEntry; } } if (dictionary.Count == 0) { return new MatchResult(null, "No exact supported upgrade identity"); } if (dictionary.Count > 1) { return new MatchResult(null, "Conflicting upgrade identities: " + string.Join(", ", dictionary.Keys.OrderBy((string x) => x)), ambiguous: true); } return new MatchResult(dictionary.Values.First(), "Exact component, upgrade ID, or prefab name"); } public static string NormalizeObjectName(string? name) { string text = (name ?? "").Trim(); if (text.EndsWith("(Clone)", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - "(Clone)".Length).TrimEnd(); } return text; } } }