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 Crafting v1.0.1
meadworks.crafting.dll
Decompiled 29 minutes 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using HarmonyLib; using MeadWorks.Core; using MeadWorks.UI; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("assembly_guiutils")] [assembly: IgnoresAccessChecksTo("assembly_utils")] [assembly: IgnoresAccessChecksTo("assembly_valheim")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("expDARE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("meadworks.crafting")] [assembly: AssemblyTitle("meadworks.crafting")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 MeadWorks.Crafting { public static class AutoDoors { private sealed class DoorGroup { public Door First; public Door Second; public float OpeningUntil; public bool SeenOpen; public bool Closing; public float ClosingUntil; } private sealed class Runner : MonoBehaviour { private float _next; private void Update() { if (Paused) { _next = Time.unscaledTime + 0.2f; } else if (!(Time.unscaledTime < _next)) { _next = Time.unscaledTime + 0.2f; Scan(); } } } private static Setting<bool> _on; private static Setting<float> _range; private static MethodInfo _canInteract; private static readonly List<DoorGroup> Opened = new List<DoorGroup>(); private static readonly Dictionary<Door, Door> ReleasedPartners = new Dictionary<Door, Door>(); private static readonly HashSet<Door> Released = new HashSet<Door>(); private static readonly List<Door> Stale = new List<Door>(); private static readonly List<Door> Doors = new List<Door>(); private static readonly List<Piece> Pieces = new List<Piece>(); private static readonly List<Character> InDoorway = new List<Character>(); internal static bool Paused; public static bool On { get { if (_on != null) { return _on.Value; } return false; } } internal static Setting<bool> Switch => _on; public static float Range { get { if (_range != null) { return AutoDoorsRules.ClampRange(_range.Value); } return 1.5f; } } internal static int Tracked { get { int num = 0; foreach (DoorGroup item in Opened) { num += (((Object)(object)item.Second == (Object)null) ? 1 : 2); } return num; } } public static void Init(SettingsPage page) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown _on = page.Toggle("auto_doors", "Auto doors", true, (SettingPolicy)0, false); _range = page.Slider("auto_doors_range", "Auto door range", 1.5f, 0.5f, 8f, 0.5f, (SettingPolicy)0, true); _canInteract = AccessTools.Method(typeof(Door), "CanInteract", (Type[])null, (Type[])null); GameObject val = new GameObject("MeadWorks.AutoDoors"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<Runner>(); LedgerTrack.Object<GameObject>(val, "crafting auto doors runner"); Ledger.Add("crafting auto doors state", (Action)delegate { Opened.Clear(); Released.Clear(); ReleasedPartners.Clear(); Paused = false; _on = null; _range = null; }); } internal static string Describe() { return "doors on=" + On + " range=" + Range.ToString("0.#") + " tracked=" + Tracked; } internal static bool IsTracked(Door door) { if ((Object)(object)door == (Object)null) { return false; } foreach (DoorGroup item in Opened) { if ((Object)(object)item.First == (Object)(object)door || (Object)(object)item.Second == (Object)(object)door) { return true; } } return false; } internal static void ForgetAll() { Opened.Clear(); Released.Clear(); ReleasedPartners.Clear(); } internal static bool IsOpen(Door door) { if ((Object)(object)door == (Object)null || (Object)(object)door.m_nview == (Object)null || !door.m_nview.IsValid()) { return false; } return door.m_nview.GetZDO().GetInt(ZDOVars.s_state, 0) != 0; } private static bool Accessible(Door door) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)door == (Object)null || (Object)(object)door.m_nview == (Object)null || !door.m_nview.IsValid()) { return false; } if (!door.m_checkGuardStone) { return true; } return PrivateArea.CheckAccess(((Component)door).transform.position, 0f, false, false); } private static bool Interactable(Door door) { if ((Object)(object)door != (Object)null) { if (!(_canInteract == null)) { return (bool)_canInteract.Invoke(door, null); } return true; } return false; } private static bool SomeoneInDoorway(Door door) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) InDoorway.Clear(); Vector3 val = Center(door); Character.GetCharactersInRange(val, 3.5f, InDoorway); for (int i = 0; i < InDoorway.Count; i++) { Character val2 = InDoorway[i]; if (!((Object)(object)val2 == (Object)null) && !val2.IsDead()) { Vector3 val3 = ((Component)val2).transform.position - val; if (AutoDoorsRules.InDoorway(val3.x, val3.y, val3.z)) { return true; } } } return false; } private static float Distance(Door door, Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Center(door) - pos; return ((Vector3)(ref val)).magnitude; } internal static void Scan() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || !On) { Opened.Clear(); Released.Clear(); ReleasedPartners.Clear(); return; } Vector3 position = ((Component)localPlayer).transform.position; float range = Range; for (int num = Opened.Count - 1; num >= 0; num--) { DoorGroup doorGroup = Opened[num]; if ((Object)(object)doorGroup.First == (Object)null) { doorGroup.First = doorGroup.Second; doorGroup.Second = null; } Door first = doorGroup.First; Door second = doorGroup.Second; if ((Object)(object)first == (Object)null) { Opened.RemoveAt(num); } else { bool flag = IsOpen(first); bool flag2 = (Object)(object)second == (Object)null || IsOpen(second); if (!doorGroup.Closing && (!flag || !flag2)) { if (!(Time.unscaledTime < doorGroup.OpeningUntil)) { if (AutoDoorsRules.ReleaseAfterShut(doorGroup.SeenOpen)) { Release(doorGroup); } Opened.RemoveAt(num); } } else { if (flag && flag2) { doorGroup.OpeningUntil = 0f; doorGroup.SeenOpen = true; } if (doorGroup.Closing) { if (!flag && ((Object)(object)second == (Object)null || !flag2)) { Opened.RemoveAt(num); } else if (Time.unscaledTime >= doorGroup.ClosingUntil) { Release(doorGroup); Opened.RemoveAt(num); } } else if (AutoDoorsRules.PairCanClose(Distance(first, position), ((Object)(object)second == (Object)null) ? Distance(first, position) : Distance(second, position), range, SomeoneInDoorway(first), (Object)(object)second != (Object)null && SomeoneInDoorway(second)) && (!flag || (Accessible(first) && Interactable(first))) && (!((Object)(object)second != (Object)null && flag2) || (Accessible(second) && Interactable(second)))) { doorGroup.Closing = true; doorGroup.ClosingUntil = Time.unscaledTime + 2f; if (flag) { first.Interact((Humanoid)(object)localPlayer, false, false); } if ((Object)(object)second != (Object)null && flag2) { second.Interact((Humanoid)(object)localPlayer, false, false); } } } } } Stale.Clear(); foreach (Door item in Released) { if ((Object)(object)item == (Object)null || AutoDoorsRules.BeyondCloseRange(Distance(item, position), range)) { Stale.Add(item); } } foreach (Door item2 in Stale) { if (!ReleasedPartners.TryGetValue(item2, out var value) || !((Object)(object)value != (Object)null) || AutoDoorsRules.BeyondCloseRange(Distance(value, position), range)) { Released.Remove(item2); ReleasedPartners.Remove(item2); } } Pieces.Clear(); Doors.Clear(); Piece.GetAllPiecesInRadius(position, AutoDoorsRules.ScanRadius(range) + 4f, Pieces); foreach (Piece piece in Pieces) { if (!((Object)(object)piece == (Object)null)) { Door component = ((Component)piece).GetComponent<Door>(); if ((Object)(object)component != (Object)null && AutoDoorsRules.Manages(On, piece.IsPlacedByPlayer(), (Object)(object)component.m_keyItem != (Object)null)) { Doors.Add(component); } } } foreach (Door door in Doors) { if (IsOpen(door) || IsTracked(door) || Released.Contains(door)) { continue; } Door val = FindPartner(door); if ((!((Object)(object)val != (Object)null) || (!Released.Contains(val) && !IsTracked(val) && !IsOpen(val))) && (AutoDoorsRules.InOpenRange(Distance(door, position), range) || (!((Object)(object)val == (Object)null) && AutoDoorsRules.InOpenRange(Distance(val, position), range))) && Accessible(door) && Interactable(door) && (!((Object)(object)val != (Object)null) || (Accessible(val) && Interactable(val)))) { door.Interact((Humanoid)(object)localPlayer, false, false); if ((Object)(object)val != (Object)null) { val.Interact((Humanoid)(object)localPlayer, false, false); } Opened.Add(new DoorGroup { First = door, Second = val, OpeningUntil = Time.unscaledTime + 1f }); } } Pieces.Clear(); Doors.Clear(); Stale.Clear(); } private static void Release(DoorGroup group) { Released.Add(group.First); if (!((Object)(object)group.Second == (Object)null)) { Released.Add(group.Second); ReleasedPartners[group.First] = group.Second; ReleasedPartners[group.Second] = group.First; } } private static Vector3 Center(Door door) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) AutoDoorsRules.TryPairGeometry(Utils.GetPrefabName(((Component)door).gameObject), out var offset, out var _); return ((Component)door).transform.TransformPoint(new Vector3(offset, 0f, 0f)); } private static bool Pairable(Door door) { float offset; float span; return AutoDoorsRules.TryPairGeometry(Utils.GetPrefabName(((Component)door).gameObject), out offset, out span); } private static Door FindPartner(Door door) { Door val = FindUniquePartner(door); if (!((Object)(object)val != (Object)null) || !((Object)(object)FindUniquePartner(val) == (Object)(object)door)) { return null; } return val; } private static Door FindUniquePartner(Door door) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) if (!Pairable(door)) { return null; } Vector3 val = Center(door); AutoDoorsRules.TryPairGeometry(Utils.GetPrefabName(((Component)door).gameObject), out var _, out var span); Door val2 = null; foreach (Door door2 in Doors) { if ((Object)(object)door2 == (Object)(object)door || Utils.GetPrefabName(((Component)door2).gameObject) != Utils.GetPrefabName(((Component)door).gameObject)) { continue; } Vector3 val3 = Center(door2); if (AutoDoorsRules.FormsPair(val.x, val.y, val.z, ((Component)door).transform.eulerAngles.y, val3.x, val3.y, val3.z, ((Component)door2).transform.eulerAngles.y, span)) { if ((Object)(object)val2 != (Object)null) { return null; } val2 = door2; } } return val2; } } public static class AutoDoorsRules { public const float DefaultRange = 1.5f; public const float MinRange = 0.5f; public const float MaxRange = 8f; public const float RangeStep = 0.5f; public const float CloseMargin = 0.5f; public const float DoorwayRadius = 1f; public const float DoorwayHeight = 2.5f; public const float ScanInterval = 0.2f; public const float LookupMargin = 0.25f; public const float PairSpan = 2f; public const float PartnerLookupReach = 4f; public const float PairTolerance = 0.15f; public const float OpenWait = 1f; public static bool InDoorway(float x, float y, float z) { if (x * x + z * z <= 1f) { return Math.Abs(y) <= 2.5f; } return false; } public static bool TryPairGeometry(string prefab, out float offset, out float span) { offset = 0f; span = 2f; switch (prefab) { case "wood_door": case "wood_gate": case "darkwood_gate": case "iron_grate": return true; case "flametal_gate": offset = 0.2f; span = 1.5f; return true; case "piece_dvergr_wood_door": case "ashwood_door": offset = -1f; return true; default: return false; } } public static bool FormsPair(float ax, float ay, float az, float yawA, float bx, float by, float bz, float yawB, float span = 2f) { double num = (double)yawA * Math.PI / 180.0; double num2 = (double)yawB * Math.PI / 180.0; float num3 = bx - ax; float num4 = bz - az; if (Math.Abs(ay - by) <= 0.15f && Math.Cos(num - num2) < -0.996 && Math.Abs((double)num3 * Math.Sin(num) + (double)num4 * Math.Cos(num)) <= 0.15000000596046448) { return Math.Abs((double)num3 * Math.Cos(num) - (double)num4 * Math.Sin(num) + (double)span) <= 0.15000000596046448; } return false; } public static bool PairCanClose(float distanceA, float distanceB, float range, bool occupiedA, bool occupiedB) { if (BeyondCloseRange(distanceA, range) && BeyondCloseRange(distanceB, range) && !occupiedA) { return !occupiedB; } return false; } public static bool KeepTrackingAfterClose(bool stillOpen) { return stillOpen; } public static bool ReleaseAfterShut(bool seenOpen) { return seenOpen; } public static float ClampRange(float range) { return Math.Max(0.5f, Math.Min(8f, range)); } public static float OpenRange(float range) { return ClampRange(range); } public static float CloseRange(float range) { return ClampRange(range) + 0.5f; } public static float ScanRadius(float range) { return OpenRange(range) + 0.25f; } public static bool Manages(bool on, bool placedByPlayer, bool keyed) { if (on && placedByPlayer) { return !keyed; } return false; } public static bool InOpenRange(float distance, float range) { return distance <= OpenRange(range); } public static bool BeyondCloseRange(float distance, float range) { return distance > CloseRange(range); } } public static class Automation { private sealed class SettingSwitch : MonoBehaviour { internal Setting<bool> Setting; internal KitToggle Toggle; private void Update() { if (Setting != null && !((Object)(object)Toggle == (Object)null)) { Toggle.SetValueWithoutNotify(Setting.Value); bool editable = ((Setting)Setting).Editable; if (Toggle.Interactable != editable) { Toggle.Interactable = editable; } } } } private sealed class StationState { internal ZDOID Id; internal Vector3 Position; internal Component Station; internal string Name; internal string Contents; internal string Time; internal int Count; internal float Progress; internal bool HasFeed; internal bool Hive; internal string Group { get { if (!((Object)(object)Station == (Object)null)) { return AutomationRules.StationGroup(Count); } return "Unloaded"; } } } private sealed class Candidate { internal ZDOID Id; internal Vector3 Position; internal Component Station; internal StationCatalogue.Entry Entry; internal float Distance; } private sealed class RowView { internal KitRow Row; internal KitButton Collect; internal KitButton Actions; internal KitMeter Meter; internal string Sub; } private sealed class StationRows : MonoBehaviour { internal KitToggle Master; internal KitList List; private float _next; private readonly Dictionary<ZDOID, RowView> _rows = new Dictionary<ZDOID, RowView>(); private readonly Dictionary<ZDOID, StationState> _states = new Dictionary<ZDOID, StationState>(); private readonly Dictionary<string, KitSection> _headers = new Dictionary<string, KitSection>(); private readonly Dictionary<string, int> _counts = new Dictionary<string, int>(); private readonly List<ZDOID> _added = new List<ZDOID>(); private readonly List<ZDOID> _removed = new List<ZDOID>(); private readonly List<Transform> _order = new List<Transform>(); private void Update() { if (Time.unscaledTime >= _next) { _next = Time.unscaledTime + 1f; Refresh(); } } private Component Current(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!_states.TryGetValue(id, out var value)) { return null; } return value.Station; } private RowView Create(StationState s) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZDOID id = s.Id; RowView rowView = new RowView { Row = List.AddRow(s.Name) }; rowView.Row.Hairline = true; if (s.Hive) { rowView.Collect = Kit.Button((Transform)(object)rowView.Row.Slot, Lang.T("crafting.collect", "Collect"), (Action)delegate { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Component val = Current(id); if (CanUseStation(val)) { Beehive val2 = (Beehive)(object)((val is Beehive) ? val : null); if (val2 != null) { val2.Interact((Humanoid)(object)Player.m_localPlayer, false, false); } } }, false); rowView.Collect.Compact = true; } if (s.HasFeed) { rowView.Actions = Kit.Button((Transform)(object)rowView.Row.Slot, Lang.T("crafting.station_actions", "Actions"), (Action)delegate { //IL_0007: Unknown result type (might be due to invalid IL or missing references) StationActions.Open(Current(id)); }, false); rowView.Actions.Compact = true; rowView.Meter = Kit.Meter((Transform)(object)rowView.Row.Slot, (string)null); ((Component)rowView.Meter).GetComponent<LayoutElement>().preferredWidth = 80f; } return rowView; } internal void Refresh() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_03b2: Unknown result type (might be due to invalid IL or missing references) //IL_03b5: Unknown result type (might be due to invalid IL or missing references) if (_master == null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Master.SetValueWithoutNotify(_master.Value); Master.Interactable = ((Setting)_master).Editable; Vector3 position = ((Component)Player.m_localPlayer).transform.position; List<StationState> list = Stations(position); string[] groups; if (_headers.Count == 0) { groups = Groups; foreach (string text in groups) { _headers[text] = List.AddGroup(AutomationRules.GroupText(text), 0); _counts[text] = 0; Readable(_headers[text]); } } _added.Clear(); _removed.Clear(); AutomationRules.Diff(_rows.Keys.ToList(), list.Select((StationState s) => s.Id).ToList(), _added, _removed); foreach (ZDOID item in _removed) { KitRow row = _rows[item].Row; _rows.Remove(item); if (!((Object)(object)row == (Object)null)) { ((Component)row).gameObject.SetActive(false); Object.Destroy((Object)(object)((Component)row).gameObject); } } _states.Clear(); foreach (StationState item2 in list) { _states[item2.Id] = item2; } foreach (ZDOID item3 in _added) { _rows[item3] = Create(_states[item3]); } _order.Clear(); groups = Groups; foreach (string text2 in groups) { _order.Add(((Component)_headers[text2]).transform.parent); int num = 0; foreach (StationState item4 in list) { if (item4.Group == text2) { _order.Add(((Component)_rows[item4.Id].Row).transform); num++; } } if (_counts[text2] != num) { _counts[text2] = num; _headers[text2].SetMeta(RowMath.Count(num)); Readable(_headers[text2]); } } for (int num2 = 0; num2 < _order.Count; num2++) { if (_order[num2].GetSiblingIndex() != num2) { _order[num2].SetSiblingIndex(num2); } } foreach (StationState item5 in list) { RowView rowView = _rows[item5.Id]; string text3 = AutomationRules.StationContents(item5.Contents, Vector3.Distance(position, item5.Position).ToString("0") + " m"); if (text3 != rowView.Sub) { rowView.Sub = text3; rowView.Row.SetSub(text3, false); } if (rowView.Row.Faint == _master.Value) { rowView.Row.Faint = !_master.Value; } bool flag = CanUseStation(item5.Station); if ((Object)(object)rowView.Meter != (Object)null) { if (((Component)rowView.Meter).gameObject.activeSelf != ((Object)(object)item5.Station != (Object)null)) { ((Component)rowView.Meter).gameObject.SetActive((Object)(object)item5.Station != (Object)null); } if ((Object)(object)item5.Station != (Object)null) { rowView.Meter.Set(item5.Progress, item5.Time); } } if ((Object)(object)rowView.Actions != (Object)null) { rowView.Actions.Interactable = StationActions.Ready(item5.Station); } if ((Object)(object)rowView.Collect != (Object)null) { rowView.Collect.Interactable = item5.Count > 0 && flag; } } } } private static Setting<bool> _chests; private static Setting<float> _chestRange; private static Setting<float> _stationRange; private static Setting<bool> _output; private static Setting<bool> _master; private static readonly string[] Groups = new string[4] { "Has contents", "Empty", "Loaded", "Unloaded" }; public static bool StoreOutput { get { if (_master != null && _master.Value && _output != null) { return _output.Value; } return false; } } public static bool Cook { get { if (_master != null) { return _master.Value; } return false; } } public static bool UseChests { get { if (_chests != null) { return _chests.Value; } return false; } } public static float ChestRange => SharedChestRange.Clamp(SharedChestRange.InventoryInstalled ? (SharedChestRange.Value ?? 30f) : ((_chestRange == null) ? 30f : _chestRange.Value)); public static float StationRange => SearchRangeRules.StationRange((_stationRange == null) ? 40f : _stationRange.Value); public static bool FeedSmelters { get { if (_master != null) { return _master.Value; } return false; } } public static float FeedRange => StationRange; private static void RangeChanged() { ChestSource.Invalidate(); } public static void Init(SettingsPage page) { AutomationReserve.Init(page); ChestSource.Init(); StationCatalogue.Init(); SmelterFeed.Init(); CookingFeed.Init(); StationChestInput.Init(); StationOutput.Init(); AutoRepair.Init(); StabilityLabel.Init(); NearbyRepair.Init(page); _master = page.Toggle("automation_master", "Feed from chests", true, (SettingPolicy)1, false); _chests = page.Toggle("automation_chests", "Use nearby chests", true, (SettingPolicy)1, false); if (!SharedChestRange.InventoryInstalled) { _chestRange = page.Slider("automation_chest_range", "Chest range", 30f, 5f, 64f, 1f, (SettingPolicy)1, true); } _stationRange = page.Slider("automation_station_range", "Station range", 40f, 10f, 100f, 1f, (SettingPolicy)1, true); ((Setting)_stationRange).Changed += StationExtensions.Refresh; SharedChestRange.Changed += RangeChanged; if (_chestRange != null) { ((Setting)_chestRange).Changed += RangeChanged; } StationExtensions.Init(); _output = page.Toggle("automation_output", "Store station output in chests", true, (SettingPolicy)1, false); Ledger.Add("crafting automation settings", (Action)delegate { ((Setting)_stationRange).Changed -= StationExtensions.Refresh; SharedChestRange.Changed -= RangeChanged; if (_chestRange != null) { ((Setting)_chestRange).Changed -= RangeChanged; } _chests = null; _chestRange = null; _stationRange = null; _output = null; _master = null; }); InitSurface(); page.Button("automation_panel", "Automation", "Open", (Action)delegate { KitHostStrip.OpenWindow("automation", 620f); }, false); } private static void InitSurface() { KitHostStrip.Register("automation", "Automation", "cog", (Action<RectTransform>)BuildSurface, (Action)null, (Func<bool>)null, 1000, (Func<bool>)null, (Func<int>)null, (Func<bool>)null, 620f, (Func<bool>)null); } internal static bool StationEnabled(Component station) { ZNetView val = (((Object)(object)station == (Object)null) ? null : station.GetComponent<ZNetView>()); if ((Object)(object)val != (Object)null && val.IsValid()) { return val.GetZDO() != null; } return false; } internal static bool Vouches(ZDO station) { GameObject val = ((station == null || (Object)(object)ZNetScene.instance == (Object)null) ? null : ZNetScene.instance.GetPrefab(station.GetPrefab())); if ((Object)(object)val == (Object)null) { return false; } return StationAccessRules.Vouches((Object)(object)val.GetComponent<Smelter>() != (Object)null, (Object)(object)val.GetComponent<CookingStation>() != (Object)null || (Object)(object)val.GetComponent<Fermenter>() != (Object)null, (Object)(object)val.GetComponent<Beehive>() != (Object)null || (Object)(object)val.GetComponent<SapCollector>() != (Object)null, FeedSmelters, Cook, StoreOutput); } internal static bool VouchesSmelterInput(ZDO station) { if (!FeedSmelters || !UseChests || AutomationReserve.Leave > 0 || station == null || (Object)(object)ZNetScene.instance == (Object)null) { return false; } GameObject prefab = ZNetScene.instance.GetPrefab(station.GetPrefab()); return (Object)(object)((prefab != null) ? prefab.GetComponent<Smelter>() : null) != (Object)null; } internal static bool CanUseStation(Component station) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; ZNetView val = (((Object)(object)station == (Object)null) ? null : station.GetComponent<ZNetView>()); if ((Object)(object)station == (Object)null || (Object)(object)localPlayer == (Object)null) { return false; } return AutomationRules.CanUseStation((Object)(object)val != (Object)null && val.IsValid() && val.GetZDO() != null, PrivateArea.CheckAccess(station.transform.position, 0f, false, false), Vector3.Distance(((Component)localPlayer).transform.position, station.transform.position), FeedRange); } private static void BuildSurface(RectTransform body) { if (_master != null) { KitToggle val = Kit.Toggle((Transform)(object)body, Lang.T("crafting.feed_from_chests", "Feed from chests"), _master.Value, (Action<bool>)delegate(bool value) { SettingsWindow.Write((Setting)(object)_master, value ? "true" : "false"); }); val.Interactable = ((Setting)_master).Editable; KitList val2 = Kit.List((Transform)(object)body, 0f); val2.Bare = true; ((Component)val2).GetComponent<LayoutElement>().flexibleHeight = 1f; Readable(Kit.Section((Transform)(object)body, Lang.T("crafting.everywhere", "Everywhere"), (string)null, true)); AddSwitch((Transform)(object)body, Lang.T("crafting.doors_close_behind_you", "Doors close behind you"), AutoDoors.Switch); AddSwitch((Transform)(object)body, Lang.T("crafting.fires_stay_lit", "Fires stay lit"), Everlit.Switch); StationRows stationRows = ((Component)val2).gameObject.AddComponent<StationRows>(); stationRows.Master = val; stationRows.List = val2; stationRows.Refresh(); } } private static void Readable(KitSection section) { if ((Object)(object)section == (Object)null) { return; } string meta = ""; TMP_Text[] componentsInChildren = ((Component)section).GetComponentsInChildren<TMP_Text>(true); foreach (TMP_Text val in componentsInChildren) { if (((Object)val).name == "Label") { Theme.StyleText(val, (TextRole)3); } else if (((Object)val).name == "Meta") { Theme.StyleText(val, (TextRole)3); meta = val.text; } } section.SetMeta(meta); } private static void AddSwitch(Transform body, string label, Setting<bool> setting) { if (setting != null) { KitToggle val = Kit.Toggle(body, label, setting.Value, (Action<bool>)delegate(bool value) { SettingsWindow.Write((Setting)(object)setting, value ? "true" : "false"); }); val.Interactable = ((Setting)setting).Editable; SettingSwitch settingSwitch = ((Component)val).gameObject.AddComponent<SettingSwitch>(); settingSwitch.Setting = setting; settingSwitch.Toggle = val; } } private static string ItemName(string prefab) { object obj; if (!((Object)(object)ObjectDB.instance == (Object)null)) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefab); obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); } else { obj = null; } return Localize(((ItemDrop)(obj?)).m_itemData?.m_shared?.m_name ?? prefab); } private static string Localize(string text) { if (Localization.instance != null) { return Localization.instance.Localize(text ?? ""); } return text ?? ""; } private static StationState Describe(Component station) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Invalid comparison between Unknown and I4 StationState stationState = new StationState { Id = station.GetComponent<ZNetView>().GetZDO().m_uid, Position = station.transform.position, Station = station, Name = StationName(station), Count = -1, Contents = "Empty", Time = "", Hive = (station is Beehive), HasFeed = (station is Smelter || station is CookingStation || station is Fermenter) }; Smelter val = (Smelter)(object)((station is Smelter) ? station : null); if (val != null) { stationState.Name = Localize(val.m_name); stationState.Count = val.GetQueueSize(); stationState.Contents = AutomationRules.StationContents(ItemName(val.GetQueuedOre()), stationState.Count + "/" + SmelterCapacity.Ore(val), (val.m_maxFuel > 0) ? (Localize(val.m_fuelItem?.m_itemData?.m_shared?.m_name) + " " + val.GetFuel().ToString("0")) : ""); if (stationState.Count > 0) { stationState.Time = AutomationRules.ProgressText(val.m_secPerProduct, val.GetBakeTimer()); stationState.Progress = val.GetBakeTimer() / Math.Max(0.01f, val.m_secPerProduct); } } else { Fermenter val2 = (Fermenter)(object)((station is Fermenter) ? station : null); if (val2 != null) { stationState.Name = Localize(val2.m_name); stationState.Count = ((val2.GetContent() != 0) ? 1 : 0); if (stationState.Count > 0) { stationState.Contents = Localize(val2.GetContentName()); stationState.Time = AutomationRules.ProgressText(val2.m_fermentationDuration, val2.GetFermentationTime()); stationState.Progress = (float)(val2.GetFermentationTime() / (double)Math.Max(0.01f, val2.m_fermentationDuration)); } } else { CookingStation val3 = (CookingStation)(object)((station is CookingStation) ? station : null); if (val3 != null) { stationState.Name = Localize(val3.m_name); stationState.Count = 0; List<string> list = new List<string>(); double num = double.MaxValue; string name = default(string); float num2 = default(float); Status val4 = default(Status); bool flag = default(bool); for (int i = 0; i < val3.m_slots.Length; i++) { val3.GetSlot(i, ref name, ref num2, ref val4, ref flag); if (string.IsNullOrEmpty(name)) { continue; } list.Add(ItemName(name)); stationState.Count++; ItemConversion val5 = ((IEnumerable<ItemConversion>)val3.m_conversion).FirstOrDefault((Func<ItemConversion, bool>)((ItemConversion c) => (Object)(object)c.m_from != (Object)null && ((Object)c.m_from).name == name)); if (val5 != null) { float num3 = (((int)val4 == 0) ? Math.Max(0f, val5.m_cookTime - num2) : 0f); if ((double)num3 < num) { num = num3; stationState.Time = (((int)val4 == 0) ? AutomationRules.ProgressText(val5.m_cookTime, num2) : (((int)val4 == 2) ? Lang.T("crafting.burned", "Burned") : Lang.T("crafting.ready", "Ready"))); stationState.Progress = num2 / Math.Max(0.01f, val5.m_cookTime); } } } if (list.Count > 0) { stationState.Contents = string.Join(", ", list); } } else { Beehive val6 = (Beehive)(object)((station is Beehive) ? station : null); if (val6 != null) { stationState.Name = Localize(val6.m_name); stationState.Count = val6.GetHoneyLevel(); stationState.Contents = Localize(val6.m_honeyItem.m_itemData.m_shared.m_name) + " " + stationState.Count + "/" + val6.m_maxHoney; } else { stationState.Contents = "Fuel " + station.GetComponent<ZNetView>().GetZDO().GetFloat(ZDOVars.s_fuel, 0f) .ToString("0.#"); } } } } return stationState; } private static string StationName(Component s) { Smelter val = (Smelter)(object)((s is Smelter) ? s : null); object text; if (val == null) { Fermenter val2 = (Fermenter)(object)((s is Fermenter) ? s : null); if (val2 == null) { CookingStation val3 = (CookingStation)(object)((s is CookingStation) ? s : null); if (val3 == null) { Beehive val4 = (Beehive)(object)((s is Beehive) ? s : null); if (val4 == null) { Fireplace val5 = (Fireplace)(object)((s is Fireplace) ? s : null); if (val5 == null) { ShieldGenerator val6 = (ShieldGenerator)(object)((s is ShieldGenerator) ? s : null); text = ((val6 != null) ? val6.m_name : ((Object)s).name); } else { text = val5.m_name; } } else { text = val4.m_name; } } else { text = val3.m_name; } } else { text = val2.m_name; } } else { text = val.m_name; } return Localize((string)text); } private static StationState Describe(StationCatalogue.Entry entry) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) ZNetScene instance = ZNetScene.instance; Component val = (((Object)(object)instance == (Object)null) ? null : StationCatalogue.Station(instance.FindInstance(entry.Id))); if ((Object)(object)val != (Object)null) { return Describe(val); } Component val2 = (((Object)(object)instance == (Object)null) ? null : StationCatalogue.Station(instance.GetPrefab(entry.Prefab))); if ((Object)(object)val2 == (Object)null) { return null; } StationState stationState = new StationState(); stationState.Id = entry.Id; stationState.Position = entry.Position; stationState.Name = StationName(val2); Smelter val3 = (Smelter)(object)((val2 is Smelter) ? val2 : null); stationState.Contents = ((val3 != null && val3.m_maxFuel > 0) ? Lang.T("crafting.fuel_amount", "Fuel {0}", new object[1] { entry.Fuel.ToString("0.#") }) : ""); stationState.Time = ""; stationState.HasFeed = val2 is Smelter || val2 is CookingStation || val2 is Fermenter; return stationState; } private static List<StationState> Stations(Vector3 origin) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) Dictionary<ZDOID, Candidate> dictionary = new Dictionary<ZDOID, Candidate>(); StationCatalogue.Entry[] array = StationCatalogue.Read(); foreach (StationCatalogue.Entry entry in array) { dictionary[entry.Id] = new Candidate { Id = entry.Id, Position = entry.Position, Entry = entry }; } foreach (Component item in StationCatalogue.Loaded()) { ZDOID uid = item.GetComponent<ZNetView>().GetZDO().m_uid; dictionary[uid] = new Candidate { Id = uid, Position = item.transform.position, Station = item }; } foreach (Candidate value in dictionary.Values) { value.Distance = Vector3.Distance(origin, value.Position); } List<Candidate> list = (from c in dictionary.Values orderby c.Distance, ((ZDOID)(ref c.Id)).UserID, ((ZDOID)(ref c.Id)).ID select c).ToList(); bool[] array2 = AutomationRules.Shown(list.Select((Candidate c) => c.Station is Fireplace).ToList()); List<StationState> list2 = new List<StationState>(); for (int num = 0; num < list.Count; num++) { if (array2[num]) { StationState stationState = (((Object)(object)list[num].Station != (Object)null) ? Describe(list[num].Station) : Describe(list[num].Entry)); if (stationState != null) { list2.Add(stationState); } } } return list2; } } internal static class AutomationReserve { private static Setting<float> _leave; internal static int Leave { get { if (_leave != null && !float.IsNaN(_leave.Value)) { return (int)Mathf.Clamp(_leave.Value, 0f, 100f); } return 0; } } internal static void Init(SettingsPage page) { _leave = page.Slider("automation_leave", "Leave each item in chests", 0f, 0f, 100f, 1f, (SettingPolicy)1, true); Ledger.Add("crafting automation reserve", (Action)delegate { _leave = null; }); } internal static int Limit(Container chest, ItemData item, int amount) { if ((Object)(object)chest == (Object)null || item?.m_shared == null || chest.GetInventory() == null) { return 0; } List<ItemData> allItems = chest.GetInventory().GetAllItems(); if (!allItems.Contains(item)) { return 0; } long total = allItems.Where((ItemData i) => i?.m_shared?.m_name == item.m_shared.m_name).Sum((Func<ItemData, long>)((ItemData i) => i.m_stack)); return AutomationReserveRules.Take(amount, item.m_stack, total, Leave); } } public static class AutomationReserveRules { public static int Take(int requested, int stack, long total, int reserve) { return (int)Math.Max(0L, Math.Min(Math.Min(Math.Max(0, requested), Math.Max(0, stack)), Math.Max(0L, total - Math.Max(0, reserve)))); } } public static class AutomationRules { public sealed class Chest { public int Id; public float Distance; public int Count; public bool Accessible; public bool Owned; public bool InUse; public bool Moving; public bool UsedForCrafting = true; } public sealed class Withdrawal { public int ChestId; public int Amount; } public const int StationRows = 40; public const int FireRows = 20; public static bool EmptiesCooking(bool cook, bool storeOutput) { return cook && storeOutput; } public static bool NeedsCookingPass(bool hasReadyOutput, bool usesFuelWithRoom, bool hasFreeSlot, bool canCook) { if (!(hasReadyOutput || usesFuelWithRoom)) { return hasFreeSlot && canCook; } return true; } public static bool NeedsFermenterPass(bool ready, bool emptiesOutput, bool empty, bool hasRoof, bool exposed) { if (!(ready && emptiesOutput)) { if (empty && hasRoof) { return !exposed; } return false; } return true; } public static bool NeedsSmelterFeed(bool canFuel, float currentFuel, int maxFuel, int fuelCap, bool hasConversions, int queuedOre, int maxOre, int oreCap) { if (!canFuel || FeedAmount(currentFuel, maxFuel, 1, fuelCap) <= 0) { if (hasConversions) { return FeedAmount(queuedOre, maxOre, 1, oreCap) > 0; } return false; } return true; } public static bool CanUseStation(bool valid, bool access, float distance, float reach) { if (valid && access && distance >= 0f && reach >= 0f) { return distance <= reach; } return false; } public static bool[] Shown(IList<bool> fireNearestFirst) { bool[] array = new bool[fireNearestFirst?.Count ?? 0]; int num = 0; int num2 = 0; for (int i = 0; i < array.Length; i++) { array[i] = (fireNearestFirst[i] ? (num2++ < 20) : (num++ < 40)); } return array; } public static void Diff<T>(ICollection<T> before, ICollection<T> after, List<T> added, List<T> removed) { HashSet<T> hashSet = new HashSet<T>(before); HashSet<T> hashSet2 = new HashSet<T>(after); foreach (T item in after) { if (!hashSet.Contains(item)) { added.Add(item); } } foreach (T item2 in before) { if (!hashSet2.Contains(item2)) { removed.Add(item2); } } } public static string StationContents(params string[] parts) { return string.Join(" · ", parts.Where((string p) => !string.IsNullOrWhiteSpace(p))); } public static string GroupText(string group) { return group switch { "Has contents" => Lang.T("crafting.group_has_contents", "Has contents"), "Empty" => Lang.T("crafting.group_empty", "Empty"), "Loaded" => Lang.T("crafting.group_loaded", "Loaded"), "Unloaded" => Lang.T("crafting.group_unloaded", "Unloaded"), _ => group, }; } public static string StationGroup(int contents) { if (contents >= 0) { if (contents <= 0) { return "Empty"; } return "Has contents"; } return "Loaded"; } public static string ProgressText(double duration, double elapsed) { if (double.IsNaN(duration) || double.IsInfinity(duration) || duration <= 0.0 || double.IsNaN(elapsed) || double.IsInfinity(elapsed)) { return ""; } return Math.Floor(Math.Min(duration, Math.Max(0.0, elapsed))).ToString("0") + "/" + duration.ToString("0") + " s"; } public static string TimeLeft(double duration, double elapsed) { if (double.IsNaN(duration) || double.IsInfinity(duration) || double.IsNaN(elapsed) || double.IsInfinity(elapsed)) { return "—"; } int num = (int)Math.Min(2147483647.0, Math.Max(0.0, Math.Ceiling(duration - Math.Max(0.0, elapsed)))); return num / 60 + ":" + (num % 60).ToString("00"); } public static bool FeedAccess(bool hasPlayer, bool stationAccess, bool chestAccess, bool checksWard, bool wardAccess) { if (hasPlayer && stationAccess && chestAccess) { return !checksWard || wardAccess; } return false; } public static bool Eligible(Chest chest, float range) { if (chest != null && !float.IsNaN(range) && !float.IsInfinity(range) && range >= 0f && chest.Distance >= 0f && chest.Distance <= range && chest.Accessible && chest.Owned && chest.UsedForCrafting && !chest.InUse && !chest.Moving) { return chest.Count > 0; } return false; } public static int Count(int inventory, IEnumerable<Chest> chests, float range) { long num = Math.Max(0, inventory); foreach (Chest item in from c in chests where Eligible(c, range) group c by c.Id into g select g.First()) { num += item.Count; } return (int)Math.Min(2147483647L, num); } public static Withdrawal[] Plan(int needed, int inventory, IEnumerable<Chest> chests, float range) { long num = Math.Max(0L, (long)needed - (long)Math.Max(0, inventory)); List<Withdrawal> list = new List<Withdrawal>(); foreach (Chest item in from c in chests where Eligible(c, range) orderby c.Distance, c.Id group c by c.Id into g select g.First()) { if (num == 0L) { break; } int num2 = (int)Math.Min(num, item.Count); list.Add(new Withdrawal { ChestId = item.Id, Amount = num2 }); num -= num2; } if (num != 0L) { return null; } return list.ToArray(); } public static int FeedAmount(float current, int maximum, int available, int cap = 5) { if (float.IsNaN(current) || float.IsInfinity(current) || current < 0f) { return 0; } return (int)Math.Max(0.0, Math.Min(Math.Min(Math.Floor((double)maximum - (double)current), available), cap)); } public static int Capacity(int current, int maximum) { return (int)Math.Min(2147483647L, Math.Max(0L, (long)maximum - (long)Math.Max(0, current))); } } internal static class AutoRepair { [HarmonyPatch(typeof(Player), "SetCraftingStation")] private static class Patch { private static void Postfix(Player __instance) { if (!_live || (Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)__instance.GetCurrentCraftingStation() == (Object)null || (Object)(object)InventoryGui.instance == (Object)null) { return; } InventoryGui instance = InventoryGui.instance; foreach (ItemData allItem in ((Humanoid)__instance).GetInventory().GetAllItems()) { if (allItem?.m_shared != null && allItem.m_shared.m_useDurability && !(allItem.m_durability >= allItem.GetMaxDurability()) && instance.CanRepair(allItem)) { allItem.m_durability = allItem.GetMaxDurability(); } } } } private static bool _live; internal static void Init() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown _live = true; Harmony val = new Harmony("expdare.meadworks.crafting.autorepair"); val.PatchAll(typeof(Patch)); LedgerTrack.Patch(val, "crafting automatic repair"); Ledger.Add("crafting automatic repair setting", (Action)delegate { _live = false; }); } } internal static class BuildCamera { private struct AimState { internal Transform Eye; internal Vector3 EyeLocal; internal float Reach; } private static class Patches { [HarmonyPrefix] [HarmonyPatch(typeof(Player), "LateUpdate")] private static void StepFlight(Player __instance) { if (IsAiming(__instance) && (Object)(object)GameCamera.instance != (Object)null) { Fly(GameCamera.instance); } } [HarmonyPostfix] [HarmonyPatch(typeof(GameCamera), "UpdateCamera")] private static void AfterCamera(GameCamera __instance) { if (_active && (Object)(object)__instance == (Object)(object)GameCamera.instance) { ApplyPose(__instance); } } [HarmonyPrefix] [HarmonyPriority(0)] [HarmonyPatch(typeof(Player), "SetControls")] private static void StandStill(Player __instance, ref Vector3 movedir, ref bool jump, ref bool crouch, ref bool run, ref bool autoRun, ref bool dodge) { //IL_0016: 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) if (_active && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { movedir = Vector3.zero; jump = false; crouch = false; run = false; autoRun = false; dodge = false; } } [HarmonyPrefix] [HarmonyPriority(0)] [HarmonyPatch(typeof(Player), "SetMouseLook")] private static void HoldLook(Player __instance, ref Vector2 mouseLook) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (_active && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { mouseLook = Vector2.zero; } } [HarmonyPrefix] [HarmonyPriority(800)] [HarmonyPatch(typeof(Player), "UpdatePlacement")] private static void AimForAction(Player __instance, out AimState __state) { AimFromCamera(__instance, out __state); } [HarmonyPrefix] [HarmonyPriority(800)] [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] private static void AimForPreview(Player __instance, out AimState __state) { AimFromCamera(__instance, out __state); } private static void AimFromCamera(Player __instance, out AimState __state) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) __state = default(AimState); if (IsAiming(__instance) && !((Object)(object)((Character)__instance).m_eye == (Object)null) && !((Object)(object)GameCamera.instance == (Object)null)) { __state = new AimState { Eye = ((Character)__instance).m_eye, EyeLocal = ((Character)__instance).m_eye.localPosition, Reach = __instance.m_maxPlaceDistance }; ((Character)__instance).m_eye.position = ((Component)GameCamera.instance).transform.position; __instance.m_maxPlaceDistance = BuildCameraRules.Reach(__state.Reach); } } [HarmonyFinalizer] [HarmonyPriority(0)] [HarmonyPatch(typeof(Player), "UpdatePlacement")] private static void RestoreAfterAction(Player __instance, AimState __state) { RestoreEye(__instance, __state); } [HarmonyFinalizer] [HarmonyPriority(0)] [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] private static void RestoreAfterPreview(Player __instance, AimState __state) { RestoreEye(__instance, __state); } private static void RestoreEye(Player __instance, AimState __state) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)__state.Eye == (Object)null)) { __instance.m_maxPlaceDistance = __state.Reach; __state.Eye.localPosition = __state.EyeLocal; } } [HarmonyPostfix] [HarmonyPriority(0)] [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] private static void CheckGhostStation(Player __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if ((int)__instance.m_placementStatus == 0 && MissingStation(__instance)) { __instance.m_placementStatus = (PlacementStatus)7; __instance.SetPlacementGhostValid(false); } } [HarmonyPrefix] [HarmonyPriority(800)] [HarmonyPatch(typeof(Player), "TryPlacePiece")] private static bool CheckStationBeforeSupply(Player __instance, bool __runOriginal = true) { if (!__runOriginal || !MissingStation(__instance)) { return __runOriginal; } ((Character)__instance).Message((MessageType)2, "$msg_missingstation", 0, (Sprite)null, false); return false; } [HarmonyTranspiler] [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Piece), typeof(RequirementMode) })] private static IEnumerable<CodeInstruction> PlacementStation(IEnumerable<CodeInstruction> instructions) { return StationAtTarget(instructions, "StationAtGhost"); } [HarmonyTranspiler] [HarmonyPatch(typeof(Player), "CheckCanRemovePiece")] private static IEnumerable<CodeInstruction> RemovalStation(IEnumerable<CodeInstruction> instructions) { return StationAtTarget(instructions, "StationAtExistingPiece"); } private static IEnumerable<CodeInstruction> StationAtTarget(IEnumerable<CodeInstruction> instructions, string replacement) { MethodInfo station = AccessTools.Method(typeof(CraftingStation), "HaveBuildStationInRange", (Type[])null, (Type[])null); MethodInfo target = AccessTools.Method(typeof(Patches), replacement, (Type[])null, (Type[])null); int sites = 0; foreach (CodeInstruction instruction in instructions) { if (!CodeInstructionExtensions.Calls(instruction, station)) { yield return instruction; continue; } sites++; yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), instruction), instruction); yield return new CodeInstruction(OpCodes.Ldarg_1, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)target); } if (sites != 1) { throw new InvalidOperationException("Build camera: expected one build station query for " + replacement); } } private static CraftingStation StationAtGhost(string name, Vector3 point, Player player, Piece piece) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (IsAiming(player) && (Object)(object)piece == (Object)(object)player.GetSelectedPiece() && HasGhost(player)) { point = player.m_placementGhost.transform.position; } return CraftingStation.HaveBuildStationInRange(name, point); } private static CraftingStation StationAtExistingPiece(string name, Vector3 point, Player player, Piece piece) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return CraftingStation.HaveBuildStationInRange(name, IsAiming(player) ? ((Component)piece).transform.position : point); } [HarmonyTranspiler] [HarmonyPatch(typeof(Player), "CopyPiece")] private static IEnumerable<CodeInstruction> CopyStation(IEnumerable<CodeInstruction> instructions) { MethodInfo select = AccessTools.Method(typeof(Player), "SetSelectedPiece", new Type[1] { typeof(Piece) }, (Type[])null); int sites = 0; foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, select)) { sites++; instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.Method(typeof(Patches), "SelectInRange", (Type[])null, (Type[])null); } yield return instruction; } if (sites != 1) { throw new InvalidOperationException("Build camera: expected one copy selection"); } } private static bool SelectInRange(Player player, Piece piece) { if (!IsAiming(player) || player.CheckCanRemovePiece(piece)) { return player.SetSelectedPiece(piece); } return false; } [HarmonyTranspiler] [HarmonyPatch(typeof(Player), "UpdatePlacement")] private static IEnumerable<CodeInstruction> RequirementsMessage(IEnumerable<CodeInstruction> instructions) { return StationMessage(instructions, "$msg_missingrequirement"); } [HarmonyTranspiler] [HarmonyPatch(typeof(Player), "TryPlacePiece")] private static IEnumerable<CodeInstruction> GhostMessage(IEnumerable<CodeInstruction> instructions) { return StationMessage(instructions, "$msg_extensionmissingstation"); } private static IEnumerable<CodeInstruction> StationMessage(IEnumerable<CodeInstruction> instructions, string key) { int sites = 0; foreach (CodeInstruction instruction in instructions) { yield return instruction; if (!(instruction.opcode != OpCodes.Ldstr) && object.Equals(instruction.operand, key)) { sites++; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patches), "PlacementMessage", (Type[])null, (Type[])null)); } } if (sites != 1) { throw new InvalidOperationException("Build camera: expected one " + key + " message"); } } private static string PlacementMessage(string native, Player player) { if (!MissingStation(player)) { return native; } return "$msg_missingstation"; } private static bool HasGhost(Player player) { if ((Object)(object)player.m_placementGhost != (Object)null) { return player.m_placementGhost.activeInHierarchy; } return false; } private static bool MissingStation(Player player) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (!IsAiming(player) || player.m_noPlacementCost || !HasGhost(player)) { return false; } CraftingStation val = player.GetSelectedPiece()?.m_craftingStation; if ((Object)(object)val != (Object)null && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)27)) { return (Object)(object)CraftingStation.HaveBuildStationInRange(val.m_name, player.m_placementGhost.transform.position) == (Object)null; } return false; } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "OnDamaged")] private static void Damaged(Player __instance) { if (_active && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { Stop(); } } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "SetLocalPlayer")] private static void PlayerChanged() { Stop(); } } private static Setting<float> _range; private static Harmony _harmony; private static bool _active; private static Vector3 _pos; private static float _yaw; private static float _pitch; private static readonly RaycastHit[] Hits = (RaycastHit[])(object)new RaycastHit[16]; internal static bool Active => _active; internal static void Init(SettingsPage page) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown _range = page.Slider("build_camera_range", "Build camera range", 30f, 5f, 50f, 1f, (SettingPolicy)1, false); Keys.Register("crafting.build_camera", "Ctrl+B", (Action)Toggle); page.Key("build_camera_key", "crafting.build_camera", "Build camera key", false); _harmony = new Harmony("expdare.meadworks.crafting.buildcamera"); _harmony.PatchAll(typeof(Patches)); LedgerTrack.Patch(_harmony, "crafting build camera"); Ledger.Add("crafting build camera state", (Action)delegate { _active = false; _range = null; if (_harmony != null) { _harmony.UnpatchSelf(); _harmony = null; } }); } private static bool ToolOut(Player player) { if ((Object)(object)player == (Object)null || !((Character)player).InPlaceMode()) { return false; } ItemData rightItem = ((Humanoid)player).GetRightItem(); return BuildCameraRules.IsBuildTool((rightItem != null && (Object)(object)rightItem.m_dropPrefab != (Object)null) ? ((Object)rightItem.m_dropPrefab).name : null); } private static bool Held(Player player) { if ((Object)(object)player != (Object)null) { if (!((Character)player).IsAttached()) { return ((Character)player).InBed(); } return true; } return false; } private static bool Paused() { return BuildCameraRules.Paused(((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || TextInput.IsVisible(), Menu.IsVisible(), InventoryGui.IsVisible(), Hud.IsPieceSelectionVisible(), WindowInput.AnyWindowOpen || SettingsWindow.IsOpen, Minimap.IsOpen()); } private static bool Ends(Player player) { if ((Object)(object)player == (Object)null || _range == null) { return true; } return BuildCameraRules.Ends(!((Character)player).IsDead(), ToolOut(player), Held(player), damaged: false, ((Character)player).IsTeleporting()); } private static void Toggle() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) if (_active) { Stop(); return; } Player localPlayer = Player.m_localPlayer; GameCamera instance = GameCamera.instance; if (!((Object)(object)localPlayer == (Object)null) && _range != null && !((Object)(object)instance == (Object)null) && BuildCameraRules.CanStart(!((Character)localPlayer).IsDead(), ToolOut(localPlayer), Held(localPlayer), Paused())) { _pos = ((Component)instance).transform.position; Vector3 eulerAngles = ((Component)instance).transform.eulerAngles; _yaw = eulerAngles.y; float num = eulerAngles.x; if (num > 180f) { num -= 360f; } _pitch = BuildCameraRules.ClampPitch(num); _active = true; } } private static void Stop() { _active = false; } private static void Fly(GameCamera camera) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if (Ends(localPlayer)) { Stop(); return; } if (!Paused()) { LookDelta(out var dx, out var dy, out var invertX, out var invertY); BuildCameraRules.Look(_yaw, _pitch, dx, dy, invertX, invertY, out _yaw, out _pitch); Quaternion val = Quaternion.Euler(_pitch, _yaw, 0f); Vector3 val2 = val * Vector3.forward; Vector3 val3 = val * Vector3.right; BuildCameraRules.Velocity(ZInput.GetButton("Forward"), ZInput.GetButton("Backward"), ZInput.GetButton("Left"), ZInput.GetButton("Right"), ZInput.GetButton("Jump"), ZInput.GetButton("Crouch"), ZInput.GetButton("Run"), val2.x, val2.y, val2.z, val3.x, val3.y, val3.z, out var vx, out var vy, out var vz); Vector3 move = new Vector3(vx, vy, vz) * Time.deltaTime; _pos = Advance(_pos, move, slide: true); Vector3 position = ((Character)localPlayer).m_eye.position; BuildCameraRules.StopAtRange(_pos.x, _pos.y, _pos.z, position.x, position.y, position.z, _range.Value, out var tx, out var ty, out var tz); Vector3 move2 = new Vector3(tx, ty, tz) - _pos; if (((Vector3)(ref move2)).sqrMagnitude > 1E-08f) { _pos = Advance(_pos, move2, slide: false); } } ApplyPose(camera); } private static void ApplyPose(GameCamera camera) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) ((Component)camera).transform.SetPositionAndRotation(_pos, Quaternion.Euler(_pitch, _yaw, 0f)); } private static void LookDelta(out float dx, out float dy, out bool invertX, out bool invertY) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) dx = (dy = 0f); invertX = false; invertY = false; if (!Hud.InRadial()) { if (ZInput.IsMouseActive()) { Vector2 mouseDelta = ZInput.GetMouseDelta(); float num = (ZInput.IsGamepadMouseActive() ? PlayerController.m_switchMouseSens : PlayerController.m_mouseSens); dx = mouseDelta.x * num; dy = mouseDelta.y * num; invertY = PlayerController.m_invertMouse; } else if (ZInput.IsGamepadActive() && !ZInput.GetButton("JoyRotate")) { float deltaTime = Time.deltaTime; dx = ZInput.GetJoyRightStickX() * 110f * deltaTime * PlayerController.m_gamepadSens; dy = (0f - ZInput.GetJoyRightStickY()) * 110f * deltaTime * PlayerController.m_gamepadSens; invertX = PlayerController.m_invertCameraX; invertY = PlayerController.m_invertCameraY; } } } private static Vector3 Advance(Vector3 pos, Vector3 move, bool slide) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (((Vector3)(ref move)).sqrMagnitude < 1E-10f) { return pos; } bool blocked = Cast(pos, move, out var distance, out var nx, out var ny, out var nz); BuildCameraRules.Slide(move.x, move.y, move.z, blocked, distance, nx, ny, nz, 0.05f, out var travelX, out var travelY, out var travelZ, out var remainX, out var remainY, out var remainZ); pos += new Vector3(travelX, travelY, travelZ); if (!slide) { return pos; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(remainX, remainY, remainZ); if (((Vector3)(ref val)).sqrMagnitude < 1E-10f) { return pos; } blocked = Cast(pos, val, out distance, out nx, out ny, out nz); BuildCameraRules.Slide(val.x, val.y, val.z, blocked, distance, nx, ny, nz, 0.05f, out travelX, out travelY, out travelZ, out remainX, out remainY, out remainZ); return pos + new Vector3(travelX, travelY, travelZ); } private static bool Cast(Vector3 from, Vector3 move, out float distance, out float nx, out float ny, out float nz) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) distance = 0f; nx = (ny = (nz = 0f)); float magnitude = ((Vector3)(ref move)).magnitude; if (magnitude < 1E-06f) { return false; } GameCamera instance = GameCamera.instance; int num = (((Object)(object)instance != (Object)null) ? ((LayerMask)(ref instance.m_blockCameraMask)).value : 0); if (num == 0) { return false; } int num2 = Physics.SphereCastNonAlloc(from, 0.2f, move / magnitude, Hits, magnitude, num, (QueryTriggerInteraction)1); Player localPlayer = Player.m_localPlayer; GameObject val = (((Object)(object)localPlayer != (Object)null) ? localPlayer.m_placementGhost : null); float num3 = magnitude; bool result = false; for (int i = 0; i < num2; i++) { RaycastHit val2 = Hits[i]; Collider collider = ((RaycastHit)(ref val2)).collider; if (!((Object)(object)collider == (Object)null) && !(((RaycastHit)(ref val2)).distance >= num3)) { Transform transform = ((Component)collider).transform; if ((!((Object)(object)localPlayer != (Object)null) || !transform.IsChildOf(((Component)localPlayer).transform)) && (!((Object)(object)val != (Object)null) || (!((Object)(object)transform == (Object)(object)val.transform) && !transform.IsChildOf(val.transform)))) { num3 = ((RaycastHit)(ref val2)).distance; distance = ((RaycastHit)(ref val2)).distance; nx = ((RaycastHit)(ref val2)).normal.x; ny = ((RaycastHit)(ref val2)).normal.y; nz = ((RaycastHit)(ref val2)).normal.z; result = true; } } } return result; } private static bool IsAiming(Player player) { if (_active) { return (Object)(object)player == (Object)(object)Player.m_localPlayer; } return false; } } public static class BuildCameraRules { public const float DefaultRange = 30f; public const float MinRange = 5f; public const float MaxRange = 50f; public const float RangeStep = 1f; public const float Speed = 10f; public const float Boost = 3f; public const float ProbeRadius = 0.2f; public const float Skin = 0.05f; public const float PitchLimit = 89f; public const float RayLength = 50f; public const string DefaultKey = "Ctrl+B"; public const string Forward = "Forward"; public const string Backward = "Backward"; public const string Left = "Left"; public const string Right = "Right"; public const string Jump = "Jump"; public const string Crouch = "Crouch"; public const string Run = "Run"; public static float ClampRange(float range) { if (float.IsNaN(range) || float.IsInfinity(range)) { return 30f; } return Math.Max(5f, Math.Min(50f, range)); } public static float Reach(float native) { if (!float.IsNaN(native) && !float.IsInfinity(native)) { return Math.Max(native, 50f); } return 50f; } public static bool IsBuildTool(string prefab) { if (!(prefab == "Hammer") && !(prefab == "Hoe")) { return prefab == "Cultivator"; } return true; } public static bool CanStart(bool alive, bool toolOut, bool attached, bool paused) { if (alive && toolOut && !attached) { return !paused; } return false; } public static bool Ends(bool alive, bool toolOut, bool attached, bool damaged, bool teleported) { return !alive || !toolOut || attached || damaged || teleported; } public static bool Paused(bool chat, bool menu, bool inventory, bool pieceMenu, bool meadWindow, bool map) { return chat || menu || inventory || pieceMenu || meadWindow || map; } public static float FlySpeed(bool run) { if (!run) { return 10f; } return 30f; } public static void Velocity(bool forward, bool back, bool left, bool right, bool up, bool down, bool run, float fwdX, float fwdY, float fwdZ, float rightX, float rightY, float rightZ, out float vx, out float vy, out float vz) { float num = (forward ? 1f : 0f) - (back ? 1f : 0f); float num2 = (right ? 1f : 0f) - (left ? 1f : 0f); float num3 = (up ? 1f : 0f) - (down ? 1f : 0f); vx = fwdX * num + rightX * num2; vy = fwdY * num + rightY * num2 + num3; vz = fwdZ * num + rightZ * num2; float num4 = (float)Math.Sqrt(vx * vx + vy * vy + vz * vz); float num5 = FlySpeed(run); if (num4 > 1f) { num5 /= num4; } else if (num4 <= 0f || float.IsNaN(num4) || float.IsInfinity(num4)) { vx = (vy = (vz = 0f)); return; } vx *= num5; vy *= num5; vz *= num5; } public static void Look(float yaw, float pitch, float deltaX, float deltaY, bool invertX, bool invertY, out float newYaw, out float newPitch) { if (float.IsNaN(deltaX) || float.IsInfinity(deltaX)) { deltaX = 0f; } if (float.IsNaN(deltaY) || float.IsInfinity(deltaY)) { deltaY = 0f; } if (invertX) { deltaX = 0f - deltaX; } if (invertY) { deltaY = 0f - deltaY; } if (float.IsNaN(yaw) || float.IsInfinity(yaw)) { yaw = 0f; } newYaw = yaw + deltaX; newPitch = ClampPitch(((float.IsNaN(pitch) || float.IsInfinity(pitch)) ? 0f : pitch) - deltaY); } public static float ClampPitch(float pitch) { if (float.IsNaN(pitch) || float.IsInfinity(pitch)) { return 0f; } if (pitch > 89f) { return 89f; } if (pitch < -89f) { return -89f; } return pitch; } public static void StopAtRange(float x, float y, float z, float playerX, float playerY, float playerZ, float range, out float tx, out float ty, out float tz) { range = ClampRange(range); float num = x - playerX; float num2 = y - playerY; float num3 = z - playerZ; float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3); if (float.IsNaN(num4) || float.IsInfinity(num4)) { tx = playerX; ty = playerY; tz = playerZ; } else if (num4 <= range || num4 <= 0f) { tx = x; ty = y; tz = z; } else { float num5 = range / num4; tx = playerX + num * num5; ty = playerY + num2 * num5; tz = playerZ + num3 * num5; } } public static void Slide(float moveX, float moveY, float moveZ, bool blocked, float hitDistance, float nx, float ny, float nz, float skin, out float travelX, out float travelY, out float travelZ, out float remainX, out float remainY, out float remainZ) { travelX = (travelY = (travelZ = (remainX = (remainY = (remainZ = 0f))))); double num = Math.Sqrt(moveX * moveX + moveY * moveY + moveZ * moveZ); if (num < 1E-06 || double.IsNaN(num) || double.IsInfinity(num)) { return; } if (!blocked || hitDistance < 0f || (double)hitDistance >= num || double.IsNaN(hitDistance)) { travelX = moveX; travelY = moveY; travelZ = moveZ; return; } float num2 = hitDistance - skin; if (num2 < 0f) { num2 = 0f; } double num3 = (double)num2 / num; travelX = (float)((double)moveX * num3); travelY = (float)((double)moveY * num3); travelZ = (float)((double)moveZ * num3); float num4 = moveX - travelX; float num5 = moveY - travelY; float num6 = moveZ - travelZ; double num7 = Math.Sqrt(nx * nx + ny * ny + nz * nz); if (!(num7 < 1E-06) && !double.IsNaN(num7)) { nx = (float)((double)nx / num7); ny = (float)((double)ny / num7); nz = (float)((double)nz / num7); float num8 = num4 * nx + num5 * ny + num6 * nz; remainX = num4 - nx * num8; remainY = num5 - ny * num8; remainZ = num6 - nz * num8; } } } public sealed class ChangeGate<T> { private bool _written; private T _last; public bool Changed(T value) { if (_written && EqualityComparer<T>.Default.Equals(_last, value)) { return false; } _written = true; _last = value; return true; } public void Write(T value, Action<T> write) { if (Changed(value)) { write(value); } } public void Reset() { _written = false; _last = default(T); } } internal static class ChestCharge { internal struct Need { public string Name; public int Quality; public int Amount; } private sealed class Held { public Container Chest; public ItemData Item; public string Name; public int Quality; public long PlayerId; public long World; } private sealed class Reservation { public Requirement[] Requirements; public Player Player; public long PlayerId; public long World; public int Frame; public bool Armed; public readonly List<Held> Items = new List<Held>(); } private sealed class Fetch { public readonly List<long> Tickets = new List<long>(); public readonly List<Container> Chests = new List<Container>(); public Player Player; public ChestChargeRules.PendingAction Pressed; public Func<ChestChargeRules.PendingAction> Now; public Func<bool> Payable; public Func<string> Blocker; public Container RefusedChest; public HandOverRefusal Refusal; public bool RetriedStale; public string StaleName; public object Subject; public Action Resume; public float Until; public int Frame; public ChestChargeRules.WaitClock Clock; } private struct Brought { public Container Chest; public string Name; public int Quality; public int Amount; public ItemData Sample; } private sealed class HeldPayment { public List<Brought> Rows; public Player Player; public float Until; } private sealed class Runner : MonoBehaviour { private void Update() { Tick(); ChestStore.Tick(); } } private const float FetchWait = 10f; private const float HandOverWait = 3f; private const float HeldWait = 10.5f; private static bool _asked; private static string _lost; private static Reservation _reserved; private static Fetch _fetch; private static readonly List<Held> Unfiled = new List<Held>(); private const float OwedEvery = 1f; private static float _owedNext; private static bool _owed; private static Player _seen; private static object _resumed; private static int _resumedFrame; private static bool _resumedRetriedStale; private static readonly Func<ItemData, int, int> Spend = (ItemData item, int units) => units; private static List<Brought> _brought; private static HeldPayment _held; internal static bool Fetching => _fetch != null; internal static bool Holding => _held != null; internal static bool Resuming(object subject) { if (_fetch != null && _fetch.Resume != null) { return _fetch.Subject == subject; } return false; } internal static void CancelResume(object subject) { if (_fetch != null && _fetch.Subject == subject) { if (ChestChargeRules.DropOnCancel(_fetch.Tickets.Count)) { _fetch = null; } else { _fetch.Resume = null; } } if (_resumed == subject) { _resumed = null; } } internal static void Init() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown GameObject val = new GameObject("MeadWorks.ChestCharge"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<Runner>(); LedgerTrack.Object<GameObject>(val, "crafting chest charge runner"); Ledger.Add("crafting chest charge state", (Action)delegate { if (_reserved != null) { Release(); } if (_brought != null) { UndoBring(); } _held = null; Settle(); if (Unfiled.Count > 0) { MwLog.Warn((object)("Crafting: " + Unfiled.Sum((Held h) => h.Item.m_stack) + " chest units are still to be handed back.")); } int num = ChestStore.Settle(); if (num > 0) { MwLog.Warn((object)("Crafting: " + num + " units of a station's batch are still kept for their chest.")); } _fetch = null; _resumed = null; _seen = null; _lost = null; }); } internal static List<Need> Missing(Player player, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier) { List<Need> list = new List<Need>(); if ((Object)(object)player == (Object)null || requirements == null) { return list; } CraftingStation currentCraftingStation = player.GetCurrentCraftingStation(); List<string> list2 = null; List<long> list3 = null; foreach (Requirement val in requirements) { if (val == null || (Object)(object)val.m_resItem == (Object)null || val.m_resItem.m_itemData?.m_shared == null || (((Object)(object)currentCraftingStation != (Object)null) ? (currentCraftingStation.m_upgrader != val.m_upgraderResource) : val.m_upgraderResource)) { continue; } long num = (long)val.GetAmount(qualityLevel) * (long)multiplier; if (num > 0) { string name = val.m_resItem.m_itemData.m_shared.m_name; if (list2 == null) { list2 = new List<string>(); list3 = new List<long>(); } int num2 = list2.IndexOf(name); if (num2 < 0) { list2.Add(name); list3.Add(num); } else { list3[num2] += num; } } } int num3 = 0; while (list2 != null && num3 < list2.Count) { int num4 = ChestChargeRules.Short(list3[num3], ((Humanoid)player).GetInventory().CountItems(list2[num3], itemQuality, true)); if (num4 > 0) { list.Add(new Need { Name = list2[num3], Quality = itemQuality, Amount = num4 }); } num3++; } return list; } private static IEnumerable<ChestChargeRules.Source> Describe(Container[] sources, Player player, Need need) { foreach (Container val in sources) { if (!((Object)(object)val == (Object)null) && ChestSource.Usable(val, player) && !ChestLink.Awaiting(val)) { int num = ChestLink.Ready(val, crafting: true); if (num != 0) { yield return new ChestChargeRules.Source { Id = ((Object)val).GetInstanceID(), Distance = Vector3.Distance(((Component)player).transform.position, ((Component)val).transform.position), Count = val.GetInventory().CountItems(need.Name, need.Quality, true), Requests = (num == 2) }; } } } } private static bool Direct(Container chest, Player player) { if ((Object)(object)chest != (Object)null && ChestSource.Usable(chest, player)) { return ChestLink.Ready(chest, crafting: true) == 1; } return false; } private static Container Find(Container[] sources, int id) { foreach (Container val in sources) { if ((Object)(object)val != (Object)null && ((Object)val).GetInstanceID() == id) { return val; } } return null; } internal static ChestChargeRules.Step Bring(Player player, object subject, List<Need> missing, Action resume, Container[] allowedSources = null, bool undoable = false, Func<ChestChargeRules.PendingAction> identity = null) { if ((Object)(object)player == (Object)null) { return ChestChargeRules.Step.Refuse; } if (missing == null || missing.Count == 0) { return ChestChargeRules.Step.Proceed; } ChestChargeRules.Step step = Secure(player, subject, missing, resume, allowedSources, identity); if (step != ChestChargeRules.Step.Proceed) { return step; } if (!MoveDirect(player, missing, allowedSources ?? ChestSource.Fresh(player), undoable)) { return ChestChargeRules.Step.Refuse; } return ChestChargeRules.Step.Proceed; } internal static int MoveToBag(Player player, Container chest, ItemData stack, int ask, bool automation = false) { if ((Object)(object)player == (Object)null || (Object)(object)chest == (Object)null || stack == null || ask <= 0 || ChestLink.Ready(chest, !automation) != 1) { return 0; } ask = (automation ? AutomationReserve.Limit(chest, stack, ask) : Math.Min(ask, stack.m_stack)); if (ask <= 0) { return 0; } ItemData val = stack.Clone(); val.m_stack = ask; if (!((Humanoid)player).GetInventory().CanAddItem(val, ask)) { return 0; } Reservation reservation = new Reservation { Player = player, PlayerId = player.GetPlayerID(), World = RefundCustody.World() }; if (!RefundCustody.Assured(player, reservation.PlayerId, reservation.World, new List<ItemData> { val })) { return 0; } int num = ChestStore.Take(chest, stack, ask, !automation); if (num <= 0) { return 0; } if (!ChestLink.Owned(chest)) { Lost(chest, stack.m_shared.m_name, ask, 0, owned: true, kept: false, written: false); chest.m_lastRevision = uint.MaxValue; return 0; } int num2 = Insert(((Humanoid)player).GetInventory(), val, num, null); if (num2 < num) { ItemData val2 = val.Clone(); val2.m_stack = num - Math.Max(0, num2); Refund(reservation, new Held { Chest = chest, Item = val2, Name = val2.m_shared.m_name, Quality = val2.m_quality }); } return Math.Max(0, num2); } internal static bool Track(object subject, IList<long> tickets, Action resume) { if (_fetch != null || tickets == null) { return false; } Fetch fetch = new Fetch { Subject = subject, Resume = resume, Until = Time.unscaledTime + 10f }; foreach (long ticket in tickets) { if (ticket != 0L) { fetch.Tickets.Add(ticket); } } if (fetch.Tickets.Count == 0) { return false; } _fetch = fetch; return true; } internal static void CommitBring() { _brought = null; } internal static void UndoBring() { List<Brought> brought = _brought; _brought = null; ReturnBrought(Player.m_localPlayer, brought); } internal static void HoldBring() { if (_brought == null || _brought.Count == 0) { _brought = null; return; } _held = new HeldPayment { Rows = _brought, Player = Player.m_localPlayer, Until = Time.unscaledTime + 10.5f }; _brought = null; } internal static void SettleBring(string answer) { SettleHeld(answered: true, answer); } private static void SettleHeld(bool answered, string answer) { HeldPayment held = _held; if (held == null) { return; } bool flag = held.Player == Player.m_localPlayer && (Object)(object)held.Player != (Object)null; ChestChargeRules.Paid paid = ChestChargeRules.HeldPayment(answered, answer, Time.unscaledTime, held.Until); if (paid == ChestChargeRules.Paid.Held && flag) { return; } _held = null; if (paid == ChestChargeRules.Paid.Returned && flag) { if (!answered) { MwLog.Info((object)"Crafting: the station gave no answer; the payment brought from chests goes back."); } ReturnBrought(held.Player, held.Rows); } } private static void ReturnBrought(Player player, List<Brought> brought) { if (brought == null) { return; } Inventory val = (((Object)(object)player != (Object)null) ? ((Humanoid)player).GetInventory() : null); for (int num = brought.Count - 1; num >= 0; num--) { Brought brought2 = brought[num]; if (val != null && brought2.Sample != null && brought2.Amount > 0 && !((Object)(object)brought2.Chest == (Object)null) && ChestLink.Ready(brought2.Chest, crafting: true) == 1) { int num2 = Units(val, brought2.Sample); val.RemoveItem(brought2.Name, brought2.Amount, brought2.Quality, true); int num3 = Math.Max(0, num2 - Units(val, brought2.Sample)); if (num3 > 0) { ItemData val2 = brought2.Sample.Clone(); val2.m_stack = num3; int num4 = num3 - Insert(brought2.Chest.GetInventory(), val2, num3, brought2.Chest); if (num4 > 0) { val2.m_stack = num4; val.AddItem(val2); } } } } } private static int DirectCells(Inventory bag, Container[] sources, Need need, List<ChestChargeRules.Part> parts) { int num = 0; ItemData val = null; foreach (ChestChargeRules.Part part in parts) { num += part.Amount; if (val != null) { continue; } Container val2 = Find(sources, part.ChestId); if (!((Object)(object)val2 == (Object)null)) { val = ((IEnumerable<ItemData>)val2.GetInventory().GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData s) => ChestSource.Matches(s, need.Name, need.Quality))); } } if (num <= 0) { return 0; } if (val == null || val.m_shared == null) { return int.MaxValue; } return ChestChargeRules.CellsNeeded(num, bag.FindFreeStackSpace(val.m_shared.m_name, (float)val.m_worldLevel), val.m_shared.m_maxStackSize); } private static bool MoveDirect(Player player, List<Need> missing, Container[] sources, bool undoable) { Inventory inventory = ((Humanoid)player).GetInventory(); List<List<ChestChargeRules.Part>> list = new List<List<ChestChargeRules.Part>>(missing.Count); List<int> list2 = new List<int>(missing.Count); for (int i = 0; i < missing.Count; i++) { List<ChestChargeRules.Part> list3 = ChestChargeRules.Plan(missing[i].Amount, Describe(sources, player, missing[i]), directOnly: true); if (list3 == null) { return false; } list.Add(list3); list2.Add(DirectCells(inventory, sources, missing[i], list3)); } if (!ChestChargeRules.FitsTogether(inventory.GetEmptySlots(), list2)) { return false; } List<Brought> list4 = new List<Brought>(); for (int j = 0; j < missing.Count; j++) { foreach (ChestChargeRules.Part item in list[j]) { Container val = Find(sources, item.ChestId); if ((Object)(object)val == (Object)null) { ReturnBrought(player, list4); return false; } int num = item.Amount; ItemData[] array = val.GetInventory().GetAllItems().ToArray(); for (int k = 0; k < array.Length; k++) { if (num <= 0) { break; } ItemData val2 = array[k]; if (ChestSource.Matches(val2, missing[j].Name, missing[j].Quality)) { int num2 = Math.Min(num, val2.m_stack); int num3 = MoveToBag(player, val, val2, num2); if (num3 > 0) { list4.Add(new Brought { Chest = val, Name = val2.m_shared.m_name, Quality = val2.m_quality, Amount = num3, Sample = val2 }); } if (num3 < num2) { ReturnBrought(player, list4); return false; } num -= num3; } } if (num > 0) { ReturnBrought(player, list4); return false; } } } if (undoable) { _brought = list4; } return true; } internal static ChestChargeRules.Step Secure(Player player, object subject, List<Need> missing, Action resume, Container[] allowedSources = null, Func<ChestChargeRules.PendingAction> identity = null) { _asked = false; Stale(); if (missing == null || missing.Count == 0) { return ChestChargeRules.Step.Proceed; } bool resumed = _resumed != null && _resumed == subject && Time.frameCount <= _resumedFrame + 1; if (_fetch != null) { if (_fetch.Subject == subject && resume != null) { _fetch.Resume = resume; } return ChestChargeRules.Step.Wait; } Container[] array = allowedSources ?? ChestSource.Fresh(player); List<List<ChestChargeRules.Part>> list = new List<List<ChestChargeRules.Part>>(missing.Count); bool flag = true; bool flag2 = false; foreach (Need item in missing) { List<ChestChargeRules.Part> list2 = ChestChargeRules.Plan(it