RacesOfValheim/JotunnModStub/Alfar/AlfarNexus.cs
Ferdinando 3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00

576 lines
25 KiB
C#

using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole
/// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers
/// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations.
///
/// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product
/// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first
/// version stepped through the products with Shift+E, which gave trouble in other races' tests, and
/// the player asked for the store. The prices are not coins: they come out of the pack, and the
/// row's tooltip lists them with how many exist and how many are allowed.
///
/// Everything is paid from the player's inventory. The crystals the Nexus makes (after the
/// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full
/// until somebody collects - and "collect" moves them to the pack.
/// </summary>
public static class AlfarNexus
{
public const string PieceName = "AlfarNexus";
public const string PieceDisplay = "$rov_piece_alfar_nexus_name";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered.");
return;
}
// The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E
// key before our Switch sees it. Everything goes except what makes it a building.
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);
}
AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>();
nexus.m_switch = prefab.AddComponent<Switch>();
nexus.m_switch.m_name = PieceDisplay;
// A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn
// by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem
// spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus
// does not have, and an unfilled list sends Trader.Interact into a null Say).
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplay;
trader.enabled = false;
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>();
Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_nexus_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true),
new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true),
},
}));
PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value),
1, "rov_msg_build_limit_alfar_nexus");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (AlfarRace.IsLocalAlfar()) return true;
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
});
}
public 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;
}
/// <summary>Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4).</summary>
public static void EnsureKnown(Player player)
{
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
Traverse traverse = Traverse.Create(player);
foreach (string name in AlfarPieces.AllNames())
{
GameObject prefab = PrefabManager.Instance.GetPrefab(name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue();
}
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>The names of every piece the Alfar can build, in one place for the lock and for learning.</summary>
public static class AlfarPieces
{
public static readonly List<string> Extra = new List<string>();
public static IEnumerable<string> AllNames()
{
yield return AlfarNexus.PieceName;
foreach (string name in Extra) yield return name;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class AlfarKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
AlfarNexus.EnsureKnown(__instance);
}
}
public class AlfarNexusBehaviour : MonoBehaviour
{
public Switch m_switch;
public static readonly List<AlfarNexusBehaviour> All = new List<AlfarNexusBehaviour>();
private const string KeySelected = "RoV_alfarSel";
private const string KeyUpgrade = "RoV_alfarUp";
private const string KeyCrystals = "RoV_alfarCr";
private const string KeyCrystalAt = "RoV_alfarCrAt";
public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 }
private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length;
private ZNetView m_nview;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
All.Add(this);
RaisedThrall.RegisterStation(transform);
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
}
private void OnDestroy()
{
All.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest Ljoskjarne whose radius covers the point, or null.</summary>
public static AlfarNexusBehaviour Covering(Vector3 point)
{
AlfarNexusBehaviour best = null;
float bestDistance = float.MaxValue;
foreach (AlfarNexusBehaviour nexus in All)
{
if (nexus == null) continue;
float distance = Vector3.Distance(nexus.transform.position, point);
if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance)
{
best = nexus;
bestDistance = distance;
}
}
return best;
}
// ─── State ───────────────────────────────────────────────────────────
private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1;
public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0;
private Product Selected
{
get
{
int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0;
return (Product)Mathf.Clamp(value, 0, ProductCount - 1);
}
}
private bool Available(Product product)
{
bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState;
switch (product)
{
case Product.Drone: return true;
case Product.Neistvordr:
case Product.Eldingvordr:
case Product.Steinvordr: return constructsOpen;
case Product.Upgrade: return !Upgraded;
case Product.Collect: return Upgraded;
}
return false;
}
// ─── Crystals: a beehive's way ───────────────────────────────────────
/// <summary>
/// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while
/// full: the clock restarts when somebody collects, like the honey. Only the owner counts.
/// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its
/// daylight rule: the Alfar have no light mechanic (doc sec. 8.6).
/// </summary>
private void Update()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return;
ZDO zdo = m_nview.GetZDO();
int cap = AlfarNexusConfig.CrystalCap.Value;
int stored = zdo.GetInt(KeyCrystals, 0);
double now = ZNet.instance.GetTimeSeconds();
if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; }
string stamp = zdo.GetString(KeyCrystalAt, "");
if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at))
{
zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return;
}
float interval = CrystalInterval();
int made = Mathf.FloorToInt((float)((now - at) / interval));
if (made <= 0) return;
stored = Mathf.Min(cap, stored + made);
zdo.Set(KeyCrystals, stored);
zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
/// <summary>Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey.</summary>
public static float CrystalInterval()
{
Beehive hive = TrentaConfig.FindVanillaBeehive();
float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f;
return honey * AlfarNexusConfig.CrystalTimeFactor.Value;
}
// ─── Costs ───────────────────────────────────────────────────────────
private struct Cost
{
public string Item;
public int Amount;
public Cost(string item, int amount) { Item = item; Amount = amount; }
}
private static List<Cost> CostOf(Product product)
{
switch (product)
{
case Product.Drone:
return new List<Cost> { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) };
case Product.Neistvordr:
return new List<Cost>
{
new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value),
new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value),
};
case Product.Eldingvordr:
return new List<Cost>
{
new Cost("Iron", AlfarNexusConfig.EldingMetal.Value),
new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value),
};
case Product.Steinvordr:
return new List<Cost>
{
new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value),
new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value),
};
case Product.Upgrade:
return new List<Cost> { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) };
}
return new List<Cost>();
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
private static bool CanPay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount <= 0) continue;
if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false;
}
return true;
}
private static void Pay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false);
}
}
private static string CostText(List<Cost> costs)
{
var parts = new List<string>();
foreach (Cost cost in costs)
{
if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}");
}
return parts.Count == 0 ? "-" : string.Join(", ", parts);
}
// ─── Counts and caps ─────────────────────────────────────────────────
private int AliveOf(Product product)
{
Vector3 anchor = transform.position;
switch (product)
{
case Product.Drone: return AlfarDrones.CountAlive(anchor);
case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr);
case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr);
case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr);
}
return 0;
}
private static int CapOf(Product product)
{
switch (product)
{
case Product.Drone: return AlfarNexusConfig.DroneCap.Value;
case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value;
case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value;
case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value;
}
return int.MaxValue;
}
private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant());
// ─── Interaction ─────────────────────────────────────────────────────
private string Hover()
{
var sb = new StringBuilder();
sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay));
sb.AppendLine($"[<color=yellow><b>$KEY_Use</b></color>] {ModText.Get("rov_alfar_nexus_open")}");
if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade"));
return Localization.instance.Localize(sb.ToString());
}
private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || m_nview == null || !m_nview.IsValid()) return false;
if (!AlfarVisuals.IsAlfarPlayer(player))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return item != null;
}
// Holding something is not a way to use the nucleus: it only opens the store.
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
}
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store"));
return false;
}
// The store reads the nucleus back out of StoreGui's own m_trader when it repaints.
StoreGui.instance.Show(trader);
return true;
}
// ─── What the store window uses ──────────────────────────────────────
/// <summary>The products on offer right now, in the order the rows are drawn.</summary>
public List<Product> OnOffer()
{
var list = new List<Product>();
foreach (Product product in System.Enum.GetValues(typeof(Product)))
{
if (Available(product)) list.Add(product);
}
return list;
}
/// <summary>Builds a product from the row the player clicked. Every check Build makes still applies.</summary>
public void BuildFromStore(Product product)
{
Player player = Player.m_localPlayer;
if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return;
m_nview.ClaimOwnership();
Build(player, product);
}
/// <summary>The short number on a row: the metal (or the crystals of the upgrade) it costs.</summary>
public static string PriceShort(Product product)
{
foreach (Cost cost in CostOf(product))
{
if (cost.Amount > 0) return cost.Amount.ToString();
}
return "-";
}
/// <summary>The full terms for the row's tooltip: the price, how many exist, how many are allowed.</summary>
public string Terms(Product product)
{
var sb = new StringBuilder();
sb.AppendLine(CostText(CostOf(product)));
int cap = CapOf(product);
if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap));
if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
sb.Append(ModText.Get("rov_alfar_store_terms"));
return sb.ToString();
}
public static string ProductName(Product product) => NameOf(product);
private void Build(Player player, Product product)
{
List<Cost> costs = CostOf(product);
if (product == Product.Collect)
{
Collect(player);
return;
}
if (AliveOf(product) >= CapOf(product))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap"));
return;
}
if (!CanPay(player, costs))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs)));
return;
}
bool done;
switch (product)
{
case Product.Drone: done = AlfarDrones.Spawn(transform.position); break;
case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break;
case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break;
case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break;
case Product.Upgrade: done = true; break;
default: done = false; break;
}
if (!done) return;
Pay(player, costs);
if (product == Product.Upgrade)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyUpgrade, 1);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded"));
}
else
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product)));
}
}
private void Collect(Player player)
{
int stored = Crystals;
if (stored <= 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals"));
return;
}
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null;
if (prefab == null) return;
// Whatever fits goes in the pack; the rest stays in the Nexus.
int taken = 0;
for (int i = 0; i < stored; i++)
{
if (!player.GetInventory().CanAddItem(prefab, 1)) break;
if (!player.GetInventory().AddItem(prefab, 1)) break;
taken++;
}
if (taken > 0)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
// Collecting restarts the clock, like emptying a hive.
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken));
}
/// <summary>Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work).</summary>
public int TakeCrystals(int wanted)
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0;
int stored = Crystals;
int taken = Mathf.Min(stored, wanted);
if (taken <= 0) return 0;
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return taken;
}
}
}