RacesOfValheim/JotunnModStub/Sverm/SvermBrood.cs
kanym 1bd09ed31d feat(text): merchants, troops and the hive's shelf come from translation files
The faction merchants' 90 jokes, their generic lines and their names now
read from merchants.json. Merchant names use the game's own creature
tokens where one matches, so they arrive translated in every language
Valheim ships; the Dverg keeps a key of its own, since vanilla's token
reads "Dvergr Rogue".

The Dvergar and Trol troop names and terms, and the Sverm hive's goods,
refusals, stage names and brood kinds, follow. Their panels fill TMP texts
themselves, so they localize the names where they draw them.

The jokes have English text only for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 18:50:54 +02:00

371 lines
17 KiB
C#

using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The army: four creatures, hatched at the market, bound to the nest that paid for them.
///
/// TWO RESOURCES IN PARALLEL, which is section 10.2 and the whole shape of the colony. The EGG
/// is the slot and it grows back on its own; the BIOMASS is the price and it does not. A troop
/// needs both, so a hive with a full tank and no eggs waits, and a hive full of eggs and no
/// biomass waits differently.
///
/// Nothing here is new machinery. A troop is a RaisedThrall - the same component the Draugh's
/// spawner, the Dvergar's bank and the Fenrir's trough hang their rosters on - so the follow and
/// stay orders, the leash, the walk home and the withering when the station falls all come for
/// free and behave exactly like every other summoned thing in the mod. The self-healing is
/// SkeletonSentryBehaviour, reused whole, which is section 11.2 word for word.
/// </summary>
public static class SvermBrood
{
/// <summary>
/// What every troop prefab's name starts with. One place, because two things ask the
/// question "is this creature one of ours" - the roster and the medicine.
/// </summary>
public const string PrefabPrefix = "SvermTroop_";
/// <summary>One rung of the ladder, from section 11's table.</summary>
public class Kind
{
public string Id;
public string Display;
public string Source; // the vanilla creature it is cloned from
public string Icon;
public float Price;
public int Stage; // the nest stage it becomes available at
public float Cooldown; // seconds between two of these
public float SpawnHeight = 0.5f; // how far above the nest it is put down
public string PrefabName => PrefabPrefix + Source;
public int Cap => CapOf(Id);
}
/// <summary>
/// Section 11's table, prices and caps and stage gates unchanged.
///
/// The cooldowns are section 20.4's: ten minutes for a Gjall and "the others scaled
/// accordingly", which is read here as scaled BY PRICE - a Brood is a tenth of a Gjall in
/// biomass, so it is a tenth of a Gjall in patience too.
/// </summary>
public static readonly List<Kind> Roster = new List<Kind>
{
new Kind { Id = "brood", Display = "$rov_troop_sverm_brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f },
new Kind { Id = "seeker", Display = "$rov_troop_sverm_seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f },
new Kind { Id = "soldier", Display = "$rov_troop_sverm_soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f },
new Kind { Id = "gjall", Display = "$rov_troop_sverm_gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f },
};
private static int CapOf(string id)
{
switch (id)
{
case "brood": return SvermConfigManagement.Brood;
case "seeker": return SvermConfigManagement.Seeker;
case "soldier": return SvermConfigManagement.Soldier;
case "gjall": return SvermConfigManagement.Gjall;
default: return 0;
}
}
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
foreach (Kind kind in Roster) RegisterOne(kind);
}
/// <summary>
/// One troop prefab: the vanilla creature, tamed at spawn, leashed, healing, worth nothing dead.
///
/// The drop table goes for the reason it always goes here - a troop that dropped seeker parts
/// would turn the colony into a trophy farm, and the biomass would be paying for itself.
/// </summary>
private static void RegisterOne(Kind kind)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(kind.Source);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{kind.Source}' to build the {kind.Display} from; " +
"that rung of the roster is missing.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source);
if (prefab == null) return;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange;
// The hive's own bounds for a fight - see SvermConfig.TroopAlertRange. Without these the
// troops kept the vanilla prefab's numbers and chased whatever they could see.
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_alertRange = SvermConfig.TroopAlertRange;
monster.m_maxChaseDistance = SvermConfig.TroopAlertRange;
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind.PrefabName;
thrall.m_commandingRace = SvermConfig.RaceId;
thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player
thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds;
thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_sverm";
// Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing
// and not respawning - a dead troop is dead, and the egg it cost is already back.
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}.");
}
// ─── Counting and hatching ───────────────────────────────────────────
/// <summary>
/// How many of this kind this nest has alive.
///
/// Counted off the thralls bound to the nest, which is the same answer every other station in
/// the mod gives - and carries the same honest limit: it can only see creatures that are
/// loaded. A troop in an unloaded zone is not counted, so a cap can be briefly exceeded by
/// hatching a replacement for something that is still alive far away.
/// </summary>
public static int CountAlive(SvermHiveBehaviour hive, Kind kind)
{
if (hive == null || kind == null) return 0;
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position))
{
if (thrall != null && thrall.Kind == kind.PrefabName) count++;
}
return count;
}
/// <summary>
/// Puts one down beside the nest, bound to it and born at whatever star the colony
/// has bought.
/// </summary>
public static bool Hatch(SvermHiveBehaviour hive, Kind kind)
{
if (hive == null || kind == null) return false;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(kind.PrefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{kind.PrefabName}' in ZNetScene; the {kind.Display} " +
"could not be hatched.");
return false;
}
Vector3 where = SpawnSpot(hive, kind);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
if (spawned == null) return false;
// The stars, and this is the ONLY thing the two star upgrades do: they are read here, at
// birth, so everything bought before them stays as it was born. Section 14's "valgono su
// tutto quello che nasce DOPO l'acquisto", enforced by the fact that nothing goes back
// and re-levels anyone.
Character character = spawned.GetComponent<Character>();
if (character != null)
{
int stars = SvermBroodStars.Of(hive.transform);
if (stars > 0) character.SetLevel(1 + stars);
}
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(hive.transform.position);
return true;
}
/// <summary>How much open ground is left between the nest's own skirt and a newborn.</summary>
private const float SpawnClearance = 2.5f;
/// <summary>
/// Where the newborn is put down: on a ring OUTSIDE the nest, never in the middle of it.
///
/// Troops were hatching at the nest's own position and half a metre up, which is inside a
/// building several metres wide - so they came out wedged in its collider. This walks a ring
/// from a random angle, takes the first spot with nothing standing on it, and drops the
/// creature on the TERRAIN height there, so a nest on a slope does not bury anyone either.
/// The per-kind height goes on top, which is what keeps the Gjall in the air.
/// </summary>
private static Vector3 SpawnSpot(SvermHiveBehaviour hive, Kind kind) => SpawnSpot(hive, kind.SpawnHeight);
/// <summary>The same ring, for anything else the nest puts on the ground - the workers.</summary>
internal static Vector3 SpawnSpot(SvermHiveBehaviour hive, float height)
{
Vector3 centre = hive.transform.position;
float radius = RingRadius(hive);
int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle");
float start = Random.Range(0f, 360f);
for (int i = 0; i < 12; i++)
{
float angle = (start + i * (360f / 12f)) * Mathf.Deg2Rad;
Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate);
if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue;
return candidate + Vector3.up * height;
}
// Twelve tries and everything is built up: due south on the ring anyway. Still outside
// the nest, which is the thing this is here to guarantee.
Vector3 fallback = centre + new Vector3(0f, 0f, -radius);
if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback);
return fallback + Vector3.up * height;
}
/// <summary>
/// How wide the ring is: the nest's own footprint plus a couple of metres.
///
/// MEASURED and not a number, because the nest grows with its stage - a stage four nest is
/// several times the width of the one that was placed, so any fixed radius that clears the
/// small one hatches troops inside the big one. Only solid meshes are measured; the hive's
/// particle effects have bounds of their own and would report a ring the size of a field.
/// </summary>
internal static float RingRadius(SvermHiveBehaviour hive)
{
Vector3 centre = hive.transform.position;
float widest = 0f;
foreach (Renderer renderer in hive.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
if (!(renderer is MeshRenderer) && !(renderer is SkinnedMeshRenderer)) continue;
Bounds bounds = renderer.bounds; // world space, so the stage's growth is already in it
float reach = Mathf.Max(Mathf.Abs(bounds.center.x - centre.x) + bounds.extents.x,
Mathf.Abs(bounds.center.z - centre.z) + bounds.extents.z);
if (reach > widest) widest = reach;
}
// Nothing readable means nothing to be stuck in either, but the floor keeps a newborn off
// the nest's own doorstep, and the ceiling stops one measuring mistake spawning troops
// half a zone away.
return Mathf.Clamp(widest, 2f, 20f) + SpawnClearance;
}
}
/// <summary>
/// The brood eggs: the slot half of the price, section 10.2.
///
/// One every twenty seconds up to five plus the stage, and it is worked out from the WORLD CLOCK
/// rather than ticked - the same trick the digestion uses. A nest nobody is standing next to
/// still fills its clutch, and there is no timer to lose when a zone unloads.
/// </summary>
public static class SvermBroodEggs
{
private const string EggKey = "RacesOfValheim_SvermEggs";
private const string ClockKey = "RacesOfValheim_SvermEggAt";
public static int Cap(Transform nest)
{
return SvermConfig.EggCapBase + SvermHiveStage.Of(nest);
}
/// <summary>What the clutch holds right now, without writing anything.</summary>
public static int Count(Transform nest)
{
ZNetView nview = View(nest);
if (nview == null) return 0;
ZDO zdo = nview.GetZDO();
int stored = zdo.GetInt(EggKey, 0);
long clock = zdo.GetLong(ClockKey, 0L);
// A clutch that has never been settled has no elapsed time to claim. Reading a missing
// clock as zero would hand a brand new nest every egg since the world began.
if (clock <= 0L) return Mathf.Clamp(stored, 0, Cap(nest));
long elapsed = WorldSecond() - clock;
int laid = elapsed > 0L ? (int)(elapsed / SvermConfig.EggInterval) : 0;
return Mathf.Clamp(stored + laid, 0, Cap(nest));
}
/// <summary>
/// Writes down what time has laid and restarts the clock. The owner calls this on a timer so
/// the number the other clients read is never far behind.
/// </summary>
public static void Settle(Transform nest)
{
ZNetView nview = View(nest);
if (nview == null || !nview.IsOwner()) return;
ZDO zdo = nview.GetZDO();
int now = Count(nest);
zdo.Set(EggKey, now);
zdo.Set(ClockKey, WorldSecond());
}
/// <summary>Takes eggs out of the clutch. All or nothing.</summary>
public static bool Take(Transform nest, int howMany)
{
ZNetView nview = View(nest);
if (nview == null) return false;
int have = Count(nest);
if (have < howMany) return false;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(EggKey, have - howMany);
nview.GetZDO().Set(ClockKey, WorldSecond());
return true;
}
private static ZNetView View(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview : null;
}
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
/// <summary>
/// Surrenal Glands and Hyperplasia: what star the colony's troops are born at.
///
/// One number on the nest, 0 to 2, and it is read at the moment a troop is hatched and never
/// again. Everything already walking around keeps the stars it was born with, which is the
/// document's own rule and also the only version that does not need to find and re-level a
/// garrison spread over half the map.
/// </summary>
public static class SvermBroodStars
{
private const string StarKey = "RacesOfValheim_SvermStars";
public static int Of(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return 0;
return Mathf.Clamp(nview.GetZDO().GetInt(StarKey, 0), 0, 2);
}
public static void Set(Transform nest, int stars)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2));
}
}
}