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 DvergrWorkers v0.17.0
DvergrWorkers.dll
Decompiled a week 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 BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DvergrWorkers.Beds; using DvergrWorkers.Core; using DvergrWorkers.Finder; using DvergrWorkers.Logistics; using DvergrWorkers.Movement; using DvergrWorkers.Prefabs; using DvergrWorkers.Roles.Collector; using DvergrWorkers.Roles.Farmer; using DvergrWorkers.Roles.MachineTender; using DvergrWorkers.Roles.Refueler; using DvergrWorkers.Roles.Repair; using DvergrWorkers.Roles.TreeFarmer; using DvergrWorkers.Roles.Woodcutter; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: IgnoresAccessChecksTo("")] [assembly: AssemblyCompany("DvergrWorkers")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Dvergr workers help around your base and defend it when it is under attack.")] [assembly: AssemblyFileVersion("0.17.0.0")] [assembly: AssemblyInformationalVersion("0.17.0+2e80ce2651e07776e80e7162e97becf8340d31b8")] [assembly: AssemblyProduct("DvergrWorkers")] [assembly: AssemblyTitle("DvergrWorkers")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.17.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [DebuggerDisplay("Count = {System.Collections.ICollection.Count}")] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } [DebuggerDisplay("Count = {System.Collections.ICollection.Count}")] [CompilerGenerated] internal sealed class <>z__ReadOnlyList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Count; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Count; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyList(List<T> items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return _items.Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return _items.IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace DvergrWorkers { [BepInPlugin("javidahmed64592.dvergrworkers", "Dvergr Workers", "0.17.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class DvergrWorkersPlugin : BaseUnityPlugin { public const string PluginGUID = "javidahmed64592.dvergrworkers"; public const string PluginName = "Dvergr Workers"; public const string PluginVersion = "0.17.0"; private Harmony _harmony; internal static ManualLogSource Log { get; private set; } private void Awake() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; WorkerConfig.Bind(((BaseUnityPlugin)this).Config); Translations.Load(); _harmony = new Harmony("javidahmed64592.dvergrworkers"); if (SafePatcher.PatchAll(_harmony, ((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger)) { PrefabManager.OnVanillaPrefabsAvailable += RegisterPrefabs; } } private void LateUpdate() { if (SafePatcher.ModEnabled) { WorkerFinder.LateUpdate(Time.deltaTime); } } private void OnDestroy() { WorkerFinder.Stop(); Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void RegisterPrefabs() { PrefabManager.OnVanillaPrefabsAvailable -= RegisterPrefabs; try { WorkerPrefabs.RegisterAll(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Failed to register Dvergr worker prefabs: " + ex)); } } } internal static class WorkerConfig { public static ConfigEntry<float> JobRadius; public static ConfigEntry<float> RespawnDelay; public static ConfigEntry<float> ThreatRadius; public static ConfigEntry<float> ThreatRetryDelay; public static ConfigEntry<int> TreesPerRound; public static ConfigEntry<int> StumpsPerRound; public static ConfigEntry<bool> TakeFromOutputChests; public static ConfigEntry<float> GroundPickupRadius; public static ConfigEntry<bool> FarmerPlantsLooseSeeds; public static ConfigEntry<bool> TreeFarmerPlantsLooseSeeds; public static ConfigEntry<float> TreeLooseSeedRadius; public static ConfigEntry<float> RefuelBelow; public static ConfigEntry<int> SeedReserve; public static ConfigEntry<int> PlantsPerTrip; public static ConfigEntry<int> MaxTrees; public static ConfigEntry<int> TreesPerTrip; public static ConfigEntry<float> TreeBuildingClearance; public static ConfigEntry<bool> WorkAtNight; public static ConfigEntry<float> WanderRadius; public static ConfigEntry<float> WanderPauseMin; public static ConfigEntry<float> WanderPauseMax; public static ConfigEntry<float> PersonalSpace; public static ConfigEntry<int> InventoryWidth; public static ConfigEntry<int> InventoryHeight; public static ConfigEntry<float> FinderArriveDistance; public static ConfigEntry<float> FinderTimeout; public static ConfigEntry<bool> FinderTrail; public static ConfigEntry<bool> FinderGlow; public static ConfigDescription Synced(string description, AcceptableValueBase range = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown return new ConfigDescription(description + " (Synced with server)", range, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } }); } public static void Bind(ConfigFile config) { //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Expected O, but got Unknown //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown JobRadius = config.Bind<float>("Workers", "JobRadius", 30f, Synced("Workers wander and perform tasks within this distance (metres) of their bed. A small tolerance is added for tasks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 100f))); RespawnDelay = config.Bind<float>("Workers", "RespawnDelay", 30f, Synced("Seconds after a worker is lost before its bed spawns a replacement.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f))); ThreatRadius = config.Bind<float>("Workers", "ThreatRadius", 25f, Synced("Workers drop their task and defend the base when an enemy hurts a player or worker within this distance (metres). Enemies that have not attacked anyone are ignored.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 80f))); ThreatRetryDelay = config.Bind<float>("Workers", "ThreatRetryDelay", 10f, Synced("Seconds after being interrupted before a worker goes back to work (once no one nearby has been hurt for a few seconds), instead of waiting for the next task interval.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f))); WorkAtNight = config.Bind<bool>("Workers", "WorkAtNight", false, Synced("If false, workers rest at night and only work in daylight.")); WanderRadius = config.Bind<float>("Idle", "WanderRadius", 12f, Synced("Idle workers stroll within this distance (metres) of their bed, favouring spots close to it. Never more than JobRadius.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 100f))); WanderPauseMin = config.Bind<float>("Idle", "PauseMin", 4f, Synced("Shortest time (seconds) an idle worker stands still between strolls.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f))); WanderPauseMax = config.Bind<float>("Idle", "PauseMax", 12f, Synced("Longest time (seconds) an idle worker stands still between strolls.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f))); PersonalSpace = config.Bind<float>("Idle", "PersonalSpace", 2.5f, Synced("An idle worker that a player stands closer to than this (metres) steps out of their way.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f))); TakeFromOutputChests = config.Bind<bool>("Workers", "TakeFromOutputChests", true, Synced("Let workers take items from output chests when another worker nearby produces them, e.g. the blacksmith taking the woodcutter's wood. Other items in output chests are never touched.")); GroundPickupRadius = config.Bind<float>("Workers", "GroundPickupRadius", 4f, Synced("Workers that tend machines (blacksmith, barley, flax, eitr and frost) and the refueler also use items lying on the ground within this distance (metres) of the machine or fire they are tending, e.g. ore dropped next to a smelter or wood next to a hearth. Items on the ground are used before those in chests. Keep it small so they leave alone items dropped for other reasons, like wood while building. 0 turns this off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 8f))); InventoryWidth = config.Bind<int>("Workers", "InventoryWidth", 8, Synced("Columns in a worker's own inventory.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 12))); InventoryHeight = config.Bind<int>("Workers", "InventoryHeight", 4, Synced("Rows in a worker's own inventory.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8))); FinderArriveDistance = config.Bind<float>("Finder", "ArriveDistance", 3f, new ConfigDescription("Pressing E on a worker's bed shows the way to its worker. It stops once you are this close (metres) to the worker.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f), Array.Empty<object>())); FinderTimeout = config.Bind<float>("Finder", "Timeout", 180f, new ConfigDescription("Seconds after which the way to a worker stops being shown if you have not reached it. 0 keeps showing it until you get there or press E on the bed again.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1800f), Array.Empty<object>())); FinderTrail = config.Bind<bool>("Finder", "ShowTrail", true, "While showing the way to a worker, lay a trail of green arrows on the ground from you to the worker, along the path you would walk."); FinderGlow = config.Bind<bool>("Finder", "Glow", true, "While showing the way to a worker, make the worker glow green."); foreach (WorkerRole item in WorkerRoles.All) { item.BindConfig(config); } RefuelBelow = config.Bind<float>(WorkerRoles.Refueler.Name, "RefuelBelow", 0.6f, Synced("A fire is topped up once its fuel falls to this fraction of its maximum.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f))); SeedReserve = config.Bind<int>(WorkerRoles.Farmer.Name, "SeedReserve", 4, Synced("The farmer plants raw ingredients (a carrot, a turnip...) to make more seeds once a crop's seeds fall to this many or fewer.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50))); PlantsPerTrip = config.Bind<int>(WorkerRoles.Farmer.Name, "PlantsPerTrip", 8, Synced("How many of one crop the farmer plants before moving on to the next, which keeps the crops evenly mixed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50))); FarmerPlantsLooseSeeds = config.Bind<bool>(WorkerRoles.Farmer.Name, "PlantLooseSeeds", true, Synced("The farmer tidies up seeds and crops lying on tilled soil in its job area. Seeds are planted before anything else and spares go to the input chest; crops such as carrots are planted when their seeds run low and otherwise go to the output chest.")); TreeFarmerPlantsLooseSeeds = config.Bind<bool>(WorkerRoles.TreeFarmer.Name, "PlantLooseSeeds", true, Synced("The tree farmer picks up tree seeds, cones and acorns lying on the ground in its job area near somewhere it would plant a tree itself (see LooseSeedRadius). It plants as many as it can, nearest where they lay first, and returns the rest to the input chest.")); TreeLooseSeedRadius = config.Bind<float>(WorkerRoles.TreeFarmer.Name, "LooseSeedRadius", 10f, Synced("Loose tree seeds are picked up if there is somewhere to plant them within this distance (metres), e.g. a stack dropped on a path next to open ground.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f))); MaxTrees = config.Bind<int>(WorkerRoles.TreeFarmer.Name, "MaxTrees", 40, Synced("The tree farmer stops planting once the job area holds this many trees and saplings, wild ones included.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 500))); TreesPerTrip = config.Bind<int>(WorkerRoles.TreeFarmer.Name, "TreesPerTrip", 5, Synced("How many of one species the tree farmer plants before moving on to the next.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50))); TreeBuildingClearance = config.Bind<float>(WorkerRoles.TreeFarmer.Name, "BuildingClearance", 8f, Synced("Trees are never planted closer than this (metres) to any building piece.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 40f))); TreesPerRound = config.Bind<int>(WorkerRoles.Woodcutter.Name, "TreesPerRound", 3, Synced("How many standing trees a woodcutter fells per round.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20))); StumpsPerRound = config.Bind<int>(WorkerRoles.Woodcutter.Name, "StumpsPerRound", 10, Synced("How many leftover tree stumps a woodcutter clears per round. 0 leaves stumps alone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50))); } } } namespace DvergrWorkers.Roles.Woodcutter { public class WoodcutterWorker : WorkerBrain { private enum Phase { Plan, Walk, Windup, Recover, Pickup, Deliver } private enum TargetKind { Tree, Stump, Log, Drop } private const float WindupTime = 0.5f; private const float RecoverTime = 1f; private const float PickupTimeout = 3f; private const int FullSlots = 2; private const float CleanupBonus = 6f; private const float StumpPenalty = 12f; private const float RetryTargetAfter = 15f; private const float MoreTreesDelay = 15f; private static readonly HashSet<string> WoodItems = new HashSet<string> { "$item_wood", "$item_finewood", "$item_corewood", "$item_elderbark", "$item_yggdrasilwood", "$item_resin", "$item_feathers" }; private Phase _phase; private TargetKind _kind; private GameObject _target; private float _timer; private bool _deliverFirst; private int _treesChopped; private int _stumpsCleared; private int _deliveredThisRound; private int _deliveredLastRound; private bool _deliveryBlocked; private readonly HashSet<GameObject> _failed = new HashSet<GameObject>(); private readonly Dictionary<GameObject, float> _skipUntil = new Dictionary<GameObject, float>(); private static HashSet<string> _treeSeeds; internal override WorkerRole Role => WorkerRoles.Woodcutter; protected override void Awake() { base.Awake(); TreeSeeds(); } protected override string IdleStatus() { if (_deliveredLastRound <= 0) { return "$dw_status_idle"; } return Text.Of("$dw_status_idle_delivered_wood", _deliveredLastRound); } protected override void OnRoundEnded(bool finished) { _target = null; _deliveredLastRound = _deliveredThisRound; } private static bool IsWood(ItemData item) { if (item == null) { return false; } string name = item.m_shared.m_name; if (!WoodItems.Contains(name)) { return TreeSeeds().Contains(name); } return true; } private static HashSet<string> TreeSeeds() { if (_treeSeeds == null) { _treeSeeds = PlantCatalogue.TreeSeedNames; WorkerRoles.Woodcutter.Produces.UnionWith(_treeSeeds); } return _treeSeeds; } private bool CarryingWood() { foreach (ItemData allItem in base.Logistics.Carried.GetAllItems()) { if (IsWood(allItem)) { return true; } } return false; } protected override bool BeginRound() { _failed.Clear(); _skipUntil.Clear(); _deliveryBlocked = false; _treesChopped = 0; _stumpsCleared = 0; _deliveredThisRound = 0; _target = null; _deliverFirst = CarryingWood(); if (!_deliverFirst && !ChooseTarget(out var _, out var _)) { _deliveredLastRound = 0; base.IdleNote = "$dw_status_no_trees"; return false; } base.Equipment.EquipTool(); _phase = Phase.Plan; DvergrWorkersPlugin.Log.LogInfo((object)"Woodcutter round started"); return true; } protected override bool RunTask(float dt) { switch (_phase) { case Phase.Plan: return Plan(); case Phase.Walk: return Walk(dt); case Phase.Windup: ((BaseAI)base.Ai).StopMoving(); Face(); _timer -= dt; if (_timer <= 0f) { Swing(); _phase = Phase.Recover; _timer = 1f; } return true; case Phase.Recover: ((BaseAI)base.Ai).StopMoving(); _timer -= dt; if (_timer <= 0f) { if (!IsAlive(_target)) { if (_kind == TargetKind.Tree) { _treesChopped++; } else if (_kind == TargetKind.Stump) { _stumpsCleared++; } _target = null; _phase = Phase.Plan; } else { _phase = Phase.Windup; _timer = 0.5f; } } return true; case Phase.Pickup: return PickUp(dt); case Phase.Deliver: return Deliver(dt); default: return false; } } private bool Plan() { Inventory carried = base.Logistics.Carried; bool flag = CarryingWood(); if (!flag && carried.GetEmptySlots() == 0) { return Abort("$dw_reason_inventory_full"); } bool flag2 = carried.GetEmptySlots() <= 2; if (flag && (flag2 || (_deliverFirst && !_deliveryBlocked))) { _deliverFirst = false; return StartDelivery(!flag2); } if (ChooseTarget(out var target, out var kind)) { if (base.Navigator.Begin(((Object)target).name, (Vector3 from) => ReachPoint(target, kind, from), rememberFailure: true)) { _target = target; _kind = kind; _phase = Phase.Walk; SetStatus(kind switch { TargetKind.Drop => "$dw_status_collecting_wood", TargetKind.Log => "$dw_status_walking_to_log", TargetKind.Stump => "$dw_status_walking_to_stump", _ => "$dw_status_walking_to_tree", }); } else { DvergrWorkersPlugin.Log.LogInfo((object)("No reachable spot next to " + ((Object)target).name + " yet, trying others first")); _skipUntil[target] = Time.time + 15f; } return true; } if (flag) { return StartDelivery(canWait: false); } bool num = _treesChopped >= WorkerConfig.TreesPerRound.Value; EndRound(finished: true); if (num) { StartNextRoundWithin(15f); } return false; } private bool ChooseTarget(out GameObject target, out TargetKind kind) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position; int toolTier = base.Equipment.ToolTier; target = null; kind = TargetKind.Tree; float best = float.MaxValue; foreach (TreeLog item in Scene.Logs.All) { Consider(((Component)item).gameObject, TargetKind.Log, item.m_minToolTier <= toolTier, position, -6f, ref best, ref target, ref kind); } foreach (ItemDrop s_instance in ItemDrop.s_instances) { if ((Object)(object)s_instance != (Object)null && IsWood(s_instance.m_itemData)) { Consider(((Component)s_instance).gameObject, TargetKind.Drop, usable: true, position, -6f, ref best, ref target, ref kind); } } if (_stumpsCleared < WorkerConfig.StumpsPerRound.Value) { foreach (Destructible item2 in Scene.Stumps.All) { Consider(((Component)item2).gameObject, TargetKind.Stump, item2.m_minToolTier <= toolTier, position, 12f, ref best, ref target, ref kind); } } if (_treesChopped < WorkerConfig.TreesPerRound.Value) { foreach (TreeBase item3 in Scene.Trees.All) { Consider(((Component)item3).gameObject, TargetKind.Tree, item3.m_minToolTier <= toolTier, position, 0f, ref best, ref target, ref kind); } } return (Object)(object)target != (Object)null; } private static Vector3 ReachPoint(GameObject target, TargetKind kind, Vector3 from) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003a: 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) if (kind == TargetKind.Tree || kind == TargetKind.Stump) { Vector3 position = target.transform.position; position.y = Mathf.Clamp(from.y, position.y, position.y + 2f); return position; } return WorkerNavigator.ClosestPointOnColliders(target, from); } private void Consider(GameObject go, TargetKind candidateKind, bool usable, Vector3 from, float bias, ref float best, ref GameObject target, ref TargetKind kind) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (usable && IsAlive(go) && !_failed.Contains(go) && InJobArea(go.transform.position) && (!_skipUntil.TryGetValue(go, out var value) || !(Time.time < value))) { float num = Vector3.Distance(go.transform.position, from) + bias; if (num < best) { best = num; target = go; kind = candidateKind; } } } private static bool IsAlive(GameObject go) { if ((Object)(object)go != (Object)null) { return go.activeInHierarchy; } return false; } private bool Abort(string reason) { DvergrWorkersPlugin.Log.LogInfo((object)("Woodcutter stopping: " + Text.Show(reason))); base.IdleNote = reason; EndRound(finished: false); return false; } private bool Walk(float dt) { if (!IsAlive(_target)) { _target = null; _phase = Phase.Plan; return true; } switch (base.Navigator.Step(dt)) { case NavResult.InReach: case NavResult.CloseEnough: if (_kind == TargetKind.Drop) { _phase = Phase.Pickup; _timer = 0f; SetStatus("$dw_status_collecting_wood"); } else { _phase = Phase.Windup; _timer = 0.5f; SetStatus(_kind switch { TargetKind.Tree => "$dw_status_chopping_tree", TargetKind.Stump => "$dw_status_clearing_stump", _ => "$dw_status_chopping_log", }); } break; case NavResult.Failed: _failed.Add(_target); _target = null; _phase = Phase.Plan; break; } return true; } private void Face() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (IsAlive(_target)) { Vector3 val = _target.transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { base.Character.SetLookDir(((Vector3)(ref val)).normalized, 0f); ((BaseAI)base.Ai).LookTowards(val); } } } private void Swing() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_009b: 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_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown if (IsAlive(_target)) { ItemData tool = base.Equipment.Tool; Vector3 val = _target.transform.position - ((Component)this).transform.position; val.y = 0f; HitData val2 = new HitData { m_damage = (DamageTypes)((tool != null) ? tool.GetDamage() : new DamageTypes { m_chop = 20f }), m_toolTier = (short)base.Equipment.ToolTier, m_point = WorkerNavigator.ClosestPointOnColliders(_target, base.Character.GetEyePoint()), m_dir = ((Vector3)(ref val)).normalized }; val2.SetAttacker(base.Character); IDestructible component = _target.GetComponent<IDestructible>(); if (component != null) { component.Damage(val2); } base.Animation.PlaySwing(); } } private bool PickUp(float dt) { ItemDrop val = (IsAlive(_target) ? _target.GetComponent<ItemDrop>() : null); if ((Object)(object)val == (Object)null) { _target = null; _phase = Phase.Plan; return true; } val.RequestOwn(); if (base.Humanoid.Pickup(_target, false, false)) { base.Animation.PlayPickup(); _target = null; _phase = Phase.Plan; return true; } _timer += dt; if (_timer > 3f) { _failed.Add(_target); _target = null; _phase = Phase.Plan; } return true; } private bool StartDelivery(bool canWait) { if (!CarryingWood()) { _phase = Phase.Plan; return true; } if (!base.Logistics.BeginDeposit(IsWood)) { if (canWait) { DvergrWorkersPlugin.Log.LogInfo((object)("Woodcutter keeps its wood for now: " + Text.Show(base.Logistics.Reason))); _deliveryBlocked = true; _phase = Phase.Plan; return true; } return Abort(base.Logistics.Reason); } _phase = Phase.Deliver; SetStatus("$dw_status_delivering_wood"); return true; } private bool Deliver(float dt) { switch (base.Logistics.Step(dt)) { case LogisticsResult.Moving: return true; case LogisticsResult.Failed: return Abort(base.Logistics.Reason); default: { _deliveredThisRound += base.Logistics.Transferred; bool flag = base.Logistics.Carried.GetEmptySlots() <= 2; if (base.Logistics.Transferred == 0) { if (!flag) { _deliveryBlocked = true; _phase = Phase.Plan; return true; } return Abort("$dw_reason_output_full"); } if (CarryingWood()) { return StartDelivery(!flag); } _deliveryBlocked = false; _phase = Phase.Plan; return true; } } } } } namespace DvergrWorkers.Roles.TreeFarmer { internal sealed class GroundSurvey : AreaSurvey<GroundSurvey.Spot> { internal readonly struct Spot { public Vector3 Position { get; } public Biome Biome { get; } public bool Dirt { get; } public Spot(Vector3 position, Biome biome, bool dirt) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: 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) Position = position; Biome = biome; Dirt = dirt; } } private const float MinWaterClearance = 0.5f; private const float FarmlandClearance = 2.5f; private const float MinRoom = 0.8f; private static readonly int SpaceMask = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid" }); private static readonly int RoofMask = LayerMask.GetMask(new string[3] { "Default", "static_solid", "piece" }); private static readonly int PieceMask = LayerMask.GetMask(new string[2] { "piece", "piece_nonsolid" }); private static readonly int TerrainMask = LayerMask.GetMask(new string[1] { "terrain" }); private float _clearance; protected override float GridStep => 2f; protected override float MaxAge => 60f; public void Refresh(Vector3 home, float radius, float limit, float clearance) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) _clearance = clearance; RefreshIfStale(home, radius, limit, clearance); } protected override void Survey(Vector3 gridPoint, List<Spot> into) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003a: 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_005f: 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) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00c4: 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_00e9: 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) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(gridPoint.x + Random.Range(-0.6f, 0.6f), 0f, gridPoint.z + Random.Range(-0.6f, 0.6f)); if (!(Utils.DistanceXZ(val, base.Home) > base.Limit)) { val.y = ZoneSystem.instance.GetGroundHeight(val); Heightmap val2 = Heightmap.FindHeightmap(val); if (!((Object)(object)val2 == (Object)null) && !(val.y <= ZoneSystem.instance.m_waterLevel + 0.5f) && !(val2.GetPaintMask(val).b > 0.3f) && !NearFarmland(val) && !Physics.CheckSphere(val, _clearance, PieceMask) && FlatEnough(val) && !Physics.CheckSphere(val + Vector3.up * 0.2f, 0.8f, SpaceMask) && !Physics.Raycast(val + Vector3.up * 0.2f, Vector3.up, 100f, RoofMask)) { into.Add(new Spot(val, Heightmap.FindBiome(val), HasDirt(val2, val))); } } } public static bool StillClear(Vector3 p, float room) { //IL_0000: 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) //IL_000a: 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) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!NearPaved(p, room)) { return !Physics.CheckSphere(p + Vector3.up * 0.2f, room + 0.3f, SpaceMask); } return false; } private static bool HasDirt(Heightmap heightmap, Vector3 p) { //IL_0001: 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) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 float vegetationMask = heightmap.GetVegetationMask(p); if ((int)heightmap.GetBiome(p, 0.02f, false) != 32) { return vegetationMask >= 0.25f; } return vegetationMask <= 0.1f; } private static bool FlatEnough(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); if (Physics.Raycast(p + Vector3.up * 2f, Vector3.down, ref val, 6f, TerrainMask)) { return ((RaycastHit)(ref val)).normal.y >= 0.8f; } return false; } private static bool NearPaved(Vector3 p, float room) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: 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) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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) if (!Paved(p + Vector3.right * room) && !Paved(p + Vector3.left * room) && !Paved(p + Vector3.forward * room)) { return Paved(p + Vector3.back * room); } return true; } private static bool Paved(Vector3 p) { //IL_0000: 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_0012: Unknown result type (might be due to invalid IL or missing references) Heightmap val = Heightmap.FindHeightmap(p); if ((Object)(object)val != (Object)null) { return val.GetPaintMask(p).b > 0.3f; } return false; } private static bool NearFarmland(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: 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) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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_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) if (!Cultivated(p) && !Cultivated(p + Vector3.right * 2.5f) && !Cultivated(p + Vector3.left * 2.5f) && !Cultivated(p + Vector3.forward * 2.5f)) { return Cultivated(p + Vector3.back * 2.5f); } return true; } private static bool Cultivated(Vector3 p) { //IL_0000: 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) Heightmap val = Heightmap.FindHeightmap(p); if ((Object)(object)val != (Object)null) { return val.IsCultivated(p); } return false; } } public class TreeFarmerWorker : WorkerBrain { private enum Phase { Plan, Fetch, Walk, Plant, Return, Gather } private const float PlantTime = 0.6f; private const int MaxReachChecks = 30; private int _reachChecksLeft; private const double MaxReachMilliseconds = 8.0; private double _reachPathsAtStart; private const float TreeSpacingMargin = 1f; private const float DefaultTreeRoom = 2f; private const float GatherInterval = 0.3f; private const int MaxGatherTries = 12; private Phase _phase; private PlantType _batchType; private readonly List<Vector3> _batchSpots = new List<Vector3>(); private float _timer; private int _planted; private int _plantedLastRound; private bool _noSupply; private bool _noSpots; private int _pendingChecks; private bool _full; private readonly HashSet<PlantType> _failedTypes = new HashSet<PlantType>(); private readonly HashSet<PlantType> _loggedBiome = new HashSet<PlantType>(); private readonly Dictionary<string, int> _plantedByFamily = new Dictionary<string, int>(); private readonly List<Occupied> _plantedSpots = new List<Occupied>(); private readonly GroundSurvey _survey = new GroundSurvey(); private readonly OccupiedGrid _occupied = new OccupiedGrid(); private readonly List<TreeBase> _nearbyTrees = new List<TreeBase>(); private readonly List<Plant> _nearbyPlants = new List<Plant>(); private int _sceneScanFrame = -1; private ItemDrop _looseSeed; private PlantType _looseType; private readonly List<(PlantType Type, Vector3 Origin)> _loosePlanted = new List<(PlantType, Vector3)>(); private int _gatherTries; private bool _walkingToSeed; private readonly HashSet<ItemDrop> _looseFailed = new HashSet<ItemDrop>(); internal override WorkerRole Role => WorkerRoles.TreeFarmer; private void ResetReachChecks() { _reachChecksLeft = 30; _reachPathsAtStart = WorkerPaths.Milliseconds; } private bool ReachCheckAllowed() { if (_reachChecksLeft > 0) { return WorkerPaths.Milliseconds - _reachPathsAtStart < 8.0; } return false; } protected override string IdleStatus() { if (_plantedLastRound <= 0) { return "$dw_status_idle"; } return Text.Of("$dw_status_idle_planted_trees", _plantedLastRound); } protected override void OnRoundEnded(bool finished) { _batchSpots.Clear(); _plantedLastRound = _planted; } internal override bool WantsItem(string sharedName) { return PlantCatalogue.TreeSeedNames.Contains(sharedName); } private int Supply(string sharedName) { return base.Logistics.Carried.CountItems(sharedName, -1, true) + base.Logistics.AvailableTo(sharedName); } private bool CarryingSeeds() { HashSet<string> treeSeedNames = PlantCatalogue.TreeSeedNames; foreach (ItemData allItem in base.Logistics.Carried.GetAllItems()) { if (treeSeedNames.Contains(allItem.m_shared.m_name)) { return true; } } return false; } private Dictionary<string, int> CountFamilies(out int total) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, int> dictionary = new Dictionary<string, int>(); foreach (PlantType tree in PlantCatalogue.Trees) { dictionary[tree.Family] = 0; } total = 0; ScanScene(); foreach (TreeBase nearbyTree in _nearbyTrees) { if (InJobArea(((Component)nearbyTree).transform.position)) { total++; PlantType plantType = PlantCatalogue.Of(((Component)nearbyTree).gameObject); if (plantType != null && plantType.IsTree) { dictionary[plantType.Family]++; } } } foreach (Plant nearbyPlant in _nearbyPlants) { if (InJobArea(((Component)nearbyPlant).transform.position)) { PlantType plantType2 = PlantCatalogue.Of(((Component)nearbyPlant).gameObject); if (plantType2 != null && plantType2.IsTree) { total++; dictionary[plantType2.Family]++; } } } foreach (KeyValuePair<string, int> item in _plantedByFamily) { if (dictionary.ContainsKey(item.Key)) { dictionary[item.Key] += item.Value; } } return dictionary; } private static List<string> OrderedFamilies(Dictionary<string, int> counts) { List<string> list = counts.Keys.ToList(); list.Sort((string a, string b) => counts[a].CompareTo(counts[b])); return list; } private PlantType ChooseType(string family) { foreach (PlantType tree in PlantCatalogue.Trees) { if (tree.Family == family && !_failedTypes.Contains(tree) && Supply(tree.RequiredShared) >= tree.Amount) { return tree; } } return null; } private List<Vector3> FindSpots(PlantType type, int max, Vector3? nearestTo = null) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_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_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) int wrongBiome = 0; float num = Room(type); OccupiedGrid occupied = OccupiedSpots(); List<Vector3> list = new List<Vector3>(); foreach (GroundSurvey.Spot spot in _survey.Spots) { if (Fits(type, spot, occupied, num, ref wrongBiome)) { list.Add(spot.Position); } } if (list.Count == 0 && wrongBiome > 0 && _loggedBiome.Add(type)) { DvergrWorkersPlugin.Log.LogInfo((object)("Tree farmer: " + ((Object)type.Prefab).name + " cannot be planted here, wrong biome (" + ((object)Heightmap.FindBiome(base.Home)/*cast due to .constrained prefix*/).ToString() + " is not in plant biomes " + ((object)Unsafe.As<Biome, Biome>(ref type.Plant.m_biome)/*cast due to .constrained prefix*/).ToString() + ")")); } Vector3 here = (Vector3)(((??)nearestTo) ?? ((Component)this).transform.position); list.Sort((Vector3 a, Vector3 b) => Vector3.Distance(a, here).CompareTo(Vector3.Distance(b, here))); List<Vector3> list2 = new List<Vector3>(); foreach (Vector3 item in list) { bool flag = false; foreach (Vector3 item2 in list2) { if (Utils.DistanceXZ(item2, item) < num * 2f + 1f) { flag = true; break; } } if (flag || UnreachableSpots.IsKnown(item) || !GroundSurvey.StillClear(item, num)) { continue; } if (UnreachableSpots.IsPending(item)) { _pendingChecks++; continue; } if (!ReachCheckAllowed()) { _pendingChecks++; break; } _reachChecksLeft--; Vector3 target = item; if (!base.Navigator.CanReach((Vector3 _) => target)) { UnreachableSpots.Suspect(item); _pendingChecks++; continue; } list2.Add(item); if (list2.Count < max) { continue; } break; } return list2; } private static float Room(PlantType type) { return Mathf.Max(type.Plant.m_growRadius, 0.5f); } private void ScanScene() { //IL_005d: 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_00cb: 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) if (_sceneScanFrame == Time.frameCount) { return; } _sceneScanFrame = Time.frameCount; float num = WorkerConfig.JobRadius.Value + 10f; _nearbyTrees.Clear(); foreach (TreeBase item in Scene.Trees.All) { if (SceneObjects<TreeBase>.IsLive(item) && Utils.DistanceXZ(((Component)item).transform.position, base.Home) <= num) { _nearbyTrees.Add(item); } } _nearbyPlants.Clear(); foreach (Plant item2 in Scene.Plants.All) { if (SceneObjects<Plant>.IsLive(item2) && Utils.DistanceXZ(((Component)item2).transform.position, base.Home) <= num) { _nearbyPlants.Add(item2); } } } private OccupiedGrid OccupiedSpots() { //IL_0081: 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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) ScanScene(); _occupied.Clear(); foreach (Occupied plantedSpot in _plantedSpots) { _occupied.Add(plantedSpot); } foreach (Plant nearbyPlant in _nearbyPlants) { if ((Object)(object)nearbyPlant != (Object)null) { _occupied.Add(new Occupied { Position = ((Component)nearbyPlant).transform.position, Radius = nearbyPlant.m_growRadius }); } } foreach (TreeBase nearbyTree in _nearbyTrees) { if ((Object)(object)nearbyTree != (Object)null) { PlantType plantType = PlantCatalogue.Of(((Component)nearbyTree).gameObject); float radius = ((plantType != null && plantType.IsTree) ? plantType.Plant.m_growRadius : 2f); _occupied.Add(new Occupied { Position = ((Component)nearbyTree).transform.position, Radius = radius }); } } return _occupied; } private static bool Fits(PlantType type, GroundSurvey.Spot spot, OccupiedGrid occupied, float room, ref int wrongBiome) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!PlantCatalogue.BiomeAllows(type, spot.Biome)) { wrongBiome++; return false; } if (!type.Piece.m_vegetationGroundOnly || spot.Dirt) { return !occupied.Crowds(spot.Position, room, 1f); } return false; } private bool NearestLooseSeed(out ItemDrop seed, out PlantType type) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0088: 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_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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) seed = null; type = null; if (!WorkerConfig.TreeFarmerPlantsLooseSeeds.Value) { return false; } HashSet<string> names = PlantCatalogue.TreeSeedNames; List<ItemDrop> list = new List<ItemDrop>(); foreach (ItemDrop item in GroundItems.Loose((ItemData i) => names.Contains(i.m_shared.m_name))) { Vector3 position = ((Component)item).transform.position; if (!_looseFailed.Contains(item) && InJobArea(position) && !UnreachableSpots.IsKnown(position) && !UnreachableSpots.IsPending(position)) { list.Add(item); } } if (list.Count == 0) { return false; } Vector3 here = ((Component)this).transform.position; list.Sort((ItemDrop a, ItemDrop b) => Vector3.Distance(((Component)a).transform.position, here).CompareTo(Vector3.Distance(((Component)b).transform.position, here))); OccupiedGrid occupied = OccupiedSpots(); foreach (ItemDrop item2 in list) { foreach (PlantType tree in PlantCatalogue.Trees) { if (tree.RequiredShared == item2.m_itemData.m_shared.m_name && !_failedTypes.Contains(tree) && HasSpotNear(tree, ((Component)item2).transform.position, occupied)) { seed = item2; type = tree; return true; } } _looseFailed.Add(item2); } return false; } private bool HasSpotNear(PlantType type, Vector3 centre, OccupiedGrid occupied) { //IL_0031: 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_0041: 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) float value = WorkerConfig.TreeLooseSeedRadius.Value; float room = Room(type); int wrongBiome = 0; foreach (GroundSurvey.Spot spot in _survey.Spots) { if (Utils.DistanceXZ(spot.Position, centre) <= value && !UnreachableSpots.IsKnown(spot.Position) && Fits(type, spot, occupied, room, ref wrongBiome) && GroundSurvey.StillClear(spot.Position, room)) { return true; } } return false; } protected override void BackgroundWork(float dt) { _survey.Continue(); } protected override bool BeginRound() { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) _planted = 0; _noSupply = false; _noSpots = false; _pendingChecks = 0; _full = false; _failedTypes.Clear(); _loggedBiome.Clear(); _plantedByFamily.Clear(); _plantedSpots.Clear(); _batchSpots.Clear(); _batchType = null; _looseSeed = null; _walkingToSeed = false; _looseFailed.Clear(); _loosePlanted.Clear(); if (!PlantCatalogue.Trees.Any()) { base.IdleNote = "$dw_status_no_saplings"; return false; } _survey.Refresh(base.Home, WorkerConfig.JobRadius.Value, WorkerConfig.JobRadius.Value + 3f, WorkerConfig.TreeBuildingClearance.Value); if (!_survey.Ready) { base.IdleNote = "$dw_status_looking_over_ground"; RetrySoon(1f); return false; } if (!AnythingToPlant()) { _plantedLastRound = 0; if (_pendingChecks > 0) { RetrySoon(15f); } base.IdleNote = NothingToDoNote(); return false; } base.Equipment.EquipTool(); _phase = Phase.Plan; DvergrWorkersPlugin.Log.LogInfo((object)"Tree farmer round started"); return true; } private bool AnythingToPlant() { ResetReachChecks(); int total; Dictionary<string, int> counts = CountFamilies(out total); if (total >= WorkerConfig.MaxTrees.Value) { _full = true; return CarryingSeeds(); } if (NearestLooseSeed(out var _, out var _)) { return true; } foreach (string item in OrderedFamilies(counts)) { PlantType plantType = ChooseType(item); if (plantType == null) { _noSupply = true; continue; } if (FindSpots(plantType, 1).Count > 0) { return true; } _noSpots = true; } return CarryingSeeds(); } private string NothingToDoNote() { bool full = _full; bool noSupply = _noSupply; bool noSpots = _noSpots; if (!full) { if (noSupply) { if (!noSpots) { return "$dw_status_waiting_for_tree_seeds"; } } else if (noSpots) { return "$dw_status_no_tree_ground"; } return null; } return "$dw_status_forest_full"; } protected override bool RunTask(float dt) { return _phase switch { Phase.Plan => Plan(), Phase.Fetch => Fetch(dt), Phase.Walk => Walk(dt), Phase.Plant => PlantNow(dt), Phase.Return => Return(dt), Phase.Gather => Gather(dt), _ => false, }; } private bool Plan() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (_batchSpots.Count > 0 && _batchType != null && base.Logistics.Carried.CountItems(_batchType.RequiredShared, -1, true) >= _batchType.Amount) { return BeginWalk(_batchSpots[0]); } _batchSpots.Clear(); if (StartLooseSeed()) { return true; } if (StartBatch()) { return true; } if (CarryingSeeds()) { return StartReturn(); } if (_planted == 0) { base.IdleNote = NothingToDoNote(); } EndRound(finished: true); if (_pendingChecks > 0) { StartNextRoundWithin(15f); } return false; } private bool StartLooseSeed() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) CountFamilies(out var total); if (total >= WorkerConfig.MaxTrees.Value) { return false; } ItemDrop seed; PlantType type; while (NearestLooseSeed(out seed, out type)) { Vector3 at = ((Component)seed).transform.position; if (base.Navigator.Begin("loose seed", (Vector3 _) => at, rememberFailure: true)) { _looseSeed = seed; _looseType = type; _walkingToSeed = true; _phase = Phase.Walk; SetStatus(Text.Of("$dw_status_picking_up_fallen", type.RequiredShared)); return true; } _looseFailed.Add(seed); } return false; } private bool Gather(float dt) { //IL_0091: 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_00c3: Unknown result type (might be due to invalid IL or missing references) ((BaseAI)base.Ai).StopMoving(); _timer -= dt; if (_timer > 0f) { return true; } _timer = 0.3f; if ((Object)(object)_looseSeed == (Object)null || ++_gatherTries > 12) { if ((Object)(object)_looseSeed != (Object)null) { _looseFailed.Add(_looseSeed); } _looseSeed = null; _phase = Phase.Plan; return true; } Vector3 position = ((Component)_looseSeed).transform.position; if (GroundItems.Take(base.Humanoid, _looseSeed) > 0) { _looseSeed = null; _loosePlanted.Add((_looseType, position)); base.Animation.PlayPickup(); _phase = Phase.Plan; } return true; } private bool StartBatch() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) ResetReachChecks(); int total; Dictionary<string, int> counts = CountFamilies(out total); int num = WorkerConfig.MaxTrees.Value - total; if (num <= 0) { _full = true; return false; } foreach (var item2 in new List<(PlantType, Vector3)>(_loosePlanted)) { PlantType item = item2.Item1; int num2 = base.Logistics.Carried.CountItems(item.RequiredShared, -1, true) / item.Amount; List<Vector3> list = ((num2 > 0 && !_failedTypes.Contains(item)) ? FindSpots(item, Math.Min(num2, num), item2.Item2) : new List<Vector3>()); if (list.Count == 0) { _loosePlanted.Remove(item2); continue; } _batchType = item; _batchSpots.Clear(); _batchSpots.AddRange(list); _phase = Phase.Plan; return true; } foreach (string item3 in OrderedFamilies(counts)) { PlantType plantType = ChooseType(item3); if (plantType == null) { _noSupply = true; continue; } List<Vector3> list2 = FindSpots(plantType, Math.Min(WorkerConfig.TreesPerTrip.Value, num)); if (list2.Count == 0) { _noSpots = true; continue; } int num3 = Math.Min(list2.Count, Supply(plantType.RequiredShared) / plantType.Amount); if (num3 > 0) { _batchType = plantType; _batchSpots.Clear(); _batchSpots.AddRange(list2.GetRange(0, num3)); int num4 = num3 * plantType.Amount - base.Logistics.Carried.CountItems(plantType.RequiredShared, -1, true); if (num4 <= 0) { _phase = Phase.Plan; return true; } string shared = plantType.RequiredShared; if (base.Logistics.BeginFetchAny((ItemData i) => i.m_shared.m_name == shared, num4)) { _phase = Phase.Fetch; SetStatus("$dw_status_fetching_seeds"); return true; } DvergrWorkersPlugin.Log.LogInfo((object)("Tree farmer fetch failed: " + Text.Show(base.Logistics.Reason))); _failedTypes.Add(plantType); _batchSpots.Clear(); } } return false; } private bool Fetch(float dt) { switch (base.Logistics.Step(dt)) { case LogisticsResult.Moving: return true; case LogisticsResult.Failed: DvergrWorkersPlugin.Log.LogInfo((object)("Tree farmer fetch failed: " + Text.Show(base.Logistics.Reason))); if (_batchType != null) { _failedTypes.Add(_batchType); } break; } _phase = Phase.Plan; return true; } private bool BeginWalk(Vector3 spot) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (!base.Navigator.Begin("planting spot", (Vector3 _) => spot, rememberFailure: true)) { DvergrWorkersPlugin.Log.LogInfo((object)"No reachable spot next to a planting spot, skipping"); _batchSpots.RemoveAt(0); _phase = Phase.Plan; return true; } _phase = Phase.Walk; SetStatus(Text.Of("$dw_status_walking_to_plant", _batchType.Piece.m_name)); return true; } private bool Walk(float dt) { //IL_00b7: 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_00c2: Unknown result type (might be due to invalid IL or missing references) bool walkingToSeed = _walkingToSeed; if (walkingToSeed && (Object)(object)_looseSeed == (Object)null) { _walkingToSeed = false; _phase = Phase.Plan; return true; } switch (base.Navigator.Step(dt)) { case NavResult.InReach: case NavResult.CloseEnough: _timer = (walkingToSeed ? 0.2f : 0.6f); _gatherTries = 0; _walkingToSeed = false; _phase = (walkingToSeed ? Phase.Gather : Phase.Plant); break; case NavResult.Failed: if (walkingToSeed) { _looseFailed.Add(_looseSeed); _looseSeed = null; _walkingToSeed = false; } else if (_batchSpots.Count > 0) { Vector3 failed = _batchSpots[0]; UnreachableSpots.Add(failed); _batchSpots.RemoveAll((Vector3 s) => Utils.DistanceXZ(s, failed) < 4f); } _phase = Phase.Plan; break; } return true; } private bool PlantNow(float dt) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0122: 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_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0193: 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_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) ((BaseAI)base.Ai).StopMoving(); _timer -= dt; if (_timer > 0f) { return true; } if (_batchSpots.Count == 0 || _batchType == null) { _phase = Phase.Plan; return true; } Vector3 val = _batchSpots[0]; _batchSpots.RemoveAt(0); PlantType batchType = _batchType; ItemData val2 = null; foreach (ItemData allItem in base.Logistics.Carried.GetAllItems()) { if (allItem.m_shared.m_name == batchType.RequiredShared && allItem.m_stack >= batchType.Amount) { val2 = allItem; break; } } int mask = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid" }); float num = Mathf.Max(batchType.Plant.m_growRadius, 0.5f); if (val2 != null && PlantCatalogue.BiomeAllows(batchType, val) && !Physics.CheckSphere(val + Vector3.up * 0.2f, num + 0.3f, mask)) { base.Logistics.Carried.RemoveItem(val2, batchType.Amount); Quaternion val3 = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f); GameObject val4 = Object.Instantiate<GameObject>(batchType.Prefab, val, val3); batchType.Piece.m_placeEffect.Create(val, val3, val4.transform, 1f, -1, default(ZDOID)); base.Animation.PlaySwing(); DvergrWorkersPlugin.Log.LogInfo((object)("Tree farmer planted " + ((Object)batchType.Prefab).name + " in " + ((object)Heightmap.FindBiome(val)/*cast due to .constrained prefix*/).ToString())); _planted++; _plantedSpots.Add(new Occupied { Position = val, Radius = num }); _plantedByFamily[batchType.Family] = (_plantedByFamily.TryGetValue(batchType.Family, out var value) ? value : 0) + 1; SetStatus(Text.Of("$dw_status_planting", batchType.Piece.m_name)); } _phase = Phase.Plan; return true; } private bool StartReturn() { HashSet<string> names = PlantCatalogue.TreeSeedNames; if (!base.Logistics.BeginDeposit((ItemData i) => names.Contains(i.m_shared.m_name), ChestKind.Input)) { EndRound(finished: true); return false; } _phase = Phase.Return; SetStatus("$dw_status_returning_seeds"); return true; } private bool Return(float dt) { switch (base.Logistics.Step(dt)) { case LogisticsResult.Moving: return true; case LogisticsResult.Failed: EndRound(finished: true); return false; default: if (base.Logistics.Transferred > 0 && CarryingSeeds()) { return StartReturn(); } EndRound(finished: true); return false; } } } } namespace DvergrWorkers.Roles.Repair { public class RepairWorker : WorkerBrain { private enum Phase { Walking, Windup, Recover } private const float WindupTime = 0.5f; private const float RecoverTime = 1.1f; private Phase _phase; private float _phaseTimer; private readonly List<WearNTear> _queue = new List<WearNTear>(); private readonly HashSet<WearNTear> _failed = new HashSet<WearNTear>(); private WearNTear _current; private int _repairedThisRound; private int _repairedLastRound; private const int MaxPicksPerFrame = 2; internal override WorkerRole Role => WorkerRoles.Repair; protected override string IdleStatus() { if (_repairedLastRound <= 0) { return "$dw_status_idle"; } return Text.Of("$dw_status_idle_repaired", _repairedLastRound); } protected override void OnRoundEnded(bool finished) { _queue.Clear(); _current = null; _repairedLastRound = _repairedThisRound; } protected override bool BeginRound() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) _queue.Clear(); _failed.Clear(); _repairedThisRound = 0; foreach (WearNTear allInstance in WearNTear.GetAllInstances()) { if ((Object)(object)allInstance != (Object)null && InJobArea(((Component)allInstance).transform.position) && NeedsRepair(allInstance)) { _queue.Add(allInstance); } } if (_queue.Count == 0) { _repairedLastRound = 0; return false; } base.Equipment.EquipTool(); _current = null; _phase = Phase.Walking; DvergrWorkersPlugin.Log.LogInfo((object)("Repair round started with " + _queue.Count + " damaged pieces")); return true; } private static bool NeedsRepair(WearNTear wnt) { if ((Object)(object)wnt == (Object)null || (Object)(object)wnt.m_nview == (Object)null || !wnt.m_nview.IsValid()) { return false; } Piece component = ((Component)wnt).GetComponent<Piece>(); if ((Object)(object)component != (Object)null && component.IsPlacedByPlayer()) { return wnt.GetHealthPercentage() < 0.999f; } return false; } protected override bool RunTask(float dt) { switch (_phase) { case Phase.Walking: return Walk(dt); case Phase.Windup: ((BaseAI)base.Ai).StopMoving(); FacePiece(); _phaseTimer -= dt; if (_phaseTimer <= 0f) { Hammer(); _phase = Phase.Recover; _phaseTimer = 1.1f; } return true; case Phase.Recover: ((BaseAI)base.Ai).StopMoving(); _phaseTimer -= dt; if (_phaseTimer <= 0f) { _current = null; _phase = Phase.Walking; } return true; default: return false; } } private bool Walk(float dt) { if ((Object)(object)_current == (Object)null && !PickNext()) { EndRound(finished: true); return false; } if (!NeedsRepair(_current)) { _current = null; return true; } switch (base.Navigator.Step(dt)) { case NavResult.InReach: case NavResult.CloseEnough: _phase = Phase.Windup; _phaseTimer = 0.5f; break; case NavResult.Failed: _failed.Add(_current); _current = null; break; } return true; } private bool PickNext() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) int num = 0; while (_queue.Count > 0) { if (num >= 2) { return true; } int num2 = -1; float num3 = float.MaxValue; for (int i = 0; i < _queue.Count; i++) { if (!((Object)(object)_queue[i] == (Object)null)) { float num4 = Vector3.Distance(((Component)_queue[i]).transform.position, ((Component)this).transform.position); if (num4 < num3) { num3 = num4; num2 = i; } } } if (num2 < 0) { _queue.Clear(); return false; } WearNTear candidate = _queue[num2]; _queue.RemoveAt(num2); if (NeedsRepair(candidate) && !_failed.Contains(candidate)) { num++; if (base.Navigator.Begin(((Object)candidate).name, (Vector3 from) => WorkerNavigator.ClosestPointOnColliders(((Component)candidate).gameObject, from), rememberFailure: true)) { _current = candidate; SetStatus(Text.Of("$dw_status_walking_to_damaged", _queue.Count + 1)); return true; } DvergrWorkersPlugin.Log.LogInfo((object)("No reachable spot next to " + ((Object)candidate).name + ", skipping")); } } return false; } private void FacePiece() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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) if (!((Object)(object)_current == (Object)null)) { Vector3 val = ((Component)_current).transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { base.Character.SetLookDir(((Vector3)(ref val)).normalized, 0f); ((BaseAI)base.Ai).LookTowards(val); } } } private void Hammer() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) if (!NeedsRepair(_current)) { return; } if (_current.Repair()) { _repairedThisRound++; SetStatus(Text.Of("$dw_status_repairing", _queue.Count)); Piece component = ((Component)_current).GetComponent<Piece>(); if ((Object)(object)component != (Object)null && component.m_placeEffect != null) { component.m_placeEffect.Create(((Component)component).transform.position, ((Component)component).transform.rotation, (Transform)null, 1f, -1, base.Character.GetZDOID()); } } base.Animation.PlaySwing(); } } } namespace DvergrWorkers.Roles.Refueler { public class RefuelerWorker : WorkerBrain { private enum Phase { Plan, Fetch, Walk, Work, Return, PickUp } private const float AddInterval = 0.35f; private const float PickUpInterval = 0.3f; private const int MaxPickUpTries = 12; private static readonly string[] FuelPrefabs = new string[7] { "Resin", "Coal", "Wood", "GreydwarfEye", "Guck", "BoneFragments", "CharredBone" }; private Phase _phase; private Component _fire; private string _fuelShared; private int _toAdd; private float _timer; private int _pickUpTries; private int _pickedUp; private bool _starved; private string _missingFuel = ""; private int _refueledThisRound; private int _refueledLastRound; private readonly HashSet<Component> _served = new HashSet<Component>(); private readonly HashSet<Component> _unreachable = new HashSet<Component>(); private readonly HashSet<string> _fuelNames = new HashSet<string>(); private static HashSet<string> _fuelSharedNames; internal override WorkerRole Role => WorkerRoles.Refueler; protected override string IdleStatus() { if (_refueledLastRound <= 0) { return "$dw_status_idle"; } return Text.Of("$dw_status_idle_refuelled", _refueledLastRound); } protected override void OnRoundEnded(bool finished) { _fire = null; _refueledLastRound = _refueledThisRound; } internal override bool WantsItem(string sharedName) { return FuelSharedNames().Contains(sharedName); } private static HashSet<string> FuelSharedNames() { if (_fuelSharedNames != null) { return _fuelSharedNames; } HashSet<string> hashSet = new HashSet<string>(); string[] fuelPrefabs = FuelPrefabs; foreach (string text in fuelPrefabs) { GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(text.Trim()) : null); ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null); if ((Object)(object)val2 != (Object)null) { hashSet.Add(val2.m_itemData.m_shared.m_name); } } if (hashSet.Count > 0) { _fuelSharedNames = hashSet; } return hashSet; } private static ZNetView View(Component fire) { Fireplace val = (Fireplace)(object)((fire is Fireplace) ? fire : null); if (val == null) { CookingStation val2 = (CookingStation)(object)((fire is CookingStation) ? fire : null); if (val2 == null) { Smelter val3 = (Smelter)(object)((fire is Smelter) ? fire : null); if (val3 == null) { return ((ShieldGenerator)(((fire is ShieldGenerator) ? fire : null)?)).m_nview; } return val3.m_nview; } return val2.m_nview; } return val.m_nview; } private static bool IsValid(Component fire) { if ((Object)(object)fire == (Object)null) { return false; } ZNetView val = View(fire); if ((Object)(object)val != (Object)null) { return val.IsValid(); } return false; } private static float Fuel(Component fire) { ShieldGenerator val = (ShieldGenerator)(object)((fire is ShieldGenerator) ? fire : null); float num = ((val != null) ? ((float)val.m_defaultFuel) : 0f); return View(fire).GetZDO().GetFloat(ZDOVars.s_fuel, num); } private static float MaxFuel(Component fire) { Fireplace val = (Fireplace)(object)((fire is Fireplace) ? fire : null); if (val == null) { CookingStation val2 = (CookingStation)(object)((fire is CookingStation) ? fire : null); if (val2 == null) { Smelter val3 = (Smelter)(object)((fire is Smelter) ? fire : null); if (val3 == null) { ShieldGenerator val4 = (ShieldGenerator)(object)((fire is ShieldGenerator) ? fire : null); if (val4 != null) { return val4.m_maxFuel; } return 0f; } return val3.m_maxFuel; } return val2.m_maxFuel; } return val.m_maxFuel; } private static List<ItemDrop> FuelItems(Component fire) { List<ItemDrop> list = new List<ItemDrop>(); Fireplace val = (Fireplace)(object)((fire is Fireplace) ? fire : null); if (val == null) { CookingStation val2 = (CookingStation)(object)((fire is CookingStation) ? fire : null); if (val2 == null) { Smelter val3 = (Smelter)(object)((fire is Smelter) ? fire : null); if (val3 == null) { ShieldGenerator val4 = (ShieldGenerator)(object)((fire is ShieldGenerator) ? fire : null); if (val4 != null) { list.AddRange(val4.m_fuelItems); } } else { list.Add(val3.m_fuelItem); } } else { list.Add(val2.m_fuelItem); } } else { list.Add(val.m_fuelItem); } list.RemoveAll((ItemDrop item) => (Object)(object)item == (Object)null); return list; } private ItemDrop FuelItem(Component fire) { ItemDrop val = null; foreach (ItemDrop item in FuelItems(fire)) { if (IsAllowedFuel(item)) { if (SupplyAt(fire, item.m_itemData.m_shared.m_name) > 0) { return item; } if (val == null) { val = item; } } } return val; } private static bool IsAllowedFuel(ItemDrop item) { return Array.IndexOf(FuelPrefabs, ((Object)((Component)item).gameObject).name.Trim()) >= 0; } private static string PrefabOf(Component fire) { return Utils.GetPrefabName(((Component)View(fire)).gameObject); } private string FuelShared(Component fire) { return FuelItem(fire).m_itemData.m_shared.m_name; } private bool IsFuel(ItemData item) { if (item != null) { return _fuelNames.Contains(item.m_shared.m_name); } return false; } private static int Room(Component fire) { float num = Fuel(fire); float num2 = MaxFuel(fire); float num3 = num2 * WorkerConfig.RefuelBelow.Value; if (!(num <= num3)) { return 0; } return Mathf.FloorToInt(num2 - num); } private static bool IsRefillable(Component fire) { if (!IsValid(fire) || FuelItems(fire).Count == 0) { return false; } Fireplace val = (Fireplace)(object)((fire is Fireplace) ? fire : null); if (val == null) { CookingStation val2 = (CookingStation)(object)((fire is CookingStation) ? fire : null); if (val2 == null) { Smelter val3 = (Smelter)(object)((fire is Smelter) ? fire : null); if (val3 == null) { ShieldGenerator val4 = (ShieldGenerator)(object)((fire is ShieldGenerator) ? fire : null); if (val4 != null) { return val4.m_maxFuel > 0; } return false; } return val3.m_maxFuel > 0 && val3.m_maxOre == 0 && val3.m_conversion.Count == 0; } return val2.m_useFuel && val2.m_maxFuel > 0; } return !val.m_infiniteFuel && val.m_canRefill && val.m_secPerFuel > 0f && val.m_nview.GetZDO().GetInt(ZDOVars.s_state, 1) == 1; } private List<Component> FindFires() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) List<Component> list = new List<Component>(); _fuelNames.Clear(); List<Component> list2 = new List<Component>(); AddLive<Fireplace>(list2, Scene.Fireplaces.All); AddLive<CookingStation>(list2, Scene.CookingStations.All); AddLive<Smelter>(list2, Scene.Smelters.All); AddLive<ShieldGenerator>(list2, ShieldGenerator.m_instances); foreach (Component item in list2) { if (!IsRefillable(item) || !InJobArea(item.transform.position) || (Object)(object)FuelItem(item) == (Object)null) { continue; } Piece componentInParent = item.GetComponentInParent<Piece>(); if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsPlacedByPlayer()) { continue; } list.Add(item); foreach (ItemDrop item2 in FuelItems(item)) { if (IsAllowedFuel(item2)) { _fuelNames.Add(item2.m_itemData.m_shared.m_name); } } } return list; } private static void AddLive<T>(List<Component> into, List<T> fires) where T : Component { foreach (T fire in fires) { if (SceneObjects<T>.IsLive(fire)) { into.Add((Component)(object)fire); } } } private int Supply(string sharedName) { return base.Logistics.Carried.CountItems(sharedName, -1, true) + base.Logistics.AvailableTo(sharedName); } private static int GroundAt(Component fire, string sharedName) { return GroundItems.CountNear(((Component)View(fire)).gameObject, sharedName); } private int SupplyAt(Component fire, string sharedName) { return Supply(sharedName) + GroundAt(fire, sharedName); } private bool CarryingFuel() { foreach (ItemData allItem in base.Logistics.Carried.GetAllItems()) { if (IsFuel(allItem)) { return true; } } return false; } protected override bool BeginRound() { _served.Clear(); _unreachable.Clear(); _starved = false; _missingFuel = ""; _refueledThisRound = 0; _fire = null; List<Component> list = FindFires(); bool flag = false; foreach (Component item in list) { if (Room(item) > 0) { if (SupplyAt(item, FuelShared(item)) > 0) { flag = true; break; } _starved = true; _missingFuel = FuelName(item); } } if (!flag) { _refueledLastRound = 0; base.IdleNote = (_starved ? Text.Of("$dw_status_waiting_for", _missingFuel) : null); return false; } base.Equipment.EquipTool(); _phase = Phase.Plan; DvergrWorkersPlugin.Log.LogInfo((object)"Refueler round started"); return true; } private string FuelName(Component fire) { return FuelItem(fire).m_itemData.m_shared.m_name; } protected override bool RunTask(float dt) { return _phase switch { Phase.Plan => Plan(), Phase.Fetch => Fetch(dt), Phase.Walk => Walk(dt), Phase.Work => Work(dt), Phase.Return => Return(dt), Phase.PickUp => PickUp(dt), _ => false, }; } private bool Plan() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) List<Component> list = FindFires(); Component val = null; float num = float.MaxValue; foreach (Component item in list) { if (_served.Contains(item) || _unreachable.Contains(item) || Room(item) <= 0) { continue; } if (SupplyAt(item, FuelShared(item)) <= 0) { _starved = true; _missingFuel = FuelName(item); continue; } float num2 = Vector3.Distance(item.transform.position, ((Component)this).transform.position); if (num2 < num) { num = num2; val = item; } } if ((Object)(object)val == (Object)null) { if (CarryingFuel()) { return StartReturn(); } if (_refueledThisRound == 0 && _starved) { base.IdleNote = Text.Of("$dw_status_waiting_for", _missingFuel); } EndRound(finished: true); return false; } _fire = val; _fuelShared = FuelShared(val); int num3 = 0; foreach (Component item2 in list) { if (!_served.Contains(item2) && !_unreachable.Contains(item2) && FuelShared(item2) == _fuelShared) { num3 += Math.Max(0, Room(item2)); } } int num4 = GroundAt(val, _fuelShared); int num5 = Math.Min(num3 - num4, Supply(_fuelShared)) - base.Logistics.Carried.CountItems(_fuelShared, -1, true); _toAdd = Math.Min(Room(val), Usable()); if (num5 > 0) { string shared = _fuelShared; if (base.Logistics.BeginFetchAny((ItemData i) => i.m_shared.m_name == shared, num5)) { _phase = Phase.Fetch; SetStatus("$dw_status_fetching_fuel"); return true; } DvergrWorkersPlugin.Log.LogInfo((object)("Refueler fetch failed: " + Text.Show(base.Logistics.Reason))); } return BeginWalk(); } private bool Fetch(float dt) { switch (base.Logistics.Step(dt)) { case LogisticsResult.Moving: return true; case LogisticsResult.Failed: DvergrWorkersPlugin.Log.LogInfo((object)("Refueler fetch failed: " + Text.Show(base.Logistics.Reason))); break; } _toAdd = (IsValid(_fire) ? Math.Min(Room(_fire), Usable()) : 0); return BeginWalk(); } private int Usable() { return base.Logistics.Carried.CountItems(_fuelShared, -1, true) + GroundAt(_fire, _fuelShared); } private bool BeginWalk() { if (!IsValid(_fire) || _toAdd <= 0) { if ((Object)(object)_fire != (Object)null) { _unreachable.Add(_fire); } _phase = Phase.Plan; return true; } Component fire = _fire; if (!base.Navigator.Begin(PrefabOf(fire), (Vector3 from) => WorkerNavigator.ClosestPointOnColliders(((Component)View(fire)).gameObject, from), rememberFailure: true)) { DvergrWorkersPlugin.Log.LogInfo((object)("No reachable spot next to " + PrefabOf(fire) + ", skipping")); _unreachable.Add(fire); _phase = Phase.Plan; return true; } _phase = Phase.Walk; SetStatus(Text.Of("$dw_status_walking_to_the", Text.NameOf(((Component)View(fire)).gameObject))); return true; } private bool Walk(float dt) { if (!IsValid(_fire)) { _phase = Phase.Plan; return true; } switch (base.Navigator.Step(dt)) { case NavResult.InReach: case NavResult.CloseEnough: View(_fire).ClaimOwnership(); _phase = Phase.PickUp; _pickUpTries = 0; _pickedUp = 0; _timer = 0.2f; SetStatus(Text.Of("$dw_status_refuelling", Text.NameOf(((Component)View(_fire)).gameObject))); break; case NavResult.Failed: _unreachable.Add(_fire); _phase = Phase.Plan; break; } return true; } private bool PickUp(float dt) { if (!IsValid(_fire)) { _phase = Phase.Plan; return true; } ((BaseAI)base.Ai).StopMoving(); _timer -= dt; if (_timer > 0f) { return true; } _timer = 0.3f; int num = _toAdd - _pickedUp; ItemDrop val = ((num > 0) ? GroundItems.FirstNear(((Component)View(_fire)).gameObject, _fuelShared) : null); if ((Object)(object)val == (Object)null || ++_pickUpTries > 12) { _phase = Phase.Work; _timer = 0.1f; return true; } int num2 = GroundItems.Take(base.Humanoid, val, num); if (num2 > 0) { _pickedUp += num2; _pickUpTries = 0; base.Animation.PlayPickup(); } return true; } private bool Work(float dt) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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) if (!IsValid(_fire)) { _phase = Phase.Plan; return true; } ((BaseAI)base.Ai).StopMoving(); Vector3 val = _fire.transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { base.Character.SetLookDir(((Vector3)(ref val)).normalized, 0f); ((BaseAI)base.Ai).LookTowards(val); } _timer -= dt; if (_timer > 0f) { return true; } _timer = 0.35f; ItemData val2 = null; foreach (ItemData allItem in base.Logistics.Carried.GetAllItems()) { if (allItem.m_shared.m_name == _fuelShared) { val2 = allItem; break; } } if (val2 == null || _toAdd <= 0 || (float)Mathf.CeilToInt(Fuel(_fire)) >= MaxFuel(_fire)) { _served.Add(_fire); _phase = Phase.Plan; return true; } base.Logistics.Carried.RemoveItem(val2, 1); View(_fire).InvokeRPC("RPC_AddFuel", Array.Empty<object>()); _toAdd--; _refueledThisRound++; return true; } private bool StartReturn() { if (!base.Logistics.BeginDeposit(IsFuel, ChestKind.Input)) { EndRound(finished: true); return false; } _phase = Phase.Return; SetStatus("$dw_status_returning_fuel"); return true; } private bool Return(float dt) { switch (base.Logistics.Step(dt)) { case LogisticsResult.Moving: return true; case LogisticsResult.Failed: EndRound(finished: true); return false; default: if (base.Logistics.Transferred > 0 && CarryingFuel()) { return StartReturn(); } EndRound(finished: true); return false; } } } } namespace DvergrWorkers.Roles.MachineTender { public class EitrWorker : MachineTenderWorker { private enum TapStage { Walk, Tap, Collect } private const string SapName = "$item_sap"; private const float TapWait = 0.8f; private const float CollectInterval = 0.3f; private const int MaxCollectTries = 12; private const float DropRadius = 3.5f; private readonly HashSet<SapCollector> _tapped = new HashSet<SapCollector>(); private readonly HashSet<SapCollector> _unreachableTaps = new HashSet<SapCollector>(); private SapCollector _extractor; private TapStage _stage; private float _timer; private int _collectTries; internal override WorkerRole Role => WorkerRoles.Eitr; protected override string AllowedMachines => "eitrrefinery"; protected override string NoMachinesNote => "$dw_status_no_eitr_refinery"; protected override bool IsSurplus(ItemData item) { return item.m_shared.m_name == "$item_sap"; } protected override void OnRoundEnded(bool finished) { base.OnRoundEnded(finished); _extractor = null; } private static ZNetView ViewOf(SapCollector extractor) { return ((Component)extractor).GetComponent<ZNetView>(); } private static string SpawnedName(SapCollector extractor) { if (!((Object)(object)extractor.m_spawnItem != (Object)null)) { return "$item_sap"; } return extractor.m_spawnItem.m_itemData.m_shared.m_name; } private static IEnumerable<ItemDrop> SapDropsNear(SapCollector extractor) { if ((Object)(object)extractor.m_spawnPoint == (Object)null) { yield break; } string name = SpawnedName(extractor); foreach (ItemDrop s_instance in ItemDrop.s_instances) { if ((Object)(object)s_instance != (Object)null && s_instance.m_itemData != null && s_instance.m_itemData.m_shared.m_name == name && Vector3.Distance(((Component)s_instance).transform.position, extractor.m_spawnPoint.position) < 3.5f) { yield return s_instance; } } } private static int SapLevel(SapCollector extractor) { ZNetView val = ViewOf(extractor); if (!((Object)(object)val != (Object)null) || !val.IsValid()) { return 0; } return val.GetZDO().GetInt(ZDOVars.s_level, 0); } private static bool HasSap(SapCollector extractor) { if (SapLevel(extractor) > 0) { return true; } using (IEnumerator<ItemDrop> enumerator = SapDropsNear(extractor).GetEnumerator()) { if (enumerator.MoveNext()) { _ = enumerator.Current; return true; } } return false; } private SapCollector NextExtractor() { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) SapCollector result = null; float num = float.MaxValue; foreach (SapCollector item in Scene.SapCollectors.All) { ZNetView val = (SceneObjects<SapCollector>.IsLive(item) ? ViewOf(item) : null); if (!((Object)(object)val == (Object)null) && val.IsValid() && InJobArea(((Component)item).transform.position) && !_tapped.Contains(item) && !_unreachableTaps.Contains(item) && HasSap(item) && (!((Object)(object)item.m_spawnItem != (Object)null) || base.Logistics.Carried.CanAddItem(item.m_spawnItem.m_itemData, 1))) { float num2 = Vector3.Distance(((Component)item).transform.position, ((Component)this).transform.position); if (num2 < num) { num = num2; result = item; } } } return result; } protected override bool BeginGather() { _tapped.Clear(); _unreachableTaps.Clear(); _extractor = null; return (Object)(object)NextExtractor() != (Object)null; } protected override bool Gather(float dt) { if ((Object)(object)_extractor == (Object)null) { _extractor = NextExtractor(); if ((Object)(object)_extractor != (Object)null) { return BeginWalkToExtractor(); } return false; } if (!Object.op_Implicit((Object)(object)_extractor) || !ViewOf(_extractor).IsValid()) { _extractor = null; return true; } switch (_stage) { case TapStage.Walk: WalkToExtractor(dt); break; case TapStage.Tap: Face(); if ((_timer -= dt) <= 0f) { Tap(); } break; case TapStage.Collect: Face(); if ((_timer -= dt) <= 0f) { CollectOne(); } break; } return true; } private bool BeginWalkToExtractor() { SapCollector extractor = _extractor; if (!base.Navigator.Begin("sap extractor", (Vector3 from) => WorkerNavigator.ClosestPointOnColliders(((Component)extractor).gameObject, from))) { DvergrWorkersPlugin.Log.LogInfo((object)"No reachable spot next to a sap extractor, skipping"); _unreachableTaps.Add(extractor); _extractor = null; return true; } _stage = TapStage.Walk; SetStatus("$dw_status_walking_to_sap_extractor"); return true; } private void WalkToExtractor(float dt) { switch (base.Navigator.Step(dt)) { case NavResult.InReach: case NavResult.CloseEnough: ViewOf(_extractor).ClaimOwnership(); _stage = TapStage.Tap; _timer = 0.2f; SetStatus("$dw_status_tapping_sap_extractor"); break; case NavResult.Failed: _unreachableTaps.Add(_extractor); _extractor = null; break; } } private void Tap() { if (SapLevel(_extractor) > 0) { ViewOf(_extractor).InvokeRPC("RPC_Extract", Array.Empty<object>()); base.Animation.PlaySwing(); _timer = 0.8f; } else { _timer = 0f; } _stage = TapStage.Collect; _collectTries = 0; } private void CollectOne() { _timer = 0.3f; ItemDrop val = null; using (IEnumerator<ItemDrop> enumerator = SapDropsNear(_extractor).GetEnumerator()) { if (enumerator.MoveNext()) { val = enumerator.Current; } } if ((Object)(object)val == (Object)null || ++_collectTries > 12) { _tapped.Add(_extractor); _extractor = null; return; } val.RequestOwn(); if (base.Humanoid.Pickup(((Component)val).gameObject, false, false)) { _collectTries = 0; base.Animation.PlayPickup(); } } private void Face() { //IL_0016: 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_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) //IL_004e: 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) ((BaseAI)base.Ai).StopMoving(); Vector3 val = ((Component)_extractor).transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { base.Character.SetLookDir(((Vector3)(ref val)).normalized, 0f); ((BaseAI)base.Ai).LookTowards(val); } } } pu