warvulture
This commit is contained in:
parent
8580d65a56
commit
0aa1dc4dc8
19 changed files with 2432 additions and 24 deletions
292
JotunnModStub/Butler/BoneServant.cs
Normal file
292
JotunnModStub/Butler/BoneServant.cs
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
using HarmonyLib;
|
||||
using Jotunn.Configs;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The two Bone Servants and their tables. Servants that work the stations around them and never
|
||||
/// lift a hand against anything.
|
||||
///
|
||||
/// TWO TRADES, and that was the first thing the working version asked for. One servant serving a
|
||||
/// whole yard spends its life walking: with the kitchen at one edge of the circle and the furnaces
|
||||
/// at the other, travel eats the margin that keeps food off the fire. So there is a SMITH for the
|
||||
/// Smelter family and a COOK for cooking stations and mead, each with its own table, each with its
|
||||
/// own twenty-metre circle - and the two circles may sit on top of each other, because the servants
|
||||
/// never look at the same station. PieceDensityLimit counts by prefab name, so "no second table
|
||||
/// within forty metres" keeps smith away from smith and cook away from cook, and needed no change
|
||||
/// at all to let a smith and a cook stand side by side.
|
||||
///
|
||||
/// The smith keeps the ORIGINAL prefab names, BoneServant and ServantTable. That is not tidiness -
|
||||
/// it means a table already standing in a test world keeps working and keeps its servant instead of
|
||||
/// becoming a missing prefab at the next load.
|
||||
///
|
||||
/// TWO PREFABS EACH, forced the same way the sentry's are: a Character cannot sit in the hammer's
|
||||
/// piece table, so the buildable thing is the table and the servant is instantiated by it. Unlike
|
||||
/// the sentry there is no seed piece to throw away, because here the table is not scaffolding - it
|
||||
/// is the anchor, the summoning point and the only interface the feature has.
|
||||
///
|
||||
/// WHAT WAS DELIBERATELY NOT REUSED. The design said the servant would be a RaisedThrall, and it is
|
||||
/// not. RaisedThrall brings the anchor, the leash and the withering, all of which are wanted - but
|
||||
/// it also brings RaisedThrallInteractPatch, which turns E on the creature into a follow command.
|
||||
/// A servant that can be told to follow you out of its own circle is a servant that stops serving,
|
||||
/// and "E does nothing on the servant" was decided explicitly. So the useful half is reused as a
|
||||
/// static - RaisedThrall.RegisterStation / StationStandsAt, which is what makes the table findable -
|
||||
/// and the anchor and wither clock are thirty lines inside BoneServantAI. The alternative was
|
||||
/// editing RaisedThrall.cs, which is shared with five other chains.
|
||||
/// </summary>
|
||||
public static class BoneServant
|
||||
{
|
||||
// The smith inherits the names the single servant had, so nothing already built is orphaned.
|
||||
public const string SmithName = "BoneServant";
|
||||
public const string SmithTableName = "ServantTable";
|
||||
public const string SmithDisplay = "Bone Smith";
|
||||
public const string SmithTableDisplay = "Smith's Table";
|
||||
|
||||
public const string CookName = "BoneCook";
|
||||
public const string CookTableName = "CookTable";
|
||||
public const string CookDisplay = "Bone Cook";
|
||||
public const string CookTableDisplay = "Cook's Table";
|
||||
|
||||
/// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the
|
||||
/// point here is to have none at all.</summary>
|
||||
private const string ServantSource = "Skeleton_NoArcher";
|
||||
|
||||
public const float Health = 100f;
|
||||
|
||||
/// <summary>Two circles of twenty metres cannot overlap if the tables are forty apart, which is
|
||||
/// how the question of two servants of the SAME trade fighting over one chest was answered - by
|
||||
/// making the situation impossible to build rather than by sharing state between them.</summary>
|
||||
public const float TableSpacing = 40f;
|
||||
|
||||
private const float TableScale = 0.8f;
|
||||
|
||||
/// <summary>
|
||||
/// One skull, one wishbone, eight stone - the same price for both tables.
|
||||
///
|
||||
/// The skull is TrophySkeleton and NOT this mod's own CursedSkull, and that is forced rather
|
||||
/// than chosen: the cursed skull is bought from the Skeleton faction's merchant, so building it
|
||||
/// into the cook's price would make the cook unbuildable by the only race allowed to build it.
|
||||
/// A skeleton trophy is a skull anyone can go and get.
|
||||
///
|
||||
/// The wishbone is a real cost and worth knowing about: it is Bonemass's drop and the only
|
||||
/// treasure-finder in the game, so a standing table keeps yours locked up. Recovered in full
|
||||
/// when the table is removed, like every other recipe in this mod.
|
||||
/// </summary>
|
||||
private static RequirementConfig[] Recipe()
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
new RequirementConfig("TrophySkeleton", 1, 0, true),
|
||||
new RequirementConfig("Wishbone", 1, 0, true),
|
||||
new RequirementConfig("Stone", 8, 0, true),
|
||||
};
|
||||
}
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge))
|
||||
{
|
||||
RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge,
|
||||
"A slab of bone and slate, dusted with ore. Something patient waits by the fires.",
|
||||
"Coal");
|
||||
|
||||
PieceDensityLimit.Register(SmithTableName, TableSpacing, 1,
|
||||
"Another smith's table stands within forty paces. One smith to a yard.");
|
||||
|
||||
// Two races, and it is the wider of the two locks: the Skeleton raises the dead to work
|
||||
// for it, and Skadi's hold is a forge under ice.
|
||||
PieceDensityLimit.RegisterGate(SmithTableName, (player, position) =>
|
||||
{
|
||||
if (SkeletonRace.IsSkeleton() || SkadiRace.IsLocalSkadi()) return true;
|
||||
|
||||
if (player != null)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
"The bones do not answer to your blood.");
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen))
|
||||
{
|
||||
RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen,
|
||||
"A slab of bone and slate, worn smooth. Something patient waits by the hearth.",
|
||||
"CookedMeat");
|
||||
|
||||
PieceDensityLimit.Register(CookTableName, TableSpacing, 1,
|
||||
"Another cook's table stands within forty paces. One cook to a yard.");
|
||||
|
||||
// Skadi alone. A hearth kept by something dead is hers, not the Skeleton's.
|
||||
PieceDensityLimit.RegisterGate(CookTableName, (player, position) =>
|
||||
{
|
||||
if (SkadiRace.IsLocalSkadi()) return true;
|
||||
|
||||
if (player != null)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
"Only Skadi's hearth is kept by the dead.");
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the servants
|
||||
|
||||
private static bool RegisterServant(string prefabName, string displayName, ButlerFamily family)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, ServantSource);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Butler] Could not clone {ServantSource}; " +
|
||||
$"{displayName} is not registered.");
|
||||
return false;
|
||||
}
|
||||
|
||||
Character character = prefab.GetComponent<Character>();
|
||||
if (character != null)
|
||||
{
|
||||
character.m_name = displayName;
|
||||
character.m_health = Health;
|
||||
character.m_faction = Character.Faction.Players;
|
||||
}
|
||||
|
||||
// Nothing in its hands, and nothing to roll for. Belt and braces with the AI prefix: the
|
||||
// code that would swing a weapon never runs, but a servant carrying a rusty sword around
|
||||
// the kitchen would still look like a mistake.
|
||||
Humanoid humanoid = prefab.GetComponent<Humanoid>();
|
||||
if (humanoid != null)
|
||||
{
|
||||
humanoid.m_defaultItems = new GameObject[0];
|
||||
humanoid.m_randomWeapon = new GameObject[0];
|
||||
humanoid.m_randomArmor = new GameObject[0];
|
||||
humanoid.m_randomShield = new GameObject[0];
|
||||
humanoid.m_randomSets = new Humanoid.ItemSet[0];
|
||||
}
|
||||
|
||||
BaseAI ai = prefab.GetComponent<BaseAI>();
|
||||
if (ai != null)
|
||||
{
|
||||
ai.m_randomMoveRange = 0f; // it never wanders: every step it takes is a decision
|
||||
ai.m_avoidFire = false; // it works next to kilns for a living
|
||||
ai.m_afraidOfFire = false;
|
||||
}
|
||||
|
||||
// A servant that dropped bones would be a bone mill, exactly as with the garrison.
|
||||
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
|
||||
{
|
||||
if (drops != null) Object.DestroyImmediate(drops);
|
||||
}
|
||||
|
||||
// Ten seconds unhurt, then two percent a second. The sentry's regeneration, whole.
|
||||
prefab.AddComponent<SkeletonSentryBehaviour>();
|
||||
|
||||
BoneServantAI servant = prefab.AddComponent<BoneServantAI>();
|
||||
servant.m_family = family;
|
||||
|
||||
PrefabManager.Instance.AddPrefab(prefab);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the tables
|
||||
|
||||
private static void RegisterTable(string pieceName, string displayName, string servantPrefab,
|
||||
ButlerFamily family, string description, string iconSource)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, "piece_cartographytable");
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Butler] Could not clone piece_cartographytable; " +
|
||||
$"the {displayName} is not registered.");
|
||||
return;
|
||||
}
|
||||
|
||||
// The MapTable trap, and it is the reason this is a blanket sweep by capability rather than
|
||||
// a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key
|
||||
// before our own Switch ever sees it and opens the shared map instead. Same bug as the
|
||||
// barrel's Container on the Fenrir trough and the Trader on the vanilla wolf; the Dvergar
|
||||
// contract bank pays for this lesson already.
|
||||
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
|
||||
{
|
||||
if (behaviour == null) continue;
|
||||
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
|
||||
Object.DestroyImmediate(behaviour);
|
||||
}
|
||||
|
||||
prefab.transform.localScale = Vector3.one * TableScale;
|
||||
|
||||
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
|
||||
table.m_switch = prefab.AddComponent<Switch>();
|
||||
table.m_switch.m_name = displayName;
|
||||
table.m_title = displayName;
|
||||
table.m_servantPrefab = servantPrefab;
|
||||
table.m_family = family;
|
||||
|
||||
Sprite icon = BorrowIcon(iconSource) ?? BorrowIcon("TrophySkeleton");
|
||||
|
||||
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
|
||||
piece.m_craftingStation = null;
|
||||
piece.m_resources = new Piece.Requirement[0];
|
||||
piece.m_name = displayName;
|
||||
piece.m_canBeRemoved = true;
|
||||
piece.m_groundPiece = true;
|
||||
piece.m_groundOnly = true;
|
||||
piece.m_icon = icon;
|
||||
|
||||
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
|
||||
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
|
||||
|
||||
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
|
||||
{
|
||||
Name = displayName,
|
||||
Description = description,
|
||||
PieceTable = PieceTables.Hammer,
|
||||
Category = PieceCategories.Crafting,
|
||||
Icon = icon,
|
||||
Requirements = Recipe(),
|
||||
}));
|
||||
}
|
||||
|
||||
public static void EnsureKnown(Player player)
|
||||
{
|
||||
if (player == null) return;
|
||||
|
||||
Traverse traverse = Traverse.Create(player);
|
||||
LearnPiece(traverse, SmithTableName);
|
||||
LearnPiece(traverse, CookTableName);
|
||||
traverse.Method("UpdateAvailablePiecesList").GetValue();
|
||||
}
|
||||
|
||||
private static void LearnPiece(Traverse player, string pieceName)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.GetPrefab(pieceName);
|
||||
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
|
||||
if (piece == null) return;
|
||||
|
||||
player.Method("AddKnownPiece", piece).GetValue();
|
||||
}
|
||||
|
||||
private static Sprite BorrowIcon(string prefabName)
|
||||
{
|
||||
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
|
||||
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
|
||||
? drop.m_itemData.m_shared.m_icons
|
||||
: null;
|
||||
return icons != null && icons.Length > 0 ? icons[0] : null;
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Player), "OnSpawned")]
|
||||
public static class BoneServantKnownPatch
|
||||
{
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
BoneServant.EnsureKnown(__instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
1286
JotunnModStub/Butler/BoneServantAI.cs
Normal file
1286
JotunnModStub/Butler/BoneServantAI.cs
Normal file
File diff suppressed because it is too large
Load diff
50
JotunnModStub/Butler/ButlerConfig.cs
Normal file
50
JotunnModStub/Butler/ButlerConfig.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using BepInEx.Configuration;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The four knobs the Bone Servant exposes, and deliberately only four.
|
||||
///
|
||||
/// Butler_BoneServant.txt sec. 14 turned down "expose everything": tick cadence, safety margins,
|
||||
/// penalty-box time and the spacing between tables are constants in the code, because they are
|
||||
/// numbers that get tuned once during the test and then never again - and every config entry is
|
||||
/// maintained forever.
|
||||
///
|
||||
/// The sigil is here for a different reason from the other three. It is a PLACEHOLDER: bone
|
||||
/// fragments stand in for a craftable sigil that only gets made if the feature leaves the test,
|
||||
/// and being able to move the mark onto another item without a rebuild is the whole point of the
|
||||
/// entry.
|
||||
/// </summary>
|
||||
public static class ButlerConfig
|
||||
{
|
||||
public static ConfigEntry<string> SigilItem;
|
||||
public static ConfigEntry<float> WorkRadius;
|
||||
public static ConfigEntry<float> FuelThreshold;
|
||||
public static ConfigEntry<float> ResummonSeconds;
|
||||
|
||||
public static void Bind(ConfigFile config)
|
||||
{
|
||||
const string section = "Butler - Bone Servant";
|
||||
|
||||
SigilItem = config.Bind(section, "Sigil Item", "BoneFragments",
|
||||
new ConfigDescription("Prefab name of the item that marks a chest as the servant's. " +
|
||||
"A chest holding at least one of these is worked from and " +
|
||||
"delivered to; every other chest is left alone. The sigil itself " +
|
||||
"is never taken and never processed."));
|
||||
|
||||
WorkRadius = config.Bind(section, "Work Radius", 20f,
|
||||
new ConfigDescription("Metres from the Servant's Table within which chests and stations " +
|
||||
"are served.", new AcceptableValueRange<float>(5f, 40f)));
|
||||
|
||||
FuelThreshold = config.Bind(section, "Fuel Threshold", 0.25f,
|
||||
new ConfigDescription("Refuel a station when its fuel drops below this fraction of its " +
|
||||
"maximum, and only while it has something to work on.",
|
||||
new AcceptableValueRange<float>(0f, 1f)));
|
||||
|
||||
ResummonSeconds = config.Bind(section, "Resummon Cooldown", 0f,
|
||||
new ConfigDescription("Seconds that must pass before a fallen servant can be raised " +
|
||||
"again. Zero is free and immediate, which is what the test runs on.",
|
||||
new AcceptableValueRange<float>(0f, 600f)));
|
||||
}
|
||||
}
|
||||
}
|
||||
496
JotunnModStub/Butler/ButlerStation.cs
Normal file
496
JotunnModStub/Butler/ButlerStation.cs
Normal file
|
|
@ -0,0 +1,496 @@
|
|||
using System;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Which servant a station belongs to.
|
||||
///
|
||||
/// The split is not cosmetic, it is the answer to the one complaint the first working version drew:
|
||||
/// with a kitchen at one edge of the circle and three furnaces at the other, a single servant spends
|
||||
/// its life walking and the margin that keeps food off the fire gets eaten by travel. Two servants
|
||||
/// with two tables in the same yard walk half as far each.
|
||||
///
|
||||
/// It also cuts the AI in half along a seam that was already there. FORGE cannot spoil - a smelter
|
||||
/// holds its ore forever and drops its own output - so the forge servant has no clock, never runs,
|
||||
/// and never pre-empts itself. All of that machinery lives on in the KITCHEN, which is the only
|
||||
/// place it was ever needed.
|
||||
/// </summary>
|
||||
public enum ButlerFamily
|
||||
{
|
||||
/// <summary>Smelter: furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
|
||||
/// refinery. Nothing here has a deadline.</summary>
|
||||
Forge,
|
||||
|
||||
/// <summary>CookingStation and Fermenter: hearths, ovens and mead. The only family with a
|
||||
/// clock.</summary>
|
||||
Kitchen,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One working station, seen through the handful of questions the servant ever asks it.
|
||||
///
|
||||
/// THREE FAMILIES, and they are not variations on a theme - they behave OPPOSITELY on output, which
|
||||
/// is the single fact the whole feature is built around (Butler_BoneServant.txt sec. 5, all of it
|
||||
/// read off assembly_valheim.dll with Cecil rather than guessed):
|
||||
///
|
||||
/// Smelter furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
|
||||
/// refinery. Its output FALLS ON THE GROUND BY ITSELF - UpdateSmelter runs
|
||||
/// RemoveOneOre -> QueueProcessed -> SpawnProcessed with nobody asking. Nothing
|
||||
/// to pull; the servant just picks the bars up.
|
||||
/// CookingStation hearth, iron cooking station, stone oven. Output STAYS IN THE SLOT and keeps
|
||||
/// cooking: Done at m_cookTime, Burnt at exactly twice it (verified: the IL
|
||||
/// literally loads m_cookTime, pushes 2 and multiplies). This is the family that
|
||||
/// can lose you food, and the only one with a clock.
|
||||
/// Fermenter mead. Output stays in until the tap is opened, and never spoils.
|
||||
///
|
||||
/// NOTHING HERE KNOWS WHAT A MATERIAL IS. Every family exposes IsItemAllowed(string) and
|
||||
/// GetItemConversion(string), matching on the PREFAB name (m_from.gameObject.name - verified), so
|
||||
/// the servant asks the station "do you take this?" instead of carrying a list of ores and crops.
|
||||
/// That is what makes it serve this mod's own stations, other races' stations, and other mods'
|
||||
/// stations without a line of code per station.
|
||||
///
|
||||
/// WHY SO MUCH REFLECTION. Every one of those question methods is PRIVATE in this build -
|
||||
/// GetQueueSize, IsItemAllowed, GetSlot, GetFuel, HaveDoneItem, IsFireLit, GetStatus, the lot - and
|
||||
/// both Status enums are private nested types, so they cannot even be named in source. The
|
||||
/// alternative was reimplementing each station's rules by reading its public m_conversion list,
|
||||
/// which would be a second copy of vanilla's logic drifting out of step at the next patch. Calling
|
||||
/// the real method through a cached MethodInfo is the smaller lie. The enum values are hard-coded
|
||||
/// as ints, and they are not guesses: Cecil reports NotDone=0, Done=1, Burnt=2 and Empty=0,
|
||||
/// Fermenting=1, Exposed=2, Ready=3.
|
||||
///
|
||||
/// Every write goes through InvokeRPC with the name the station REGISTERED, which carries the
|
||||
/// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op,
|
||||
/// which is exactly the class of bug that takes an evening to find, so the four names below were
|
||||
/// read out of each Awake() rather than remembered.
|
||||
/// </summary>
|
||||
public abstract class ButlerStation
|
||||
{
|
||||
public Component Behaviour;
|
||||
public ZNetView Nview;
|
||||
public Transform Transform;
|
||||
|
||||
public Vector3 Position { get { return Transform.position; } }
|
||||
|
||||
public ZDOID Id
|
||||
{
|
||||
get { return Nview != null && Nview.IsValid() ? Nview.GetZDO().m_uid : ZDOID.None; }
|
||||
}
|
||||
|
||||
public bool Alive { get { return Behaviour != null && Nview != null && Nview.IsValid(); } }
|
||||
|
||||
/// <summary>Wraps whichever of the three this object is, or null if it is not a station.</summary>
|
||||
public static ButlerStation From(GameObject go)
|
||||
{
|
||||
if (go == null) return null;
|
||||
|
||||
ZNetView nview = go.GetComponent<ZNetView>();
|
||||
if (nview == null || !nview.IsValid()) return null;
|
||||
|
||||
Smelter smelter = go.GetComponent<Smelter>();
|
||||
if (smelter != null) return Fill(new SmelterStation { m_smelter = smelter }, smelter, nview);
|
||||
|
||||
CookingStation cooking = go.GetComponent<CookingStation>();
|
||||
if (cooking != null) return Fill(new CookingStationStation { m_cooking = cooking }, cooking, nview);
|
||||
|
||||
Fermenter fermenter = go.GetComponent<Fermenter>();
|
||||
if (fermenter != null) return Fill(new FermenterStation { m_fermenter = fermenter }, fermenter, nview);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ButlerStation Fill(ButlerStation station, Component behaviour, ZNetView nview)
|
||||
{
|
||||
station.Behaviour = behaviour;
|
||||
station.Nview = nview;
|
||||
station.Transform = behaviour.transform;
|
||||
return station;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Taking ownership before writing is the multiplayer rule of this feature (sec. 10), and it
|
||||
/// buys a second thing that matters here: once we own the ZDO the RPC runs locally and
|
||||
/// immediately, so GetQueueSize and GetFuel answer truthfully on the very next line instead of
|
||||
/// a network round trip later.
|
||||
/// </summary>
|
||||
protected void Claim()
|
||||
{
|
||||
if (Nview != null && Nview.IsValid() && !Nview.IsOwner()) Nview.ClaimOwnership();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- what the servant asks
|
||||
|
||||
/// <summary>Which of the two servants this one belongs to.</summary>
|
||||
public abstract ButlerFamily Family { get; }
|
||||
|
||||
/// <summary>Can it work at all right now - fire lit, roof up? An inoperable station is skipped
|
||||
/// in silence, which is a decision and not an oversight (sec. 7.7).</summary>
|
||||
public abstract bool Operable { get; }
|
||||
|
||||
/// <summary>How many more items it can take. Zero means full.</summary>
|
||||
public abstract int FreeSlots { get; }
|
||||
|
||||
public abstract bool Accepts(string prefabName);
|
||||
|
||||
/// <summary>Puts one unit in. Called FreeSlots times at most, never more.</summary>
|
||||
public abstract void Add(string prefabName);
|
||||
|
||||
/// <summary>True while it has something to work on - so an empty furnace is never stoked.</summary>
|
||||
public abstract bool HasWork { get; }
|
||||
|
||||
public abstract string FuelPrefab { get; }
|
||||
|
||||
/// <summary>Units of fuel it wants right now, already filtered by the configured threshold.</summary>
|
||||
public abstract int FuelWanted { get; }
|
||||
|
||||
public abstract void AddFuel();
|
||||
|
||||
/// <summary>Something finished and needs a hand to get out. Always false for the Smelter, which
|
||||
/// throws its own output on the floor.</summary>
|
||||
public abstract bool HasOutput { get; }
|
||||
|
||||
/// <summary>Gets the finished goods onto the ground at <paramref name="at"/>, where the one
|
||||
/// pickup routine will find them.</summary>
|
||||
public abstract void PullOutput(Vector3 at);
|
||||
|
||||
/// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that
|
||||
/// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary>
|
||||
public virtual float SecondsToSpoil { get { return float.MaxValue; } }
|
||||
|
||||
// ================================================================ the private doors
|
||||
|
||||
/// <summary>
|
||||
/// Every private member of the three station classes this feature touches, resolved once.
|
||||
///
|
||||
/// Anything that fails to resolve stays null and its caller falls back to the safe answer -
|
||||
/// "cannot tell, do not act" - so a future patch that renames one method costs that one
|
||||
/// capability and a line in the log, not a servant that stands still or, worse, one that keeps
|
||||
/// pouring ore into a station it can no longer read.
|
||||
/// </summary>
|
||||
private static class Vanilla
|
||||
{
|
||||
public static readonly MethodInfo SmelterQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize");
|
||||
public static readonly MethodInfo SmelterAllowed =
|
||||
AccessTools.Method(typeof(Smelter), "IsItemAllowed", new[] { typeof(string) });
|
||||
public static readonly MethodInfo SmelterFuel = AccessTools.Method(typeof(Smelter), "GetFuel");
|
||||
public static readonly FieldInfo SmelterHaveRoof = AccessTools.Field(typeof(Smelter), "m_haveRoof");
|
||||
|
||||
public static readonly MethodInfo CookGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot");
|
||||
public static readonly MethodInfo CookEmpty = AccessTools.Method(typeof(CookingStation), "IsEmpty");
|
||||
public static readonly MethodInfo CookHaveDone = AccessTools.Method(typeof(CookingStation), "HaveDoneItem");
|
||||
public static readonly MethodInfo CookAllowed =
|
||||
AccessTools.Method(typeof(CookingStation), "IsItemAllowed", new[] { typeof(string) });
|
||||
public static readonly MethodInfo CookConversion =
|
||||
AccessTools.Method(typeof(CookingStation), "GetItemConversion", new[] { typeof(string) });
|
||||
public static readonly MethodInfo CookFuel = AccessTools.Method(typeof(CookingStation), "GetFuel");
|
||||
public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit");
|
||||
|
||||
public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus");
|
||||
public static readonly MethodInfo FermenterAllowed =
|
||||
AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(string) });
|
||||
|
||||
// CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named
|
||||
// in source, so they travel as ints. Values read from the assembly, not assumed.
|
||||
public const int CookNotDone = 0;
|
||||
public const int CookDone = 1;
|
||||
public const int CookBurnt = 2;
|
||||
|
||||
public const int FermentEmpty = 0;
|
||||
public const int FermentExposed = 2;
|
||||
public const int FermentReady = 3;
|
||||
|
||||
public static bool Call(MethodInfo method, object target, bool fallback)
|
||||
{
|
||||
if (method == null) return fallback;
|
||||
return (bool)method.Invoke(target, null);
|
||||
}
|
||||
|
||||
public static int CallInt(MethodInfo method, object target, int fallback)
|
||||
{
|
||||
if (method == null) return fallback;
|
||||
return Convert.ToInt32(method.Invoke(target, null));
|
||||
}
|
||||
|
||||
public static float CallFloat(MethodInfo method, object target, float fallback)
|
||||
{
|
||||
if (method == null) return fallback;
|
||||
return Convert.ToSingle(method.Invoke(target, null));
|
||||
}
|
||||
|
||||
public static bool Allowed(MethodInfo method, object target, string prefabName)
|
||||
{
|
||||
if (method == null || string.IsNullOrEmpty(prefabName)) return false;
|
||||
return (bool)method.Invoke(target, new object[] { prefabName });
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================ Smelter
|
||||
|
||||
private class SmelterStation : ButlerStation
|
||||
{
|
||||
public Smelter m_smelter;
|
||||
|
||||
public override ButlerFamily Family { get { return ButlerFamily.Forge; } }
|
||||
|
||||
public override bool Operable
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!m_smelter.m_requiresRoof) return true;
|
||||
if (Vanilla.SmelterHaveRoof == null) return true; // cannot tell: let it try
|
||||
return (bool)Vanilla.SmelterHaveRoof.GetValue(m_smelter);
|
||||
}
|
||||
}
|
||||
|
||||
private int Queued { get { return Vanilla.CallInt(Vanilla.SmelterQueueSize, m_smelter, int.MaxValue); } }
|
||||
|
||||
public override int FreeSlots
|
||||
{
|
||||
get { return Mathf.Max(0, m_smelter.m_maxOre - Queued); }
|
||||
}
|
||||
|
||||
public override bool Accepts(string prefabName)
|
||||
{
|
||||
return Vanilla.Allowed(Vanilla.SmelterAllowed, m_smelter, prefabName);
|
||||
}
|
||||
|
||||
public override void Add(string prefabName)
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_AddOre", prefabName);
|
||||
}
|
||||
|
||||
public override bool HasWork { get { return Queued > 0; } }
|
||||
|
||||
public override string FuelPrefab
|
||||
{
|
||||
get { return m_smelter.m_fuelItem != null ? m_smelter.m_fuelItem.gameObject.name : null; }
|
||||
}
|
||||
|
||||
public override int FuelWanted
|
||||
{
|
||||
get
|
||||
{
|
||||
if (m_smelter.m_fuelItem == null || m_smelter.m_maxFuel <= 0) return 0;
|
||||
if (!HasWork) return 0;
|
||||
|
||||
float fuel = Vanilla.CallFloat(Vanilla.SmelterFuel, m_smelter, float.MaxValue);
|
||||
if (fuel >= m_smelter.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
|
||||
|
||||
return Mathf.Max(0, Mathf.FloorToInt(m_smelter.m_maxFuel - fuel));
|
||||
}
|
||||
}
|
||||
|
||||
public override void AddFuel()
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_AddFuel");
|
||||
}
|
||||
|
||||
// The whole point of this family: nothing to collect, it drops its own.
|
||||
public override bool HasOutput { get { return false; } }
|
||||
public override void PullOutput(Vector3 at) { }
|
||||
}
|
||||
|
||||
// ================================================================ CookingStation
|
||||
|
||||
private class CookingStationStation : ButlerStation
|
||||
{
|
||||
public CookingStation m_cooking;
|
||||
|
||||
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
|
||||
|
||||
private int SlotCount
|
||||
{
|
||||
get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; }
|
||||
}
|
||||
|
||||
/// <summary>GetSlot hands back three values through out parameters, one of which is a
|
||||
/// private enum. Through reflection that means an args array and an int.</summary>
|
||||
private bool ReadSlot(int index, out string name, out float cooked, out int status)
|
||||
{
|
||||
name = null;
|
||||
cooked = 0f;
|
||||
status = Vanilla.CookNotDone;
|
||||
|
||||
if (Vanilla.CookGetSlot == null) return false;
|
||||
|
||||
object[] args = new object[] { index, null, null, null };
|
||||
Vanilla.CookGetSlot.Invoke(m_cooking, args);
|
||||
|
||||
name = args[1] as string;
|
||||
cooked = Convert.ToSingle(args[2]);
|
||||
status = Convert.ToInt32(args[3]);
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool Operable
|
||||
{
|
||||
get { return !m_cooking.m_requireFire || Vanilla.Call(Vanilla.CookFireLit, m_cooking, false); }
|
||||
}
|
||||
|
||||
public override int FreeSlots
|
||||
{
|
||||
get
|
||||
{
|
||||
int free = 0;
|
||||
for (int i = 0; i < SlotCount; i++)
|
||||
{
|
||||
string name;
|
||||
float cooked;
|
||||
int status;
|
||||
if (!ReadSlot(i, out name, out cooked, out status)) return 0;
|
||||
if (string.IsNullOrEmpty(name)) free++;
|
||||
}
|
||||
return free;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool Accepts(string prefabName)
|
||||
{
|
||||
return Vanilla.Allowed(Vanilla.CookAllowed, m_cooking, prefabName);
|
||||
}
|
||||
|
||||
public override void Add(string prefabName)
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_AddItem", prefabName);
|
||||
}
|
||||
|
||||
public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } }
|
||||
|
||||
public override string FuelPrefab
|
||||
{
|
||||
get
|
||||
{
|
||||
return m_cooking.m_useFuel && m_cooking.m_fuelItem != null
|
||||
? m_cooking.m_fuelItem.gameObject.name
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
public override int FuelWanted
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!m_cooking.m_useFuel || m_cooking.m_fuelItem == null || m_cooking.m_maxFuel <= 0) return 0;
|
||||
if (!HasWork) return 0;
|
||||
|
||||
float fuel = Vanilla.CallFloat(Vanilla.CookFuel, m_cooking, float.MaxValue);
|
||||
if (fuel >= m_cooking.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
|
||||
|
||||
return Mathf.Max(0, Mathf.FloorToInt(m_cooking.m_maxFuel - fuel));
|
||||
}
|
||||
}
|
||||
|
||||
public override void AddFuel()
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_AddFuel");
|
||||
}
|
||||
|
||||
public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } }
|
||||
|
||||
/// <summary>
|
||||
/// ONE per done slot, and the 1 is not a stylistic choice. RPC_RemoveDoneItem spawns the
|
||||
/// item <c>amount</c> times PER SLOT (verified in the IL: the inner loop runs to the
|
||||
/// argument), so passing anything above 1 would not collect faster - it would print money.
|
||||
/// </summary>
|
||||
public override void PullOutput(Vector3 at)
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is
|
||||
/// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its
|
||||
/// remaining half is all that stands between dinner and charcoal.
|
||||
///
|
||||
/// GetItemConversion is asked with whatever name the slot currently holds, which is the raw
|
||||
/// item before Done and the COOKED one after: CookingStation.GetItemConversion matches on
|
||||
/// both m_from and m_to (verified), so the cook time is readable in either phase.
|
||||
/// </summary>
|
||||
public override float SecondsToSpoil
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Vanilla.CookConversion == null) return float.MaxValue;
|
||||
|
||||
float soonest = float.MaxValue;
|
||||
|
||||
for (int i = 0; i < SlotCount; i++)
|
||||
{
|
||||
string name;
|
||||
float cooked;
|
||||
int status;
|
||||
if (!ReadSlot(i, out name, out cooked, out status)) break;
|
||||
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
if (status == Vanilla.CookBurnt) continue; // already lost, no hurry
|
||||
|
||||
CookingStation.ItemConversion conversion =
|
||||
Vanilla.CookConversion.Invoke(m_cooking, new object[] { name })
|
||||
as CookingStation.ItemConversion;
|
||||
if (conversion == null) continue;
|
||||
|
||||
float left = conversion.m_cookTime * 2f - cooked;
|
||||
if (left < soonest) soonest = left;
|
||||
}
|
||||
|
||||
return soonest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================ Fermenter
|
||||
|
||||
private class FermenterStation : ButlerStation
|
||||
{
|
||||
public Fermenter m_fermenter;
|
||||
|
||||
/// <summary>Mead goes with the food. It has no deadline of its own, so it costs the cook
|
||||
/// nothing beyond one more thing to fill and one more tap to open.</summary>
|
||||
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
|
||||
|
||||
private int Status
|
||||
{
|
||||
get { return Vanilla.CallInt(Vanilla.FermenterStatus, m_fermenter, Vanilla.FermentExposed); }
|
||||
}
|
||||
|
||||
public override bool Operable { get { return Status != Vanilla.FermentExposed; } }
|
||||
|
||||
public override int FreeSlots { get { return Status == Vanilla.FermentEmpty ? 1 : 0; } }
|
||||
|
||||
public override bool Accepts(string prefabName)
|
||||
{
|
||||
return Vanilla.Allowed(Vanilla.FermenterAllowed, m_fermenter, prefabName);
|
||||
}
|
||||
|
||||
public override void Add(string prefabName)
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_AddItem", prefabName);
|
||||
}
|
||||
|
||||
public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } }
|
||||
|
||||
public override string FuelPrefab { get { return null; } }
|
||||
public override int FuelWanted { get { return 0; } }
|
||||
public override void AddFuel() { }
|
||||
|
||||
public override bool HasOutput { get { return Status == Vanilla.FermentReady; } }
|
||||
|
||||
/// <summary>Opens the tap. The bottles are not out yet when this returns - DelayedTap waits
|
||||
/// m_tapDelay for the animation - so the servant collects them on a later pass, which the
|
||||
/// pickup sweep handles without knowing anything about fermenting.</summary>
|
||||
public override void PullOutput(Vector3 at)
|
||||
{
|
||||
Claim();
|
||||
Nview.InvokeRPC("RPC_Tap");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
170
JotunnModStub/Butler/ServantTableBehaviour.cs
Normal file
170
JotunnModStub/Butler/ServantTableBehaviour.cs
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// A servant's table: an anchor, a summoning point and the feature's only window. One class serves
|
||||
/// both trades - what changes between the smith's and the cook's is three fields set at
|
||||
/// registration, not behaviour.
|
||||
///
|
||||
/// It does no work of its own. Everything it knows it asks the servant, and everything the servant
|
||||
/// says it says here - the hover text is the ONE feedback channel this feature has, by decision, so
|
||||
/// a servant that has stopped must be able to explain itself from a line of text or it is
|
||||
/// indistinguishable from a broken mod.
|
||||
///
|
||||
/// E RAISES, and that is all E does. There is no pause switch and no automatic re-forming: a fallen
|
||||
/// servant leaves the table empty until somebody notices. That was chosen over a sixty-second
|
||||
/// respawn on the grounds that a death nobody notices is a death that might as well not happen.
|
||||
///
|
||||
/// It registers itself with RaisedThrall's station list, which is what BoneServantAI's wither clock
|
||||
/// asks when it wants to know whether its table is still standing. That list is the only part of
|
||||
/// the thrall machinery this feature uses.
|
||||
/// </summary>
|
||||
public class ServantTableBehaviour : MonoBehaviour
|
||||
{
|
||||
public Switch m_switch;
|
||||
|
||||
/// <summary>Set on the prefab at registration, so both travel to every instance.</summary>
|
||||
public string m_title = "Servant's Table";
|
||||
public string m_servantPrefab = BoneServant.SmithName;
|
||||
public ButlerFamily m_family = ButlerFamily.Forge;
|
||||
|
||||
private const string KeyLastRaise = "RoV_butlerRaisedAt";
|
||||
|
||||
/// <summary>Where the servant stands up: in front of the table, clear of the mesh.</summary>
|
||||
private const float RaiseOffset = 1.2f;
|
||||
|
||||
private ZNetView m_nview;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
RaisedThrall.RegisterStation(transform);
|
||||
|
||||
m_nview = GetComponent<ZNetView>();
|
||||
|
||||
if (m_switch != null)
|
||||
{
|
||||
m_switch.m_onUse = OnUse;
|
||||
m_switch.m_onHover = Hover;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
RaisedThrall.UnregisterStation(transform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- interaction
|
||||
|
||||
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
|
||||
{
|
||||
Player player = user as Player;
|
||||
if (player == null) return false;
|
||||
|
||||
if (item != null)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Servant() != null)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "It is already at work.");
|
||||
return false;
|
||||
}
|
||||
|
||||
float wait = Cooldown();
|
||||
if (wait > 0f)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
$"The bones are not ready. {Mathf.CeilToInt(wait)}s.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return Raise(player);
|
||||
}
|
||||
|
||||
private bool Raise(Player player)
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid()) return false;
|
||||
if (ZNetScene.instance == null) return false;
|
||||
|
||||
GameObject prefab = ZNetScene.instance.GetPrefab(m_servantPrefab);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised.");
|
||||
player.Message(MessageHud.MessageType.Center, "Nothing answers.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Owner-only, so in multiplayer exactly one servant stands up rather than one per client.
|
||||
m_nview.ClaimOwnership();
|
||||
|
||||
Vector3 at = transform.position + transform.forward * RaiseOffset;
|
||||
GameObject spawned = Object.Instantiate(prefab, at, Quaternion.identity);
|
||||
|
||||
BoneServantAI servant = spawned.GetComponent<BoneServantAI>();
|
||||
if (servant != null) servant.Bind(transform.position);
|
||||
|
||||
if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks);
|
||||
|
||||
player.Message(MessageHud.MessageType.Center, "The servant rises.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Seconds still to wait, or zero. Kept in world time so logging out does not pay it off
|
||||
/// for free - and configured to zero for the test, where it is simply never in the way.</summary>
|
||||
private float Cooldown()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0f;
|
||||
|
||||
float required = ButlerConfig.ResummonSeconds.Value;
|
||||
if (required <= 0f) return 0f;
|
||||
|
||||
long stamp = m_nview.GetZDO().GetLong(KeyLastRaise, 0L);
|
||||
if (stamp == 0L) return 0f;
|
||||
|
||||
double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds;
|
||||
return Mathf.Max(0f, required - (float)elapsed);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the hover
|
||||
|
||||
private string Hover()
|
||||
{
|
||||
BoneServantAI servant = Servant();
|
||||
|
||||
if (servant == null)
|
||||
{
|
||||
return m_title + "\nNo servant stands here.\n" +
|
||||
"[<color=yellow><b>$KEY_Use</b></color>] Raise one";
|
||||
}
|
||||
|
||||
string status = servant.Status;
|
||||
if (string.IsNullOrEmpty(status)) status = "Waiting.";
|
||||
|
||||
return m_title + "\n" + status;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This table's servant, if it is alive and loaded.
|
||||
///
|
||||
/// Matched by anchor rather than by a stored id, so a table rebuilt on the same spot adopts the
|
||||
/// servant already standing there - and by TRADE as well, because a smith's table and a cook's
|
||||
/// table are allowed to stand a metre apart and must not adopt each other's servant.
|
||||
/// </summary>
|
||||
private BoneServantAI Servant()
|
||||
{
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character.IsDead()) continue;
|
||||
|
||||
BoneServantAI servant = character.GetComponent<BoneServantAI>();
|
||||
if (servant == null || servant.m_family != m_family) continue;
|
||||
if (servant.IsBoundTo(transform.position)) return servant;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue