RacesOfValheim/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs
Ferdinando 5c5b8c34d2 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>
2026-08-08 14:58:43 +02:00

290 lines
11 KiB
C#

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})");
}
}
}