feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones

Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Ferdinando 2026-08-08 14:58:43 +02:00
commit 5c5b8c34d2
20 changed files with 3784 additions and 17 deletions

View file

@ -0,0 +1,455 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Dvergar's station: a contract bank. Coin goes on the table, a crew signs on.
///
/// The Trol's war totem is the twin of this file and the two should be read together - same five
/// group slots, same empty Trader driving vanilla's store window, same "a dead band is money spent".
/// What is NOT shared is deliberate: the dvergr are hired professionals rather than a shouted-for
/// warband, and everything different here follows from that one sentence.
///
/// - they are TAMED and answer the follow command, like every servant in this mod (RaisedThrall);
/// - they knit their own wounds shut, the sentry's regeneration reused whole;
/// - they are NOT merchants, which costs no code at all: FactionMerchantSetupPatch matches the
/// exact prefab name and these clones are DvergarMerc_*. This is the same mechanism that made
/// every tameable wolf in the world a shop window until the catalogue stopped listing "Wolf",
/// read from the other side;
/// - they keep their race's truce. A hired crew walking into a dvergr outpost does not start a
/// war with the shopkeeper - see DvergarMercenaryTrucePatch at the bottom, which is the one
/// rule in this file that has no counterpart on the totem;
/// - they can be given drink, later. Nothing here is needed for that: a rune barrel will buff
/// whatever RaisedThrall is bound to this bank's anchor, so the mercenaries need no hook of
/// their own and this file does not have to be reopened to add one.
///
/// The seekers in the low bands are not allies, they are LEASHED. A dvergr contract sends you two
/// workers and their beasts, which is also why the truce has to cover them: wild dvergr shoot
/// seekers on sight, and a firefight started by a brood at your heel would be retaliation damage,
/// which IsEnemy has no say over once it has begun.
/// </summary>
public static class DvergarBanco
{
public const string PieceName = "DvergarContractBank";
public const string PieceDisplayName = "Contract Bank";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for
/// a mistlands station: the dvergr do not take Yagluth's leavings seriously.</summary>
public const string UpgradeItem = "QueenDrop";
public const int UpgradeProgressionState = 7; // The Queen
public const int MaxTroops = 5;
/// <summary>Written into each hired creature's ZDO so the bank can tell its crews apart -
/// five slots means counting contracts, not bodies.</summary>
public const string KeyGroup = "RoV_dvergarGroup";
public const float LeashRange = 12f;
public const float WitherSeconds = 60f;
public const float HomeCheckRange = 25f;
/// <summary>No cap: a signed contract walks out as a contract.</summary>
public const int MaxFollowers = -1;
// One per square kilometre. Looser than the Fenrir's pen (2.59 km2) because a bank does not
// grow anything on its own, stricter than the Trol's totem, which has no limit at all and
// should probably get one once it is out of test.
public const int MaxBanksInRange = 1;
public const float DensityAreaKm2 = 1f;
// ---------------------------------------------------------------- the look, in metres
/// <summary>A cartography table, slightly cut down. The dvergr write smaller than we do.</summary>
private const float TableScale = 0.8f;
/// <summary>
/// How high the coin pile sits, in the piece's own space and BEFORE TableScale is applied.
/// Unlike the totem's head this is not measured: the table keeps its own vanilla mesh, so
/// there is no borrowed holder to call ModelBorrow.HeightOf on. If the pile floats or sinks,
/// this is the ONE number to touch.
/// </summary>
private const float PileHeight = 1.05f;
private const float PileSize = 0.45f;
public class Troop
{
public string Id;
public string Display;
public int Price;
public bool NeedsUpgrade;
/// <summary>Trophy of whoever leads the crew - the face it wears in the rack.</summary>
public string Icon;
/// <summary>Vanilla creature prefab -> how many of it.</summary>
public KeyValuePair<string, int>[] Members;
}
// Anchored at the same 400-2000 as the Trol's totem, and laddered against ITS bands rather
// than against head count: one Dverger is worth rather more than six greydwarves, so the
// bodies come down as the coin goes up and the seekers make up the difference at the bottom.
//
// The top band is knowingly stronger than the totem's two thousand coin fuling war band. It
// sits behind the Queen and it dies for good; if it proves too much in play, the lever is to
// drop the support mage out of it before touching the price.
public static readonly Troop[] Troops =
{
new Troop
{
Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
new KeyValuePair<string, int>("SeekerBrood", 2),
}
},
new Troop
{
Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
new KeyValuePair<string, int>("SeekerBrood", 2),
}
},
new Troop
{
Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
new KeyValuePair<string, int>("DvergerMageFire", 1),
new KeyValuePair<string, int>("SeekerBrood", 3),
}
},
new Troop
{
Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
new KeyValuePair<string, int>("DvergerMageIce", 1),
new KeyValuePair<string, int>("DvergerMageSupport", 1),
}
},
new Troop
{
Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute",
Members = new[]
{
new KeyValuePair<string, int>("DvergerAshlands", 2),
new KeyValuePair<string, int>("DvergerMageSupport", 1),
new KeyValuePair<string, int>("SeekerBrute", 1),
}
},
};
public static Troop Find(string id)
{
foreach (Troop troop in Troops) if (troop.Id == id) return troop;
return null;
}
/// <summary>
/// What this player actually pays, after the Dvergar's own trader discount.
///
/// It reads the LOCAL player's tier, which is correct rather than convenient: the coin comes
/// out of that player's own inventory, on that player's own client, and a contract bank is not
/// a shared till. The discount table stops at 25% at state 7 (DvergarConfig.cs), which is the
/// same state that unlocks the two upgraded bands - so the top of the list can never be
/// discounted before it can be bought, and no separate ceiling is needed.
/// </summary>
public static int PriceFor(Troop troop)
{
if (troop == null) return 0;
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
return Mathf.Max(1, Mathf.RoundToInt(troop.Price * (1f - discount)));
}
/// <summary>Every distinct creature the bank can hire, so their clones exist before anyone signs.</summary>
private static readonly Dictionary<string, string> HiredPrefabs = new Dictionary<string, string>();
public static string HiredNameFor(string vanillaPrefab) =>
HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null;
/// <summary>The mercenary prefabs, by name, so the truce can recognise its own cheaply.</summary>
private static readonly HashSet<string> HiredNames = new HashSet<string>();
public static bool IsHiredName(string prefabName) =>
!string.IsNullOrEmpty(prefabName) && HiredNames.Contains(prefabName);
public static void Register()
{
HashSet<string> sources = new HashSet<string>();
foreach (Troop troop in Troops)
{
foreach (KeyValuePair<string, int> member in troop.Members) sources.Add(member.Key);
}
foreach (string source in sources) RegisterHired(source);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange,
"There is already {0} contract bank within a day's walk. One ledger per valley.");
}
// ---------------------------------------------------------------- the hired
/// <summary>
/// One signed mercenary: the vanilla creature, tamed, leashed, healing, and worth nothing dead.
///
/// CharacterDrop is destroyed for the reason it always is here, and it matters more on this
/// chain than on any other: dvergr and seekers both carry loot that SELLS. A mercenary that
/// dropped its own parts would make the bank a way of turning coin into more coin.
/// </summary>
private static void RegisterHired(string source)
{
string prefabName = "DvergarMerc_" + source;
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Dvergar] Could not clone {source}; that crew member cannot be hired. " +
"The rest of its band still signs on without it.");
return;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = prefabName;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = WitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "Your name is not on the contract.";
// Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with
// the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead.
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
HiredPrefabs[source] = prefabName;
HiredNames.Add(prefabName);
}
// ---------------------------------------------------------------- the bank
private static void RegisterPiece()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Dvergar] Could not clone piece_cartographytable; the contract bank " +
"is not registered.");
return;
}
// EVERY behaviour goes except the three that make it a building, and the blanket sweep is
// the point rather than laziness: the cartography table's MapTable is Interactable AND
// Hoverable, so it takes the E key before our own Switch ever sees it and opens the shared
// map instead of the ledger. That is the same bug as the barrel's Container on the Fenrir
// trough and the Trader on the vanilla wolf, and stripping by capability instead of by
// type name means it cannot come back if a future patch renames or adds a component.
//
// Unlike the Trol's totem the renderers are KEPT: the table is the look, there is nothing
// borrowed underneath it.
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);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
prefab.transform.localScale = Vector3.one * TableScale;
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
bank.m_switch = prefab.AddComponent<Switch>();
bank.m_switch.m_name = PieceDisplayName;
// An empty catalogue IS the design: the bank sells crews and buys nothing. Every list is
// filled in even though this trader never talks, because a Trader added with AddComponent
// comes up with all of them null and Trader.Interact walks into Say(m_randomStartTrade)
// if the player's E happens to reach it instead of our Switch.
//
// The empty list would also throw out of StoreGui.FillList on its last instruction - that
// is fixed once and for everyone by StoreGuiEmptyCatalogueGuardPatch over in
// Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here.
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplayName;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
trader.m_randomGiveItemNo = new List<string>();
trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
// The mark of a bank that has been paid: a heap of coin on the table, hidden until the
// Queen has fallen and the ledger has been rewritten.
//
// 'treasure_pile' is the player's own choice of prop and is NOT verified against this
// build - nothing else in the project references it. ModelBorrow is null-safe by
// construction, so a wrong name costs exactly one warning in the log and an empty holder;
// if that warning appears, 'Coins' is the fallback and this is a one-string change.
bank.m_coinPile = ModelBorrow.Attach(prefab.transform, "BankCoinPile", "treasure_pile",
new Vector3(0f, PileHeight, 0f), Quaternion.identity,
PileSize, "Dvergar");
bank.m_coinPile.SetActive(false);
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null; // a bank is built where the work is, not at a bench
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
// Coin in the RECIPE, and that is the whole reason this chain needs no gate item bought
// from a merchant the way the other three do: the Dvergar pay for everything, so the
// station opens by being paid for rather than by being unlocked.
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyDvergr"),
Requirements = new[]
{
new RequirementConfig("BlackMarble", 10, 0, true),
new RequirementConfig("YggdrasilWood", 5, 0, true),
new RequirementConfig("Sap", 2, 0, true),
new RequirementConfig("Coins", 100, 0, true),
}
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").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 DvergarBancoKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DvergarBanco.EnsureKnown(__instance);
}
}
/// <summary>
/// The race lock, caught at placement so the marble and the coin are not spent before the refusal.
/// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer
/// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBancoRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it.");
return false;
}
}
/// <summary>
/// A hired crew keeps its employer's truce.
///
/// Without this the station fights itself: a Dvergar player is at peace with the mountain's dvergr
/// (FactionHostilityPatch), and those dvergr are where the player BUYS - so walking into an outpost
/// with an escort would mean the escort killing the shopkeeper. Taming a creature puts it in the
/// player faction, which makes it an enemy of everything the player is merely not fighting.
///
/// One condition covers the whole band, seekers included, because every hired body is a RaisedThrall
/// carrying the same commanding race - so the leashed brood at your heel is as welcome in an outpost
/// as the dvergr holding its chain, even though wild dvergr shoot seekers on sight. That was the
/// player's call and it is the only reason a bank is usable in the mistlands at all: retaliation
/// damage does not go through IsEnemy, so one shot fired by an outpost would have escalated into a
/// war this patch could no longer stop.
///
/// A postfix that only ever says "not enemies", layered on top of the older hostility patch on the
/// same method exactly as that one layers on RaceHostilityManager. It cannot make anything hostile
/// that was not already.
/// </summary>
[HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })]
public static class DvergarMercenaryTrucePatch
{
/// <summary>The mountain's dvergr, by prefab name. The same roster FactionHostilityPatch uses
/// for the player's own truce - kept as its own copy so a change to one is a deliberate change
/// to that one, since these two lists answer different questions.</summary>
private static readonly HashSet<string> WildDvergr = new HashSet<string>
{
"Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands",
};
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
if (IsTruce(a, b) || IsTruce(b, a)) __result = false;
}
/// <summary>True if <paramref name="mercenary"/> is one of ours and <paramref name="other"/> is
/// a wild dvergr.</summary>
private static bool IsTruce(Character mercenary, Character other)
{
RaisedThrall thrall = mercenary.GetComponent<RaisedThrall>();
if (thrall == null || thrall.m_commandingRace != DvergarBanco.RaceId) return false;
return WildDvergr.Contains(Utils.GetPrefabName(other.gameObject));
}
}
}

View file

@ -0,0 +1,290 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bank's logic: five contracts, bought with coin, and no way to cancel one.
///
/// Slots count CREWS, not bodies - a fire crew of five is one slot, and it stays one slot as its
/// members die. Each hired body carries its crew's id in its own ZDO, so the count survives a reload
/// and corrects itself when a whole crew is wiped, with nothing tallied anywhere.
///
/// This is TrolTotemBehaviour's twin and was written from it. The differences are all consequences
/// of one thing - these are paid professionals rather than a shouted-for warband:
/// - the price a player pays is discounted by their own Dvergar tier (DvergarBanco.PriceFor);
/// - the upgrade is the Queen's drop rather than Yagluth's, and it puts coin on the table
/// instead of a head on a post.
/// If a bug is found in one of the two files, look for it in the other before assuming it is local.
/// </summary>
public class DvergarBancoBehaviour : MonoBehaviour
{
public Switch m_switch;
public GameObject m_coinPile;
private const string KeyUpgraded = "RoV_dvergarBankUpgraded";
private const string KeyNextGroup = "RoV_dvergarBankNextGroup";
private ZNetView m_nview;
private void Awake()
{
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string>("RoV_DvergarHire", RPC_Hire);
m_nview.Register("RoV_DvergarUpgrade", RPC_Upgrade);
InvokeRepeating("UpdatePile", 0.5f, 2f);
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The coin is mounted from the start; the tier decides whether it is there to see.</summary>
private void UpdatePile()
{
if (m_coinPile != null) m_coinPile.SetActive(IsUpgraded());
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (!DvergarRace.IsDvergar())
{
player.Message(MessageHud.MessageType.Center, "The ledger is not written for you.");
return false;
}
// The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews.
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == DvergarBanco.UpgradeItem)
{
return TryUpgrade(player, item);
}
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
return OpenStore(player);
}
private bool TryUpgrade(Player player, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist.");
return false;
}
player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DvergarUpgrade");
player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now.");
return true;
}
/// <summary>
/// Opens the vanilla store window, with the crew column hung off it by DvergarBancoStore. A
/// Trader has to be present for StoreGui.Show to have anything to show; this one's catalogue is
/// empty, which is how "hires crews, buys nothing" is expressed.
/// </summary>
private bool OpenStore(Player player)
{
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, "The ledger is shut.");
return false;
}
// Nothing is handed to the panel: DvergarBancoStore reads the bank back out of StoreGui's
// own m_trader when it repaints, so the window cannot draw one bank's crews while showing
// another's, and there is no static left over to go stale.
StoreGui.instance.Show(trader);
return true;
}
// ---------------------------------------------------------------- what the store calls
/// <summary>Sign a crew by id, from a row the player clicked. Every check TryHire made applies.</summary>
public void HireFromStore(string troopId)
{
Player player = Player.m_localPlayer;
if (player == null) return;
DvergarBanco.Troop troop = DvergarBanco.Find(troopId);
if (troop == null) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
if (CountGroups() >= DvergarBanco.MaxTroops)
{
player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds.");
return;
}
Inventory inventory = player.GetInventory();
if (inventory == null) return;
// Priced here and NOT on the way in from the row: the button only draws a number, and the
// player's tier could have changed since the window was opened.
int price = DvergarBanco.PriceFor(troop);
if (CountCoins(inventory) < price)
{
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney");
return;
}
TakeCoins(inventory, price);
m_nview.InvokeRPC("RoV_DvergarHire", troop.Id);
player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on.");
}
private const string CoinsPrefab = "Coins";
private static int CountCoins(Inventory inventory)
{
int total = 0;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == CoinsPrefab)
{
total += item.m_stack;
}
}
return total;
}
private static void TakeCoins(Inventory inventory, int amount)
{
foreach (ItemDrop.ItemData item in new List<ItemDrop.ItemData>(inventory.GetAllItems()))
{
if (amount <= 0) return;
if (item == null || item.m_dropPrefab == null || item.m_dropPrefab.name != CoinsPrefab) continue;
int take = Mathf.Min(amount, item.m_stack);
inventory.RemoveItem(item, take);
amount -= take;
}
}
// ---------------------------------------------------------------- hiring
private void RPC_Hire(long sender, string troopId)
{
if (!m_nview.IsOwner()) return;
DvergarBanco.Troop troop = DvergarBanco.Find(troopId);
if (troop == null || CountGroups() >= DvergarBanco.MaxTroops) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
int next = m_nview.GetZDO().GetInt(KeyNextGroup) + 1;
m_nview.GetZDO().Set(KeyNextGroup, next);
string group = troopId + "#" + next;
foreach (KeyValuePair<string, int> member in troop.Members)
{
string hired = DvergarBanco.HiredNameFor(member.Key);
if (hired == null) continue;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Dvergar] No '{hired}' in ZNetScene; part of {troop.Display} " +
"did not turn up for work.");
continue;
}
for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group);
}
}
private void SpawnOne(GameObject prefab, string group)
{
Vector3 offset = Random.insideUnitSphere * 3f;
offset.y = 0f;
Vector3 position = transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
ZNetView nview = spawned.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(DvergarBanco.KeyGroup, group);
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
// ---------------------------------------------------------------- state
public bool IsUpgraded() =>
m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private static string GroupOf(RaisedThrall thrall)
{
ZNetView nview = thrall != null ? thrall.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return null;
string group = nview.GetZDO().GetString(DvergarBanco.KeyGroup, "");
return string.IsNullOrEmpty(group) ? null : group;
}
/// <summary>
/// Live crews, counted as distinct groups rather than as bodies. Nothing is stored: the count
/// is the truth, and it corrects itself the moment a crew is wiped out.
/// </summary>
public int CountGroups()
{
HashSet<string> groups = new HashSet<string>();
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
string group = GroupOf(thrall);
if (group != null) groups.Add(group);
}
return groups.Count;
}
private string Hover()
{
string body = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}";
// Said in as many words: a player who cannot see their own discount will read the lower
// number in the window as a mistake.
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off";
if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)";
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Read the ledger";
return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})");
}
}
}

View file

@ -0,0 +1,211 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// The contract bank's window: the merchant's own store, with a column of hireable crews in it.
///
/// TWINNED WITH Trol/TrolTotemStore.cs. This is a copy of that file, taken deliberately rather than
/// refactored into something shared, so the Trol's totem is not touched while it is in test - the
/// two are the same panel drawn from a different roster. A FIX TO ONE BELONGS IN THE OTHER; when
/// the totem is settled they should collapse into one panel driven by a common station interface.
///
/// Two things are deliberately NOT copied across:
/// - StoreGuiEmptyCatalogueGuardPatch, which is what stops vanilla FillList throwing on an empty
/// catalogue and taking every postfix down with it. It is generic - it fires for any trader with
/// nothing to sell - so it already covers this bank, and a second copy would just be a second
/// prefix on the same method doing the same work.
/// - the slot rack. There was one on the totem and it was removed at the player's call: a crew
/// that dies is dead, and a butcher knife already dismisses one that has outlived its use.
///
/// The two columns cannot collide. Each one clears itself at the top of its own Refresh and only
/// switches on when the trader the window belongs to carries ITS behaviour, so at most one is ever
/// drawn - a bank is not a totem.
/// </summary>
public static class DvergarBancoStore
{
private static RectTransform _crewList;
private static readonly List<GameObject> _rows = new List<GameObject>();
/// <summary>
/// The bank the open window belongs to, read back out of StoreGui's own m_trader rather than
/// pushed in before Show(). Same field the factions sell panel and the totem's column read.
/// </summary>
public static DvergarBancoBehaviour ActiveBank(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<DvergarBancoBehaviour>() : null;
}
// ---------------------------------------------------------------- build
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null)
{
Jotunn.Logger.LogWarning("[Dvergar] StoreGui has no m_listRoot; the contract bank's window " +
"cannot be built.");
return;
}
if (_crewList != null) return;
GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "DvergarCrewList";
_crewList = clone.GetComponent<RectTransform>();
_crewList.anchoredPosition = gui.m_listRoot.anchoredPosition;
// The clone carries whatever rows the vanilla list held at Awake. Usually none, but a
// leftover would sit under ours forever, so it starts empty by construction.
foreach (Transform child in _crewList) Object.Destroy(child.gameObject);
_crewList.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) Object.Destroy(row);
_rows.Clear();
if (_crewList != null) _crewList.gameObject.SetActive(false);
}
// ---------------------------------------------------------------- fill
public static void Refresh(StoreGui gui)
{
Clear();
DvergarBancoBehaviour bank = ActiveBank(gui);
if (bank == null) return; // an ordinary merchant, or the Trol's totem. Not ours.
if (_crewList == null)
{
Jotunn.Logger.LogWarning("[Dvergar] The contract bank's column was never built (did the patch " +
"on StoreGui.Awake fail?), so nothing can be drawn into it.");
return;
}
_crewList.gameObject.SetActive(true);
int row = 0;
int hidden = 0;
foreach (DvergarBanco.Troop troop in DvergarBanco.Troops)
{
if (troop.NeedsUpgrade && !bank.IsUpgraded()) { hidden++; continue; }
BuildRow(gui, bank, troop, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_crewList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
Mathf.Max(baseSize, row * gui.m_itemSpacing));
Jotunn.Logger.LogInfo($"[Dvergar] Contract bank window: {row} crews on offer, {hidden} still behind " +
$"the Queen, {bank.CountGroups()}/{DvergarBanco.MaxTroops} contracts live.");
}
private static void BuildRow(StoreGui gui, DvergarBancoBehaviour bank, DvergarBanco.Troop troop, int rowIndex)
{
GameObject element = Object.Instantiate(gui.m_listElement, _crewList);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_crewList.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
Sprite icon = TrophyIcon(troop.Icon);
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " +
"keeps whatever the cloned element was showing.");
element.transform.Find("name").GetComponent<TMP_Text>().text = troop.Display;
// The DISCOUNTED price, because that is what will actually leave the player's pocket.
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString();
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() =>
{
bank.HireFromStore(id);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
/// <summary>Who actually turns up, so two thousand coin is not spent blind.</summary>
private static string Composition(DvergarBanco.Troop troop)
{
StringBuilder text = new StringBuilder();
foreach (KeyValuePair<string, int> member in troop.Members)
{
if (text.Length > 0) text.Append('\n');
text.Append(member.Value).Append(" x ").Append(CreatureName(member.Key));
}
int full = troop.Price;
int paid = DvergarBanco.PriceFor(troop);
if (paid < full) text.Append("\n\nList price ").Append(full).Append(" - your seal takes it to ").Append(paid).Append('.');
text.Append("\n\nThey answer the follow command, knit their own wounds shut, keep your truce with " +
"the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.");
return text.ToString();
}
private static string CreatureName(string prefabName)
{
Character character = Jotunn.Managers.PrefabManager.Cache.GetPrefab<Character>(prefabName);
if (character == null || string.IsNullOrEmpty(character.m_name)) return prefabName;
return Localization.instance.Localize(character.m_name);
}
// ---------------------------------------------------------------- helpers
private static Sprite TrophyIcon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
ItemDrop drop = Jotunn.Managers.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;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class DvergarBancoStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class DvergarBancoStoreFillPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class DvergarBancoStoreHidePatch
{
public static void Postfix() => DvergarBancoStore.Clear();
}
}

View file

@ -0,0 +1,309 @@
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The rune barrel: drink for a hired crew.
///
/// Second half of the Dvergar chain and the answer to "can they be given potions". They can, and it
/// costs the mercenaries nothing of their own - a creature carries an SEMan exactly like a player
/// does, so the barrel pours a vanilla consumable's own status effect straight into whoever is
/// standing around it. Nothing new had to be added to DvergarBanco.cs for this to work, which was
/// the whole point of choosing a barrel over a hand-held flask: the buff is something you PREPARE
/// before walking out, not a button you press mid-fight.
///
/// WHAT ACTUALLY WORKS IS NOT A DESIGN DECISION, IT IS A FACT ABOUT EACH POTION. A mead that heals
/// over time heals a dvergr; a mead that regenerates stamina does nothing at all, because a creature
/// has no stamina bar to fill. The barrel therefore refuses nothing and promises nothing - it pours
/// what you put in it. `dumppotions` at the bottom of this file is how the two lists were told
/// apart: it reads every consumable in ObjectDB and reports, by reflection, what its effect actually
/// carries, so no guess about a field name is involved.
///
/// The serving code is race-agnostic on purpose - it drinks to any RaisedThrall in range, whoever
/// raised it - but the piece itself is locked to the Dvergar like the bank. If another chain ever
/// wants a barrel of its own, the lock is the only line that has to change.
/// </summary>
public static class DvergarBotte
{
public const string PieceName = "DvergarRuneBarrel";
public const string PieceDisplayName = "Rune Barrel";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>How many drinks it holds. One dose is one mercenary served, so twenty is four
/// rounds for a full five-crew bank and a reason to keep brewing.</summary>
public const int MaxDoses = 20;
/// <summary>
/// Who is close enough to be handed a cup. Deliberately a range around the BARREL rather than
/// "everyone bound to the bank": a crew that is out across the map following its master is not
/// at the table, and buffing it from three biomes away would make the barrel a remote control.
/// </summary>
public const float ServeRange = 30f;
private const float BarrelScale = 0.7f;
/// <summary>Dvergr brass and verdigris, so it does not read as the Fenrir's trough - which is
/// the same barrel, tinted brown and rather bigger.</summary>
private static readonly Color BarrelTint = new Color(0.30f, 0.42f, 0.40f, 1f);
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_chest_barrel");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Dvergar] Could not clone piece_chest_barrel; the rune barrel is " +
"not registered.");
return;
}
// The barrel's Container is both the Hoverable and the Interactable, so a chest would
// swallow the click that fills it and the hover text that reports it. Same strip as the
// Fenrir trough, and the same reason.
foreach (Container container in prefab.GetComponentsInChildren<Container>(true))
{
if (container != null) Object.DestroyImmediate(container);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
DvergarBotteBehaviour barrel = prefab.AddComponent<DvergarBotteBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
barrel.m_switch = prefab.AddComponent<Switch>();
barrel.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * BarrelScale;
Recolour(prefab, BarrelTint);
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
// Cheap on purpose. The barrel is not the cost - the potions poured into it are, forever.
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "Pour a brew in and the crew drinks. What it does to them is whatever it " +
"would have done to you - if they have the parts for it.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"),
Requirements = new[]
{
new RequirementConfig("FineWood", 10, 0, true),
new RequirementConfig("BlackMarble", 5, 0, true),
new RequirementConfig("Sap", 1, 0, true),
}
}));
}
// ---------------------------------------------------------------- what a brew is
/// <summary>
/// The status effect a consumable would hand to whoever drank it, or null if the item is not a
/// drink at all. This is the ONLY test the barrel makes: anything with an effect on it can go
/// in, and whether that effect means anything to a dvergr is the potion's business, not ours.
/// </summary>
public static StatusEffect BrewEffect(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null;
return drop.m_itemData.m_shared.m_consumeStatusEffect;
}
public static bool IsBrew(string prefabName) => BrewEffect(prefabName) != null;
public static string BrewDisplayName(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return prefabName;
return Localization.instance.Localize(drop.m_itemData.m_shared.m_name);
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
// ---------------------------------------------------------------- helpers
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;
}
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
}
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class DvergarBotteKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DvergarBotte.EnsureKnown(__instance);
}
}
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBotteRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "You do not know what goes in it.");
return false;
}
}
/// <summary>
/// [DEBUG] Every drinkable in the game, and what its effect ACTUALLY carries.
///
/// Written because "which potions work on a mercenary" cannot be answered from the names: two meads
/// with almost the same label can be a heal-over-time and a stamina regen, and only one of those
/// means anything to a creature. Reading the effect is the answer, and reading it BY REFLECTION is
/// what makes this command safe to write without knowing a single field name of this build's
/// StatusEffect classes - a renamed or missing field is one line that does not print, not a
/// compile error and not a wrong answer.
///
/// dumppotions every consumable with an effect
/// dumppotions mead only the ones whose prefab name contains "mead"
/// </summary>
public class DumpPotionsCommand : ConsoleCommand
{
public override string Name => "dumppotions";
public override string Help =>
"[DEBUG] Lists every consumable with a status effect and what that effect carries, so it " +
"can be told whether a mercenary would feel it. Optional filter: dumppotions <substring>.";
public override void Run(string[] args)
{
if (ObjectDB.instance == null)
{
Console.instance.Print("ObjectDB is not up yet - be in a world.");
return;
}
string filter = args.Length > 0 ? args[0].ToLowerInvariant() : null;
int found = 0;
foreach (GameObject item in ObjectDB.instance.m_items)
{
if (item == null) continue;
if (filter != null && !item.name.ToLowerInvariant().Contains(filter)) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
StatusEffect effect = drop.m_itemData.m_shared.m_consumeStatusEffect;
if (effect == null) continue;
found++;
Jotunn.Logger.LogInfo($"[Potion] {item.name} ({effect.GetType().Name} '{effect.name}')" +
$"\n {Describe(effect)}");
}
string message = found == 0
? "No consumable carried a status effect - check the filter."
: $"{found} drinkable(s) written to the log with everything their effect carries.";
Console.instance.Print(message);
Jotunn.Logger.LogInfo($"[Potion] {message}");
}
/// <summary>
/// Every public field of the effect that is not at its default, as "name=value". Reflection
/// rather than a hand-written list of fields: this build's StatusEffect subclasses are whatever
/// they are, and the whole point of the command is to find that out instead of assuming it.
/// </summary>
private static string Describe(StatusEffect effect)
{
StringBuilder text = new StringBuilder();
foreach (FieldInfo field in effect.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
object value = field.GetValue(effect);
if (IsDefault(value)) continue;
// Collections and objects are reported as "present" rather than dumped - what matters
// is whether the effect has any, not what is in them.
string printed;
if (value is float f) printed = f.ToString("0.###");
else if (value is int || value is bool || value is string) printed = value.ToString();
else if (value is System.Collections.ICollection collection) printed = $"[{collection.Count}]";
else printed = value.GetType().Name;
if (text.Length > 0) text.Append(", ");
text.Append(field.Name).Append('=').Append(printed);
}
return text.Length > 0 ? text.ToString() : "(carries nothing - a flavour effect only)";
}
private static bool IsDefault(object value)
{
if (value == null) return true;
if (value is float f) return Mathf.Approximately(f, 0f);
if (value is int i) return i == 0;
if (value is bool b) return !b;
if (value is string s) return string.IsNullOrEmpty(s);
if (value is System.Collections.ICollection collection) return collection.Count == 0;
// A Unity object reference that has been destroyed compares equal to null.
if (value is Object unityObject) return unityObject == null;
return false;
}
}
}

View file

@ -0,0 +1,267 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The barrel's logic: one brew at a time, one dose per mercenary, poured by hand.
///
/// Two gestures on one key, and the split is the same one the bank uses:
/// - a potion USED on the barrel fills it (and tops it up, if it is the same brew);
/// - a bare E pours a round - and fills it from your pack first if it is empty, so the common
/// case is one click rather than the inventory dance. The Fenrir trough does the same thing
/// with meat, for the same reason.
///
/// Serving is MANUAL and never automatic. An automatic barrel would drink itself dry keeping a
/// buff up on a crew that is standing still doing nothing, and the whole point of a barrel over a
/// flask was that the buff is something you spend on purpose before walking out.
///
/// HONEST LIMIT, in the shape this project writes them: the round is poured by the client that
/// clicked. It claims ownership of each mercenary before adding the effect, so the effect is
/// simulated by someone who has it - but a mercenary that is not loaded on that client cannot be
/// served at all, and in multiplayer the dose count can be spent twice if two players click in the
/// same instant. Neither is worth a handshake for a barrel of mead.
/// </summary>
public class DvergarBotteBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyBrew = "RoV_dvergarBotteBrew";
private const string KeyDoses = "RoV_dvergarBotteDoses";
private ZNetView m_nview;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string, int>("RoV_DvergarBotteFill", RPC_Fill);
m_nview.Register<int>("RoV_DvergarBotteSpend", RPC_Spend);
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
// A drink handed to the barrel always fills it, whatever is already in there.
if (item != null)
{
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (!DvergarBotte.IsBrew(prefabName))
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
return Fill(player, inventory, item, prefabName);
}
// Bare hands: pour a round if there is one, otherwise go looking for something to pour.
if (GetDoses() > 0) return Serve(player);
ItemDrop.ItemData found = FindAnyBrew(inventory);
if (found == null)
{
player.Message(MessageHud.MessageType.Center, "It is empty, and so are you.");
return false;
}
return Fill(player, inventory, found, found.m_dropPrefab.name);
}
private ItemDrop.ItemData FindAnyBrew(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
if (DvergarBotte.IsBrew(candidate.m_dropPrefab.name)) return candidate;
}
return null;
}
// ---------------------------------------------------------------- filling
/// <summary>
/// Pours a stack in. One brew at a time: a barrel holding two different meads would have to
/// decide which one a mercenary gets, and there is no answer to that which is not arbitrary.
/// </summary>
private bool Fill(Player player, Inventory inventory, ItemDrop.ItemData item, string prefabName)
{
string current = GetBrew();
if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0)
{
player.Message(MessageHud.MessageType.Center,
$"There is still {DvergarBotte.BrewDisplayName(current)} in it.");
return false;
}
int room = DvergarBotte.MaxDoses - GetDoses();
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int poured = Mathf.Min(room, Mathf.Max(1, item.m_stack));
inventory.RemoveItem(item, poured);
m_nview.InvokeRPC("RoV_DvergarBotteFill", prefabName, poured);
player.Message(MessageHud.MessageType.Center,
$"$msg_added {DvergarBotte.BrewDisplayName(prefabName)} x{poured}");
return true;
}
private void RPC_Fill(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) return;
// A barrel that has been drunk dry forgets what it held, so the next brew can be anything.
string current = GetBrew();
if (string.IsNullOrEmpty(current) || GetDoses() <= 0) m_nview.GetZDO().Set(KeyBrew, prefabName);
else if (current != prefabName) return;
SetDoses(GetDoses() + count);
}
// ---------------------------------------------------------------- serving
/// <summary>
/// One round: every mercenary in reach gets a cup, and every cup is a dose. Whoever is out of
/// range or already dead simply is not served - there is no queue and no leftovers.
/// </summary>
private bool Serve(Player player)
{
string brew = GetBrew();
StatusEffect effect = DvergarBotte.BrewEffect(brew);
if (effect == null)
{
player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone.");
return false;
}
List<RaisedThrall> drinkers = InRange();
if (drinkers.Count == 0)
{
player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel.");
return false;
}
int doses = GetDoses();
int served = 0;
foreach (RaisedThrall thrall in drinkers)
{
if (served >= doses) break;
if (Pour(thrall, effect)) served++;
}
if (served == 0)
{
player.Message(MessageHud.MessageType.Center, "Not a drop went down.");
return false;
}
m_nview.InvokeRPC("RoV_DvergarBotteSpend", served);
string what = DvergarBotte.BrewDisplayName(brew);
player.Message(MessageHud.MessageType.Center, served < drinkers.Count
? $"{served} drink {what}. The barrel runs dry."
: $"{served} drink {what}.");
return true;
}
/// <summary>
/// Hands one creature the drink. The effect object is passed the same way vanilla passes it
/// when a player swallows a potion - Humanoid.UseItem does exactly this - so whatever SEMan
/// does with the shared asset internally, it is what the game already does to itself.
/// </summary>
private static bool Pour(RaisedThrall thrall, StatusEffect effect)
{
Character character = thrall != null ? thrall.GetComponent<Character>() : null;
if (character == null || character.IsDead()) return false;
// Claimed so that the client pouring is the one simulating the effect. Without this the
// drink would tick on a machine that does not own the creature, which for a heal-over-time
// means it quietly does nothing.
ZNetView nview = character.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
character.GetSEMan().AddStatusEffect(effect, true);
return true;
}
private List<RaisedThrall> InRange()
{
List<RaisedThrall> near = new List<RaisedThrall>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
if (Vector3.SqrMagnitude(character.transform.position - transform.position) >
DvergarBotte.ServeRange * DvergarBotte.ServeRange) continue;
near.Add(thrall);
}
return near;
}
private void RPC_Spend(long sender, int count)
{
if (!m_nview.IsOwner()) return;
SetDoses(GetDoses() - Mathf.Max(0, count));
}
// ---------------------------------------------------------------- state and display
private string GetBrew() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetString(KeyBrew, "") : "";
private int GetDoses() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyDoses, 0) : 0;
private void SetDoses(int value)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyDoses, Mathf.Clamp(value, 0, DvergarBotte.MaxDoses));
}
private string Hover()
{
int doses = GetDoses();
string brew = GetBrew();
string body;
if (doses <= 0 || string.IsNullOrEmpty(brew))
{
body = "empty\n[<color=yellow><b>$KEY_Use</b></color>] Pour a brew in";
}
else
{
int waiting = InRange().Count;
body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" +
$"\n{waiting} at the barrel" +
$"\n[<color=yellow><b>$KEY_Use</b></color>] Pour a round";
}
return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})");
}
}
}

View file

@ -28,6 +28,14 @@ namespace RacesOfValheim
public void CreateModAssets()
{
DvergarStatusEffects.RegisterStatusEffects();
// The contract bank and every mercenary it can hire. Race-locked at placement, like the
// Trol's war totem and unlike every other station in the mod.
DvergarBanco.Register();
// The barrel the crews drink from. Separate piece, no dependency in either direction:
// it serves whatever RaisedThrall is standing near it.
DvergarBotte.Register();
}
/// <summary>

View file

@ -141,9 +141,24 @@ namespace RacesOfValheim
}
};
private static readonly ShopDefinition WolfShop = new ShopDefinition
/// <summary>
/// The mountain's animal bench. It used to be the WOLF, and moving it was not a preference:
/// a bench is a Trader, a Trader is Interactable, and it wins the E key. The wolf is the ONLY
/// creature vanilla lets you tame that this catalogue ever made a merchant, so every wolf in
/// the world - including the two in your own pen - answered a click with a shop window
/// instead of being pettable, nameable or commandable. Taming an animal you cannot handle is
/// not taming.
///
/// The Ulv carries the whole line now, wolf goods included. It is a mountain creature of the
/// same faction, it is not tameable, and nothing about it is spent by being a shopkeeper.
///
/// Checked while fixing this: Boar, Lox, Hen and Asksvin - the rest of what vanilla lets you
/// tame - are not benches and never were. This was the only one, so the whole class of bug
/// closes here rather than needing a rule.
/// </summary>
private static readonly ShopDefinition UlvShop = new ShopDefinition
{
DisplayName = "Wolf",
DisplayName = "Ulv",
JokeCategory = JokeLupoLicantropo,
Items = new List<CatalogEntry>
{
@ -154,18 +169,8 @@ namespace RacesOfValheim
new CatalogEntry("FreezeGland", 5), // Drake, folded in here: no talk-capable rig
new CatalogEntry("OnionSeeds", 20),
new CatalogEntry("TrophyWolf", 350),
new CatalogEntry("TrophyHatchling", 350), // Drake (internal id "Hatchling")
}
};
private static readonly ShopDefinition UlvShop = new ShopDefinition
{
DisplayName = "Ulv",
JokeCategory = JokeLupoLicantropo,
Items = new List<CatalogEntry>
{
new CatalogEntry("WolfFang", 5),
new CatalogEntry("TrophyUlv", 350),
new CatalogEntry("TrophyHatchling", 350), // Drake (internal id "Hatchling")
}
};
@ -176,6 +181,8 @@ namespace RacesOfValheim
Items = new List<CatalogEntry>
{
new CatalogEntry("WolfFang", 5),
new CatalogEntry("Ulvsblod", 500), // gates the Fenrir pack trough
new CatalogEntry("GreaterUlvsblod", 1500), // upgrades it: the fenrir themselves
new CatalogEntry("TrophyFenring", 350),
}
};
@ -187,6 +194,7 @@ namespace RacesOfValheim
Items = new List<CatalogEntry>
{
new CatalogEntry("JuteRed", 2),
new CatalogEntry("GreaterFrostHeart", 1500), // gates the Skadi's hidden hollow
new CatalogEntry("TrophyCultist", 1500),
}
};
@ -284,7 +292,10 @@ namespace RacesOfValheim
{ "GoblinBrute", FulingShop },
{ "GoblinShaman", GoblinShamanShop }, // the only bench carrying the crop line
{ "Wolf", WolfShop },
// NO "Wolf" ENTRY, and it must stay that way: a bench is a Trader and a Trader takes the
// E key, which would make every tameable wolf in the world a shop instead of an animal.
// Its goods live on the Ulv now. (The wolf stays in FactionHostilityPatch's mountain
// roster - that list is about who attacks whom and is a different question entirely.)
{ "Ulv", UlvShop },
{ "Fenring", FenringShop },
{ "Fenring_Cultist", CultistShop },

View file

@ -0,0 +1,516 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Fenrir station: a trough that keeps a standing pack, in three ranks.
///
/// Seventh of the per-race chains, and the same family as the Draugh's body pile and the
/// Skeleton's bone pile - meat goes in, a roster fills up, and a death is a slot that refills
/// itself. The ranks fill in order and each one waits for the one below it to be full:
///
/// 10 wolves, one every two minutes
/// then 6 ulv, one every three
/// upgraded: 15 wolves, 10 ulv, and 5 fenrir on top
///
/// CORRECTION, and the reason this file was rewritten: the first two versions bred the pack
/// instead of raising it - the trough rewrote what the animals in its circle gave birth to, and
/// the ranks were meant to fill through vanilla's own Procreation. It cannot work. Cubs are a
/// different prefab from adults, so they either count towards the cap - and then the pen jams at
/// its first litter, because vanilla stops breeding at four head - or they do not, and then
/// nothing stops the pen breeding until it is shoulder to shoulder. There is no third option,
/// and the whole ladder of chances and forced rungs went with it. What is left is smaller, has
/// no cache to prime, no private fields to reach into, and cannot overshoot.
///
/// It is still not a spawner of the kind the guide warns against (4.9b), and the difference is
/// the same one the Skeleton's pile has: nothing here is free or immediate. The pack is paid for
/// in meat, arrives one animal at a time over the better part of an hour, and dies for good if
/// the trough does - so it is a herd you keep, not a button you press before a fight.
/// </summary>
public static class FenrirMangiatoia
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "FenrirPackTrough";
public const string PieceDisplayName = "Pack Trough";
public const string UlvsblodName = "Ulvsblod";
public const string UlvsblodDisplayName = "Ulvsblod";
public const string GreaterUlvsblodName = "GreaterUlvsblod";
public const string GreaterUlvsblodDisplayName = "Greater Ulvsblod";
public const int UlvsblodPrice = 500;
public const int GreaterUlvsblodPrice = 1500;
public const string WolfName = "FenrirPack_Wolf";
public const string UlvName = "FenrirPack_Ulv";
public const string FenrirName = "FenrirPack_Fenrir";
public const string WolfDisplayName = "Pack Wolf";
public const string UlvDisplayName = "Ulv";
public const string FenrirDisplayName = "Fenrir";
public const string KindWolf = "FenrirPackWolf";
public const string KindUlv = "FenrirPackUlv";
public const string KindFenrir = "FenrirPackFenrir";
public const string RaceId = "Fenrir";
// Moder needs no state check of her own: her drop is IN the recipe, so a trough cannot be
// built without her having fallen. Yagluth's is checked as well as spent, because the
// upgrade is bought with coin and a drop rather than built.
public const string ModerDrop = "DragonTear";
public const string YagluthDrop = "YagluthDrop";
public const int UpgradeProgressionState = 6; // Yagluth
// ─── The roster ──────────────────────────────────────────────────────
public const int WolfSlots = 10;
public const int UlvSlots = 6;
public const int FenrirSlots = 0; // none at all until upgraded
public const int WolfSlotsUpgraded = 15;
public const int UlvSlotsUpgraded = 10;
public const int FenrirSlotsUpgraded = 5;
/// <summary>
/// How long each rank takes to put one more up. Local seconds, and only while the zone is
/// loaded: a pack that rebuilt itself in an unloaded zone would mean walking away was the
/// fastest way to raise one.
///
/// The fenrir's five minutes is the one number here nobody specified. It is set longest
/// because it is the rank worth waiting for; it is one constant.
/// </summary>
public const float WolfSeconds = 120f;
public const float UlvSeconds = 180f;
public const float FenrirSeconds = 300f;
/// <summary>
/// What one of each costs out of the tank, on AswidBloodRefinery.FleshValue's scale - the
/// same one three other chains use, so a lox steak already counts for more than a neck tail
/// without a second table.
///
/// Anchored to the Draugh's hundred-per-thrall rather than picked: a fenrir is worth one of
/// those, and the ranks below it step down from there.
/// </summary>
public const float WolfCost = 25f;
public const float UlvCost = 50f;
public const float FenrirCost = 100f;
/// <summary>The tank. Four fenrir deep, so a full pack is several trips and not one.</summary>
public const float TankCap = 400f;
public const float TickSeconds = 5f;
// ─── Behaviour ───────────────────────────────────────────────────────
// Five minutes. Long enough to notice the mistake and rebuild, short enough that the wither
// is really doing its job. The trough cannot be broken by accident anyway - it is immune to
// pickaxes - so losing a pack is always a deliberate act.
public const float OrphanWitherSeconds = 300f;
public const float HomeCheckRange = 45f;
public const float LeashRange = 15f;
// No cap, and that is a balance decision rather than an oversight: this chain sits AFTER the
// mountain - Moder to build it, Yagluth for the fenrir at all - and five fenrir is a small
// number next to what the other races field by then.
public const int MaxFollowers = -1;
// One per square mile. 2.59 km2, and stricter than every other station in the mod because of
// what stands around this one.
public const int MaxTroughsInRange = 1;
public const float DensityAreaKm2 = 2.59f;
// ─── Looks ───────────────────────────────────────────────────────────
private const float TroughScale = 1.1f;
/// <summary>
/// A fenrir is a Fenring, and the player's own race turns INTO a Fenring at tier 4. If the
/// two are the same size they are the same silhouette in a melee. This is the only number
/// written over a vanilla creature's own, and it is a legibility fix, not a stat.
/// </summary>
private const float FenrirScale = 1.6f;
private static readonly Color TroughTint = new Color(0.42f, 0.36f, 0.30f, 1f);
private static readonly Color UlvsblodTint = new Color(0.55f, 0.10f, 0.12f, 1f);
private static readonly Color GreaterUlvsblodTint = new Color(0.30f, 0.16f, 0.42f, 1f);
public static void Register()
{
RegisterUlvsblod(UlvsblodName, UlvsblodDisplayName, UlvsblodTint,
"Wolf blood, kept warm by something that should not be able to keep anything warm. " +
"The Fenring sell it and do not explain it.");
RegisterUlvsblod(GreaterUlvsblodName, GreaterUlvsblodDisplayName, GreaterUlvsblodTint,
"Older blood, and further down the line. A trough given one of these starts raising " +
"something worse than ulv.");
RegisterPackAnimal(WolfName, "Wolf", WolfDisplayName, KindWolf,
"It answers to the blood of the wolf, not to you.", 1f);
RegisterPackAnimal(UlvName, "Ulv", UlvDisplayName, KindUlv,
"It answers to the blood of the wolf, not to you.", 1f);
RegisterPackAnimal(FenrirName, "Fenring", FenrirDisplayName, KindFenrir,
"Only the blood of the wolf commands this one.", FenrirScale);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxTroughsInRange,
"There is already {0} of these within a day's walk. A pack needs room.");
}
// ---------------------------------------------------------------- items
private static void RegisterUlvsblod(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "Bloodbag");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone Bloodbag; {displayName} not registered.");
return;
}
Recolour(prefab, tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 1f;
shared.m_maxStackSize = 10;
// A Bloodbag is food in vanilla. Left alone, someone eats the gate item.
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodRegen = 0f;
shared.m_foodBurnTime = 0f;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- the pack
/// <summary>
/// One rank of the pack: a vanilla creature, born tame, leashed to the trough that raised it,
/// and carrying nothing on death.
///
/// Everything it is - health, damage, resistances, speed - stays exactly as vanilla has it.
/// The only number written over is the fenrir's scale, and only so it cannot be mistaken for
/// a transformed player at a glance.
///
/// No Procreation on any of them, deliberately: the trough raises the pack, the pack does not
/// raise itself. That is the whole correction this file was rewritten for.
///
/// The CharacterDrop goes for the usual reason and one of this chain's own: a slot refills
/// itself forever, so an animal that dropped its pelt would not be a farm but a mint.
/// </summary>
private static void RegisterPackAnimal(string prefabName, string source, string displayName,
string kind, string refusal, float scale)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
if (scale != 1f) prefab.transform.localScale = Vector3.one * scale;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
// A raised pack does not breed. Vanilla gives the Ulv and the Fenring none anyway; the
// wolf comes with one, and it goes.
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
{
if (breeding != null) Object.DestroyImmediate(breeding);
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Vanilla gives the Ulv and the Fenring no Tameable at all. Without one they are tamed
// animals that cannot be named or handled like one, so the wolf's is copied across.
if (prefab.GetComponent<Tameable>() == null)
{
GameObject wolf = PrefabManager.Cache.GetPrefab<GameObject>("Wolf");
Tameable source_tame = wolf != null ? wolf.GetComponent<Tameable>() : null;
if (source_tame != null) CopyPublicFields(source_tame, prefab.AddComponent<Tameable>(), prefabName);
}
// "Ten seconds unhurt, then 2% a second" - the same one the Trol's troops already use.
// The postfix that resets its clock on a hit looks for the component, not for a skeleton.
prefab.AddComponent<SkeletonSentryBehaviour>();
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = refusal;
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Fenrir] {prefabName} from '{source}': tamed, leashed, no drops, no breeding.");
}
/// <summary>True if the trough takes this as meat. Any flesh, by the scale three chains share.</summary>
public static bool IsMeat(string prefabName)
{
return !string.IsNullOrEmpty(prefabName) && AswidBloodRefinery.FleshValue(prefabName) > 0;
}
public static float FeedValue(string prefabName)
{
int flesh = AswidBloodRefinery.FleshValue(prefabName);
return flesh > 0 ? flesh : 0f;
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// A barrel, because a trough is a barrel that someone left open. piece_chest_barrel is
// free - the taken list names piece_chest_wood, which is the Trenta's.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_chest_barrel");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Fenrir] Could not clone piece_chest_barrel; the trough is not registered.");
return;
}
// The barrel's Container is itself the Hoverable AND the Interactable, so a chest would
// swallow both the click that feeds the trough and the hover text that carries the
// roster. The model stays; the chest goes.
foreach (Container container in prefab.GetComponentsInChildren<Container>(true))
{
if (container != null) Object.DestroyImmediate(container);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
FenrirMangiatoiaBehaviour behaviour = prefab.AddComponent<FenrirMangiatoiaBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
behaviour.m_switch = prefab.AddComponent<Switch>();
behaviour.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * TroughScale;
Recolour(prefab, TroughTint);
// Ten silver ingots in the recipe, and a pickaxe that does literally nothing to it.
// "Silver hit points" is not a thing - WearNTear.MaterialType has no silver - but an
// immunity is more precise than a big number anyway: a stray swing while mining out a pen
// cannot cost a pack, and the hammer still takes it down deliberately, because removing a
// piece in Valheim does not go through damage at all.
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_damages.m_pickaxe = HitData.DamageModifier.Immune;
wear.m_materialType = WearNTear.MaterialType.Iron;
Jotunn.Logger.LogInfo($"[Fenrir] Trough health {wear.m_health} (inherited), pickaxe immune.");
}
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophyFenring");
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 = PieceDisplayName,
Description = "Fill it with meat and the pack comes. One at a time, and it remembers its dead.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyFenring"),
Requirements = new[]
{
new RequirementConfig(UlvsblodName, 1, 0, true),
new RequirementConfig("Silver", 10, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig("FineWood", 20, 0, true),
}
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
// ---------------------------------------------------------------- helpers
/// <summary>
/// Copies every public instance field from one component to another of the same type. Private
/// ones are left alone - they are the caches Awake fills in.
/// </summary>
private static void CopyPublicFields<T>(T source, T target, string label) where T : Component
{
if (source == null || target == null) return;
int copied = 0;
foreach (System.Reflection.FieldInfo field in typeof(T).GetFields(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
field.SetValue(target, field.GetValue(source));
copied++;
}
Jotunn.Logger.LogInfo($"[Fenrir] {label}: {copied} {typeof(T).Name} values taken from the vanilla Wolf.");
}
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;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Fenrir] Could not borrow the icon from '{prefabName}'.");
return null;
}
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
}
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class FenrirMangiatoiaKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
FenrirMangiatoia.EnsureKnown(__instance);
}
}
/// <summary>
/// [DEBUG] The pack, without the hour it takes to raise one.
///
/// A full roster is 30 animals at two to five minutes each, which is most of an afternoon, and
/// the things worth looking at - what a rank looks like, whether a slot refills after a death,
/// whether the upgrade opens the third rank - are all at the far end of it.
/// </summary>
public class FenrirPackSpawnCommand : ConsoleCommand
{
public override string Name => "fenrirpack";
public override string Help =>
"[DEBUG] fenrirpack now [count] - the nearest trough raises its next animals immediately. " +
"'fenrirpack fill' tops up its meat; 'fenrirpack [wolf|ulv|fenrir] [count]' puts animals " +
"in front of you directly, roster or no roster.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null)
{
Console.instance.Print("You must be in-game.");
return;
}
string what = args.Length > 0 ? args[0].ToLowerInvariant() : "wolf";
if (what == "fill") { FenrirMangiatoiaBehaviour.FillNearby(player); return; }
if (what == "now")
{
// No number given means "as many as the roster still wants" - 30 is past the biggest
// possible roster, so the loop stops when NextShort says the pack is whole.
int wanted = 30;
if (args.Length > 1 && !int.TryParse(args[1], out wanted)) wanted = 30;
FenrirMangiatoiaBehaviour.ForceNearby(player, Mathf.Clamp(wanted, 1, 30));
return;
}
string prefabName;
switch (what)
{
case "wolf": prefabName = FenrirMangiatoia.WolfName; break;
case "ulv": prefabName = FenrirMangiatoia.UlvName; break;
case "fenrir": prefabName = FenrirMangiatoia.FenrirName; break;
default:
Console.instance.Print($"'{what}'? wolf, ulv, fenrir - or now / fill.");
return;
}
int count = 2;
if (args.Length > 1 && !int.TryParse(args[1], out count)) count = 2;
count = Mathf.Clamp(count, 1, 30);
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Console.instance.Print($"No '{prefabName}' in ZNetScene - the chain did not register.");
return;
}
// Bound to a trough if there is one in reach, so they count against its roster exactly as
// if it had raised them. Loose otherwise, which is its own useful test.
FenrirMangiatoiaBehaviour trough = FenrirMangiatoiaBehaviour.NearestTo(player.transform.position);
for (int i = 0; i < count; i++)
{
float angle = i * Mathf.PI * 2f / count;
Vector3 ring = new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * 3f;
Vector3 position = player.transform.position + player.transform.forward * 3f + ring + Vector3.up * 0.5f;
GameObject spawned = Object.Instantiate(prefab, position, Quaternion.identity);
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null && trough != null) thrall.Bind(trough.transform.position);
}
Console.instance.Print(trough != null
? $"{count} {prefabName}, bound to the trough {Mathf.RoundToInt(Vector3.Distance(player.transform.position, trough.transform.position))}m away."
: $"{count} {prefabName}, bound to nothing - no trough within range.");
}
}
}

View file

@ -0,0 +1,468 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The trough's logic: one rank at a time, one animal at a time, paid for in meat.
///
/// Same shape as DraughSpawnerBehaviour and SkeletonBonePileBehaviour, and deliberately so - all
/// the state in the ZDO, owner-only accounting, and a roster that is COUNTED rather than tallied.
/// Counting fresh on every tick is what makes "when one dies its slot comes back" need no code at
/// all: a death, a despawn, or a player killing his own wolf all correct themselves.
///
/// The ranks fill in order - wolves, then ulv, then fenrir - and whichever rank is short is the
/// one the clock is running for. That is also what "the timer for that one restarts" means: a
/// wolf dying while the trough is working on ulv moves the clock back to the wolf rank, because
/// the lowest short rank always wins.
///
/// HONEST LIMIT, the same one the Skeleton's pile carries: RaisedThrall.BoundTo can only see
/// LOADED creatures. A pack that is off across the map following its owner does not count, and a
/// trough left alone will fill the slots it thinks are empty. The wither is what stops that
/// becoming permanent - a trough only sustains one pack - but a player who ferries animals away
/// and comes back can hold more than the roster says. Closing it properly needs the animals to
/// carry their own bookkeeping, which is the version this replaced and which cost more than it
/// was worth.
/// </summary>
public class FenrirMangiatoiaBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyFeed = "RoV_fenrirFeed";
private const string KeyUpgraded = "RoV_fenrirUpgraded";
private static readonly List<FenrirMangiatoiaBehaviour> Live = new List<FenrirMangiatoiaBehaviour>();
private ZNetView m_nview;
/// <summary>Seconds towards the next animal of whichever rank is currently short.</summary>
private float m_timer;
/// <summary>Which rank the clock is running for, so that a change resets it.</summary>
private string m_waitingFor;
// ---------------------------------------------------------------- life
private void Awake()
{
Live.Add(this);
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string, int>("RoV_FenrirFeed", RPC_Feed);
m_nview.Register("RoV_FenrirUpgrade", RPC_Upgrade);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", FenrirMangiatoia.TickSeconds, FenrirMangiatoia.TickSeconds);
}
private void OnDestroy()
{
Live.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest loaded trough, or null if none is in reach.</summary>
public static FenrirMangiatoiaBehaviour NearestTo(Vector3 position)
{
FenrirMangiatoiaBehaviour best = null;
float bestSq = 60f * 60f;
for (int i = Live.Count - 1; i >= 0; i--)
{
FenrirMangiatoiaBehaviour trough = Live[i];
if (trough == null) { Live.RemoveAt(i); continue; }
float sq = Vector3.SqrMagnitude(trough.transform.position - position);
if (sq > bestSq) continue;
bestSq = sq;
best = trough;
}
return best;
}
/// <summary>[DEBUG] Tops up every nearby trough, so a test does not start with a meat run.</summary>
public static void FillNearby(Player player)
{
int filled = 0;
foreach (FenrirMangiatoiaBehaviour trough in Live)
{
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid()) continue;
if (Vector3.Distance(trough.transform.position, player.transform.position) > 60f) continue;
trough.m_nview.ClaimOwnership();
trough.SetFeed(FenrirMangiatoia.TankCap);
filled++;
}
Console.instance.Print(filled == 0 ? "No troughs within 60m." : $"{filled} filled to the brim.");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (!NextShort(out string kind, out string prefabName, out float wait, out float cost))
{
// Nothing short: the pack is whole. The clock does not run, so a death does not get a
// head start it never earned.
m_timer = 0f;
m_waitingFor = null;
return;
}
// A rank that has just fallen short takes the clock over from the one above it, and it
// starts from zero. This is "the timer for that one restarts", and it is why a death
// costs the full wait rather than whatever happened to be left on another rank's clock.
if (m_waitingFor != kind)
{
m_waitingFor = kind;
m_timer = 0f;
}
if (GetFeed() < cost) return; // no meat, no clock
m_timer += FenrirMangiatoia.TickSeconds;
if (m_timer < wait) return;
m_timer = 0f;
if (Spawn(prefabName)) SetFeed(GetFeed() - cost);
}
/// <summary>
/// The lowest rank that is short, and what raising one of it costs and takes. Ranks fill in
/// order, so this one method is the whole scheduler.
///
/// Extracted so the debug command that forces a spawn goes through EXACTLY this, and cannot
/// quietly fill a rank out of order, past its cap, or before the upgrade opens it. A test
/// tool that skips the rule it is testing proves nothing.
///
/// Returns false when the pack is whole.
/// </summary>
private bool NextShort(out string kind, out string prefabName, out float wait, out float cost)
{
Count(out int wolves, out int ulv, out int fenrir);
if (wolves < WolfCap())
{
kind = FenrirMangiatoia.KindWolf;
prefabName = FenrirMangiatoia.WolfName;
wait = FenrirMangiatoia.WolfSeconds;
cost = FenrirMangiatoia.WolfCost;
return true;
}
if (ulv < UlvCap())
{
kind = FenrirMangiatoia.KindUlv;
prefabName = FenrirMangiatoia.UlvName;
wait = FenrirMangiatoia.UlvSeconds;
cost = FenrirMangiatoia.UlvCost;
return true;
}
if (fenrir < FenrirCap())
{
kind = FenrirMangiatoia.KindFenrir;
prefabName = FenrirMangiatoia.FenrirName;
wait = FenrirMangiatoia.FenrirSeconds;
cost = FenrirMangiatoia.FenrirCost;
return true;
}
kind = null;
prefabName = null;
wait = 0f;
cost = 0f;
return false;
}
/// <summary>
/// [DEBUG] Raises the next <paramref name="count"/> animals at once, skipping only the wait.
///
/// The meat is still charged and the tank is topped up to cover it, because a full roster is
/// far more meat than a tank holds and the point of the command is to skip the CLOCK, not the
/// economy. Everything else - which rank is next, its cap, whether the upgrade has opened the
/// third one - comes from NextShort, the same call the timer uses.
/// </summary>
public static void ForceNearby(Player player, int count)
{
FenrirMangiatoiaBehaviour trough = NearestTo(player.transform.position);
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid())
{
Console.instance.Print("No trough within 60m.");
return;
}
trough.m_nview.ClaimOwnership();
int raised = 0;
for (int i = 0; i < count; i++)
{
if (!trough.NextShort(out _, out string prefabName, out _, out float cost)) break;
if (trough.GetFeed() < cost) trough.SetFeed(FenrirMangiatoia.TankCap);
if (!trough.Spawn(prefabName)) break;
trough.SetFeed(trough.GetFeed() - cost);
raised++;
}
trough.m_timer = 0f;
Console.instance.Print(raised == 0
? "The pack is already whole."
: $"{raised} raised on the spot. The roster picked them, in its own order.");
}
/// <summary>
/// The roster, counted fresh. Never banked: a tally would have to be corrected on death, on
/// despawn and on a player killing his own, and any one of those going missing leaves a
/// trough that thinks it is full forever.
/// </summary>
private void Count(out int wolves, out int ulv, out int fenrir)
{
wolves = 0;
ulv = 0;
fenrir = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
if (thrall.Kind == FenrirMangiatoia.KindWolf) wolves++;
else if (thrall.Kind == FenrirMangiatoia.KindUlv) ulv++;
else if (thrall.Kind == FenrirMangiatoia.KindFenrir) fenrir++;
}
}
private bool Spawn(string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] No '{prefabName}' in ZNetScene; the trough cannot raise anything.");
return false;
}
Vector3 offset = UnityEngine.Random.insideUnitSphere * 3f;
offset.y = 0f;
Vector3 position = transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
// Bind tames it, marks whose it is, and sends it home - all three.
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
return true;
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
if (user == null) return false;
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindAnyInput(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, "It wants meat. Any meat.");
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName == null) return false;
if (prefabName == FenrirMangiatoia.GreaterUlvsblodName) return TryUpgrade(user, inventory, item);
if (!FenrirMangiatoia.IsMeat(prefabName))
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (GetFeed() >= FenrirMangiatoia.TankCap)
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
// A whole stack per click. A full tank is a lot of neck tails and clicking them out one
// at a time is not a mechanic.
int stack = Mathf.Max(1, item.m_stack);
user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{stack}");
inventory.RemoveItem(item, stack);
m_nview.InvokeRPC("RoV_FenrirFeed", prefabName, stack);
return true;
}
private ItemDrop.ItemData FindAnyInput(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
string name = candidate.m_dropPrefab.name;
if (name == FenrirMangiatoia.GreaterUlvsblodName) return candidate;
if (FenrirMangiatoia.IsMeat(name)) return candidate;
}
return null;
}
/// <summary>
/// The 1500-coin upgrade, and the second boss gate. Nothing about the trough changes to look
/// at - which is exactly why the hover text has to say it, or the next thing that happens is
/// somebody buys a second one.
/// </summary>
private bool TryUpgrade(Humanoid user, Inventory inventory, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
user.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < FenrirMangiatoia.UpgradeProgressionState)
{
user.Message(MessageHud.MessageType.Center, "The blood will not take. Something in the plains has to fall first.");
return false;
}
if (inventory.CountItems(YagluthDropName()) < 1)
{
user.Message(MessageHud.MessageType.Center, "It wants what Yagluth left behind.");
return false;
}
inventory.RemoveItem(YagluthDropName(), 1);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_FenrirUpgrade");
user.Message(MessageHud.MessageType.Center, "The trough takes it. The line runs deeper now.");
return true;
}
/// <summary>Inventory.RemoveItem and CountItems work on the DISPLAYED name, not the prefab.</summary>
private static string YagluthDropName()
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(FenrirMangiatoia.YagluthDrop);
return drop != null ? drop.m_itemData.m_shared.m_name : FenrirMangiatoia.YagluthDrop;
}
// ---------------------------------------------------------------- accounting
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) count = 1;
SetFeed(GetFeed() + FenrirMangiatoia.FeedValue(prefabName) * count);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
/// <summary>
/// The trough sustains the pack, so it takes the pack with it - on the wither's delay rather
/// than on the spot. Without some form of this, a trough is a duplication exploit: fill it,
/// dismantle it, rebuild it elsewhere, and keep every animal from every round.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
foreach (RaisedThrall thrall in bound) thrall.MarkOrphaned();
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
$"The trough is broken. {bound.Count} will not outlast it by long.");
}
SetFeed(0f);
}
// ---------------------------------------------------------------- state and display
public bool IsUpgraded() =>
m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private int WolfCap() => IsUpgraded() ? FenrirMangiatoia.WolfSlotsUpgraded : FenrirMangiatoia.WolfSlots;
private int UlvCap() => IsUpgraded() ? FenrirMangiatoia.UlvSlotsUpgraded : FenrirMangiatoia.UlvSlots;
private int FenrirCap() => IsUpgraded() ? FenrirMangiatoia.FenrirSlotsUpgraded : FenrirMangiatoia.FenrirSlots;
private float GetFeed() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFeed) : 0f;
private void SetFeed(float value)
{
if (m_nview != null && m_nview.IsValid())
{
m_nview.GetZDO().Set(KeyFeed, Mathf.Clamp(value, 0f, FenrirMangiatoia.TankCap));
}
}
/// <summary>
/// Everything a player needs without opening a log, which is the standard this project
/// arrived at the hard way: a mechanic that cannot say whether it is working looks exactly
/// like one that is broken.
/// </summary>
private string Hover()
{
Count(out int wolves, out int ulv, out int fenrir);
string body = $"meat {Mathf.Floor(GetFeed())}/{FenrirMangiatoia.TankCap}" +
$"\nwolves {wolves}/{WolfCap()}, ulv {ulv}/{UlvCap()}";
// Said in as many words, because the upgrade is deliberately invisible on the model.
body += IsUpgraded()
? $", fenrir {fenrir}/{FenrirCap()}"
: "\nthe blood is thin here - it raises no fenrir yet";
if (m_waitingFor != null)
{
float wait = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfSeconds
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvSeconds
: FenrirMangiatoia.FenrirSeconds;
float cost = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfCost
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvCost
: FenrirMangiatoia.FenrirCost;
body += GetFeed() < cost
? $"\nnot enough meat for the next one ({cost} needed)"
: $"\nnext in {Mathf.Max(1, Mathf.CeilToInt(wait - m_timer))}s";
}
else
{
body += "\nthe pack is whole";
}
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Fill it with meat";
return Localization.instance.Localize($"{FenrirMangiatoia.PieceDisplayName} ({body})");
}
}
}

View file

@ -30,6 +30,11 @@ namespace RacesOfValheim {
public void CreateModAssets()
{
// The pack trough and its bloodline. Registered here because the faction merchant
// catalogue resolves its entries by prefab name, so both Ulvsblod have to exist before a
// Fenring is ever set up as a bench.
FenrirMangiatoia.Register();
curseSE = ScriptableObject.CreateInstance<SE_FenrirCurse>();
curseSE.name = "SE_FenrirCurse";
curseSE.m_name = "Fenrir's Blood";

View file

@ -141,7 +141,28 @@ namespace RacesOfValheim
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (!HollowAllowsPiece(__instance, __0)) return false;
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
/// <summary>
/// "You may build in your hollow, but nothing takes root there." Rides along on this prefix
/// rather than adding a second one, which is the whole reason this class exists.
///
/// Worth knowing that the refusal is about the MESSAGE, not about making the impossible
/// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated-
/// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate
/// and no biome to match, so a seed would have failed anyway - with a vanilla error that says
/// nothing useful about why.
/// </summary>
private static bool HollowAllowsPiece(Player player, Piece piece)
{
if (!SkadiHollow.IsInside(player)) return true;
if (piece.GetComponentInChildren<Plant>(true) == null) return true;
player.Message(MessageHud.MessageType.Center, "Nothing takes root here.");
return false;
}
}
}

View file

@ -0,0 +1,212 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// "A troll cave is a house, if you are the right sort of thing."
///
/// Skadi and Trol may build inside ANY troll cave in the world.
///
/// THE ACTUAL RESTRICTION, found only after the game was asked instead of guessed at: a troll
/// cave counts as a DUNGEON, and Valheim refuses any piece whose Piece.m_allowedInDungeons is
/// false while the player is in one - "Can't build in a dungeon". That is a per-PIECE flag, not a
/// per-location one.
///
/// Two earlier versions of this file cleared Location.m_noBuild instead. That is a real
/// restriction and it is still cleared below, but it was never the one refusing these
/// placements, which is why lifting it changed nothing twice in a row. The lesson is in the log
/// line this class now prints: Player.m_placementStatus names the exact reason, and reading it
/// would have answered the question on the first report rather than the third.
///
/// The flag is flipped only while an eligible player is actually standing in a troll cave, and
/// put back when they leave, so this does not quietly become "build anywhere in any crypt". It
/// touches only the pieces on the build tables the player is carrying, and placement checks are
/// client-side, so nobody else's game is affected.
/// </summary>
public class RaceCaveBuilding : MonoBehaviour
{
/// <summary>Matches both troll cave locations this build has: TrollCave and TrollCave02.</summary>
private const string CaveNameFragment = "TrollCave";
/// <summary>Slack on the location's own radius, since the inside of a cave is not a neat sphere.</summary>
private const float RadiusSlack = 12f;
private const float CheckInterval = 0.25f;
private float nextCheck;
private bool allowing;
private readonly List<Piece> flipped = new List<Piece>();
private string lastReport;
private string lastHow = "not checked yet";
private void Update()
{
if (Time.time < nextCheck) return;
nextCheck = Time.time + CheckInterval;
Player player = Player.m_localPlayer;
if (player == null) return;
if (!SkadiRace.IsLocalSkadi() && !TrolRace.IsTrol())
{
Restore();
return;
}
bool inCave = IsInTrollCave(player, out string how);
lastHow = how;
if (inCave && !allowing) Allow(player);
else if (!inCave && allowing) Restore();
ReportWhyIfRefused(player);
}
/// <summary>
/// Two ways of asking, because the two cases are genuinely different.
///
/// FIRST, Location.GetLocation(point, checkDungeons: true). That flag exists for exactly this
/// question - "which location owns this point, counting dungeon interiors" - and it is the
/// only one of the two that can answer it when the interior is not where the mouth is. The
/// previous version of this file dropped it in favour of a distance sweep, and that is why
/// the log said "in troll cave=False" while the player was standing in one: a distance test
/// against the mouth cannot find a player who is inside.
///
/// SECOND, the sweep, kept as the case the first one is weakest at: standing at the mouth,
/// outside, where there is no interior to own the point.
/// </summary>
private static bool IsInTrollCave(Player player, out string how)
{
Vector3 position = player.transform.position;
Location owning = Location.GetLocation(position, true);
if (owning != null && IsTrollCave(owning))
{
LiftOutrightBan(owning);
how = $"GetLocation -> {owning.gameObject.name}";
return true;
}
foreach (Location location in Object.FindObjectsByType<Location>(FindObjectsSortMode.None))
{
if (location == null || !IsTrollCave(location)) continue;
if (Vector3.Distance(position, location.transform.position) > location.GetMaxRadius() + RadiusSlack) continue;
LiftOutrightBan(location);
how = $"nearby -> {location.gameObject.name}";
return true;
}
how = owning != null ? $"owned by '{owning.gameObject.name}', not a cave" : "no location owns this point";
return false;
}
private static bool IsTrollCave(Location location)
{
return location.gameObject.name.IndexOf(CaveNameFragment, System.StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// Cheap and harmless while we are here: a location may also forbid building outright, and
/// that ban would beat everything else. It is NOT what refuses a piece in a troll cave - that
/// was two wrong guesses ago - but a cave that did set it would be unbuildable for a second,
/// separate reason.
/// </summary>
private static void LiftOutrightBan(Location location)
{
if (!location.m_noBuild) return;
location.m_noBuild = false;
Jotunn.Logger.LogInfo($"[Races] '{location.gameObject.name}' also forbade building outright; cleared that too.");
}
/// <summary>
/// Marks every piece on the build tables the player is carrying as dungeon-legal, remembering
/// which ones were not so they can be put back exactly as they were.
/// </summary>
private void Allow(Player player)
{
Inventory inventory = player.GetInventory();
if (inventory == null) return;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
PieceTable table = item?.m_shared?.m_buildPieces;
if (table == null || table.m_pieces == null) continue;
foreach (GameObject entry in table.m_pieces)
{
Piece piece = entry != null ? entry.GetComponent<Piece>() : null;
if (piece == null || piece.m_allowedInDungeons) continue;
piece.m_allowedInDungeons = true;
flipped.Add(piece);
}
}
allowing = true;
Jotunn.Logger.LogInfo($"[Races] In a troll cave: {flipped.Count} pieces temporarily allowed in dungeons.");
player.Message(MessageHud.MessageType.Center, "This cave will hold what you build in it.");
}
/// <summary>
/// Puts the flags back. Without this the permission would follow the player into every crypt
/// and sunken chamber in the world, which is not what was asked for.
/// </summary>
private void Restore()
{
if (!allowing) return;
foreach (Piece piece in flipped)
{
if (piece != null) piece.m_allowedInDungeons = false;
}
Jotunn.Logger.LogInfo($"[Races] Left the troll cave: {flipped.Count} pieces set back to dungeon-forbidden.");
flipped.Clear();
allowing = false;
}
private void OnDestroy()
{
Restore();
}
/// <summary>
/// Says, in the log, exactly why the game is refusing a placement right now. m_placementStatus
/// is private and Player cannot be inspected offline at all, so it is read with Traverse and
/// printed by name - the enum's own ToString does the translating, so this cannot fall out of
/// step with the game's own list of reasons. Only speaks when the answer changes.
/// </summary>
private void ReportWhyIfRefused(Player player)
{
object status = Traverse.Create(player).Field("m_placementStatus").GetValue();
if (status == null) return;
string statusName = status.ToString();
if (statusName == "Valid") { lastReport = null; return; }
string report = statusName + "|" + lastHow;
if (report == lastReport) return;
lastReport = report;
// The player's own position and the distance to the nearest troll cave MOUTH are here for
// one reason: if a refusal ever survives with "in troll cave=False", these two numbers say
// whether the interior sits near its mouth or has been relocated somewhere else entirely -
// which is the difference between a tolerance to widen and a wrong idea about the world.
Vector3 position = player.transform.position;
string nearest = "<none in this world>";
if (ZoneSystem.instance != null
&& ZoneSystem.instance.FindClosestLocation("TrollCave02", position, out ZoneSystem.LocationInstance closest))
{
nearest = $"{Vector3.Distance(position, closest.m_position):0} m away at {closest.m_position}";
}
Jotunn.Logger.LogInfo($"[Races] Placement refused: {statusName} " +
$"(in troll cave={allowing}, pieces flipped={flipped.Count}). " +
$"Detection said: {lastHow}. Player at {position}; nearest TrollCave02 mouth {nearest}.");
}
}
}

View file

@ -46,6 +46,9 @@ namespace RacesOfValheim
gameObject.AddComponent<DraughRace>();
gameObject.AddComponent<DvergarRace>();
gameObject.AddComponent<TrentaRace>();
// Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it
// gets its own component rather than living inside either one's Update.
gameObject.AddComponent<RaceCaveBuilding>();
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
@ -53,6 +56,8 @@ namespace RacesOfValheim
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
CommandManager.Instance.AddConsoleCommand(new DumpElderCommand());
CommandManager.Instance.AddConsoleCommand(new FenrirPackSpawnCommand());
CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand());
}
/// <summary>

View file

@ -34,6 +34,12 @@
<Reference Include="assembly_valheim">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll</HintPath>
</Reference>
<!-- Needed by SkadiHollow: ZoneSystem.ZoneLocation.m_prefab is a SoftReference<GameObject>,
and touching any member of it (Load/Asset/IsLoaded) does not compile unless the assembly
that declares SoftReference<T> is referenced. Nothing else in the mod uses it yet. -->
<Reference Include="SoftReferenceableAssets">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\SoftReferenceableAssets.dll</HintPath>
</Reference>
<!-- Jotunn 2.29.2 references a Unity module this build of Valheim no longer ships, and the
unresolvable reference warned on every build. Nothing here uses it. -->
<Reference Remove="UnityEngine.ProfilerModule" />

View file

@ -48,6 +48,12 @@ namespace RacesOfValheim
// ─── Passive combat ──────────────────────────────────────────────────
public static ConfigEntry<float> BonusFrostDamagePerState;
// ─── Skadis Nokkel / the hidden hollow ───────────────────────────────
public static ConfigEntry<float> HollowCooldown;
public static ConfigEntry<float> HollowPortalCloseDelay;
public static ConfigEntry<float> HollowPortalSpawnDistance;
public static ConfigEntry<float> HollowEntryHeight;
// ─── Dragon forms: scale ─────────────────────────────────────────────
public static ConfigEntry<float> DrakeScale;
public static ConfigEntry<float> ModerScale;
@ -102,6 +108,16 @@ namespace RacesOfValheim
BonusFrostDamagePerState = config.Bind(combat, "Bonus Frost Damage Per State", 2f,
new ConfigDescription("Flat frost damage added to every hit the player lands, multiplied by the current progression state.", new AcceptableValueRange<float>(0f, 10f)));
const string hollow = "Skadi - Hidden Hollow";
HollowCooldown = config.Bind(hollow, "Cooldown", 120f,
new ConfigDescription("Seconds between openings of the hollow. This is the only brake on Skadis Nokkel - it costs no stamina, eitr or health - and it never applies to LEAVING: stepping in and changing your mind must not lock you in.", new AcceptableValueRange<float>(0f, 600f)));
HollowPortalCloseDelay = config.Bind(hollow, "Portal Close Delay", 5f,
new ConfigDescription("Seconds the portal pair lingers after the player comes back out. Until then both ends simply stand there - unlike the Trenta portal, this one has no lifetime of its own.", new AcceptableValueRange<float>(0f, 60f)));
HollowPortalSpawnDistance = config.Bind(hollow, "Portal Spawn Distance", 2f,
new ConfigDescription("Metres in front of the player the outside end of the portal appears.", new AcceptableValueRange<float>(0.5f, 10f)));
HollowEntryHeight = config.Bind(hollow, "Entry Height", 1f,
new ConfigDescription("Height above the claimed troll cave's own origin that the inner portal stands at. Raise it if arriving ever puts the player inside the ground.", new AcceptableValueRange<float>(0f, 20f)));
const string spell = "Skadi - Cold Spell";
SpellStaminaCost = config.Bind(spell, "Stamina Cost", 20f,
new ConfigDescription("Stamina spent per cast.", new AcceptableValueRange<float>(0f, 100f)));

View file

@ -0,0 +1,57 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Greater Frost Heart - the bought leg of the Skadi recipe, and the piece that keeps this chain
/// hooked to the faction merchant system the way every other race's does. 1500 coins from the
/// Cultist bench, which is the same price band as GreaterUlvsblod, GreaterCursedBone and
/// GreaterCursedSkull: the reagent that unlocks the last step of a race's chain.
///
/// A NOTE ON THE SHOP KEY, because it has already cost this project once: the Cultist shop in
/// FactionMerchantCatalog is mapped on the mob "Fenring_Cultist", NOT on "Fenring" - that one is
/// a different bench belonging to the Fenrir trough. Selling from the wrong one puts the item in
/// a shop nobody expects.
/// </summary>
public static class SkadiFrostHeart
{
public const string PrefabName = "GreaterFrostHeart";
public const string DisplayName = "Greater Frost Heart";
public const int Price = 1500;
private const string SourcePrefab = "FreezeGland";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
SkadiIce.Apply(prefab);
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "Older cold than the mountain's. The cultists sell it and will not say where they dig.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 10;
shared.m_value = Price;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered at {Price} coins.");
}
}
}

View file

@ -0,0 +1,256 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Where Skadis Nokkel takes you: a troll cave that already exists in the world, the same one
/// every time, claimed the first time the staff is used.
///
/// THIRD AND FINAL SHAPE, and it is by far the smallest. What used to be here - instantiating a
/// cave shell, learning where its interior was, emptying it of trolls, standing three benches up
/// in it - is all gone. Four things that could each fail, and between them always did.
///
/// What makes the cave usable now is not here at all: RaceCaveBuilding lets a Skadi (and a Trol)
/// build inside ANY troll cave, by lifting the one restriction that mattered. So this file has
/// nothing left to arrange. It picks a cave, it remembers which, and it opens a door to it.
///
/// The three failed designs are on the record in Skadi_PortaleGhiaccio.txt sections 0c to 0g, in
/// particular the two facts that killed them: DestroyImmediate is forbidden inside an animation
/// event callback (and the cast runs in one), and a location's m_position is its MOUTH rather
/// than its inside - which is why the portal kept putting the player out on the hillside.
/// </summary>
public static class SkadiHollow
{
/// <summary>
/// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to
/// us), MountainCave01, MountainCave02 and Hildir_cave.
/// </summary>
public const string SourceLocation = "TrollCave02";
// ─── Which cave ───────────────────────────────────────────────────────
//
// "Half way out, and away from the north." Half of the world's ~10 km radius is 5000, and the
// band is generous because a Black Forest troll cave has to actually exist in it.
private const float ClaimRadiusMin = 3500f;
private const float ClaimRadiusMax = 6500f;
/// <summary>
/// Everything with a positive Z is thrown out, which is the whole northern half of the map.
/// Cruder than a bearing test and that is deliberate: it cannot accidentally admit the Deep
/// North, which is where the first design landed.
/// </summary>
private const float MaxNorthing = 0f;
/// <summary>
/// How far from the cave counts as "at my hollow" - used only by the no-planting rule now.
/// Wide, because the cave's origin is its mouth and the inside is some way past it.
/// </summary>
public const float Radius = 72f;
// The claim is written down rather than recomputed. It depends on where this world's troll
// caves are and on the order the candidates come back in, so recomputing it after any change
// to either would hand the player a different cave and orphan everything built in the old one.
private const string CaveKey = "Skadi_HollowCave";
private const string ReturnPointKey = "Skadi_HollowReturn";
private static float lastCastTime = -100000f;
// ─── Claiming ─────────────────────────────────────────────────────────
/// <summary>
/// This player's cave, if they have claimed one. Does not allocate: it is called from the
/// build prefix, which runs on every attempted placement.
/// </summary>
public static bool TryGetCave(Player player, out Vector3 cave)
{
cave = Vector3.zero;
if (player == null || player.m_customData == null) return false;
return TryReadVector(player, CaveKey, out cave);
}
public static bool IsInside(Player player)
{
if (player == null) return false;
if (!TryGetCave(player, out Vector3 cave)) return false;
return (player.transform.position - cave).sqrMagnitude <= Radius * Radius;
}
private static bool TryClaimCave(Player player, out Vector3 cave)
{
if (TryGetCave(player, out cave)) return true;
List<Vector3> candidates = FindCandidateCaves();
if (candidates.Count == 0)
{
Jotunn.Logger.LogWarning($"[Skadi] No '{SourceLocation}' found in the Black Forest between " +
$"{ClaimRadiusMin:0} m and {ClaimRadiusMax:0} m of the centre, south of the equator. " +
"The hollow cannot be claimed in this world.");
return false;
}
// Sorted before indexing, because GetLocationList() makes no promise about order and an
// unstable order would mean an unstable claim on the very first cast.
candidates.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.z.CompareTo(b.z));
cave = candidates[(int)(HashOf(player) % (uint)candidates.Count)];
player.m_customData[CaveKey] = FormatVector(cave);
Jotunn.Logger.LogInfo($"[Skadi] Hollow claimed for '{player.GetPlayerName()}': {SourceLocation} at {cave} " +
$"({BiomeAt(cave)}, {new Vector2(cave.x, cave.z).magnitude:0} m from the centre) " +
$"- chosen from {candidates.Count} candidates.");
return true;
}
private static List<Vector3> FindCandidateCaves()
{
List<Vector3> found = new List<Vector3>();
if (ZoneSystem.instance == null) return found;
foreach (ZoneSystem.LocationInstance instance in ZoneSystem.instance.GetLocationList())
{
if (instance.m_location == null) continue;
if (instance.m_location.m_prefabName != SourceLocation) continue;
Vector3 position = instance.m_position;
if (position.z > MaxNorthing) continue;
float distance = new Vector2(position.x, position.z).magnitude;
if (distance < ClaimRadiusMin || distance > ClaimRadiusMax) continue;
if (BiomeAt(position) != Heightmap.Biome.BlackForest) continue;
found.Add(position);
}
return found;
}
private static Heightmap.Biome BiomeAt(Vector3 point)
{
if (WorldGenerator.instance == null) return Heightmap.Biome.None;
return WorldGenerator.instance.GetBiome(new Vector3(point.x, 0f, point.z));
}
private static uint HashOf(Player player)
{
long id = player != null ? player.GetPlayerID() : 0L;
if (id == 0L)
{
string name = player != null ? player.GetPlayerName() : null;
id = string.IsNullOrEmpty(name) ? 1L : name.GetStableHashCode();
}
// Knuth's multiplicative hash, so two ids one apart do not pick neighbouring caves.
return (uint)(id ^ (id >> 32)) * 2654435761u;
}
// ─── The cast ─────────────────────────────────────────────────────────
/// <summary>
/// What Skadis Nokkel does. Outside, it opens the pair; inside, it takes the player straight
/// back out. The cooldown applies to going IN only - stepping in and changing your mind must
/// not lock you in a cave for two minutes.
///
/// The far end stands at the cave's mouth, and the player walks in from there. That is not a
/// compromise any more: since building works in the cave itself, there is nothing waiting
/// inside that has to be lined up with, so the one point we can name honestly is the right
/// one to use.
/// </summary>
public static void Cast(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
if (IsInside(player))
{
Leave(player);
return;
}
float cooldown = SkadiConfig.HollowCooldown.Value;
float waited = Time.time - lastCastTime;
if (waited < cooldown)
{
int remaining = Mathf.CeilToInt(cooldown - waited);
player.Message(MessageHud.MessageType.Center, $"The frost has not gathered again ({remaining}s).");
return;
}
if (!TryClaimCave(player, out Vector3 cave))
{
player.Message(MessageHud.MessageType.Center, "No hollow answers you.");
return;
}
lastCastTime = Time.time;
SkadiRace.ApplyCooldownIcon(SkadiRace.HOLLOW_COOLDOWN_SE, SkadiConfig.HollowCooldown.Value);
// Remembered across a logout, so casting from inside always has somewhere to put them.
player.m_customData[ReturnPointKey] = FormatVector(player.transform.position);
Vector3 castPoint = player.transform.position
+ player.transform.forward * SkadiConfig.HollowPortalSpawnDistance.Value;
SkadiHollowPortal.Open(castPoint, player.transform.rotation,
cave + Vector3.up * SkadiConfig.HollowEntryHeight.Value);
}
private static void Leave(Player player)
{
player.TeleportTo(ReturnPointFor(player), player.transform.rotation, true);
SkadiHollowPortal.CloseSoon();
}
/// <summary>
/// Called by the portal when the player walks through. Going in changes nothing - the pair
/// stands as long as they are inside. Coming out starts the collapse.
/// </summary>
public static void OnTraversed(bool intoHollow)
{
if (!intoHollow) SkadiHollowPortal.CloseSoon();
}
private static Vector3 ReturnPointFor(Player player)
{
if (TryReadVector(player, ReturnPointKey, out Vector3 stored)
&& TryGetCave(player, out Vector3 cave)
&& (stored - cave).sqrMagnitude > Radius * Radius) // a point inside would strand them
{
return stored;
}
// Same fallback the Trenta portal uses for its home end, and for the same reason: the
// respawn point is the one place the game itself considers always valid.
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
if (profile != null)
{
return profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint;
}
return PlayerProfile.m_originalSpawnPoint;
}
// ─── customData helpers ───────────────────────────────────────────────
private static string FormatVector(Vector3 v)
{
return $"{v.x:R};{v.y:R};{v.z:R}";
}
private static bool TryReadVector(Player player, string key, out Vector3 value)
{
value = Vector3.zero;
if (player == null || player.m_customData == null) return false;
if (!player.m_customData.TryGetValue(key, out string stored) || string.IsNullOrEmpty(stored)) return false;
string[] parts = stored.Split(';');
if (parts.Length != 3) return false;
System.Globalization.CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture;
const System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Float;
if (!float.TryParse(parts[0], style, invariant, out float x)) return false;
if (!float.TryParse(parts[1], style, invariant, out float y)) return false;
if (!float.TryParse(parts[2], style, invariant, out float z)) return false;
value = new Vector3(x, y, z);
return true;
}
}
}

View file

@ -0,0 +1,234 @@
using System.Collections;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// One end of the pair of portals Skadis Nokkel opens. Deliberately a copy of
/// TrentaPortalLink rather than a shared abstraction: the two diverge on colour, on who is
/// allowed through, and above all on when they close (the Trenta pair dies on a timer, this
/// one waits for the player to come back out), and three differences in a forty-line class is
/// cheaper duplicated than parameterised.
///
/// Everything the Trenta version earned is kept: a plain GameObject with no ZNetView, so it is
/// unregistered and purely local - which is most of "only the player can go in", since remote
/// clients never learn the thing exists - plus its own trigger, its own teleport call, and the
/// same guard against the same-frame ping-pong.
/// </summary>
public class SkadiHollowPortalLink : MonoBehaviour
{
public SkadiHollowPortalLink Other;
/// <summary>True on the end that stands inside the hollow.</summary>
public bool IsHollowSide;
// Without this, a player who arrives is still standing in the destination's own trigger and
// gets bounced straight back the way they came, forever.
private float reentryBlockedUntil = -1f;
private void OnTriggerEnter(Collider other)
{
if (Other == null || Time.time < reentryBlockedUntil) return;
Player player = other.GetComponentInParent<Player>();
if (player == null) return;
// The requirement spelled out, even though the portal being local already means no
// other player can reach this line: only the owner walks through.
if (player != Player.m_localPlayer) return;
Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f;
player.TeleportTo(destination, Other.transform.rotation, true);
Other.reentryBlockedUntil = Time.time + 1.5f;
// Going in leaves the pair standing; coming out starts the collapse.
SkadiHollow.OnTraversed(intoHollow: !IsHollowSide);
}
}
public static class SkadiHollowPortal
{
private static Material cachedVfxMaterial;
private static bool vfxMaterialResolved;
private static GameObject outsideEnd;
private static GameObject hollowEnd;
private static Coroutine closing;
public static bool IsOpen => outsideEnd != null || hollowEnd != null;
/// <summary>
/// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end
/// has a lifetime - they stand until CloseSoon is called.
/// </summary>
public static void Open(Vector3 outsidePoint, Quaternion outsideRotation, Vector3 hollowPoint)
{
CloseNow();
outsideEnd = SpawnEnd(outsidePoint, outsideRotation, isHollowSide: false);
hollowEnd = SpawnEnd(hollowPoint, Quaternion.identity, isHollowSide: true);
SkadiHollowPortalLink outsideLink = outsideEnd.GetComponent<SkadiHollowPortalLink>();
SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent<SkadiHollowPortalLink>();
outsideLink.Other = hollowLink;
hollowLink.Other = outsideLink;
}
/// <summary>
/// Takes both ends down after the configured grace period. Called when the player leaves the
/// hollow - by walking out or by casting from inside - which is the only thing that closes
/// this pair.
/// </summary>
public static void CloseSoon()
{
if (!IsOpen || closing != null) return;
if (SkadiRace.Instance == null) { CloseNow(); return; }
closing = SkadiRace.Instance.StartCoroutine(
CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value));
}
/// <summary>No grace period, no animation. For reopening, and for shutting down.</summary>
public static void CloseNow()
{
if (closing != null && SkadiRace.Instance != null)
{
SkadiRace.Instance.StopCoroutine(closing);
}
closing = null;
if (outsideEnd != null) Object.Destroy(outsideEnd);
if (hollowEnd != null) Object.Destroy(hollowEnd);
outsideEnd = null;
hollowEnd = null;
}
private static GameObject SpawnEnd(Vector3 position, Quaternion rotation, bool isHollowSide)
{
GameObject portal = new GameObject(isHollowSide ? "SkadiHollowPortal_In" : "SkadiHollowPortal_Out");
portal.transform.position = position;
portal.transform.rotation = rotation;
CapsuleCollider trigger = portal.AddComponent<CapsuleCollider>();
trigger.isTrigger = true;
trigger.height = 3f;
trigger.radius = 1.2f;
trigger.center = new Vector3(0, 1.5f, 0);
SkadiHollowPortalLink link = portal.AddComponent<SkadiHollowPortalLink>();
link.IsHollowSide = isHollowSide;
BuildSwirlVfx(portal.transform);
return portal;
}
/// <summary>
/// The swirl only, no wooden frame - same shape and same reasoning as the Trenta portal's:
/// borrow a particle material off the real portal prefab by READING it (never instantiating
/// it, so none of the real portal's gameplay components ever get a chance to run), then
/// drive shape, emission and colour from here. The one change is the colour, which is
/// Skadi's ice instead of the Trenta's toxic purple.
/// </summary>
private static void BuildSwirlVfx(Transform parent)
{
if (!vfxMaterialResolved)
{
vfxMaterialResolved = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("portal_wood");
if (source != null)
{
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
}
if (cachedVfxMaterial == null)
{
Jotunn.Logger.LogWarning("[Skadi] Hollow portal: no particle material on 'portal_wood'; using the default particle material.");
}
}
GameObject vfx = new GameObject("Swirl");
vfx.transform.SetParent(parent, false);
vfx.transform.localPosition = new Vector3(0, 1.2f, 0);
ParticleSystem ps = vfx.AddComponent<ParticleSystem>();
var main = ps.main;
main.loop = true;
main.startLifetime = 1.5f;
main.startSpeed = 0f;
main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f);
main.maxParticles = 200;
main.simulationSpace = ParticleSystemSimulationSpace.Local;
var emission = ps.emission;
emission.rateOverTime = 80f;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Circle;
shape.radius = 1f;
shape.radiusThickness = 0.1f; // hollow ring, not a filled disc
var rotationOverLifetime = ps.rotationOverLifetime;
rotationOverLifetime.enabled = true;
rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f);
ParticleSystemRenderer renderer = ps.GetComponent<ParticleSystemRenderer>();
if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(SkadiIce.PortalSwirl, 0f), new GradientColorKey(SkadiIce.PortalSwirl, 1f) },
new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) }
);
colorOverLifetime.color = grad;
ps.Play();
}
private static IEnumerator CloseAfter(float seconds)
{
yield return new WaitForSeconds(seconds);
GameObject a = outsideEnd;
GameObject b = hollowEnd;
outsideEnd = null;
hollowEnd = null;
closing = null;
yield return Collapse(a);
yield return Collapse(b);
}
/// <summary>
/// Link and trigger die first, so nothing can walk through mid-collapse, then a one-second
/// shrink stands in for a closing animation - vanilla portals are simply present or absent,
/// so there is no real one to borrow.
/// </summary>
private static IEnumerator Collapse(GameObject portal)
{
if (portal == null) yield break;
SkadiHollowPortalLink link = portal.GetComponent<SkadiHollowPortalLink>();
if (link != null) Object.Destroy(link);
CapsuleCollider trigger = portal.GetComponent<CapsuleCollider>();
if (trigger != null) Object.Destroy(trigger);
float t = 0f;
Vector3 startScale = portal.transform.localScale;
while (t < 1f)
{
if (portal == null) yield break;
t += Time.deltaTime;
portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
yield return null;
}
if (portal != null) Object.Destroy(portal);
}
}
}

View file

@ -0,0 +1,396 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
/// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the
/// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8.
/// </summary>
public static class SkadiIce
{
public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f);
/// <summary>
/// Multiplies the ice tint over whatever the base texture already carries instead of
/// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
/// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
/// that one it copies each material first so the vanilla asset is never touched.
/// </summary>
public static void Apply(GameObject root)
{
if (root == null) return;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] source = renderer.sharedMaterials;
Material[] tinted = new Material[source.Length];
for (int i = 0; i < source.Length; i++)
{
if (source[i] == null) continue;
Material material = new Material(source[i]);
if (material.HasProperty("_Color"))
{
Color baseColor = material.GetColor("_Color");
material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
baseColor.g * Albedo.g,
baseColor.b * Albedo.b,
baseColor.a));
}
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
tinted[i] = material;
}
renderer.sharedMaterials = tinted;
}
}
}
/// <summary>
/// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no
/// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal
/// into the player's own hidden hollow (SkadiHollow).
///
/// The name is the point. It is not a weapon that happens to open a door, it is a key - and a
/// reproducible one: losing it costs a trip to the forge, not the hollow.
///
/// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping:
/// - every field that could carry a cost or a summon is zeroed on the clone (Strip below);
/// - the attack trigger itself is intercepted and vanilla's never runs for this staff
/// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it;
/// taking over the method means that code path is not merely defused, it is unreachable.
/// </summary>
public static class SkadiNokkel
{
public const string PrefabName = "SkadiNokkel";
public const string DisplayName = "Skadis Nokkel";
private const string SourcePrefab = "StaffSkeleton";
private const string ModerDrop = "DragonTear";
private const string SkullTrophy = "TrophySkeleton";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " +
"that is yours and no one else's - and used again, it lets you out.";
shared.m_useDurability = false;
// ItemType is left exactly as the vanilla staff has it, on purpose: it decides the
// equip slot and which animation set the character uses, and the cast gesture is the
// whole reason this is a staff and not a trinket.
Strip(shared);
SkadiIce.Apply(prefab);
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
LogCosts("straight after registering", shared);
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
Requirements = new[]
{
new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig(SkullTrophy, 1, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon.");
}
/// <summary>
/// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
/// secondary is a separate Attack with its own copy of every cost.
///
/// The summon is the interesting one: it comes from a SpawnAbility component (verified class,
/// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off
/// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not
/// knowable from the game files, so all of them go. Nulling three fields that might each be
/// the culprit costs nothing; guessing wrong costs a skeleton every cast.
///
/// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment
/// someone wants to flee into their hollow is exactly the moment they have no stamina left.
/// The only brake on this staff is its cooldown.
/// </summary>
private static void Strip(ItemDrop.ItemData.SharedData shared)
{
StripAttack(shared.m_attack);
StripAttack(shared.m_secondaryAttack);
}
private static void StripAttack(Attack attack)
{
if (attack == null) return;
attack.m_attackEitr = 0f;
attack.m_drawEitrDrain = 0f;
attack.m_reloadEitrDrain = 0f;
attack.m_attackHealth = 0f;
attack.m_attackHealthPercentage = 0f;
attack.m_attackHealthLowBlockUse = false;
attack.m_attackHealthReturnHit = 0f;
attack.m_attackStamina = 0f;
attack.m_drawStaminaDrain = 0f;
attack.m_reloadStaminaDrain = 0f;
attack.m_attackProjectile = null;
attack.m_spawnOnTrigger = null;
attack.m_spawnOnHit = null;
attack.m_spawnOnHitChance = 0f;
// The animation stays. It is the summoning gesture, which is the right gesture for
// opening a way, and it is the same one TrentaAbilities plays by hand for its portal.
}
/// <summary>
/// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands
/// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks
/// AswidRace.IsAswid() before doing anything at all.
/// </summary>
public static void OnCast(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
if (!SkadiRace.IsLocalSkadi())
{
player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else.");
return;
}
SkadiHollow.Cast(player);
}
public static bool IsNokkel(ItemDrop.ItemData item)
{
return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
}
/// <summary>
/// True when a cost being asked about belongs to this staff.
///
/// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost
/// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned
/// by the time the cost is checked. It is deliberately only consulted when m_weapon is null,
/// so a creature's own attack cannot be zeroed just because the player happens to be holding
/// the staff at the time.
/// </summary>
public static bool IsNokkelContext(ItemDrop.ItemData weapon)
{
if (weapon != null) return IsNokkel(weapon);
Player local = Player.m_localPlayer;
return local != null && IsNokkel(local.GetCurrentWeapon());
}
/// <summary>
/// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a
/// mystery and becomes a number with a timestamp. Called once at registration and again from
/// the F8 dump, which between them say whether the zeroes were never written or were written
/// and then overwritten by something else.
/// </summary>
public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared)
{
if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; }
Attack primary = shared.m_attack;
Attack secondary = shared.m_secondaryAttack;
Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " +
$"primary eitr={Describe(primary, a => a.m_attackEitr)} " +
$"health={Describe(primary, a => a.m_attackHealth)} " +
$"health%={Describe(primary, a => a.m_attackHealthPercentage)} " +
$"stamina={Describe(primary, a => a.m_attackStamina)} | " +
$"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " +
$"stamina={Describe(secondary, a => a.m_attackStamina)}");
}
private static string Describe(Attack attack, System.Func<Attack, float> read)
{
return attack == null ? "<no attack>" : read(attack).ToString("0.##");
}
/// <summary>
/// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once
/// off a running game: which field of the vanilla staff carries the summon, and what the
/// troll cave location is really called in this build.
/// </summary>
public static void DumpSource()
{
Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ===");
GameObject staff = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
ItemDrop staffDrop = staff != null ? staff.GetComponent<ItemDrop>() : null;
if (staffDrop == null)
{
Jotunn.Logger.LogWarning($"{SourcePrefab} not found.");
}
else
{
Attack attack = staffDrop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}");
Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}");
Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}");
Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%");
foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger })
{
if (candidate == null) continue;
foreach (SpawnAbility ability in candidate.GetComponentsInChildren<SpawnAbility>(true))
{
string spawns = "<none>";
if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0)
{
string[] names = new string[ability.m_spawnPrefab.Length];
for (int i = 0; i < names.Length; i++)
{
names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : "<null>";
}
spawns = string.Join(", ", names);
}
Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}");
}
}
}
// The clone as the game currently holds it, not as Register() left it. If these are not
// zero, the write in Strip() did not survive - which is the whole reason
// SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still
// needed or whether the fields hold after all.
GameObject clone = PrefabManager.Cache.GetPrefab<GameObject>(PrefabName);
ItemDrop cloneDrop = clone != null ? clone.GetComponent<ItemDrop>() : null;
if (cloneDrop == null)
{
Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache.");
}
else
{
LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared);
Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}");
}
// The other half: is 'TrollCave02' actually what it is called here?
Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---");
if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null)
{
Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first.");
}
else
{
// m_locations, not GetLocationList(): the latter is public but returns the locations
// PLACED in this world, and the hollow needs the definition, not an instance.
foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations)
{
if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue;
if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue;
Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " +
$"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})");
}
}
Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ===");
}
}
/// <summary>
/// The cast hook, and the second half of "remove the unwanted components".
///
/// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters -
/// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's
/// parameter types could not even be loaded for inspection outside the game. It also fires at
/// the moment the animation reaches its release point, which is exactly when a cast should land.
///
/// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff
/// vanilla's attack-trigger code never executes at all. The summon and the projectile are not
/// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the
/// nulls we left behind either, which a postfix would have been at the mercy of.
///
/// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple
/// underscore field injection rather than off __instance - which is also why they are spelled
/// out here instead of being read with Traverse: the injection is checked at patch time, so a
/// rename shows up as a startup error instead of a silent null every cast.
/// </summary>
[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
public static class SkadiNokkelCastPatch
{
public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
{
if (!SkadiNokkel.IsNokkel(___m_weapon)) return true;
SkadiNokkel.OnCast(___m_character as Player);
return false;
}
}
/// <summary>
/// The staff costs nothing, guaranteed - and this is what guarantees it.
///
/// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in
/// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus
/// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData
/// carries none at all (checked field by field). In game the cost came back anyway, which means
/// the write to the clone's own SharedData does not survive something - so relying on that write
/// is relying on a mechanism that has already been observed to fail.
///
/// These three getters are the single funnel every cost check flows through: Attack.Start asks
/// them before it will start, and the tooltip asks them for what to print. Forcing them to zero
/// makes the staff free no matter what any field says, which is the same reasoning as the prefix
/// above - do not defuse the code path, remove it.
///
/// All three are PRIVATE and take no parameters, so they are addressed by name through
/// AccessTools and share one postfix.
/// </summary>
[HarmonyPatch]
public static class SkadiNokkelFreeCastPatch
{
[HarmonyTargetMethods]
private static System.Collections.Generic.IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
}
[HarmonyPostfix]
private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
{
if (__result == 0f) return;
if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return;
__result = 0f;
}
}
}

View file

@ -33,6 +33,7 @@ namespace RacesOfValheim
// rebuild - see CONFIGURATION-MANAGER-HOWTO.md.
public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown";
public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown";
public const string HOLLOW_COOLDOWN_SE = "SE_SkadiHollowCooldown";
private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value;
private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value;
@ -50,6 +51,12 @@ namespace RacesOfValheim
public void CreateModAssets()
{
// The reagent goes first: the faction merchant catalogue resolves its entries by prefab
// name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a
// bench - and the staff's recipe references it by name too.
SkadiFrostHeart.Register();
SkadiNokkel.Register();
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
se.name = "SE_SkadiStats";
se.m_name = "Skadi's Blessing";
@ -101,6 +108,13 @@ namespace RacesOfValheim
attackCd.m_tooltip = "Your dragon shape must ready itself to strike again.";
attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false));
var hollowCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
hollowCd.name = HOLLOW_COOLDOWN_SE;
hollowCd.m_name = "Skadis Nokkel";
hollowCd.m_tooltip = "The way to your hollow must freeze over again before it will open.";
hollowCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(hollowCd, fixReference: false));
}
// Drives the HUD countdown: Valheim prints the remaining time on any status effect whose
@ -133,8 +147,17 @@ namespace RacesOfValheim
public bool IsSkadi()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
return IsLocalSkadi();
}
/// <summary>
/// The same check, reachable without an Instance - which the Nokkel's Harmony patch and the
/// hollow both need, since they run from static context.
/// </summary>
public static bool IsLocalSkadi()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skadi";
}
@ -231,7 +254,8 @@ namespace RacesOfValheim
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!");
SkadiNokkel.DumpSource();
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader + Nokkel debug info to console!");
}
}