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 CrossModCompat v1.0.1
BepInEx/plugins/CrossModCompat/CrossModCompat.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using ConditionalConfigSync; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using Splatform; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("CrossModCompat")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("CrossModCompat")] [assembly: AssemblyTitle("CrossModCompat")] [assembly: InternalsVisibleTo("CrossModCompat.Tests")] [assembly: AssemblyVersion("1.0.1.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlySingleElementList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { private sealed class Enumerator : IDisposable, IEnumerator, IEnumerator<T> { object IEnumerator.Current => _item; T IEnumerator<T>.Current => _item; public Enumerator(T item) { _item = item; } bool IEnumerator.MoveNext() { if (!_moveNextCalled) { return _moveNextCalled = true; } return false; } void IEnumerator.Reset() { _moveNextCalled = false; } void IDisposable.Dispose() { } } int ICollection.Count => 1; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => 1; T IReadOnlyList<T>.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } } int ICollection<T>.Count => 1; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } public <>z__ReadOnlySingleElementList(T item) { _item = item; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.CopyTo(Array array, int index) { array.SetValue(_item, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return EqualityComparer<T>.Default.Equals(_item, (T)value); } int IList.IndexOf(object value) { if (!EqualityComparer<T>.Default.Equals(_item, (T)value)) { return -1; } return 0; } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(_item); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return EqualityComparer<T>.Default.Equals(_item, item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { array[arrayIndex] = _item; } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { if (!EqualityComparer<T>.Default.Equals(_item, item)) { return -1; } return 0; } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } 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 System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { internal bool ReturnValue { get; } internal NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, Inherited = false)] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class CompilerFeatureRequiredAttribute : Attribute { internal string FeatureName { get; } internal bool IsOptional { get; init; } internal CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } } namespace CrossModCompat { public sealed class ResourceStack<TItem, TSource> where TItem : notnull where TSource : notnull { public readonly TItem Id; public readonly TSource Source; public readonly string Name; public readonly int Quality; public readonly int WorldLevel; public readonly int Count; public readonly bool Container; public readonly int Index; public ResourceStack(TItem id, TSource source, string name, int quality, int worldLevel, int count, bool container, int index = 0) { Id = id; Source = source; Name = name; Quality = quality; WorldLevel = worldLevel; Count = count; Container = container; Index = index; } } public sealed class ResourceNeed<TSource> { public readonly string Name; public readonly int MaximumQuality; public readonly int Count; public readonly Func<TSource, bool> AllowsSource; public ResourceNeed(string name, int maximumQuality, int count, Func<TSource, bool> allowsSource) { Name = name; MaximumQuality = maximumQuality; Count = count; AllowsSource = allowsSource; } } public sealed class Allocation<TItem, TSource> where TItem : notnull where TSource : notnull { public readonly ResourceStack<TItem, TSource> Stack; public readonly int Count; public Allocation(ResourceStack<TItem, TSource> stack, int count) { Stack = stack; Count = count; } } public sealed class SelectedIngredient<TItem, TSource> where TItem : notnull where TSource : notnull { public readonly ResourceNeed<TSource> Need; public readonly int Tier; public readonly IReadOnlyList<Allocation<TItem, TSource>> Allocations; public SelectedIngredient(ResourceNeed<TSource> need, int tier, List<Allocation<TItem, TSource>> allocations) { Need = need; Tier = tier; Allocations = allocations.AsReadOnly(); } } public sealed class IngredientPlan<TItem, TSource> where TItem : notnull where TSource : notnull { public readonly IReadOnlyList<SelectedIngredient<TItem, TSource>> Ingredients; public IEnumerable<Allocation<TItem, TSource>> Allocations => Ingredients.SelectMany((SelectedIngredient<TItem, TSource> i) => i.Allocations); public IngredientPlan(List<SelectedIngredient<TItem, TSource>> ingredients) { Ingredients = ingredients.AsReadOnly(); } } public static class IngredientSelector { public static IngredientPlan<TItem, TSource>? Select<TItem, TSource>(IReadOnlyList<ResourceStack<TItem, TSource>> stacks, IReadOnlyList<ResourceNeed<TSource>> needs, int worldLevel, bool leaveOne) where TItem : notnull where TSource : notnull { Dictionary<TItem, int> remaining = stacks.ToDictionary((ResourceStack<TItem, TSource> s) => s.Id, (ResourceStack<TItem, TSource> s) => s.Count); List<SelectedIngredient<TItem, TSource>> list = new List<SelectedIngredient<TItem, TSource>>(); foreach (ResourceNeed<TSource> need in needs) { if (need.Count > 0) { SelectedIngredient<TItem, TSource> selectedIngredient = SelectNeed(stacks, remaining, need, worldLevel, leaveOne); if (selectedIngredient == null) { return null; } list.Add(selectedIngredient); } } return new IngredientPlan<TItem, TSource>(list); } private static SelectedIngredient<TItem, TSource>? SelectNeed<TItem, TSource>(IReadOnlyList<ResourceStack<TItem, TSource>> stacks, Dictionary<TItem, int> remaining, ResourceNeed<TSource> need, int worldLevel, bool leaveOne) where TItem : notnull where TSource : notnull { List<ResourceStack<TItem, TSource>> candidates = stacks.Where((ResourceStack<TItem, TSource> s) => s.Name == need.Name && s.WorldLevel >= worldLevel && need.AllowsSource(s.Source)).ToList(); if (Capacity(candidates) < need.Count) { return null; } int tier = SelectTier(need, candidates, Capacity); List<Allocation<TItem, TSource>> allocations = Allocate(need, candidates, remaining, tier, leaveOne) ?? throw new InvalidOperationException("Selection capacity and allocation disagreed."); return new SelectedIngredient<TItem, TSource>(need, tier, allocations); int Capacity(IEnumerable<ResourceStack<TItem, TSource>> subset) { return (from s in subset group s by s.Source).Sum((IGrouping<TSource, ResourceStack<TItem, TSource>> group) => Usable(group.Sum((ResourceStack<TItem, TSource> s) => remaining[s.Id]), group.First(), candidates, remaining, leaveOne)); } } private static int SelectTier<TItem, TSource>(ResourceNeed<TSource> need, List<ResourceStack<TItem, TSource>> candidates, Func<IEnumerable<ResourceStack<TItem, TSource>>, int> capacity) where TItem : notnull where TSource : notnull { int quality; for (quality = 1; quality <= need.MaximumQuality; quality++) { if (need.MaximumQuality <= 1) { break; } if (capacity(candidates.Where((ResourceStack<TItem, TSource> s) => s.Quality == quality)) >= need.Count) { return quality; } } return 0; } private static List<Allocation<TItem, TSource>>? Allocate<TItem, TSource>(ResourceNeed<TSource> need, List<ResourceStack<TItem, TSource>> candidates, Dictionary<TItem, int> remaining, int tier, bool leaveOne) where TItem : notnull where TSource : notnull { int num = need.Count; List<Allocation<TItem, TSource>> list = new List<Allocation<TItem, TSource>>(); foreach (ResourceStack<TItem, TSource> candidate in candidates) { if (tier > 0 && candidate.Quality != tier) { continue; } int num2 = Math.Min(Usable(remaining[candidate.Id], candidate, candidates, remaining, leaveOne), num); if (num2 > 0) { list.Add(new Allocation<TItem, TSource>(candidate, num2)); remaining[candidate.Id] -= num2; num -= num2; if (num == 0) { break; } } } if (num != 0) { return null; } return list; } public static int Available(int total, bool leaveOne) { if (!leaveOne) { return total; } return Math.Max(0, total - 1); } private static int Usable<TItem, TSource>(int count, ResourceStack<TItem, TSource> stack, List<ResourceStack<TItem, TSource>> candidates, Dictionary<TItem, int> remaining, bool leaveOne) where TItem : notnull where TSource : notnull { if (!leaveOne || !stack.Container) { return count; } int total = candidates.Where((ResourceStack<TItem, TSource> s) => object.Equals(s.Source, stack.Source)).Sum((ResourceStack<TItem, TSource> s) => remaining[s.Id]); return Math.Min(count, Available(total, leaveOne)); } } public enum ReservationState { Planned, Reserved, Committed, RolledBack } public sealed class IngredientReservation<TItem, TSource> where TItem : notnull where TSource : notnull { private readonly record struct Saved(ResourceStack<TItem, TSource> Stack, int Count); private readonly IngredientPlan<TItem, TSource> plan; private readonly List<Saved> before = new List<Saved>(); public ReservationState State { get; private set; } public IngredientReservation(IngredientPlan<TItem, TSource> plan) { this.plan = plan; } public bool Reserve(Func<ResourceStack<TItem, TSource>, int> currentCount, Func<Allocation<TItem, TSource>, bool> remove, Action<ResourceStack<TItem, TSource>, int> restore) { if (State != ReservationState.Planned) { return false; } List<Saved> list = new List<Saved>(); foreach (IGrouping<TItem, Allocation<TItem, TSource>> item in from a in plan.Allocations group a by a.Stack.Id) { ResourceStack<TItem, TSource> stack = item.First().Stack; int num = currentCount(stack); if (num < item.Sum((Allocation<TItem, TSource> a) => a.Count)) { return false; } list.Add(new Saved(stack, num)); } before.AddRange(list); try { foreach (Allocation<TItem, TSource> allocation in plan.Allocations) { if (!remove(allocation)) { Rollback(restore); return false; } } State = ReservationState.Reserved; return true; } catch { Rollback(restore); throw; } } public void Complete(bool outputCreated, Action<ResourceStack<TItem, TSource>, int> restore) { if (State == ReservationState.Reserved) { if (outputCreated) { State = ReservationState.Committed; } else { Rollback(restore); } } } public void Rollback(Action<ResourceStack<TItem, TSource>, int> restore) { ReservationState state = State; if ((uint)(state - 2) <= 1u) { return; } foreach (Saved item in (from saved in before group saved by saved.Stack.Source).SelectMany((IGrouping<TSource, Saved> source) => source.OrderBy((Saved saved) => saved.Stack.Index))) { restore(item.Stack, item.Count); } before.Clear(); State = ReservationState.RolledBack; } } public static class CompatEvents { internal sealed class OperationHandle { private readonly Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>>? track; private readonly Action<Exception?>? end; internal OperationHandle(Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>>? track, Action<Exception?>? end) { this.track = track; this.end = end; } internal void TrackChests(IReadOnlyList<Container> refreshed, IReadOnlyList<(Container Chest, float Distance)> outside) { if (track != null) { Safe("CompatEvents.TrackChests", delegate { track(refreshed, outside); }); } } internal void End(Exception? exception) { if (end != null) { Safe("CompatEvents.EndOperation", delegate { end(exception); }); } } } private sealed class Observer { internal required Action<string, Container?, string, int, string> OnEvent { get; init; } internal required Func<string, Action?> OnOperationScope { get; init; } internal required Func<Player, string, IReadOnlyList<Inventory>, bool, Action<Exception?>?> OnCraft { get; init; } internal required Func<string, Player, float, (Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>> TrackChests, Action<Exception?> End)?> OnOperation { get; init; } } private sealed class Registration : IDisposable { private readonly Observer owned; internal Registration(Observer owned) { this.owned = owned; } public void Dispose() { lock (gate) { if (observer == owned) { observer = null; } } } } internal const int Info = 0; internal const int Warning = 1; internal const int Problem = 2; private static readonly object gate = new object(); private static readonly HashSet<string> reportedFaults = new HashSet<string>(StringComparer.Ordinal); private static Observer? observer; internal static bool HasObserver => observer != null; public static Func<string>? ChestSettingsSummary { get; internal set; } public static Func<ZSyncTransform, bool>? IsIdleSettled { get; internal set; } public static Func<(bool Active, int Settled, long Skipped, long Checked)>? IdleSyncStats { get; internal set; } public static IDisposable? Register(Action<string, Container?, string, int, string> onEvent, Func<string, Action?> onOperationScope, Func<Player, string, IReadOnlyList<Inventory>, bool, Action<Exception?>?> onCraft, Func<string, Player, float, (Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>> TrackChests, Action<Exception?> End)?> onOperation) { lock (gate) { if (observer != null) { return null; } observer = new Observer { OnEvent = onEvent, OnOperationScope = onOperationScope, OnCraft = onCraft, OnOperation = onOperation }; return new Registration(observer); } } public static string PatchOutcomes() { return CompatibilityInstaller.Outcomes(); } internal static void Emit(string kind, Container? chest, string details = "", int severity = 0, string extra = "") { Observer current = observer; if (current != null) { Safe("CompatEvents.OnEvent", delegate { current.OnEvent(kind, chest, details, severity, extra); }); } } internal static Action? EnterScope(string operation) { Observer current = observer; if (current == null) { return null; } Action restore = Safe("CompatEvents.OnOperationScope", () => current.OnOperationScope(operation)); if (restore != null) { return delegate { Safe("CompatEvents.EndScope", restore); }; } return null; } internal static Action<Exception?>? BeginCraft(Player player, string description, IReadOnlyList<Inventory> inventories, bool unmeasured) { Observer current = observer; if (current == null) { return null; } Action<Exception?> end = Safe("CompatEvents.OnCraft", () => current.OnCraft(player, description, inventories, unmeasured)); if (end != null) { return delegate(Exception? exception) { Safe("CompatEvents.EndCraft", delegate { end(exception); }); }; } return null; } internal static OperationHandle? BeginOperation(string operation, Player player, float range) { Observer current = observer; if (current == null) { return null; } (Action<IReadOnlyList<Container>, IReadOnlyList<(Container, float)>>, Action<Exception>)? tuple = Safe("CompatEvents.OnOperation", () => current.OnOperation(operation, player, range)); if (tuple.HasValue) { return new OperationHandle(tuple.Value.Item1, tuple.Value.Item2); } return null; } internal static string Short(string hash) { if (hash.Length <= 12) { return hash; } return hash.Substring(0, 12); } private static void Safe(string site, Action call) { try { call(); } catch (Exception error) { ReportFault(site, error); } } private static T? Safe<T>(string site, Func<T?> call) { try { return call(); } catch (Exception error) { ReportFault(site, error); return default(T); } } private static void ReportFault(string site, Exception error) { bool flag; lock (gate) { flag = reportedFaults.Add(site); } if (flag) { CompatibilityInstaller.Error("CompatEvents observer fault in " + site + "; gameplay continues. " + error); } } } public static class CompatibilityInstaller { internal static Action<string> Info = delegate { }; internal static Action<string> Warning = delegate { }; internal static Action<string> Error = delegate { }; internal const string DeepNorthCompatConflict = "CrossModCompat: DeepNorthCompat is also installed; skipping all patches so they don't run twice. Remove DeepNorthCompat and restart."; private static readonly List<(Action Verify, Action<Exception> Fail)> verifications = new List<(Action, Action<Exception>)>(); private static readonly object outcomeGate = new object(); private static readonly List<string> reported = new List<string>(); private static readonly Dictionary<string, bool> failed = new Dictionary<string, bool>(StringComparer.Ordinal); internal static void Outcome(string group, bool applied) { lock (outcomeGate) { if (!failed.ContainsKey(group)) { reported.Add(group); } failed[group] = !applied; } } internal static string Outcomes() { lock (outcomeGate) { return string.Join(", ", reported.Select((string group) => (!failed[group]) ? group : ("FAILED " + group))); } } public static void Install(Func<string, Assembly?> resolve, Action<string> info, Action<string> warning, Action<string> error) { Info = info; Warning = warning; Error = error; verifications.Clear(); lock (outcomeGate) { reported.Clear(); failed.Clear(); } if (resolve("DeepNorthCompat") != null) { Error("CrossModCompat: DeepNorthCompat is also installed; skipping all patches so they don't run twice. Remove DeepNorthCompat and restart."); return; } Assembly impact = resolve("MidnightsFX.ImpactfulSkills"); Assembly crafty = resolve("Azumatt.AzuCraftyBoxes"); Add(() => DropRangePatch.SeaAnimals, delegate { DropRangePatch.PrepareSeaAnimals(resolve("marlthon.SeaAnimals")); }, DropRangePatch.VerifySeaAnimals); Add(() => DropRangePatch.AirAnimals, delegate { DropRangePatch.PrepareAirAnimals(resolve("marlthon.AirAnimals")); }, DropRangePatch.VerifyAirAnimals); Add(() => QualityPatch.Group, delegate { QualityPatch.Install(impact, crafty, resolve("Azumatt.AzuAntiArthriticCrafting")); }, QualityPatch.Verify); Add(() => ForgeSpeedPatch.Group, delegate { ForgeSpeedPatch.Prepare(resolve("Azumatt.AzuAntiArthriticCrafting")); }, ForgeSpeedPatch.Verify); Add(() => RecipeRowsPatch.Group, delegate { RecipeRowsPatch.Prepare(resolve("Azumatt.AzuAntiArthriticCrafting")); }, RecipeRowsPatch.Verify); Add(() => CraftWaitPatch.Group, delegate { CraftWaitPatch.Prepare(resolve("akuichi.ReforgedPotential")); }, CraftWaitPatch.Verify); Add(() => CharacterPreviewPatch.Group, delegate { CharacterPreviewPatch.Prepare(resolve("Azumatt.AzuExtendedPlayerInventory")); }, CharacterPreviewPatch.Verify); Add(() => VpoTerrainGrassPatch.Group, delegate { VpoTerrainGrassPatch.Prepare(resolve("dev.ontrigger.vpo")); }, VpoTerrainGrassPatch.Verify); Add(() => VpoMaterialsPatch.Group, delegate { VpoMaterialsPatch.Prepare(resolve("dev.ontrigger.vpo"), resolve("ru.ivest.valheimvisuals")); }, VpoMaterialsPatch.Verify); Add(() => FarLandsRenderingPatch.Group, delegate { FarLandsRenderingPatch.Prepare(resolve("ru.ivest.farlands"), resolve("dev.ontrigger.vpo")); }, FarLandsRenderingPatch.Verify); Add(() => StructureSupportPatch.Group, delegate { StructureSupportPatch.Prepare(resolve("ru.ivest.steadyframe"), resolve("dev.ontrigger.vpo")); }, StructureSupportPatch.Verify); Add(() => VpoAnimationPatch.Group, delegate { VpoAnimationPatch.Prepare(resolve("dev.ontrigger.vpo"), resolve("ZenDragon.Zen.ModLib")); }, VpoAnimationPatch.Verify); Add(() => IdleSyncPatch.Group, IdleSyncPatch.Prepare, IdleSyncPatch.Verify); Add(() => RuneIcePatch.Group, delegate { RuneIcePatch.Prepare(resolve("hyleanlegend.RuneMagic")); }, RuneIcePatch.Verify); Add(() => RuneSpritePatch.Group, delegate { RuneSpritePatch.Prepare(resolve("hyleanlegend.RuneMagic")); }, RuneSpritePatch.Verify); Add(() => RuneRequirementPatch.Group, delegate { RuneRequirementPatch.Prepare(resolve("hyleanlegend.RuneMagic")); }, RuneRequirementPatch.Verify); Add(() => VisibleLocalizationPatch.Group, VisibleLocalizationPatch.Prepare, VisibleLocalizationPatch.Verify); Add(() => TabAudioPatch.Group, TabAudioPatch.Prepare, TabAudioPatch.Verify); Add(() => PanelInputPatch.Group, delegate { PanelInputPatch.Prepare(resolve("odinplus.TeleportEverything")); }, PanelInputPatch.Verify); Add(() => AmmoCountPatch.Group, delegate { AmmoCountPatch.Prepare(resolve("shudnal.MyLittleUI")); }, AmmoCountPatch.Verify); Assembly magic = resolve("blacks7ar.MagicRevamp"); Assembly backpacks = resolve("org.bepinex.plugins.backpacks"); Add(() => MagicRevampInventoryPatch.Group, delegate { MagicRevampInventoryPatch.Prepare(magic, backpacks); }, MagicRevampInventoryPatch.Verify); Add(() => MagicRevampCraftingPatch.Group, delegate { MagicRevampCraftingPatch.Prepare(magic, backpacks); }, MagicRevampCraftingPatch.Verify); Add(() => MagicRevampEitrPatch.Group, delegate { MagicRevampEitrPatch.Prepare(magic); }, MagicRevampEitrPatch.Verify); Add(() => MagicRevampHudPatch.Group, delegate { MagicRevampHudPatch.Prepare(magic); }, MagicRevampHudPatch.Verify); Add(() => MagicRevampCyclePatch.Group, delegate { MagicRevampCyclePatch.Prepare(magic, backpacks); }, MagicRevampCyclePatch.Verify); Add(() => MagicRevampPortalPatch.Group, delegate { MagicRevampPortalPatch.Prepare(magic); }, MagicRevampPortalPatch.Verify); Add(() => MagicRevampAmmoDisplayPatch.Group, delegate { MagicRevampAmmoDisplayPatch.Prepare(magic, backpacks, resolve("shudnal.MyLittleUI")); }, MagicRevampAmmoDisplayPatch.Verify); Add(() => GridCostPatch.Group, delegate { GridCostPatch.Prepare(resolve("advize.PlantEasily")); }, GridCostPatch.Verify); Add(() => FireplaceControlsPatch.Group, delegate { FireplaceControlsPatch.Prepare(resolve("TastyChickenLegs.NoSmokeStayLit")); }, FireplaceControlsPatch.Verify); Add(() => PlacementDustPatch.Group, delegate { PlacementDustPatch.Prepare(resolve("advize.PlantEverything"), resolve("Azumatt.NoCultivatorDust"), resolve("Azumatt.NoBuildDust")); }, PlacementDustPatch.Verify); Add(() => ClientShutdownPatch.Group, delegate { ClientShutdownPatch.Prepare(resolve("akoozie.valheimtune")); }, ClientShutdownPatch.Verify); Assembly hearth = resolve("Azumatt.HearthBelow"); Add(() => GpuGrassTerrainPatch.Group, delegate { GpuGrassTerrainPatch.Prepare(hearth, resolve("ru.ivest.steadyframe"), resolve("ru.ivest.farlands")); }, GpuGrassTerrainPatch.Verify); Add(() => HearthReplayPatch.Group, delegate { HearthReplayPatch.Prepare(hearth); }, HearthReplayPatch.Verify); Add(() => HearthTerrainPatch.Group, delegate { HearthTerrainPatch.Prepare(hearth, resolve("hyleanlegend.RuneMagic")); }, HearthTerrainPatch.Verify); Add(() => PrecisionLimitsPatch.Group, delegate { PrecisionLimitsPatch.Prepare(resolve("Searica.Valheim.TerrainTools"), resolve("digitalroot.mods.heightmapunlimitedjvl"), resolve("Searica.Valheim.AdvancedHeightMap")); }, PrecisionLimitsPatch.Verify); Add(() => PrecisionTerrainPatch.Hearth, delegate { PrecisionTerrainPatch.PrepareHearth(resolve("Searica.Valheim.TerrainTools"), hearth); }, PrecisionTerrainPatch.Verify); Add(() => FarLandsTerrainPatch.Group, delegate { FarLandsTerrainPatch.Prepare(resolve("ru.ivest.farlands"), resolve("digitalroot.mods.heightmapunlimitedjvl")); }, FarLandsTerrainPatch.Verify); Add(() => PathEffectsAndCartPatch.Effects, delegate { PathEffectsAndCartPatch.PrepareEffects(resolve("RustyMods.UsefulPaths")); }, PathEffectsAndCartPatch.VerifyEffects); Add(() => PathEffectsAndCartPatch.Cart, delegate { PathEffectsAndCartPatch.PrepareCart(resolve("RustyMods.UsefulPaths"), impact); }, PathEffectsAndCartPatch.VerifyCart); Assembly odin = resolve("marlthon.OdinShip"); Add(() => OdinShipCorePatch.Group, delegate { OdinShipCorePatch.Prepare(odin); }, OdinShipCorePatch.Verify); Add(() => OdinShipInputPatch.Group, delegate { OdinShipInputPatch.Prepare(odin); }, OdinShipInputPatch.Verify); Add(() => OdinShipFishPatch.Group, delegate { OdinShipFishPatch.Prepare(odin); }, OdinShipFishPatch.Verify); Add(() => OdinShipConstructionPatch.Group, delegate { OdinShipConstructionPatch.Prepare(odin); }, OdinShipConstructionPatch.Verify); Assembly betterMap = resolve("xtav1m.BetterMap"); Add(() => BetterMapCartographyPatch.Group, delegate { BetterMapCartographyPatch.Prepare(betterMap, resolve("advize.CartographySkill")); }, BetterMapCartographyPatch.Verify); Add(() => BetterMapSessionPatch.Group, delegate { BetterMapSessionPatch.Prepare(betterMap); }, BetterMapSessionPatch.Verify); Add(() => BetterMapPersistencePatch.Group, delegate { BetterMapPersistencePatch.Prepare(betterMap); }, BetterMapPersistencePatch.Verify); Add(() => BetterMapPortalPatch.Group, delegate { BetterMapPortalPatch.Prepare(betterMap); }, BetterMapPortalPatch.Verify); Add(() => BetterMapVehiclePatch.Group, delegate { BetterMapVehiclePatch.Prepare(betterMap); }, BetterMapVehiclePatch.Verify); Add(() => ChestRegistry.Group, delegate { ChestRegistry.Install(crafty); }, ChestRegistry.Verify); Add(() => ChestCraftPatch.Group, delegate { ChestCraftPatch.Install(crafty); }, ChestCraftPatch.Verify); Add(() => ChestSyncPatch.Group, delegate { ChestSyncPatch.Install(resolve("com.maxsch.valheim.MultiUserChest"), resolve("goldenrevolver.quick_stack_store")); }, ChestSyncPatch.Verify); CompatEvents.ChestSettingsSummary = () => "Crafty range " + CraftyAccess.Range.ToString(CultureInfo.InvariantCulture) + " m, leave one " + CraftyAccess.LeavingOne + "; crafting handoff " + (ChestCraftPatch.Group.Enabled ? "active" : "inactive") + "; Quick Stack range " + ChestSyncPatch.StackRange.ToString(CultureInfo.InvariantCulture) + " m, restock range " + ChestSyncPatch.RestockRange.ToString(CultureInfo.InvariantCulture) + " m"; CompatEvents.IsIdleSettled = IdleSyncPatch.IsSettled; CompatEvents.IdleSyncStats = () => (Active: IdleSyncPatch.Active, Settled: IdleSyncPatch.Settled, Skipped: IdleSyncPatch.Skipped, Checked: IdleSyncPatch.Checked); } public static void Verify() { foreach (var (action, action2) in verifications) { try { action(); } catch (Exception obj) { action2(obj); } } } private static void Add(Func<PatchGroup> owner, Action prepare, Action verify) { PatchGroup patchGroup; try { patchGroup = owner(); } catch (TypeInitializationException ex) { string text = ex.TypeName.Substring(ex.TypeName.LastIndexOf('.') + 1); Error(text + ": NOT APPLIED; its game members did not resolve; nothing was patched. " + ex); Outcome(text, applied: false); return; } verifications.Add((verify, patchGroup.Fail)); try { prepare(); } catch (Exception exception) { patchGroup.Fail(exception); } } } internal static class ExpectedBuilds { internal const string ValheimClient = "9D03AE0E9A4C3C891EAB1A2981B8892D43A8C5654F272864276EBBB12D8CC25C"; internal const string ValheimWindowsServer = "ACAC158E958E25D0E214B267197A956EE53F896D28D436C1FBAB3F26D01BFC1D"; internal const string ValheimLinuxServer = "EE143639D82BB35ED40AA5184540443181C462D6E8F7527FEA1523C03D75480E"; internal const string GuiUtilsClient = "4A7BD9F822CC505CF755D6D6315A692C91F221C459E0A9293A6C7298F13E7199"; internal const string UnityTextMeshPro = "3C0B42BB494AB0808A0C917EE053DC809952142BABDE64C3EC38E8EC4D22F88C"; internal static readonly string[] ValheimServers = new string[2] { "ACAC158E958E25D0E214B267197A956EE53F896D28D436C1FBAB3F26D01BFC1D", "EE143639D82BB35ED40AA5184540443181C462D6E8F7527FEA1523C03D75480E" }; internal static readonly string[] ValheimAllRoles = new string[3] { "9D03AE0E9A4C3C891EAB1A2981B8892D43A8C5654F272864276EBBB12D8CC25C", "ACAC158E958E25D0E214B267197A956EE53F896D28D436C1FBAB3F26D01BFC1D", "EE143639D82BB35ED40AA5184540443181C462D6E8F7527FEA1523C03D75480E" }; internal const string AaaCrafting = "D511490759B3EE7A1041CBEF9BAF27BAEF9530C6F225323D824628638B62E6AF"; internal const string AirAnimals = "B29905FFDA5204570D64958CB18D74E08D7CEE8AA361485E1D988B54242F2F85"; internal const string AzuEpi = "5F026B5DD4529CBA498377D293432157A53082CFD3FC06C2384D23DBA5307AC6"; internal const string Backpacks = "8B87E770095001271EED051065A83E589F8AECCDA46FB7BB0298B92323BA43F4"; internal const string BetterMap = "BB0A0A2E4E9EA2B388CD55F486A61057BF57F982D5647AA649375D4B1E7BAE04"; internal const string Cartography = "2379F6884BEC32843DAFA1306F693CAD8FC2FB1208E9D2BEE3D3745EFB2DC529"; internal const string CraftyBoxes = "381883FE4625D1DD119BB425A2F3C7522457FBC08AE1DB60159F8256DE940D6E"; internal const string FarLands = "D1B71083EA8BF8FEF7E187D7B42F94442A7B34DF43224F63ED31D794ECB84213"; internal const string HearthBelow = "85E2F266C36EC916E714832C48B771F6FA61F80C7360DF095E813E21B372C5E1"; internal const string HeightmapUnlimited = "F7C2C869CA3CAE30309D657984197B700C9E541C6C18D264AE8E422A9969D4A9"; internal const string ImpactfulSkills = "A5041A00113442866221355322AD7BE2F6695739DC996A15E33A476BB72943B8"; internal const string MagicRevamp = "B8BD009ED03EEF3BB388ED603474C45F70339DB275564D28EAB6A2A4ABF0E385"; internal const string MultiUserChest = "AFE0D6B437495FB6624A049BA72C2393572C8C02E1221AC090F16C0D99914514"; internal const string MyLittleUi = "D3DC94CEEB7A45EA9A1671E666BC20F4557A3326DBB15A6A4B4745894346BD90"; internal const string NoBuildDust = "80329CE6E96341F59D2CE9C77E4F1826E19B8D171473332A007B68AEA0963604"; internal const string NoCultivatorDust = "D3761A25915D573207BF529C7DEF9372E2CABFEBEBFDC932D799837126F4EEB3"; internal const string NoSmokeStayLit = "59F3F524CCF88D36FC35A634DDDCB2E895301DFFD37E0FFBFA7AA2D560895AD2"; internal const string OdinShip = "976803BF829EB3E7ABD258BDDA28A2C9C309483FF6F2BA3BBCAD1452CD9CA5DE"; internal const string PlantEasily = "9D56DAE0117798E504B0BAE000E4C848AEAF8642648E19CE99E36D59FA173ECB"; internal const string PlantEverything = "AE6F90220AC138E9CC90DEEFA530E934007DE4BF899B4AC51712525E268F6147"; internal const string QuickStack = "71CCC644DA95D4FA94897968D5D90331210A574A6C65129DC8EC6032E3CF6EEB"; internal const string ReforgedPotential = "4807FA77BF3162643D3908A3CCF10C509E9BC7DEFDC4AEE8CE7CE7C94451DC04"; internal const string RuneMagic = "618B66574C52F5E9C953BF75066A21C0542C4AF1814616AF0527C3C548123856"; internal const string SeaAnimals = "3F57F6AD089D5616A924D5917851A0A7C99715CC0B2062EF23B2FA15D07C721A"; internal const string SteadyFrame = "01255BF687217D57962A01470A3AC6F13C5CF4176E57000BDB7DAFDDF257384D"; internal const string TeleportEverything = "E640BF00744DDCBFE63303BE2CB678F35E33E3BCB47B2E93AA6B763B60278C50"; internal const string TerrainTools = "7054FE6C688A5C2885135B64F1079478C0547E0DCA4FE9E92FD11971EDF59879"; internal const string UsefulPaths = "BFBA84D4AEA9860F48265321C9BE07B2602F8C735CAAA57EB60B662A511EFCE3"; internal const string ValheimTune = "48D407B7CF76B0767AAD259C89BFBD2058C8A09EB214EA7079D1363AEE8B9C55"; internal const string Vcp = "D429A728C9D44A258504E5170F4B6F45806E0141C9BB2657007C7543816D8DE2"; internal const string Visuals = "EBED14A90F03C75C3C87AD5F7E2A581A2600D730FB8B6CE1F7A3FD6F09006F71"; internal const string Vpo = "5C5ABE8A4434C22F48A536896F856299AFE8285466685F2C0D434118D0055721"; internal const string VpoIndirect = "3B01AF5787DEF910FC254A7029C28B1828999E5143FDD40F2A8FC12652E51EAB"; internal const string ZenModLib = "ACEB707B5D249498155E319464EA33683B83D7D94C647B720CCEEB208E86601A"; } public static class Guard { private static readonly object gate = new object(); private static readonly Dictionary<string, (long Length, DateTime Written, string Hash)> hashes = new Dictionary<string, (long, DateTime, string)>(StringComparer.Ordinal); internal static bool KnownServerBuild() { return ExpectedBuilds.ValheimServers.Contains(Sha256(typeof(ZNet).Assembly.Location)); } public static void Build(Assembly assembly, params string[] expectedHashes) { string text = Sha256(assembly.Location); if (!expectedHashes.Contains(text)) { throw new NotSupportedException(assembly.GetName().Name + " build changed; expected " + string.Join(" or ", expectedHashes) + ", found " + text + ". Re-audit required."); } } internal static string Sha256(string path) { FileInfo fileInfo = new FileInfo(path); long length = fileInfo.Length; DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc; lock (gate) { if (hashes.TryGetValue(path, out (long, DateTime, string) value) && value.Item1 == length && value.Item2 == lastWriteTimeUtc) { return value.Item3; } } string text; using (SHA256 sHA = SHA256.Create()) { using FileStream inputStream = File.OpenRead(path); text = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", ""); } lock (gate) { hashes[path] = (length, lastWriteTimeUtc, text); return text; } } internal static Type Type(Assembly assembly, string name) { return assembly.GetType(name, throwOnError: true); } internal static MethodInfo Method(Type type, string name, Type returnType, params Type[] parameters) { MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null); if (method == null || method.ReturnType != returnType || !(from p in method.GetParameters() select p.ParameterType).SequenceEqual(parameters)) { throw new MissingMethodException(type.FullName, name); } return method; } internal static MethodInfo Getter(Type type, string name, Type propertyType) { MethodInfo methodInfo = AccessTools.PropertyGetter(type, name); if (methodInfo == null || methodInfo.ReturnType != propertyType) { throw new MissingMethodException(type.FullName, name); } return methodInfo; } internal static MethodInfo Setter(Type type, string name, Type propertyType) { MethodInfo methodInfo = AccessTools.PropertySetter(type, name); if (methodInfo == null || !(from p in methodInfo.GetParameters() select p.ParameterType).SequenceEqual(new <>z__ReadOnlySingleElementList<Type>(propertyType))) { throw new MissingMethodException(type.FullName, name); } return methodInfo; } internal static FieldInfo Field(Type type, string name, Type expected, bool? isStatic = null) { FieldInfo fieldInfo = AccessTools.DeclaredField(type, name); if (fieldInfo == null || fieldInfo.FieldType != expected || (isStatic.HasValue && fieldInfo.IsStatic != isStatic)) { throw new MissingFieldException(type.FullName, name); } return fieldInfo; } internal unsafe static Patch Sole(MethodBase target, MethodInfo hook, string owner, HarmonyPatchType kind) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) Patches patchInfo = Harmony.GetPatchInfo(target); Patch[] array = (from p in All(patchInfo) where p.PatchMethod == hook select p).ToArray(); if (array.Length != 1 || array[0].owner != owner || patchInfo == null || !Of(patchInfo, kind).Contains(array[0])) { throw new NotSupportedException("Expected one " + owner + " " + ((object)(*(HarmonyPatchType*)(&kind))/*cast due to .constrained prefix*/).ToString().ToLowerInvariant() + " " + Name(hook) + " on " + Name(target) + "."); } return array[0]; } internal static void Restore(MethodBase target, Patch patch, HarmonyPatchType kind) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Invalid comparison between Unknown and I4 Patches patchInfo = Harmony.GetPatchInfo(target); if (patchInfo == null || !All(patchInfo).Any((Patch p) => p.PatchMethod == patch.PatchMethod)) { if ((int)kind != 1 && (int)kind != 2) { throw new ArgumentOutOfRangeException("kind"); } HarmonyMethod val = new HarmonyMethod(patch.PatchMethod, patch.priority, patch.before, patch.after, (bool?)patch.debug); new Harmony(patch.owner).Patch(target, ((int)kind == 1) ? val : null, ((int)kind == 2) ? val : null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } internal static IEnumerable<Patch> All(Patches? info) { if (info != null) { return info.Prefixes.Concat(info.Postfixes).Concat(info.Transpilers).Concat(info.Finalizers) .Concat(info.ILManipulators); } return Array.Empty<Patch>(); } internal static IEnumerable<Patch> Of(Patches? info, HarmonyPatchType kind) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected I4, but got Unknown if (info == null) { return Array.Empty<Patch>(); } return (kind - 1) switch { 0 => info.Prefixes, 1 => info.Postfixes, 2 => info.Transpilers, 3 => info.Finalizers, 5 => info.ILManipulators, _ => throw new ArgumentOutOfRangeException("kind"), }; } internal static int Registrations(MethodBase target, MethodInfo hook) { return All(Harmony.GetPatchInfo(target)).Count((Patch p) => p.PatchMethod == hook); } internal static bool RunsBefore(MethodBase target, MethodInfo first, MethodInfo second) { Patches patchInfo = Harmony.GetPatchInfo(target); if (patchInfo == null) { return false; } List<MethodInfo> sortedPatchMethods = PatchProcessor.GetSortedPatchMethods(target, patchInfo.Prefixes.ToArray()); if (sortedPatchMethods.IndexOf(first) >= 0 && sortedPatchMethods.IndexOf(second) >= 0) { return sortedPatchMethods.IndexOf(first) < sortedPatchMethods.IndexOf(second); } return false; } internal static string Name(MethodBase target) { Type declaringType = target.DeclaringType; if (!(declaringType == null)) { return declaringType.Assembly.GetName().Name + ":" + declaringType.FullName + "." + target.Name; } return target.Name; } } internal static class ILMatch { private static readonly OpCode[] shortLoads = new OpCode[4] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }; private static readonly OpCode[] shortStores = new OpCode[4] { OpCodes.Stloc_0, OpCodes.Stloc_1, OpCodes.Stloc_2, OpCodes.Stloc_3 }; internal static int Site(List<CodeInstruction> code, Func<int, bool> matches) { int num = Unique(code, matches); if (num < 0 || !Plain(code[num])) { return -1; } return num; } internal static int Unique(List<CodeInstruction> code, Func<int, bool> matches) { int[] array = Enumerable.Range(0, code.Count).Where(matches).ToArray(); if (array.Length != 1) { return -1; } return array[0]; } internal static bool Plain(CodeInstruction code) { if (code.labels.Count == 0) { return code.blocks.Count == 0; } return false; } internal static Func<CodeInstruction, bool> Plain(Func<CodeInstruction, bool> match) { return (CodeInstruction code) => match(code) && Plain(code); } internal static bool NoBlocks(CodeInstruction code) { return code.blocks.Count == 0; } internal static bool Sequence(List<CodeInstruction> code, int start, params Func<CodeInstruction, bool>[] pattern) { if (start >= 0 && start + pattern.Length <= code.Count) { return Enumerable.Range(0, pattern.Length).All((int i) => pattern[i](code[start + i])); } return false; } internal static bool Branch(List<CodeInstruction> code, int index, out Label target) { target = default(Label); if (index < 0 || index >= code.Count || !(code[index].operand is Label label)) { return false; } target = label; return true; } internal static bool BranchesTo(List<CodeInstruction> code, int from, int to) { if (Branch(code, from, out var target) && to >= 0 && to < code.Count) { return code[to].labels.Contains(target); } return false; } internal static bool Locals(MethodBase method, int count, params (int Index, Type Type)[] expected) { MethodBody methodBody = method.GetMethodBody(); if (methodBody == null) { return false; } IList<LocalVariableInfo> locals = methodBody.LocalVariables; if (locals.Count == count) { return expected.All(((int Index, Type Type) local) => locals[local.Index].LocalType == local.Type); } return false; } internal static Func<CodeInstruction, bool> Is(OpCode opcode) { return (CodeInstruction code) => code.opcode == opcode; } internal static Func<CodeInstruction, bool> Float(float value) { return (CodeInstruction code) => code.opcode == OpCodes.Ldc_R4 && code.operand is float num && num == value; } internal static bool Limit(CodeInstruction code) { if (code.opcode == OpCodes.Ldc_R4) { return true; } if (code.opcode != OpCodes.Call || !(code.operand is MethodInfo methodInfo)) { return false; } if (methodInfo.IsStatic && methodInfo.ReturnType == typeof(float)) { return methodInfo.GetParameters().Length == 0; } return false; } internal static Func<CodeInstruction, bool> Loads(FieldInfo field) { return (CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, field, false); } internal static Func<CodeInstruction, bool> Calls(MethodInfo method) { return (CodeInstruction code) => CodeInstructionExtensions.Calls(code, method); } internal static Func<CodeInstruction, bool> IsLoad(int index) { return (CodeInstruction code) => (index < shortLoads.Length && code.opcode == shortLoads[index]) || ((code.opcode == OpCodes.Ldloc || code.opcode == OpCodes.Ldloc_S) && Local(code) == index); } internal static Func<CodeInstruction, bool> IsStore(int index) { return (CodeInstruction code) => (index < shortStores.Length && code.opcode == shortStores[index]) || ((code.opcode == OpCodes.Stloc || code.opcode == OpCodes.Stloc_S) && Local(code) == index); } private static int Local(CodeInstruction code) { if (!(code.operand is LocalVariableInfo localVariableInfo)) { return Convert.ToInt32(code.operand); } return localVariableInfo.LocalIndex; } } internal static class ModAccess { private enum Pass { Direct, Cast, Unbox, Box, OutUpcast } internal static T Emit<T>(string name, Action<ILGenerator> body) where T : Delegate { MethodInfo methodInfo = typeof(T).GetMethod("Invoke") ?? throw new ArgumentException("T is a delegate without an Invoke method.", "T"); Type[] parameterTypes = (from p in methodInfo.GetParameters() select p.ParameterType).ToArray(); DynamicMethod dynamicMethod = new DynamicMethod(name, methodInfo.ReturnType, parameterTypes, typeof(ModAccess), skipVisibility: true); body(dynamicMethod.GetILGenerator()); return (T)dynamicMethod.CreateDelegate(typeof(T)); } internal static T Call<T>(MethodInfo method) where T : Delegate { Type type = method.DeclaringType ?? throw Mismatch(method, "has no declaring type"); if (method.ContainsGenericParameters) { throw Mismatch(method, "is an open generic method"); } if (!method.IsStatic && type.IsValueType) { throw Mismatch(method, "is an instance method of a struct"); } MethodInfo methodInfo = typeof(T).GetMethod("Invoke") ?? throw new ArgumentException("T is a delegate without an Invoke method.", "T"); ParameterInfo[] parameters = method.GetParameters(); Type[] array = (from p in methodInfo.GetParameters() select p.ParameterType).ToArray(); Type[] targets = parameters.Select((ParameterInfo p) => p.ParameterType).ToArray(); bool[] outs = parameters.Select((ParameterInfo p) => p.IsOut).ToArray(); if (!method.IsStatic) { targets = targets.Prepend(type).ToArray(); outs = outs.Prepend(element: false).ToArray(); } if (array.Length != targets.Length) { throw Mismatch(method, $"takes {targets.Length} arguments, but {typeof(T).Name} passes {array.Length}"); } Pass[] arguments = array.Select((Type source, int i) => Argument(method, source, targets[i], outs[i])).ToArray(); Pass result = Result(method, method.ReturnType, methodInfo.ReturnType); return Emit<T>("CMC_" + type.Name + "." + method.Name, delegate(ILGenerator il) { List<(short, LocalBuilder)> list = new List<(short, LocalBuilder)>(); for (short num = 0; num < targets.Length; num++) { if (arguments[num] == Pass.OutUpcast) { LocalBuilder localBuilder = il.DeclareLocal(targets[num].GetElementType()); list.Add((num, localBuilder)); il.Emit(OpCodes.Ldloca, localBuilder); } else { il.Emit(OpCodes.Ldarg, num); Convert(il, arguments[num], targets[num]); } } il.Emit(method.IsStatic ? OpCodes.Call : OpCodes.Callvirt, method); Convert(il, result, method.ReturnType); foreach (var (arg, local) in list) { il.Emit(OpCodes.Ldarg, arg); il.Emit(OpCodes.Ldloc, local); il.Emit(OpCodes.Stind_Ref); } il.Emit(OpCodes.Ret); }); } internal static T New<T>(ConstructorInfo constructor) where T : Delegate { Type declaring = constructor.DeclaringType ?? throw Mismatch(constructor, "has no declaring type"); if (constructor.IsStatic || declaring.IsAbstract || declaring.ContainsGenericParameters) { throw Mismatch(constructor, "can't create an instance"); } MethodInfo methodInfo = typeof(T).GetMethod("Invoke") ?? throw new ArgumentException("T is a delegate without an Invoke method.", "T"); Type[] array = (from p in methodInfo.GetParameters() select p.ParameterType).ToArray(); Type[] targets = (from p in constructor.GetParameters() select p.ParameterType).ToArray(); if (array.Length != targets.Length) { throw Mismatch(constructor, $"takes {targets.Length} arguments, but {typeof(T).Name} passes {array.Length}"); } if (Array.Exists(targets, (Type target) => target.IsByRef)) { throw Mismatch(constructor, "has a by-ref parameter"); } Pass[] arguments = array.Select((Type source, int i) => Argument(constructor, source, targets[i], isOut: false)).ToArray(); Pass result = Result(constructor, declaring, methodInfo.ReturnType); return Emit<T>("CMC_new_" + declaring.Name, delegate(ILGenerator il) { for (short num = 0; num < targets.Length; num++) { il.Emit(OpCodes.Ldarg, num); Convert(il, arguments[num], targets[num]); } il.Emit(OpCodes.Newobj, constructor); Convert(il, result, declaring); il.Emit(OpCodes.Ret); }); } internal static Func<object, F> BoxedGetter<F>(FieldInfo field) { Type declaring = StructField<F>(field); return Emit<Func<object, F>>("CMC_get_" + declaring.Name + "." + field.Name, delegate(ILGenerator il) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Unbox, declaring); il.Emit(OpCodes.Ldfld, field); il.Emit(OpCodes.Ret); }); } internal static Action<object, F> BoxedSetter<F>(FieldInfo field) { Type declaring = StructField<F>(field); return Emit<Action<object, F>>("CMC_set_" + declaring.Name + "." + field.Name, delegate(ILGenerator il) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Unbox, declaring); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); }); } private static Type StructField<F>(FieldInfo field) { if (!field.IsStatic) { Type declaringType = field.DeclaringType; if ((object)declaringType != null && declaringType.IsValueType && !(field.FieldType != typeof(F))) { return declaringType; } } throw new ArgumentException(field.DeclaringType?.FullName + "." + field.Name + " is not an instance " + typeof(F).Name + " field of a struct.", "field"); } private static Pass Argument(MethodBase member, Type source, Type target, bool isOut) { bool isByRef = source.IsByRef; bool isByRef2 = target.IsByRef; Pass? pass; if (isByRef) { if (!isByRef2) { goto IL_0038; } pass = ByRefArgument(source.GetElementType(), target.GetElementType(), isOut); } else { if (isByRef2) { goto IL_0038; } pass = ValueArgument(source, target); } goto IL_0042; IL_0038: pass = null; goto IL_0042; IL_0042: return pass ?? throw Mismatch(member, "takes " + target.Name + " where the delegate passes " + source.Name); } private static Pass? ByRefArgument(Type source, Type target, bool isOut) { if (SameStorage(source, target)) { return Pass.Direct; } if (!isOut || !IsUpcast(target, source)) { return null; } return Pass.OutUpcast; } private static Pass? ValueArgument(Type source, Type target) { if (SameStorage(source, target) || IsUpcast(source, target)) { return Pass.Direct; } if (source != typeof(object)) { return null; } if (IsReference(target)) { return Pass.Cast; } if (!target.IsValueType) { return null; } return Pass.Unbox; } private static Pass Result(MethodBase member, Type actual, Type returns) { if (SameStorage(actual, returns) || IsUpcast(actual, returns)) { return Pass.Direct; } if (returns == typeof(object) && actual.IsValueType && actual != typeof(void)) { return Pass.Box; } throw Mismatch(member, "returns " + actual.Name + " where the delegate returns " + returns.Name); } private static bool SameStorage(Type a, Type b) { if (!(a == b) && (!a.IsEnum || !(Enum.GetUnderlyingType(a) == b))) { if (b.IsEnum) { return Enum.GetUnderlyingType(b) == a; } return false; } return true; } private static bool IsUpcast(Type from, Type to) { if (IsReference(from) && IsReference(to)) { return to.IsAssignableFrom(from); } return false; } private static bool IsReference(Type type) { if (!type.IsClass) { return type.IsInterface; } return true; } private static void Convert(ILGenerator il, Pass pass, Type type) { switch (pass) { case Pass.Cast: il.Emit(OpCodes.Castclass, type); break; case Pass.Unbox: il.Emit(OpCodes.Unbox_Any, type); break; case Pass.Box: il.Emit(OpCodes.Box, type); break; case Pass.OutUpcast: throw new InvalidOperationException("OutUpcast is handled directly by Call."); case Pass.Direct: break; } } private static ArgumentException Mismatch(MethodBase member, string problem) { return new ArgumentException(member.DeclaringType?.FullName + "." + member.Name + " " + problem + ".", "member"); } } internal static class Mods { internal const string ImpactfulSkills = "MidnightsFX.ImpactfulSkills"; internal const string CraftyBoxes = "Azumatt.AzuCraftyBoxes"; internal const string AaaCrafting = "Azumatt.AzuAntiArthriticCrafting"; internal const string ReforgedPotential = "akuichi.ReforgedPotential"; internal const string SeaAnimals = "marlthon.SeaAnimals"; internal const string AirAnimals = "marlthon.AirAnimals"; internal const string AzuEpi = "Azumatt.AzuExtendedPlayerInventory"; internal const string Vpo = "dev.ontrigger.vpo"; internal const string ValheimVisuals = "ru.ivest.valheimvisuals"; internal const string SteadyFrame = "ru.ivest.steadyframe"; internal const string FarLands = "ru.ivest.farlands"; internal const string ZenModLib = "ZenDragon.Zen.ModLib"; internal const string Vcp = "MidnightsFX.ValheimCommunityPatch"; internal const string ValheimTune = "akoozie.valheimtune"; internal const string MultiUserChest = "com.maxsch.valheim.MultiUserChest"; internal const string QuickStack = "goldenrevolver.quick_stack_store"; internal const string OdinShip = "marlthon.OdinShip"; internal const string BetterMap = "xtav1m.BetterMap"; internal const string Cartography = "advize.CartographySkill"; internal const string HearthBelow = "Azumatt.HearthBelow"; internal const string RuneMagic = "hyleanlegend.RuneMagic"; internal const string TerrainTools = "Searica.Valheim.TerrainTools"; internal const string HeightmapUnlimited = "digitalroot.mods.heightmapunlimitedjvl"; internal const string AdvancedHeightMap = "Searica.Valheim.AdvancedHeightMap"; internal const string UsefulPaths = "RustyMods.UsefulPaths"; internal const string TeleportEverything = "odinplus.TeleportEverything"; internal const string MyLittleUi = "shudnal.MyLittleUI"; internal const string PlantEasily = "advize.PlantEasily"; internal const string NoSmokeStayLit = "TastyChickenLegs.NoSmokeStayLit"; internal const string PlantEverything = "advize.PlantEverything"; internal const string NoCultivatorDust = "Azumatt.NoCultivatorDust"; internal const string NoBuildDust = "Azumatt.NoBuildDust"; internal const string MagicRevamp = "blacks7ar.MagicRevamp"; internal const string Backpacks = "org.bepinex.plugins.backpacks"; internal const string ConditionalConfigSync = "_shudnal.ConditionalConfigSync"; internal const string DeepNorthCompat = "DeepNorthCompat"; } internal static class ForgeSpeedPatch { internal sealed class Members { internal required Func<int> OverrideMode { get; init; } internal required ConfigEntry<float> Duration { get; init; } internal required FieldInfo UpgraderDuration { get; init; } internal required FieldInfo UpgraderPerLevel { get; init; } } internal static readonly PatchGroup<Members> Group = new PatchGroup<Members>("Crafting.ForgeOfPotential", "vanilla forge timing retained"); private static readonly MethodInfo hook = AccessTools.DeclaredMethod(typeof(ForgeSpeedPatch), "Duration", (Type[])null, (Type[])null); private static ConfigEntry<bool>? forgeSpeed; internal static void BindConfig(ConfigFile config, ConfigSync sync) { ConfigEntry<bool> val = config.Bind<bool>("Crafting", "Forge of Potential speed", true, "Apply AAA Crafting's Crafting Speed to the Forge of Potential when Override Crafting Speed is on. Server-controlled by default; takes effect immediately."); ((ConditionalConfigSync)sync).AddConfigEntry<bool>(val); forgeSpeed = val; } internal static void Prepare(Assembly? assembly) { if (!Group.Installed && !Group.Absent(assembly, "AzuAntiArthriticCrafting") && !Group.OnServer()) { Guard.Build(assembly, "D511490759B3EE7A1041CBEF9BAF27BAEF9530C6F225323D824628638B62E6AF"); Guard.Build(typeof(InventoryGui).Assembly, "9D03AE0E9A4C3C891EAB1A2981B8892D43A8C5654F272864276EBBB12D8CC25C"); Type type = Guard.Type(assembly, "AzuAntiArthriticCrafting.AzuAntiArthriticCraftingPlugin"); Type type2 = Guard.Type(assembly, type.FullName + "+Toggle"); FieldInfo fieldInfo = Guard.Field(type, "OverrideCraftingDuration", typeof(ConfigEntry<>).MakeGenericType(type2), true); FieldInfo fieldInfo2 = Guard.Field(type, "CraftingDuration", typeof(ConfigEntry<float>), true); object entry = AccessTools.StaticFieldRefAccess<object>(fieldInfo).Invoke() ?? throw new InvalidOperationException("AAA Crafting's speed override config is not initialized."); Func<object, int> mode = ModAccess.Call<Func<object, int>>(Guard.Getter(fieldInfo.FieldType, "Value", type2)); Group.State = new Members { OverrideMode = () => mode(entry), Duration = (AccessTools.StaticFieldRefAccess<ConfigEntry<float>>(fieldInfo2).Invoke() ?? throw new InvalidOperationException("AAA Crafting's duration config is not initialized.")), UpgraderDuration = Guard.Field(typeof(InventoryGui), "m_upgraderDuration", typeof(float)), UpgraderPerLevel = Guard.Field(typeof(InventoryGui), "m_upgraderDurationPerLevel", typeof(float)) }; MethodInfo target = Guard.Method(typeof(InventoryGui), "UpdateRecipe", typeof(void), typeof(Player), typeof(float)); Group.Transpiler((MethodBase)target, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(Rewrite)); } } internal static void Verify() { Group.Confirm("Forge of Potential uses AAA Crafting's crafting speed."); } internal static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions, MethodBase original) { return Group.Transpile(original, instructions, (CodeMatcher matcher) => EditRewrite(matcher, Group.State)); } private static string? EditRewrite(CodeMatcher matcher, Members m) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown CodeMatch[] array = (CodeMatch[])(object)new CodeMatch[8] { new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)m.UpgraderDuration, (string)null), new CodeMatch((OpCode?)OpCodes.Ldloc_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Conv_R4, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)m.UpgraderPerLevel, (string)null), new CodeMatch((OpCode?)OpCodes.Mul, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Add, (object)null, "sum") }; matcher.MatchStartForward(array); string text = Reject(matcher, m, array.Length); if (text != null) { return text; } CodeInstruction obj = matcher.NamedMatch("sum"); obj.opcode = OpCodes.Call; obj.operand = hook; return null; } private static string? Reject(CodeMatcher matcher, Members m, int length) { List<CodeInstruction> source = matcher.InstructionEnumeration().ToList(); if (source.Count((CodeInstruction i) => CodeInstructionExtensions.LoadsField(i, m.UpgraderDuration, false)) != 1 || source.Count((CodeInstruction i) => CodeInstructionExtensions.LoadsField(i, m.UpgraderPerLevel, false)) != 1) { return "InventoryGui.UpdateRecipe does not load each upgrader duration field exactly once"; } if (matcher.IsInvalid) { return "InventoryGui.UpdateRecipe has no upgrader duration sum"; } if (matcher.Instructions(length).Skip(1).Any((CodeInstruction i) => i.labels.Count != 0 || i.blocks.Count != 0)) { return "the upgrader duration sum contains a branch target or exception boundary"; } return null; } private static float Duration(float baseDuration, float levelDuration) { if (Group.Active(out Members members)) { ConfigEntry<bool> val = forgeSpeed; if (val != null && val.Value && members.OverrideMode() != 0) { return members.Duration.Value; } } return baseDuration + levelDuration; } } internal static class RecipeRowsPatch { internal static readonly PatchGroup Group = new PatchGroup("UI.AAARecipeRows", "AAA behavior retained"); private static readonly MethodInfo contains = Guard.Method(typeof(HashSet<GameObject>), "Contains", typeof(bool), typeof(GameObject)); private static readonly MethodInfo setActive = Guard.Method(typeof(GameObject), "SetActive", typeof(void), typeof(bool)); private static readonly MethodInfo discard = AccessTools.DeclaredMethod(typeof(RecipeRowsPatch), "Discard", (Type[])null, (Type[])null); internal static void Prepare(Assembly? assembly) { if (!Group.Installed && !Group.Absent(assembly, "AzuAntiArthriticCrafting") && !Group.OnServer()) { Guard.Build(assembly, "D511490759B3EE7A1041CBEF9BAF27BAEF9530C6F225323D824628638B62E6AF"); Guard.Build(typeof(InventoryGui).Assembly, "9D03AE0E9A4C3C891EAB1A2981B8892D43A8C5654F272864276EBBB12D8CC25C"); MethodInfo target = Guard.Method(Guard.Type(assembly, "AzuAntiArthriticCrafting.Patches.PaginatorPatches+InventoryGuiUpdateRecipeListPatch"), "Postfix", typeof(void), typeof(InventoryGui), typeof(List<Recipe>).MakeByRefType()); Group.Transpiler((MethodBase)target, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(Rewrite)); } } internal static void Verify() { Group.Confirm("cleaning up discarded AAA Crafting upgrade recipe rows."); } private static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Group.Transpile(__originalMethod, instructions, "the discarded-row branch no longer matches", (List<CodeInstruction> code) => Edit(__originalMethod, code)); } private static bool Edit(MethodBase method, List<CodeInstruction> code) { int num = ILMatch.Site(code, (int i) => ILMatch.Sequence(code, i, ILMatch.IsLoad(10), ILMatch.IsLoad(35), ILMatch.Calls(contains), BranchTrue, ILMatch.IsLoad(35), ILMatch.Is(OpCodes.Ldc_I4_0), ILMatch.Calls(setActive), ILMatch.IsLoad(34)) && ILMatch.BranchesTo(code, i + 3, i + 7) && code.Skip(i).Take(7).All(ILMatch.Plain)); if (num < 0 || !ILMatch.Locals(method, 47, (10, typeof(HashSet<GameObject>)), (34, typeof(int)), (35, typeof(GameObject)))) { return false; } code[num + 6].opcode = OpCodes.Call; code[num + 6].operand = discard; return true; } private static bool BranchTrue(CodeInstruction code) { if (!(code.opcode == OpCodes.Brtrue)) { return code.opcode == OpCodes.Brtrue_S; } return true; } private static void Discard(GameObject row, bool active) { row.SetActive(active); if (Group.Enabled) { Object.Destroy((Object)(object)row); } } } internal static class PrecisionLimitsPatch { internal sealed class CoreMembers { internal required Type Operations { get; init; } internal required MethodInfo Min { get; init; } internal required MethodInfo Max { get; init; } internal required MethodInfo Raise { get; init; } } internal sealed class Members { internal required MethodInfo Min { get; init; } internal required MethodInfo Max { get; init; } internal required MethodInfo UnlimitedMin { get; init; } internal required MethodInfo UnlimitedMax { get; init; } } internal static readonly PatchGroup<Members> Group = new PatchGroup<Members>("Terrain.PrecisionLimits"); private static void CheckGame() { Guard.Build(typeof(TerrainComp).Assembly, ExpectedBuilds.ValheimAllRoles); } internal static CoreMembers Terrain(Assembly assembly) { Guard.Build(assembly, "7054FE6C688A5C2885135B64F1079478C0547E0DCA4FE9E92FD11971EDF59879"); CheckGame(); Type type = Guard.Type(assembly, "TerrainTools.Core.TerrainOperations"); Type type2 = Guard.Type(assembly, "AdvancedHeightMap.API.AdvancedHeightMapAPI"); MethodInfo min = Guard.Method(type2, "GetMinHeightChange", typeof(float)); MethodInfo max = Guard.Method(type2, "GetMaxHeightChange", typeof(float)); MethodInfo raise = Guard.Method(type, "PreciseRaiseTerrain", typeof(void), typeof(TerrainComp), typeof(Vector3), typeof(float)); return new CoreMembers { Operations = type, Min = min, Max = max, Raise = raise }; } internal static void Prepare(Assembly? terrain, Assembly? unlimited, Assembly? advancedHeightMap) { if (!Group.Installed && !Group.Absent(terrain, "TerrainTools") && !Group.Absent(unlimited, "HeightmapUnlimited")) { if (advancedHeightMap != null) { Group.Inactive("AdvancedHeightMap sets the limits"); return; } CoreMembers coreMembers = Terrain(terrain); Guard.Build(unlimited, "F7C2C869CA3CAE30309D657984197B700C9E541C6C18D264AE8E422A9969D4A9"); Type type = Guard.Type(unlimited, "Digitalroot.HeightmapUnlimitedJvL.Main"); Group.State = new Members { Min = coreMembers.Min, Max = coreMembers.Max, UnlimitedMin = Guard.Method(type, "Min", typeof(float)), UnlimitedMax = Guard.Method(type, "Max", typeof(float)) }; Group.Transpiler((MethodBase)coreMembers.Raise, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewriteLimits)); } } internal static void Verify() { Group.Confirm("precision raising uses Heightmap Unlimited JvL limits."); } private static IEnumerable<CodeInstruction> RewriteLimits(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Group.Transpile(__originalMethod, instructions, "precision limits changed", delegate(List<CodeInstruction> code) { Members l = Group.State; int num = ILMatch.Unique(code, (int i) => CodeInstructionExtensions.Calls(code[i], l.Min)); if (num < 0 || !ILMatch.Sequence(code, num, ILMatch.Calls(l.Min), ILMatch.Calls(l.Max)) || code.Count((CodeInstruction i) => CodeInstructionExtensions.Calls(i, l.Max)) != 1) { return false; } code[num].operand = l.UnlimitedMin; code[num + 1].operand = l.UnlimitedMax; return true; }); } } internal static class PrecisionTerrainPatch { internal sealed class Members { internal required MethodInfo FootprintOf { get; init; } internal required MethodInfo NewOp { get; init; } internal required MethodInfo VoxelOperations { get; init; } internal required MethodInfo FlattenAt { get; init; } internal required MethodInfo ClampRaise { get; init; } internal required FieldInfo Index { get; init; } internal required FieldInfo OpDepth { get; init; } internal required Type IndexType { get; init; } internal required Type IndexEnumerator { get; init; } internal required Type OverlayType { get; init; } internal required Type DigProfile { get; init; } internal required Type VoxelOperationType { get; init; } internal required Func<float> Spinner { get; init; } internal required Func<float, float> ClampDelta { get; init; } internal required Func<Vector3, float, bool, bool> Flatten { get; init; } } internal static readonly PatchGroup<Members> Hearth = new PatchGroup<Members>("Terrain.HearthBelow.Precision", "original behavior retained", null, HearthTerrainPatch.Group); private static readonly MethodInfo clamp = Guard.Method(typeof(Mathf), "Clamp", typeof(float), typeof(float), typeof(float), typeof(float)); private static readonly FieldInfo levelDelta = Guard.Field(typeof(TerrainComp), "m_levelDelta", typeof(float[])); private static readonly FieldInfo smoothDelta = Guard.Field(typeof(TerrainComp), "m_smoothDelta", typeof(float[])); private static readonly FieldInfo modifiedHeight = Guard.Field(typeof(TerrainComp), "m_modifiedHeight", typeof(bool[])); private static readonly FieldInfo levelSetting = Guard.Field(typeof(Settings), "m_level", typeof(bool)); private static readonly MethodInfo raised = Injected("Raised"); private static readonly MethodInfo skipped = Injected("Skipped"); private static readonly MethodInfo smoothed = Injected("Smoothed"); private static readonly MethodInfo squareFootprint = Injected("SquareFootprint"); private static readonly MethodInfo precisionRadius = Injected("PrecisionRadius"); private static readonly MethodInfo precisionFlatten = Injected("PrecisionFlatten"); private static readonly MethodInfo precisionDelta = Injected("PrecisionDelta"); private static readonly MethodInfo preparePlacement = Injected("PreparePlacement"); private static bool Ready => Hearth.Enabled; internal static void PrepareHearth(Assembly? terrain, Assembly? hearth) { if (!Hearth.Installed && !Hearth.Absent(terrain, "TerrainTools") && !Hearth.Absent(hearth, "HearthBelow")) { Guard.Build(hearth, "85E2F266C36EC916E714832C48B771F6FA61F80C7360DF095E813E21B372C5E1"); PrecisionLimitsPatch.CoreMembers coreMembers = PrecisionLimitsPatch.Terrain(terrain); Type operations = coreMembers.Operations; Type type = Guard.Type(terrain, "TerrainTools.Core.TerrainOperations+HeightIndex"); Type indexEnumerator = typeof(IEnumerator<>).MakeGenericType(type); FieldInfo index = Guard.Field(type, "Index", typeof(int)); MethodInfo target = Guard.Method(operations, "PreciseSmoothTerrain", typeof(void), typeof(TerrainComp), typeof(Vector3)); Type type2 = Guard.Type(hearth, "HearthBelow.VoxelMagic.VoxelWorld"); Type type3 = Guard.Type(hearth, "HearthBelow.VoxelMagic.CarveOp"); Type type4 = Guard.Type(hearth, "HearthBelow.VoxelMagic.VoxelOpType"); FieldInfo opDepth = Guard.Field(type3, "Depth", typeof(float)); Type type5 = Guard.Type(hearth, "HearthBelow.Patches.TerrainComp_InternalDoOperation_Patch"); Type type6 = Guard.Type(hearth, "HearthBelow.Patches.TerrainOp_Awake_Patch"); Type type7 = Guard.Type(terrain, "TerrainTools.Core.GroundLevelSpinner"); Type overlayType = Guard.Type(terrain, "TerrainTools.Visualization.OverlayVisualizer"); Type digProfile = Guard.Type(hearth, "HearthBelow.Digging.DigProfile"); Func<float> spinner = AccessTools.MethodDelegate<Func<float>>(Guard.Getter(type7, "Value", typeof(float)), (object)null, true); MethodInfo footprintOf = Guard.Method(type2, "ShapeOf", typeof(byte), typeof(bool)); MethodInfo newOp = Guard.Method(type2, "NewOp", type3, type4, typeof(byte), typeof(Vector3), typeof(float)); MethodInfo voxelOperations = Guard.Method(type5, "ApplyAsVoxelOps", typeof(void), typeof(Vector3), typeof(Settings)); MethodInfo target2 = Guard.Method(type6, "Prefix", typeof(void), typeof(TerrainOp)); MethodInfo target3 = Guard.Method(type2, "RaiseAt", typeof(bool), typeof(Vector3), typeof(float), typeof(float), typeof(float), typeof(bool)); MethodInfo target4 = Guard.Method(type2, "SmoothAt", typeof(bool), typeof(Vector3), typeof(float), typeof(float)); MethodInfo methodInfo = Guard.Method(type2, "FlattenAt", typeof(bool), typeof(Vector3), typeof(float), typeof(bool)); Func<Vector3, float, bool, bool> flatten = AccessTools.MethodDelegate<Func<Vector3, float, bool, bool>>(methodInfo, (object)null, true); MethodInfo methodInfo2 = Guard.Method(type2, "ClampRaiseDelta", typeof(float), typeof(float)); Func<float, float> clampDelta = AccessTools.MethodDelegate<Func<float, float>>(methodInfo2, (object)null, true); Hearth.State = new Members { FootprintOf = footprintOf, NewOp = newOp, VoxelOperations = voxelOperations, FlattenAt = methodInfo, ClampRaise = methodInfo2, Index = index, OpDepth = opDepth, IndexType = type, IndexEnumerator = indexEnumerator, OverlayType = overlayType, DigProfile = digProfile, VoxelOperationType = type3, Spinner = spinner, ClampDelta = clampDelta, Flatten = flatten }; Rewrite(coreMembers.Raise, new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewriteRaise)); Rewrite(target, new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewriteSmooth)); Hearth.Transpiler((MethodBase)target3, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewriteVoxelRaise)); Hearth.Transpiler((MethodBase)target4, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewriteVoxelSmooth)); Hearth.Transpiler((MethodBase)target2, (Delegate)new Func<IEnumerable<CodeInstruction>, MethodBase, IEnumerable<CodeInstruction>>(RewritePlacement)); } } private static void Rewrite(MethodInfo target, Delegate rewrite) { Hearth.Prefix(target, new <>A{00000002}<bool>(Begin), 400); Hearth.Transpiler(target, rewrite); Hearth.Finalizer(target, new Func<Exception, bool, Exception>(End)); } internal static void Verify() { Hearth.Confirm("precision tools also fill pickaxe cuts."); } private static IEnumerable<CodeInstruction> RewriteRaise(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Transpile(instructions, __originalMethod, delegate(List<CodeInstruction> code) { //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Expected O, but got Unknown //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Expected O, but got Unknown //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Expected O, but got Unknown //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Expected O, but got Unknown //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Expected O, but got Unknown //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Expected O, but got Unknown //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Expected O, but got Unknown Members state = Hearth.State; int num = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], clamp)); int num2 = ILMatch.Site(code, (int i) => ILMatch.Sequence(code, i - 4, ILMatch.IsLoad(1), ILMatch.Is(OpCodes.Ldarg_2), ILMatch.Is(OpCodes.Add), ILMatch.IsStore(3), ILMatch.Is(OpCodes.Ldarg_2))); if (!ILMatch.Sequence(code, num - 11, ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Loads(levelDelta), ILMatch.IsLoad(6), ILMatch.Loads(state.Index), ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Loads(levelDelta), ILMatch.IsLoad(6), ILMatch.Loads(state.Index), ILMatch.Is(OpCodes.Ldelem_R4), ILMatch.Limit, ILMatch.Limit, ILMatch.Calls(clamp), ILMatch.Is(OpCodes.Stelem_R4), ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Loads(modifiedHeight), ILMatch.IsLoad(6), ILMatch.Loads(state.Index), ILMatch.Is(OpCodes.Ldc_I4_1), ILMatch.Is(OpCodes.Stelem_I1)) || num2 < 0 || num2 >= num || !PrecisionLocals(__originalMethod, state)) { return false; } code[num].operand = raised; code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[6] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Ldarg_2, (object)null), Load(6), new CodeInstruction(OpCodes.Ldfld, (object)state.Index), Load(3) }); code.InsertRange(num2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[8] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Ldarg_2, (object)null), Load(6), new CodeInstruction(OpCodes.Ldfld, (object)state.Index), Load(2), Load(3), new CodeInstruction(OpCodes.Call, (object)skipped) }); return true; }); } private static IEnumerable<CodeInstruction> RewriteSmooth(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Transpile(instructions, __originalMethod, delegate(List<CodeInstruction> code) { //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Expected O, but got Unknown //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Expected O, but got Unknown //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Expected O, but got Unknown Members state = Hearth.State; int num = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], clamp)); if (!ILMatch.Sequence(code, num - 9, ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Loads(smoothDelta), ILMatch.IsLoad(6), ILMatch.Loads(state.Index), ILMatch.IsLoad(4), ILMatch.IsLoad(3), ILMatch.Is(OpCodes.Add), ILMatch.Float(-1f), ILMatch.Float(1f), ILMatch.Calls(clamp), ILMatch.Is(OpCodes.Stelem_R4), ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Loads(modifiedHeight), ILMatch.IsLoad(6), ILMatch.Loads(state.Index), ILMatch.Is(OpCodes.Ldc_I4_1), ILMatch.Is(OpCodes.Stelem_I1)) || !PrecisionLocals(__originalMethod, state)) { return false; } code[num].operand = smoothed; code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[6] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), Load(6), new CodeInstruction(OpCodes.Ldfld, (object)state.Index), Load(2), Load(4) }); return true; }); } private static IEnumerable<CodeInstruction> RewriteVoxelRaise(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Transpile(instructions, __originalMethod, delegate(List<CodeInstruction> code) { //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Expected O, but got Unknown Members m = Hearth.State; int num = ILMatch.Unique(code, (int i) => CodeInstructionExtensions.Calls(code[i], m.FlattenAt)); int num2 = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], m.ClampRaise)); if (!ILMatch.Sequence(code, num - 3, ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Is(OpCodes.Ldarg_1), Arg4, ILMatch.Calls(m.FlattenAt), ILMatch.Is(OpCodes.Ret)) || !ILMatch.Sequence(code, num2 - 1, ILMatch.Is(OpCodes.Ldarg_2), ILMatch.Calls(m.ClampRaise), (CodeInstruction i) => CodeInstructionExtensions.StoresField(i, m.OpDepth)) || !ILMatch.Locals(__originalMethod, 1, (0, m.VoxelOperationType))) { return false; } code[num].operand = precisionFlatten; code[num2].operand = precisionDelta; code.Insert(num2, new CodeInstruction(OpCodes.Ldarg_1, (object)null)); return RewriteVoxelFootprint(code, ILMatch.Is(OpCodes.Ldc_I4_5), Arg4); }); } private static IEnumerable<CodeInstruction> RewriteVoxelSmooth(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Transpile(instructions, __originalMethod, (List<CodeInstruction> code) => RewriteVoxelFootprint(code, ILMatch.Is(OpCodes.Ldc_I4_4), ILMatch.Is(OpCodes.Ldc_I4_0))); } private static bool RewriteVoxelFootprint(List<CodeInstruction> code, Func<CodeInstruction, bool> kind, Func<CodeInstruction, bool> square) { //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected O, but got Unknown Members m = Hearth.State; int num = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], m.FootprintOf)); if (!ILMatch.Sequence(code, num - 2, kind, square, ILMatch.Calls(m.FootprintOf), ILMatch.Is(OpCodes.Ldarg_0), ILMatch.Is(OpCodes.Ldarg_1), ILMatch.Plain(ILMatch.Float(0.5f)), ILMatch.Float(6f), ILMatch.Calls(clamp), ILMatch.Calls(m.NewOp))) { return false; } code.Insert(num + 3, new CodeInstruction(OpCodes.Call, (object)precisionRadius)); code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Call, (object)squareFootprint) }); return true; } private static IEnumerable<CodeInstruction> RewritePlacement(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return Transpile(instructions, __originalMethod, delegate(List<CodeInstruction> code) { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected O, but got Unknown //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown Members m = Hearth.State; int num = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], m.VoxelOperations)); if (!ILMatch.Sequence(code, num - 2, ILMatch.IsLoad(0), ILMatch.IsLoad(1), ILMatch.Calls(m.VoxelOperations), ILMatch.IsLoad(1), ILMatch.Is(OpCodes.Ldc_I4_0), (CodeInstruction i) => CodeInstructionExtensions.StoresField(i, levelSetting)) || !ILMatch.Locals(__originalMethod, 3, (0, typeof(Vector3)), (1, typeof(Settings)), (2, m.DigProfile))) { return false; } code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Dup, (object)null), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)preparePlacement) }); return true; }); } private static bool PrecisionLocals(MethodBase method, Members m) { return ILMatch.Locals(method, 7, (0, typeof(int)), (1, typeof(float)), (2, typeof(float)), (3, typeof(float)), (4, typeof(float)), (5, m.IndexEnumerator), (6, m.IndexType)); } private static bool Arg4(CodeInstruction instruction) { if (instruction.opcode == OpCodes.Ldarg_S) { if (!(instruction.operand is ParameterInfo parameterInfo)) { return object.Equals(instruction.operand, (byte)4); } return parameterInfo.Position == 4; } return false; } private static CodeInstruction Load(int slot) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new CodeInstruction(OpCodes.Ldloc_S, (object)(byte)slot); } private static MethodInfo Injected(string name) { return AccessTools.DeclaredMethod(typeof(PrecisionTerrainPatch), name, (Type[])null, (Type[])null); } private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions, MethodBase method, Func<List<CodeInstruction>, bool> edit) { return Hearth.Transpile(method, instructions, "precision tool IL changed on " + method.Name, edit); } private static float Raised(float value, float minimum, float maximum, TerrainComp comp, Vector3 target, float step, int vertex, float height) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp(value, minimum, maximum); if (Ready) { HearthTerrainPatch.PrecisionRaise(comp, target, step, vertex, ((Component)comp).transform.position.y + height + num - value); } return num; } private static void Skipped(TerrainComp comp, Vector3 target, float step, int vertex, float height, float requested) { //IL_000e: 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) if (Ready && requested < height) { HearthTerrainPatch.PrecisionRaise(comp, target, step, vertex, ((Component)comp).transform.position.y + height); } } private static float Smoothed(float value, float minimum, float maximum, TerrainComp comp, Vector3 target, int vertex, float height, float previous) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp(value, minimum, maximum); if (Ready) { HearthTerrainPatch.PrecisionSmooth(comp, target, vertex, ((Component)comp).transform.position.y + height + num - previous); } return num; } private static bool SquareFootprint(bool square, float radius) { if (!square) { if (Ready) { return float.IsNegativeInfinity(radius); } return false; } return true; } private static float PrecisionRadius(float radius) { if (!Ready || !float.IsNegativeInfinity(radius)) { return radius; } return 1f; } private static bool PrecisionFlatten(Vector3 point, float radius, bool square) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) Members state = Hearth.State; if (Ready && float.IsNegativeInfinity(radius)) { return false; } return state.Flatten(point, radius, square); } private static float PrecisionDelta(float delta, float radius) { Members state = Hearth.State; if (Ready && float.IsNegativeInfinity(radius) && delta > 0f && delta < 0.1f) { return delta; } return state.ClampDelta(delta); } private static void PreparePlacement(Settings settings, TerrainOp operation) { Members state = Hearth.State; if (Ready && Object.op_Implicit((Object)(object)((Component)operation).GetComponentInChildren(state.OverlayType))) { if (settings.m_smooth) { settings.m_smoothRadius = float.NegativeInfinity; } if (settings.m_raise && settings.m_raiseDelta >= 0f) { settings.m_raiseRadius = float.NegativeInfinity; settings.m_raiseDelta = state.Spinner(); } } } private static void Begin(out bool __state) { __state = Ready; if (__state) { HearthTerrainPatch.Begin(); } } private static Exception? End(Exception? __exception, bool __state) { if (!__state) { return __exception; } return HearthTerrainPatch.End(__exception); } } internal static class ChestCraftPatch { internal sealed class Members { internal required CraftyAccess Crafty { get; init; } internal required FieldRef<int> QueryFrame { get; init; } internal required FieldRef<float> QueryTime { get; init; } internal required FieldRef<int> BankFrame { get; init; } internal required Action InvalidateCounts { get; init; } internal required FieldRef<InventoryGui, float> CraftTimer { get; init; } } private sealed class CraftState { internal readonly Action? EndScope = CompatEvents.EnterScope("craft"); internal readonly bool Consuming = consuming; internal Action<Exception?>? EndCraft; internal bool Ran; } internal sealed class Request { internal readonly Container Chest; internal long Target; internal long Nonce; internal int Attempts; internal uint Revision; internal string? Hash; internal bool Granted; internal Request(Container chest) { Chest = chest; } } internal sealed class Pending { internal readonly InventoryGui Gui; internal readonly Player Player; internal readonly CraftRequest Craft; internal readonly List<Request> Requests; internal readonly List<Container> Owned; internal readonly float Started; internal readonly float Timer; internal Pending(InventoryGui gui, Player player, CraftRequest craft, IEnumerable<Container> remote, IEnumerable<Container> owned) { Gui = gui; Player = player; Craft = craft; Requests = remote.Select((Container chest) => new Request(chest)).ToList(); Owned = owned.ToList(); Started = Time.unscaledTime; Timer = Group.State.CraftTimer.Invoke(gui); } } private enum Handoff { Ready, Waiting, Cancelled } internal static readonly PatchGroup<Members> Group = new PatchGroup<Members>("ChestCraft", "original behavior retained", delegate { Stop("rolled-back"); }, ChestRegistry.Group); private const float Timeout = 8f; private const float ReservationTime = 10f; private const int MaxAttempts = 3; private static long sequence; internal static Pending? pending; private static bool consuming; private static readonly Dictionary<Container, float> reserved = new Dictionary<Container, float>(ReferenceComparer<Container>.Instance); internal static void Install(Assembly? assembly) { //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Expected O, but got Unknown if (!Group.Installed && !Group.Absent(assembly, "AzuCraftyBoxes") && !Group.OnServer()) { Guard.Build(assembly, "381883FE4625D1DD119BB425A2F3C7522457FBC08AE1DB60159F8256DE940D6E"); CraftRequest.Resolve(); CraftyAccess craftyAccess = CraftyAccess.Resolve(assembly); Group.State = new Members { Crafty = craftyAccess, QueryFrame = AccessTools.StaticFieldRefAccess<int>(Guard.Field(craftyAccess.QueryGet.DeclaringType, "FrameId", typeof(int), true)), QueryTime = AccessTools.StaticFieldRefAccess<float>(Guard.Field(craftyAccess.Boxes, "_lastQueryTime", typeof(float), true)), BankFrame = AccessTools.StaticFieldRefAccess<int>(Guard.Field(Guard.Type(assembly, "AzuCraftyBoxes.Util.Functions.UiItemBank"), "_frameId", typeof(int), true)), InvalidateCounts = AccessTools.MethodDelegate<Action>(Guard.Method(craftyAccess.Boxes, "InvalidateCounts", typeof(void)), (object)null, true), CraftTimer = AccessTools.FieldRefAccess<InventoryGui, float>(Guard.Field(typeof(InventoryGui), "m_craftTimer", typeof(float), false)) }; Group.Postfix(craftyAccess.QueryGet, new HarmonyMethod(AccessTools.Method(typeof(ChestCraftPatch), "OwnedSources", (Type[])null, (Type[])null).MakeGenericMethod(craftyAccess.Container))); HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(ChestCraftPatch), "BeforeCraft", (Type[])null, (Type[])null)) { priority = 900 }; val.before = new string[3] { QualityPatch.Group.Owner, "MidnightsFX.ImpactfulSkills", "Azumatt.AzuAntiArthriticCrafting" }; MethodInfo target = Guard.Method(typeof(InventoryGui), "DoCrafting", typeof(void), typeof(Player)); Group.Prefix(target, val); Group.Finalizer(target, new Func<Exception, CraftState, Exception>(EndCraft)); MethodInfo target2 = Guard.Method(typeof(InventoryGui), "UpdateCraftingPanel", typeof(void), typeof(bool)); Group.Prefix(target2, new <>A{00000002}<bool>(BeginPanel), 800); Group.Finalizer(target2, new Func<Exception, bool, Exception>(EndPanel)); Group.Postfix(Guard.Method(typeof(InventoryGui), "OnCraftPressed", typeof(void)), new Action<InventoryGui>(Pressed), 400); MethodInfo target3 = Guard.Method(typeof(InventoryGui), "UpdateRecipe", typeof(void), typeof(Player), typeof(float)); Group.Prefix(target3, new Func<InventoryGui, bool>(Update), 900); Group.Postfix(target3, new Action<InventoryGui>(KeepTimer), 900); string[] array = new string[2] { "Hide", "OnCraftCancelPressed" }; foreach (string name in array) { Group.Prefix(Guard.Method(typeof(InventoryGui), name, typeof(void)), new Action(Cancel), 400); } } } internal static void Verify() { Group.Confirm("chest crafting waits for an owner-approved handoff and inventory refresh."); } internal static void InvalidateQuery() { if (Group.Active(out Members members)) { members.QueryFrame.Invoke() = -1; members.QueryTime.Invoke() = float.NegativeInfinity; members.BankFrame.Invoke() = -1; members.InvalidateCounts(); } } private static void OwnedSources<T>(ref List<T> __result) { if (consuming && Group.Active(out Members m)) { __result = __result.Where(delegate(T adapter) { Container val = ((adapter == null) ? null : new CraftyContainer(m.Crafty, adapter).Vanilla); return val == null || ChestRegistry.Owned(val); }).ToList(); } } private static void BeginPanel(out bool __state) { __state = consuming; consuming = false; } private static Exception? EndPanel(Exception? __exception, bool __state) { consuming = __state; return __exception; } private static List<CraftyContainer> Sources(Player player) { if (!Group.Active(out Members members)) { return new List<CraftyContainer>(); } return members.Crafty.Containers(player).ToList(); } private static bool CanPull(CraftyContainer adapter, Requirement requirement) { string prefab = adapter.Prefab; if (prefab != null) { return Group.State.Crafty.CanPull(prefab, ((Object)requirement.m_resItem).name, ""); } return false; } private static List<Container> Needed(Player player, CraftRequest request) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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) float num = CraftyAccess.Range * CraftyAccess.Range; Container[] containers = ChestRegistry.Containers; foreach (Container chest in containers) { ZDO val = ChestRegistry.LiveZdo(chest); if (val != null) { Vector3 val2 = val.GetPosition() - ((Component)player).transform.position; if (((Vector3)(ref val2)).sqrMagnitude <= num) { ChestRegistry.Refresh(chest); } } } InvalidateQuery(); List<Container> list = QualityPatch.CraftContainers(player, request); if (list != null) { return list; } List<Requirement> requirements = request.Requirements(); List<CraftyContainer> adapters = Sources(player); if (request.Recipe.m_requireOnlyOneIngredient) { return SingleSource(player, requirements, adapters, request); } return MultiSource(player, requirements, adapters, request); } private static List<Container> MultiSource(Player player, List<Requirement> requirements, List<CraftyContainer> adapters, CraftRequest request) { List<Container> result = new List<Container>(); foreach (Requirement requirement in requirements) { PullRequirement(player, requirement, adapters, result, request.Amount(requirement)); } return result; } private static void PullRequirement(Player player, Requirement requirement, List<CraftyContainer> adapters, List<Container> result, int amount) { string name = requirement.m_resItem.m_itemData.m_shared.m_name; int num = amount - ((Humanoid)player).GetInventory().CountItems(name, -1, true); HashSet<Container> hashSet = new HashSet<Container>(result, ReferenceComparer<Container>.Instance); foreach (CraftyContainer adapter in adapters) { if (num <= 0) { break; } if (!CanPull(adapter, requirement)) { continue; } int num2 = CraftyAccess.Pullable(adapter.Count(name)); if (num2 > 0) { Container vanilla = adapter.Vanilla; if ((Object)(object)vanilla != (Object)null && hashSet.Add(vanilla)) { result.Add(vanilla); } num -= num2; } } } private static List<Container> SingleSource(Player player, List<Requirement> requirements, List<CraftyContainer> adapters, CraftRequest request) { foreach (Requirement requirement in requirements) { if (PlayerCovers(player, requirement, request.Amount(requirement))) { return new Lis