Merge pull request 'race-chains-and-stations' (#17) from race-chains-and-stations into main

Reviewed-on: #17
This commit is contained in:
kanym 2026-08-07 17:16:09 +02:00
commit 4d3d790e2e
33 changed files with 7041 additions and 69 deletions

View file

@ -0,0 +1,298 @@
using System.Collections;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The second step of the refinement chain, brewed at the Mead Ketill:
///
/// 5 Blood Essence -> 1 Superior Blood Essence
/// 3 Blood Essence + 5 Blueberries
/// + 5 Yellow Mushrooms -> Blood Potion mead base
/// 3 Superior Blood Essence + 5 Sap
/// + 5 Cloudberry -> Superior Blood Potion mead base
///
/// Either base then goes into a Fermenter and comes out as five bottles. Drinking one force
/// feeds every food slot with the matching essence - full stomachs and all - and heals a
/// percentage of maximum health over eight seconds.
/// </summary>
public static class AswidBloodPotions
{
public const string BaseName = "MeadBaseBloodPotion";
public const string PotionName = "MeadBloodPotion";
public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion";
public const string SuperiorPotionName = "MeadSuperiorBloodPotion";
private const string PotionDisplayName = "Blood Potion";
private const string SuperiorPotionDisplayName = "Superior Blood Potion";
private const float HealDuration = 8f;
private const float HealFraction = 0.05f;
private const float SuperiorHealFraction = 0.10f;
// Five bottles per barrel, as designed.
private const int BottlesPerBrew = 5;
/// <summary>
/// Blood brews are done in a quarter of the normal time. The fermenter keeps a single
/// duration for every recipe, so instead of shortening it - which would speed up every
/// vanilla mead in the barrel - the elapsed time is multiplied while our base is inside.
/// </summary>
public const double FermentSpeedMultiplier = 4.0;
private static readonly System.Reflection.MethodInfo GetContentMethod =
AccessTools.Method(typeof(Fermenter), "GetContent");
public static void Register()
{
SE_BloodPotion drink = CreateEffect("SE_BloodPotion", PotionDisplayName, HealFraction,
AswidBloodRefinery.EssenceName, "GemstoneRed");
SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName,
SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore");
GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "Blood Potion Mead Base",
"Blood, berries and crypt light, waiting on a barrel.");
GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName,
"Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, " +
"full or not, and knits the flesh back together.");
GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "Superior Blood Potion Mead Base",
"The twice-rendered draught, still raw.");
GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName,
"The same mercy, twice as deep.");
AttachEffect(potion, drink);
AttachEffect(superiorPotion, superiorDrink);
AddRecipe(AswidBloodRefinery.SuperiorEssenceName, new[]
{
new RequirementConfig(AswidBloodRefinery.EssenceName, 5),
});
AddRecipe(BaseName, new[]
{
new RequirementConfig(AswidBloodRefinery.EssenceName, 3),
new RequirementConfig("Blueberries", 5),
// "Funghi luminosi": the Yellow Mushroom, the one that glows in the burial
// chambers. Same tier as the blueberries, unlike the Mistlands blue one.
new RequirementConfig("MushroomYellow", 5),
});
AddRecipe(SuperiorBaseName, new[]
{
new RequirementConfig(AswidBloodRefinery.SuperiorEssenceName, 3),
new RequirementConfig("Sap", 5),
new RequirementConfig("Cloudberry", 5),
});
AddFermenterConversion(meadBase, potion);
AddFermenterConversion(superiorBase, superiorPotion);
}
// ---------------------------------------------------------------- items
private static GameObject CloneItem(string prefabName, string source, string displayName, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Aswid] Could not clone '{source}'; {displayName} not registered.");
return null;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
// The clone arrives carrying the vanilla health mead's own effect; ours is attached
// afterwards, and the mead bases must carry none at all.
shared.m_consumeStatusEffect = null;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
private static void AttachEffect(GameObject potion, SE_BloodPotion effect)
{
ItemDrop drop = potion != null ? potion.GetComponent<ItemDrop>() : null;
if (drop == null || effect == null) return;
drop.m_itemData.m_shared.m_consumeStatusEffect = effect;
}
private static void AddRecipe(string item, RequirementConfig[] requirements)
{
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = item,
Amount = 1,
CraftingStation = CraftingStations.MeadKetill,
Requirements = requirements,
}));
}
/// <summary>
/// Teaches the vanilla fermenter one more brew. The vanilla prefab's conversion list is
/// appended to rather than replaced, so every stock mead still works.
/// </summary>
private static void AddFermenterConversion(GameObject from, GameObject to)
{
if (from == null || to == null) return;
GameObject barrel = PrefabManager.Cache.GetPrefab<GameObject>("fermenter");
Fermenter fermenter = barrel != null ? barrel.GetComponent<Fermenter>() : null;
if (fermenter == null)
{
Jotunn.Logger.LogWarning("[Aswid] No fermenter prefab; blood potions cannot be brewed.");
return;
}
ItemDrop fromDrop = from.GetComponent<ItemDrop>();
ItemDrop toDrop = to.GetComponent<ItemDrop>();
if (fromDrop == null || toDrop == null) return;
foreach (Fermenter.ItemConversion existing in fermenter.m_conversion)
{
if (existing != null && existing.m_from == fromDrop) return; // already taught
}
fermenter.m_conversion.Add(new Fermenter.ItemConversion
{
m_from = fromDrop,
m_to = toDrop,
m_producedItems = BottlesPerBrew,
});
}
// ---------------------------------------------------------------- status effect
private static SE_BloodPotion CreateEffect(string name, string displayName, float fraction,
string essencePrefab, string iconSource)
{
SE_BloodPotion effect = ScriptableObject.CreateInstance<SE_BloodPotion>();
effect.name = name;
effect.m_name = displayName;
effect.m_tooltip = $"Stomachs filled with blood. Healing {Mathf.RoundToInt(fraction * 100f)}% over {HealDuration:0} seconds.";
effect.m_ttl = HealDuration;
effect.m_healFraction = fraction;
effect.m_essencePrefab = essencePrefab;
// A flat m_healthOverTime cannot express "5% of maximum health", so the real number is
// computed per drinker in SE_BloodPotion.Setup. One tick a second over the eight.
effect.m_healthOverTimeDuration = HealDuration;
effect.m_healthOverTimeInterval = 1f;
ItemDrop source = PrefabManager.Cache.GetPrefab<ItemDrop>(iconSource);
Sprite[] icons = source != null && source.m_itemData != null && source.m_itemData.m_shared != null
? source.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0) effect.m_icon = icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(effect, fixReference: false));
return effect;
}
/// <summary>
/// Force feeds every food slot with the given essence, ignoring whether the stomachs are
/// full - that refusal is the whole point of drinking the potion. The Aswid's fourth slot
/// is filled too once the progression has unlocked it.
/// </summary>
public static void FillStomachs(Player player, string essencePrefabName)
{
if (player == null || ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(essencePrefabName);
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop == null) return;
Traverse traverse = Traverse.Create(player);
IList foods = traverse.Field("m_foods").GetValue<IList>();
if (foods == null) return;
foods.Clear();
for (int slot = 0; slot < 3; slot++)
{
foods.Add(MakeFood(drop, prefab, essencePrefabName));
}
if (AswidRace.IsAswid() && BossProgressionManager.GetCurrentProgressionState() >= 8)
{
ItemDrop.ItemData item = drop.m_itemData.Clone();
item.m_dropPrefab = prefab;
AswidFoodManager.SetExtraFood(player, item);
}
traverse.Method("UpdateFood", 0f, true).GetValue();
}
/// <summary>True while one of our two mead bases is the thing fermenting in that barrel.</summary>
public static bool IsBloodBrew(Fermenter fermenter)
{
if (fermenter == null || GetContentMethod == null) return false;
string content = GetContentMethod.Invoke(fermenter, null) as string;
return content == BaseName || content == SuperiorBaseName;
}
private static Player.Food MakeFood(ItemDrop drop, GameObject prefab, string prefabName)
{
ItemDrop.ItemData item = drop.m_itemData.Clone();
// Vanilla reads m_dropPrefab.name when it rebuilds a food entry, and a cloned
// ItemData off a raw prefab does not carry it.
item.m_dropPrefab = prefab;
return new Player.Food
{
m_name = prefabName,
m_item = item,
m_time = item.m_shared.m_foodBurnTime,
m_health = item.m_shared.m_food,
m_stamina = item.m_shared.m_foodStamina,
m_eitr = item.m_shared.m_foodEitr,
};
}
}
/// <summary>
/// Blood ferments fast. GetFermentationTime is the single place the barrel measures progress
/// from - GetStatus is its only caller - so scaling the elapsed time here makes the brew ready
/// at a quarter of the duration and keeps the hover text agreeing with it, without touching
/// m_fermentationDuration and dragging every vanilla mead along.
/// </summary>
[HarmonyPatch(typeof(Fermenter), "GetFermentationTime")]
public static class AswidBloodPotionFermentPatch
{
public static void Postfix(Fermenter __instance, ref double __result)
{
if (__result <= 0.0) return;
if (!AswidBloodPotions.IsBloodBrew(__instance)) return;
__result *= AswidBloodPotions.FermentSpeedMultiplier;
}
}
/// <summary>
/// The effect both potions apply. Heals a fraction of maximum health rather than a flat
/// amount, which SE_Stats cannot express on its own, and refills the drinker's food slots.
/// </summary>
public class SE_BloodPotion : SE_Stats
{
public float m_healFraction = 0.05f;
public string m_essencePrefab = "";
public override void Setup(Character character)
{
// SEMan clones the effect before setting it up, so writing the resolved amount here
// touches this drinker's copy only.
if (character != null) m_healthOverTime = character.GetMaxHealth() * m_healFraction;
base.Setup(character);
AswidBloodPotions.FillStomachs(character as Player, m_essencePrefab);
}
}
}

View file

@ -0,0 +1,573 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Aswid station: a half-size, blood-dark copy of the Eitr Refinery that eats raw flesh
/// and bone and produces Blood Essence, the base currency of the (future) Aswid potion tree.
///
/// The whole chain is gated behind the Blood Core, an item sold by the Draugr faction
/// merchant, so the station cannot be reached without going through the Factions system.
///
/// The vanilla refinery is a <see cref="Smelter"/>: a queue of "ore" names plus a single
/// fuel type, one product per queued item. That shape does not fit two numeric tanks fed by
/// many different items with different yields, so the Smelter component is stripped after its
/// scene references (switches, animators, output point, effect lists, state objects) are
/// handed over to <see cref="BloodRefineryBehaviour"/>. That is why the animation and the VFX
/// stay exactly the ones the vanilla refinery plays.
/// </summary>
public static class AswidBloodRefinery
{
public const string PieceName = "AswidBloodRefinery";
public const string EssenceName = "BloodEssence";
public const string SuperiorEssenceName = "SuperiorBloodEssence";
public const string CoreName = "BloodCore";
// The Aswid food patches recognise a meal by its display name, so these strings are part
// of the contract with AswidPatches - see IsAswidMeal.
public const string EssenceDisplayName = "Blood Essence";
public const string SuperiorEssenceDisplayName = "Superior Blood Essence";
public const string CoreDisplayName = "Blood Core";
public const string PieceDisplayName = "Blood Refinery";
// Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and
// 80 hp gives 6.67 without a second number to keep in sync.
private const float RegenPerHealth = 12f;
public static GameObject EssencePrefab { get; private set; }
public static GameObject SuperiorEssencePrefab { get; private set; }
// Half size, as designed. Everything under the root scales with it.
private const float ModelScale = 0.5f;
private static readonly Color BodyTint = new Color(0.13f, 0.07f, 0.07f, 1f);
private static readonly Color BodyEmission = new Color(0.20f, 0.01f, 0.01f, 1f);
private static readonly Color EssenceTint = new Color(0.62f, 0.03f, 0.04f, 1f);
private static readonly Color SuperiorEssenceTint = new Color(0.85f, 0.0f, 0.02f, 1f);
private static readonly Color EssenceEmission = new Color(0.16f, 0.0f, 0.0f, 1f);
/// <summary>
/// Every bone in the game and what it is worth to the machine. Bones carry no food values
/// to derive a number from, unlike meat, so this table is explicit. Names verified against
/// the shipped asset manifest, not guessed; entries the running game does not have are
/// simply never matched.
/// </summary>
public static readonly Dictionary<string, int> BoneValues = new Dictionary<string, int>
{
{ "BoneFragments", 1 }, // Swamp / skeletons, the common one
{ "CharredBone", 2 }, // Ashlands
{ "Charredskull", 3 }, // Ashlands
{ "WitheredBone", 3 }, // Bonemass offering, still just a bone
{ "AsksvinCarrionNeck", 2 }, // Ashlands asksvin carrion
{ "AsksvinCarrionPelvic", 2 },
{ "AsksvinCarrionRibcage", 3 },
{ "AsksvinCarrionSkull", 3 },
{ "UndeadBjornRibcage", 3 }, // Deep North
};
// Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working.
private static readonly string[] CookingStationPrefabs =
{
"piece_cookingstation",
"piece_cookingstation_iron",
};
private static Dictionary<string, string> meatToCooked;
public static void Register()
{
RegisterCore();
RegisterEssence();
RegisterPiece();
AswidBloodPotions.Register();
}
/// <summary>
/// True for anything the Aswid is allowed to put in a food slot: the blood drained from a
/// mob, or refined Blood Essence. AswidPatches routes both through the same slot logic.
/// </summary>
public static bool IsAswidMeal(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false;
return item.m_shared.m_name.StartsWith("Aswid Food:")
|| item.m_shared.m_name == EssenceDisplayName
|| IsEssence(item);
}
/// <summary>Either tier of refined blood - the things only an Aswid may swallow.</summary>
public static bool IsEssence(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false;
return item.m_shared.m_name == EssenceDisplayName || item.m_shared.m_name == SuperiorEssenceDisplayName;
}
// ---------------------------------------------------------------- items
private static void RegisterCore()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(CoreName, "Bloodbag");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Aswid] Could not clone Bloodbag; Blood Core not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = CoreDisplayName;
shared.m_description = "A knot of clotted blood kept beating by something that is not a heart. " +
"The dead trade them; only the dead know how they are made.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 20;
Sprite icon = BorrowIcon("MorgenHeart");
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
private static void RegisterEssence()
{
EssencePrefab = BuildEssence(
EssenceName,
EssenceDisplayName,
"Blood rendered down to what it actually is. The only real food an Aswid can " +
"still chew, and the base of every draught worth brewing.",
food: 60f,
tint: EssenceTint,
iconSource: "GemstoneRed");
SuperiorEssencePrefab = BuildEssence(
SuperiorEssenceName,
SuperiorEssenceDisplayName,
"The same blood, rendered twice. Darker, thicker, and worth five of the first pass.",
food: 80f,
tint: SuperiorEssenceTint,
iconSource: "MoltenCore");
}
/// <summary>
/// Both essences are the same object with a different weight of red behind them. Stamina
/// and burn time are deliberately shared: only the health and the regeneration that scales
/// off it change between the two tiers.
/// </summary>
private static GameObject BuildEssence(string prefabName, string displayName, string description,
float food, Color tint, string iconSource)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "Eitr");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Aswid] Could not clone Eitr; {displayName} not registered.");
return null;
}
// Refined eitr carries a Radiator of its own plus a point light. The design calls for
// red spheres that emit no light and hurt nothing, so both go.
StripOffensive(prefab, prefabName);
StripGlow(prefab, prefabName);
Recolour(prefab, tint, EssenceEmission);
RedShiftEffects(prefab, tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
shared.m_weight = 0.2f;
// Top of the food ladder on purpose: it costs a station, a purchased Core, and a pile
// of corpses, and no other race can swallow it.
shared.m_food = food;
shared.m_foodStamina = 60f;
shared.m_foodEitr = 0f;
shared.m_foodBurnTime = 2400f; // 40 minutes
shared.m_foodRegen = food / RegenPerHealth;
shared.m_consumeStatusEffect = null;
// Repainting the eitr sprite pixel by pixel produced an empty slot in the inventory
// (the icon atlas is not readable), so a vanilla red icon is borrowed instead.
Sprite icon = BorrowIcon(iconSource);
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "eitrrefinery");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Aswid] Could not clone eitrrefinery; Blood Refinery not registered.");
return;
}
Smelter smelter = prefab.GetComponentInChildren<Smelter>(true);
if (smelter == null)
{
Jotunn.Logger.LogWarning("[Aswid] eitrrefinery clone has no Smelter; Blood Refinery not registered.");
return;
}
BloodRefineryBehaviour refinery = smelter.gameObject.AddComponent<BloodRefineryBehaviour>();
refinery.m_addMeatSwitch = smelter.m_addOreSwitch; // the soft tissue slot
refinery.m_addBoneSwitch = smelter.m_addWoodSwitch; // the sap slot
refinery.m_outputPoint = smelter.m_outputPoint;
refinery.m_enabledObject = smelter.m_enabledObject;
refinery.m_disabledObject = smelter.m_disabledObject;
refinery.m_haveBoneObject = smelter.m_haveFuelObject;
refinery.m_haveMeatObject = smelter.m_haveOreObject;
refinery.m_noMeatObject = smelter.m_noOreObject;
refinery.m_animators = smelter.m_animators;
refinery.m_meatAddedEffects = smelter.m_oreAddedEffects;
refinery.m_boneAddedEffects = smelter.m_fuelAddedEffects;
refinery.m_produceEffects = smelter.m_produceEffects;
refinery.m_smokeSpawner = smelter.m_smokeSpawner;
Object.DestroyImmediate(smelter);
// Two Radiators under _enabled are what shot the tester: see IsOffensive.
StripOffensive(prefab, PieceName);
SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".oreAdded");
SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".fuelAdded");
SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce");
prefab.transform.localScale = Vector3.one * ModelScale;
Recolour(prefab, BodyTint, BodyEmission);
RedShiftEffects(prefab);
Piece piece = prefab.GetComponent<Piece>();
if (piece != null)
{
// Same call as RaceMenuWard: a piece whose crafting station is out of range is
// hidden from the hammer entirely, and this one has to be findable.
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
}
PieceConfig config = new PieceConfig
{
Name = PieceDisplayName,
Description = "Flesh goes in, bone goes in, and what is left of both comes out red.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Requirements = new[]
{
new RequirementConfig(CoreName, 1, 0, true),
new RequirementConfig("Stone", 20, 0, true),
new RequirementConfig("Bronze", 10, 0, true),
}
};
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
}
/// <summary>
/// A piece only shows up in the hammer once it is in the player's known recipes, and the
/// vanilla learning pass misses pieces injected after the fact - the same trap
/// RaceMenuWard fell into. The Blood Core requirement is the real gate; this only makes
/// the entry visible (greyed out until you own one).
/// </summary>
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();
}
// ---------------------------------------------------------------- input values
/// <summary>Units of blood a single piece of this item is worth, 0 if it is not flesh.</summary>
public static int BloodValue(string prefabName)
{
EnsureMeatMap();
if (string.IsNullOrEmpty(prefabName) || !meatToCooked.TryGetValue(prefabName, out string cookedName)) return 0;
// The yield is what the COOKED version would have given the eater: health plus
// stamina, so a lox steak is worth more than a neck tail without a second table.
ItemDrop.ItemData.SharedData source = SharedOf(cookedName) ?? SharedOf(prefabName);
if (source == null) return 1;
int units = Mathf.CeilToInt((source.m_food + source.m_foodStamina) / 20f);
return Mathf.Max(1, units);
}
/// <summary>
/// The same question BloodValue answers - "how much soft tissue is this piece of flesh
/// worth" - under a name that does not say "blood", for callers outside the Aswid. The
/// Trenta's Composter rots the same meat this refinery renders, so it asks here rather
/// than keeping a second table that would drift out of step with this one.
/// </summary>
public static int FleshValue(string prefabName) => BloodValue(prefabName);
/// <summary>Units of bone a single piece of this item is worth, 0 if it is not a bone.</summary>
public static int BoneValue(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return 0;
return BoneValues.TryGetValue(prefabName, out int units) ? units : 0;
}
private static void EnsureMeatMap()
{
if (meatToCooked != null) return;
// The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs)
{
GameObject station = PrefabManager.Cache.GetPrefab<GameObject>(stationName);
CookingStation cooking = station != null ? station.GetComponent<CookingStation>() : null;
if (cooking == null || cooking.m_conversion == null) continue;
foreach (CookingStation.ItemConversion conversion in cooking.m_conversion)
{
if (conversion == null || conversion.m_from == null || conversion.m_to == null) continue;
string from = conversion.m_from.gameObject.name;
if (!meatToCooked.ContainsKey(from)) meatToCooked[from] = conversion.m_to.gameObject.name;
}
}
}
private static ItemDrop.ItemData.SharedData SharedOf(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 : null;
}
// ---------------------------------------------------------------- prefab surgery
/// <summary>
/// Removes anything on the prefab that can hurt somebody. Kept type-based rather than
/// name-based so a game update that renames a child object cannot quietly bring the
/// damage back.
/// </summary>
internal static void StripOffensive(GameObject root, string label)
{
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null || !IsOffensive(behaviour)) continue;
Jotunn.Logger.LogInfo($"[Aswid] {label}: stripped {behaviour.GetType().Name} from '{behaviour.gameObject.name}'.");
Object.DestroyImmediate(behaviour);
}
}
private static bool IsOffensive(MonoBehaviour behaviour)
{
// Radiator is the one that shoots. It is a plain MonoBehaviour holding a projectile
// prefab in a field and firing it every 2-5 seconds while its object is enabled, which
// is why neither an interface check nor a hierarchy scan for projectiles found it. The
// refinery carries two under _enabled (so only while it is running) and refined eitr
// carries one of its own - hence the 60 damage plus poison out of nowhere.
if (behaviour is Radiator) return true;
if (behaviour is IProjectile || behaviour is Aoe || behaviour is Turret) return true;
// An EffectArea is usually harmless bookkeeping - PlayerBase marks the thing as part of
// a home, and stripping that was a mistake in the first pass. Only the burning kinds go.
EffectArea area = behaviour as EffectArea;
if (area == null) return false;
return (area.m_type & (EffectArea.Type.Heat | EffectArea.Type.Fire | EffectArea.Type.Burning)) != 0;
}
private static bool IsOffensivePrefab(GameObject prefab)
{
if (prefab == null) return false;
if (prefab.name.ToLowerInvariant().Contains("radiation")) return true;
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null && IsOffensive(behaviour)) return true;
}
return false;
}
/// <summary>
/// Drops any effect the refinery plays that carries something damaging with it. Only the
/// list on our own clone is rebuilt - the referenced prefabs are the vanilla ones and are
/// never touched, so the real eitr refinery keeps working.
/// </summary>
private static void SanitiseEffects(EffectList list, string label)
{
if (list == null || list.m_effectPrefabs == null) return;
List<EffectList.EffectData> kept = new List<EffectList.EffectData>();
foreach (EffectList.EffectData data in list.m_effectPrefabs)
{
if (data == null || data.m_prefab == null) continue;
if (IsOffensivePrefab(data.m_prefab))
{
Jotunn.Logger.LogInfo($"[Aswid] {label}: dropped effect '{data.m_prefab.name}' (carries damage).");
continue;
}
Jotunn.Logger.LogInfo($"[Aswid] {label}: kept effect '{data.m_prefab.name}'.");
kept.Add(data);
}
list.m_effectPrefabs = kept.ToArray();
}
private static void StripGlow(GameObject root, string label)
{
// LightFlicker and LightLod both grab the Light in Awake without a null check, so
// deleting the Light on its own threw on every sphere the machine produced. They go
// first, and the light after.
foreach (LightFlicker flicker in root.GetComponentsInChildren<LightFlicker>(true))
{
if (flicker != null) Object.DestroyImmediate(flicker);
}
foreach (LightLod lod in root.GetComponentsInChildren<LightLod>(true))
{
if (lod != null) Object.DestroyImmediate(lod);
}
foreach (Light light in root.GetComponentsInChildren<Light>(true))
{
if (light != null) Object.DestroyImmediate(light);
}
foreach (Transform child in root.GetComponentsInChildren<Transform>(true))
{
if (child == null || child == root.transform) continue;
string name = child.gameObject.name.ToLowerInvariant();
if (name.Contains("radiation") || name.Contains("gamma") || name.Contains("halo") || name.Contains("glow"))
{
Jotunn.Logger.LogInfo($"[Aswid] {label}: removed glow child '{child.gameObject.name}'.");
Object.DestroyImmediate(child.gameObject);
}
}
}
/// <summary>
/// Turns the borrowed eitr VFX from purple to blood: particle tint and every remaining
/// light. The refinery keeps its lights - a running one should glow red - while the
/// essence spheres had theirs removed outright by StripGlow.
/// </summary>
private static void RedShiftEffects(GameObject root)
{
RedShiftEffects(root, EssenceTint);
}
private static void RedShiftEffects(GameObject root, Color tint)
{
foreach (ParticleSystem particles in root.GetComponentsInChildren<ParticleSystem>(true))
{
if (particles == null) continue;
ParticleSystem.MainModule main = particles.main;
main.startColor = new ParticleSystem.MinMaxGradient(tint);
}
foreach (Light light in root.GetComponentsInChildren<Light>(true))
{
if (light != null) light.color = tint;
}
}
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($"[Aswid] Could not borrow the icon from '{prefabName}'.");
return null;
}
private static void Recolour(GameObject root, Color tint, Color emission)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
// Particle renderers are handled by RedShiftEffects - painting flames and smoke
// with the dark body tint just turns the VFX into soot.
if (renderer is ParticleSystemRenderer) continue;
// renderer.material instantiates a copy, so the vanilla refinery and the vanilla
// eitr keep their own look.
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", emission);
}
}
}
}
/// <summary>
/// Teaches the piece on spawn, exactly like RaceMenuWard does, because a piece registered
/// after the vanilla learning pass never reaches the hammer on its own.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class AswidBloodRefineryKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
AswidBloodRefinery.EnsureKnown(__instance);
}
}
/// <summary>
/// Blood Essence is Aswid food. Anyone else who tries to swallow it gets nothing, the same
/// way the Draugh's human meat is refused to the living.
/// </summary>
[HarmonyPatch(typeof(Player), "CanConsumeItem")]
public static class AswidBloodEssenceGatePatch
{
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance != Player.m_localPlayer || item == null || item.m_shared == null) return;
if (!AswidBloodRefinery.IsEssence(item)) return;
if (AswidRace.IsAswid()) return;
__result = false;
}
}
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class AswidBloodEssenceMessagePatch
{
public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer || item == null || item.m_shared == null) return true;
if (!AswidBloodRefinery.IsEssence(item)) return true;
if (AswidRace.IsAswid()) return true;
player.Message(MessageHud.MessageType.Center, "Living blood curdles in a living throat.");
return false;
}
}
}

View file

@ -285,7 +285,7 @@ namespace RacesOfValheim
{
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:"))
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item))
{
var foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (foods != null)
@ -339,7 +339,7 @@ namespace RacesOfValheim
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
hiddenFoods.Clear();
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:"))
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item))
{
var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)

View file

@ -24,7 +24,11 @@ namespace RacesOfValheim
{ "Leech", "TrophyLeech" },
{ "Hatchling", "TrophyHatchling" },
{ "Lox", "TrophyLox" },
{ "Goblin", "TrophyGoblin" }, // "Goblin" is the real prefab id - "Fuling" is only the in-game display name
// The Fuling family is named Goblin* in code - "Fuling" is only ever the display name,
// and no prefab by that name exists. These three keys never matched anything, so the
// Aswid could not drain a Fuling of any kind. Verified against the asset manifest.
{ "Goblin", "TrophyGoblin" },
{ "GoblinArcher", "TrophyGoblin" },
{ "GoblinShaman", "TrophyGoblinShaman" },
{ "GoblinBrute", "TrophyGoblinBrute" },
{ "Deathsquito", "TrophyDeathsquito" },
@ -35,7 +39,7 @@ namespace RacesOfValheim
{ "Gjall", "TrophyGjall" },
{ "Tick", "TrophyTick" },
{ "Ulv", "TrophyUlv" },
{ "Cultist", "TrophyCultist" },
{ "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist"
{ "Asksvin", "TrophyAsksvin" },
{ "Volture", "TrophyVolture" }
};
@ -84,6 +88,7 @@ namespace RacesOfValheim
{
AswidStatusEffects.RegisterStatusEffects();
CreateFoodItems();
AswidBloodRefinery.Register();
GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Fenring_Cultist_Hildir");
if (geirrhafa != null)
@ -137,6 +142,9 @@ namespace RacesOfValheim
{
float foodHp = Mathf.Min(c.m_health / 2f, 150f);
float burnTime = c.m_health * 2f;
// StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was
// never a prefab prefix - the family is Goblin* - so that arm of the
// test matched nothing until now.
if (mobName == "Cultist" || mobName.StartsWith("Fenring") || mobName.StartsWith("Goblin"))
{
burnTime = 1200f; // 20 minutes

View file

@ -0,0 +1,299 @@
using System;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Blood Refinery's logic. Modelled on <see cref="Smelter"/> - same one-second tick, same
/// owner-only accounting with everything in the ZDO so it keeps working in multiplayer and
/// keeps ticking while the zone is unloaded - but with two numeric tanks instead of an ore
/// queue and a single fuel item.
///
/// Raw flesh is destroyed on the spot and becomes blood; bone is destroyed on the spot and
/// becomes bone dust. When both tanks can pay, the machine refines a Blood Essence and spits
/// it out of the vanilla output point. It never deals damage - see AswidBloodRefinery for the
/// strip pass that guarantees that.
/// </summary>
public class BloodRefineryBehaviour : MonoBehaviour
{
// Wired up from the vanilla Smelter before it is destroyed, which is what keeps the
// animation and the VFX identical to the eitr refinery's.
public Switch m_addMeatSwitch;
public Switch m_addBoneSwitch;
public Transform m_outputPoint;
public GameObject m_enabledObject;
public GameObject m_disabledObject;
public GameObject m_haveMeatObject;
public GameObject m_haveBoneObject;
public GameObject m_noMeatObject;
public Animator[] m_animators;
public EffectList m_meatAddedEffects;
public EffectList m_boneAddedEffects;
public EffectList m_produceEffects;
public SmokeSpawner m_smokeSpawner;
// Balance. Ten units of blood is roughly one cooked lox steak's worth.
public float m_maxBlood = 50f;
public float m_maxBone = 20f;
public float m_bloodPerEssence = 5f;
public float m_bonePerEssence = 2f;
public float m_secPerEssence = 20f;
private const string KeyBlood = "RoV_blood";
private const string KeyBone = "RoV_bone";
private const string KeyTimer = "RoV_refineTimer";
private const string KeyAccumulator = "RoV_accTime";
private const string KeyStartTime = "RoV_startTime";
private ZNetView m_nview;
private bool m_blockedSmoke;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
if (m_nview == null) m_nview = GetComponentInParent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_addMeatSwitch != null)
{
m_addMeatSwitch.m_onUse = OnAddMeat;
m_addMeatSwitch.m_onHover = HoverMeat;
}
if (m_addBoneSwitch != null)
{
m_addBoneSwitch.m_onUse = OnAddBone;
m_addBoneSwitch.m_onHover = HoverBone;
}
m_nview.Register<string>("RoV_AddMeat", RPC_AddMeat);
m_nview.Register<string>("RoV_AddBone", RPC_AddBone);
WearNTear wear = GetComponent<WearNTear>();
if (wear == null) wear = GetComponentInParent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("UpdateRefinery", 1f, 1f);
}
// ---------------------------------------------------------------- input
private bool OnAddMeat(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return TryAdd(user, item, isMeat: true);
}
private bool OnAddBone(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return TryAdd(user, item, isMeat: false);
}
private bool TryAdd(Humanoid user, ItemDrop.ItemData item, bool isMeat)
{
if (user == null) return false;
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindUsable(inventory, isMeat);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, isMeat ? "No raw flesh to render." : "No bone to grind.");
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
int value = isMeat ? AswidBloodRefinery.BloodValue(prefabName) : AswidBloodRefinery.BoneValue(prefabName);
if (value <= 0)
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
float stored = isMeat ? GetBlood() : GetBone();
float capacity = isMeat ? m_maxBlood : m_maxBone;
if (stored >= capacity)
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC(isMeat ? "RoV_AddMeat" : "RoV_AddBone", prefabName);
return true;
}
private ItemDrop.ItemData FindUsable(Inventory inventory, bool isMeat)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
string prefabName = candidate.m_dropPrefab.name;
int value = isMeat ? AswidBloodRefinery.BloodValue(prefabName) : AswidBloodRefinery.BoneValue(prefabName);
if (value > 0) return candidate;
}
return null;
}
private void RPC_AddMeat(long sender, string prefabName)
{
if (!m_nview.IsOwner()) return;
int value = AswidBloodRefinery.BloodValue(prefabName);
if (value <= 0) return;
SetBlood(Mathf.Min(m_maxBlood, GetBlood() + value));
if (m_meatAddedEffects != null) m_meatAddedEffects.Create(transform.position, transform.rotation);
}
private void RPC_AddBone(long sender, string prefabName)
{
if (!m_nview.IsOwner()) return;
int value = AswidBloodRefinery.BoneValue(prefabName);
if (value <= 0) return;
SetBone(Mathf.Min(m_maxBone, GetBone() + value));
if (m_boneAddedEffects != null) m_boneAddedEffects.Create(transform.position, transform.rotation, transform);
}
// ---------------------------------------------------------------- the loop
private void UpdateRefinery()
{
if (m_nview == null || !m_nview.IsValid()) return;
m_blockedSmoke = m_smokeSpawner != null && m_smokeSpawner.IsBlocked();
UpdateState();
if (!m_nview.IsOwner()) return;
float accumulator = m_nview.GetZDO().GetFloat(KeyAccumulator) + (float)GetDeltaTime();
if (accumulator > 3600f) accumulator = 3600f; // one hour of catch-up, as vanilla
while (accumulator >= 1f)
{
accumulator -= 1f;
if (!IsActive()) continue;
float timer = m_nview.GetZDO().GetFloat(KeyTimer) + 1f;
if (timer >= m_secPerEssence)
{
timer = 0f;
SetBlood(GetBlood() - m_bloodPerEssence);
SetBone(GetBone() - m_bonePerEssence);
Produce();
}
m_nview.GetZDO().Set(KeyTimer, timer);
}
m_nview.GetZDO().Set(KeyAccumulator, accumulator);
}
private void Produce()
{
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(AswidBloodRefinery.EssenceName)
: null;
if (prefab == null || m_outputPoint == null) return;
if (m_produceEffects != null) m_produceEffects.Create(transform.position, transform.rotation);
GameObject spawned = Instantiate(prefab, m_outputPoint.position, m_outputPoint.rotation);
ItemDrop drop = spawned.GetComponent<ItemDrop>();
if (drop != null)
{
drop.m_itemData.m_stack = 1;
ItemDrop.OnCreateNew(drop);
}
}
/// <summary>
/// Bones survive the machine, blood does not, so a demolished refinery gives the bone back
/// and keeps the blood. The hover text says so before anyone swings a hammer at it.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
int bones = Mathf.FloorToInt(GetBone());
SetBone(0f);
SetBlood(0f);
if (bones <= 0) return;
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("BoneFragments") : null;
if (prefab == null) return;
for (int i = 0; i < bones; i++)
{
Vector3 position = transform.position + Vector3.up * 0.5f + UnityEngine.Random.insideUnitSphere * 0.3f;
Quaternion rotation = Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f);
ItemDrop.OnCreateNew(Instantiate(prefab, position, rotation));
}
}
// ---------------------------------------------------------------- state and display
public bool IsActive()
{
if (m_blockedSmoke) return false;
return GetBlood() >= m_bloodPerEssence && GetBone() >= m_bonePerEssence;
}
private void UpdateState()
{
bool active = IsActive();
if (m_enabledObject != null) m_enabledObject.SetActive(active);
if (m_disabledObject != null) m_disabledObject.SetActive(!active);
if (m_haveBoneObject != null) m_haveBoneObject.SetActive(GetBone() > 0f);
if (m_haveMeatObject != null) m_haveMeatObject.SetActive(GetBlood() > 0f);
if (m_noMeatObject != null) m_noMeatObject.SetActive(GetBlood() <= 0f);
if (m_animators == null) return;
foreach (Animator animator in m_animators)
{
if (animator == null || !animator.gameObject.activeInHierarchy) continue;
animator.SetBool("active", active);
animator.SetFloat("activef", active ? 1f : 0f);
}
}
private string HoverMeat()
{
return Localization.instance.Localize(
$"{AswidBloodRefinery.PieceDisplayName} (blood {Mathf.Floor(GetBlood())}/{m_maxBlood})\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Render raw flesh");
}
private string HoverBone()
{
return Localization.instance.Localize(
$"{AswidBloodRefinery.PieceDisplayName} (bone {Mathf.Floor(GetBone())}/{m_maxBone})\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Grind bone");
}
// ---------------------------------------------------------------- ZDO accessors
private double GetDeltaTime()
{
DateTime now = ZNet.instance.GetTime();
DateTime last = new DateTime(m_nview.GetZDO().GetLong(KeyStartTime, now.Ticks));
m_nview.GetZDO().Set(KeyStartTime, now.Ticks);
return (now - last).TotalSeconds;
}
private float GetBlood() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyBlood) : 0f;
private float GetBone() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyBone) : 0f;
private void SetBlood(float value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyBlood, Mathf.Max(0f, value));
}
private void SetBone(float value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyBone, Mathf.Max(0f, value));
}
}
}

View file

@ -18,6 +18,11 @@ namespace RacesOfValheim
public void CreateModAssets()
{
// The body pile and its thralls. Registered here because the faction merchant catalogue
// resolves its entries by prefab name, so the two cursed bones have to exist before a
// Draugr is ever set up as a bench.
DraughSpawner.Register();
// Generate EdibleUncooked prefabs for Draugh raw food logic
foreach (var mapping in DraughFoodPatches.rawToCookedMapping)
{

View file

@ -0,0 +1,335 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Draugh station: a smaller, green body pile that eats raw flesh and answers with tamed
/// draugr. Third of the per-race station chains, after the Aswid's Blood Refinery and the
/// Trenta's Composter, and it takes its input rules straight from the second one - 100 units of
/// flesh valued by <see cref="AswidBloodRefinery.FleshValue"/>, one batch, one draugr.
///
/// What makes it a Draugh thing rather than a piece of furniture anyone can use: the pile itself
/// works for whoever built it, but the draugr only take ORDERS from a Draugh. Anyone else gets a
/// grave that defends its own ten metres; a Draugh gets an escort. That asymmetry is the design,
/// not a limitation.
///
/// Two special inputs, both of them draugr remains, because the pile is not fussy about where the
/// meat comes from: a Draugr trophy is worth a whole batch, and an Elite trophy is worth an elite
/// outright once the pile has been upgraded to hold any.
/// </summary>
public static class DraughSpawner
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "DraughBodyPile";
public const string PieceDisplayName = "Cursed Body Pile";
public const string BoneName = "CursedBone";
public const string BoneDisplayName = "Cursed Bone";
public const string GreaterBoneName = "GreaterCursedBone";
public const string GreaterBoneDisplayName = "Greater Cursed Bone";
public const string ThrallName = "DraughThrall_Draugr";
public const string ThrallEliteName = "DraughThrall_DraugrElite";
public const string ThrallDisplayName = "Draugr Thrall";
public const string ThrallEliteDisplayName = "Draugr Elite Thrall";
// RaisedThrall groups by kind for follower caps and for the roster, so these are the strings
// that decide "is this one an officer" - no longer a display-name comparison.
public const string KindNormal = "DraughDraugr";
public const string KindElite = "DraughDraugrElite";
public const string RaceId = "Draugh";
// The two trophies the pile accepts in place of meat.
public const string TrophyDraugr = "TrophyDraugr";
public const string TrophyDraugrElite = "TrophyDraugrElite";
// ─── Balance ─────────────────────────────────────────────────────────
// 100 units is one full Composter batch on the same FleshValue scale, which is deliberate:
// it makes a Draugr trophy (worth exactly one batch) the real currency and raw meat the
// fallback. A trophy drops from roughly one draugr in ten, so the pile is fed mostly by
// doing the thing it is thematically about.
public const float FleshPerThrall = 100f;
public const int AliveCap = 5;
public const int AliveCapUpgraded = 7; // +2 normals, as designed
public const int EliteCap = 0; // none at all until upgraded
public const int EliteCapUpgraded = 3;
public const int ReserveCap = 5;
public const int ReserveCapElite = 3;
// Local seconds, and only while the zone is loaded - see DraughSpawnerBehaviour.
public const float RespawnSeconds = 60f;
// How long a thrall outlives the pile that made it. The same minute as the respawn on
// purpose: the player learns one number and it reads as "this pile thinks in minutes".
//
// Not zero, which is what it used to be. Killing them on the spot closed the duplication
// exploit but read terribly - dismantle your own pile and ten bodies drop with no
// explanation - and it disarmed you mid-fight if a raid took the pile down while your
// escort was out with you. A minute is short enough that rebuilding elsewhere to keep the
// old thralls is not worth the walk, and the anchor check in RaisedThrall is what actually
// closes that door rather than the length of this timer.
//
// World time, not local: an orphan has to keep withering while its zone is unloaded, or
// walking away would be a way to keep a dead pile's army alive indefinitely.
public const float OrphanWitherSeconds = 60f;
// A thrall only asks "is my pile still standing?" when it is this close to home, because the
// answer can only be trusted where the pile would be loaded if it existed. Further out - out
// following its master, most of the time - the question is unanswerable and gets skipped.
// The leash is 10 m; this leaves room for one that has been knocked about.
public const float HomeCheckRange = 20f;
// How far a thrall strays from the pile when it is not following anybody. Written onto the
// clone's BaseAI.m_randomMoveRange, which is the radius vanilla's own patrol wandering uses.
public const float LeashRange = 10f;
// An escort, not a doomstack. The pile can hold ten; it can lend you four.
public const int MaxFollowers = 3;
public const int MaxEliteFollowers = 1;
// Upgrading is gated on the lord of the swamp dead rather than on money alone.
public const int UpgradeProgressionState = 4; // Bonemass
// ─── Density ─────────────────────────────────────────────────────────
// Five piles per 1.6 square kilometres, enforced by PieceDensityLimit. For scale, a Valheim
// zone is 64 m square, so 1.6 km2 is a disc about 22 zones across - big enough that five
// piles is a regional army rather than base decoration.
public const int MaxPilesInRange = 5;
public const float DensityAreaKm2 = 1.6f;
// ─── Looks ───────────────────────────────────────────────────────────
// Bigger than the vanilla pile, not smaller. The first pass went to 0.8 on the assumption that
// a buildable wants to be unobtrusive; in game it read as a scrap heap rather than as something
// that raises the dead. 1.2 gives it the presence the feature deserves.
private const float ModelScale = 1.2f;
// Green, and far enough from the vanilla pile's brown-grey to be told apart across a swamp.
private static readonly Color PileTint = new Color(0.22f, 0.52f, 0.24f, 1f);
private static readonly Color BoneTint = new Color(0.35f, 0.45f, 0.30f, 1f);
private static readonly Color GreaterBoneTint = new Color(0.20f, 0.55f, 0.25f, 1f);
public static void Register()
{
RegisterBone(BoneName, BoneDisplayName, BoneTint,
"A bone that will not stay quiet. The dead sell them; the dead do not say why.");
RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint,
"The same bone, older, and louder. A pile fed one of these starts keeping officers.");
RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers);
RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"The ground here already carries {0} of these. Find another country.");
}
// ---------------------------------------------------------------- items
private static void RegisterBone(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "BoneFragments");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Draugh] Could not clone BoneFragments; {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;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- thralls
/// <summary>
/// A draugr that is born tame and on a leash.
///
/// Cloned rather than tamed in place so the leash range, the name and the loot table are the
/// prefab's own business and no vanilla draugr is touched. Its CharacterDrop is destroyed
/// outright: a conjured corpse leaves nothing behind. Without that, killing your own thralls
/// would farm the entrails and bone fragments this whole chain is built out of - and, at a one
/// in ten trophy rate, hand back a slice of the flesh that paid for it.
/// </summary>
private static void RegisterThrall(string prefabName, string source, string displayName,
string kind, int maxFollowers)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Draugh] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
// The radius vanilla's own patrol wandering keeps to around m_patrolPoint, which
// RaisedThrall pins to the pile.
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 = kind;
thrall.m_commandingRace = RaceId; // only a Draugh may give these orders
thrall.m_maxFollowers = maxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "The dead do not take orders from the living.";
PrefabManager.Instance.AddPrefab(prefab);
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// Spawner_DraugrPile is the visible, destructible body pile of the swamps - the only one
// of the seven Spawner_Draugr* prefabs with hit and destruction effects of its own, which
// is what says it has a model rather than being a world-generation spawn point.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "Spawner_DraugrPile");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Draugh] Could not clone Spawner_DraugrPile; the body pile is not registered.");
return;
}
// The vanilla pile's whole job is spawning hostile draugr on a timer at anyone who walks
// past. Every bit of that goes: what it produces, when, and for whom is ours now.
foreach (SpawnArea area in prefab.GetComponentsInChildren<SpawnArea>(true))
{
if (area != null) Object.DestroyImmediate(area);
}
// Same belt as the Composter: a bone pile carries nothing that shoots, but the eitr
// refinery taught this codebase not to assume. A silent log is the proof.
AswidBloodRefinery.StripOffensive(prefab, PieceName);
DraughSpawnerBehaviour behaviour = prefab.AddComponent<DraughSpawnerBehaviour>();
// One interaction point, as on the Composter: what is in your hand decides what the click
// means. Any Switch the prefab happened to carry goes first so it cannot win the hover
// from a child collider - the components only, never their colliders.
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 * ModelScale;
Recolour(prefab, PileTint);
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(TrophyDraugr);
// Learned on the Furling's bushes: a Piece added to world scenery is born with no icon
// and no place effect, and a null icon is a blank, unclickable square in the build menu.
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 = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon(TrophyDraugr),
Requirements = new[]
{
new RequirementConfig(BoneName, 1, 0, true),
new RequirementConfig("Entrails", 10, 0, true),
new RequirementConfig("BoneFragments", 20, 0, true),
}
}));
}
/// <summary>
/// Same reason as the Composter's and the Furling's: a piece registered after the vanilla
/// learning pass never reaches the hammer on its own. The purchased Cursed Bone is the gate.
/// </summary>
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;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Draugh] 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 DraughSpawnerKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DraughSpawner.EnsureKnown(__instance);
}
}
}

View file

@ -0,0 +1,366 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The body pile's logic. Same skeleton as ComposterBehaviour - one Switch, one numeric tank fed
/// by many different meats, all state in the ZDO, owner-only accounting - with a roster on top.
///
/// Two deliberate differences from the Composter's timing, both of them about not punishing the
/// player for walking away:
/// - the respawn timer runs on LOCAL time and only while the zone is loaded. The Composter's
/// seal time is world time, because rotting happens whether anyone watches; a grave refilling
/// itself while unloaded would instead let a wandering troll drain the whole reserve into a
/// field of corpses nobody was there to use.
/// - the roster is counted, never tallied. Alive thralls are found by asking the world which
/// creatures are bound to this pile, so a death, a despawn or a player killing his own thrall
/// all correct themselves with no bookkeeping to drift.
/// </summary>
public class DraughSpawnerBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyFlesh = "RoV_draughFlesh";
private const string KeyReserve = "RoV_draughReserve";
private const string KeyReserveElite = "RoV_draughReserveElite";
private const string KeyUpgraded = "RoV_draughUpgraded";
private ZNetView m_nview;
private float m_respawnTimer;
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
private void Awake()
{
// The shared registry RaisedThrall consults to answer "is my pile still standing?".
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_DraughFeed", RPC_Feed);
m_nview.Register("RoV_DraughUpgrade", RPC_Upgrade);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("UpdatePile", 2f, 2f);
}
// ---------------------------------------------------------------- interaction
/// <summary>
/// One interaction point, like the Composter's: what is in hand decides what the click means.
/// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a
/// Greater Cursed Bone upgrades it. Empty hands just report.
/// </summary>
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 flesh, or the head of one of its own.");
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName == null) return false;
if (prefabName == DraughSpawner.GreaterBoneName) return TryUpgrade(user, inventory, item);
if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded())
{
user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet.");
return false;
}
if (prefabName != DraughSpawner.TrophyDraugr &&
prefabName != DraughSpawner.TrophyDraugrElite &&
AswidBloodRefinery.FleshValue(prefabName) <= 0)
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
// Fullness depends on which shelf the input goes on. Asking the wrong one is not cosmetic:
// an Elite trophy accepted here and then dropped by RPC_Feed for want of an officer slot
// would be an item destroyed for nothing.
bool elite = prefabName == DraughSpawner.TrophyDraugrElite;
if (elite ? GetReserveElite() >= DraughSpawner.ReserveCapElite : IsFull())
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
// An Elite trophy banks an officer each, and the shelf holds three - so a stack of ten
// would have had seven of them clamped away by RPC_Feed and destroyed. Found on the
// Skeleton's pile, which has the identical shape, and fixed here before it could bite.
// Flesh needs no equivalent because its remainder stays in the tank rather than vanishing.
if (elite)
{
int room = DraughSpawner.ReserveCapElite - GetReserveElite();
int takenElite = Mathf.Min(Mathf.Max(1, item.m_stack), room);
user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{takenElite}");
inventory.RemoveItem(item, takenElite);
m_nview.InvokeRPC("RoV_DraughFeed", prefabName, takenElite);
return true;
}
// A whole stack per click. The Composter asks for a hundred units one item at a time and
// gets away with it because a batch is the end of the story; a full complement here is ten
// batches, and clicking that out one neck tail at a time is not a mechanic.
//
// The count goes over as an argument rather than as one RPC per item - a stack of fifty
// neck tails would otherwise be fifty round trips to say the same thing.
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_DraughFeed", 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 == DraughSpawner.TrophyDraugr) return candidate;
if (name == DraughSpawner.TrophyDraugrElite && IsUpgraded()) return candidate;
if (AswidBloodRefinery.FleshValue(name) > 0) return candidate;
}
return null;
}
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() < DraughSpawner.UpgradeProgressionState)
{
user.Message(MessageHud.MessageType.Center, "The bone will not wake. Something older has to fall first.");
return false;
}
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DraughUpgrade");
user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now.");
return true;
}
// ---------------------------------------------------------------- accounting
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) count = 1;
// An Elite trophy is not flesh - it banks an officer outright.
if (prefabName == DraughSpawner.TrophyDraugrElite)
{
if (!IsUpgraded()) return;
SetReserveElite(GetReserveElite() + count); // the setter clamps to the shelf
return;
}
float value = prefabName == DraughSpawner.TrophyDraugr
? DraughSpawner.FleshPerThrall // a head is worth a whole batch
: AswidBloodRefinery.FleshValue(prefabName);
if (value <= 0f) return;
float flesh = GetFlesh() + value * count;
// Every complete batch becomes a banked thrall. A loop rather than a single test so a
// trophy - or a stack of them - cannot overflow into flesh that never gets counted.
while (flesh >= DraughSpawner.FleshPerThrall && GetReserve() < DraughSpawner.ReserveCap)
{
flesh -= DraughSpawner.FleshPerThrall;
SetReserve(GetReserve() + 1);
}
SetFlesh(flesh);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
private void UpdatePile()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
int aliveNormal = 0;
int aliveElite = 0;
foreach (RaisedThrall thrall in bound)
{
if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++;
}
bool wantsNormal = aliveNormal < AliveCap() && GetReserve() > 0;
bool wantsElite = aliveElite < EliteCap() && GetReserveElite() > 0;
if (!wantsNormal && !wantsElite)
{
m_respawnTimer = 0f;
return;
}
m_respawnTimer += 2f; // the tick interval
if (m_respawnTimer < DraughSpawner.RespawnSeconds) return;
m_respawnTimer = 0f;
// Officers first: they are the scarcer resource and the reason to upgrade at all.
if (wantsElite)
{
if (Spawn(DraughSpawner.ThrallEliteName)) SetReserveElite(GetReserveElite() - 1);
}
else if (wantsNormal)
{
if (Spawn(DraughSpawner.ThrallName)) SetReserve(GetReserve() - 1);
}
}
private bool Spawn(string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Draugh] No '{prefabName}' in ZNetScene; the pile cannot raise anything.");
return false;
}
Vector3 offset = UnityEngine.Random.insideUnitSphere * 2f;
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));
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
return true;
}
/// <summary>
/// The pile sustains them, so it takes them with it - but on a minute's delay rather than on
/// the spot. Without some form of this a pile is a duplication exploit: fill it, dismantle it,
/// rebuild it elsewhere, fill it again, and keep every thrall from every round.
///
/// This marks the ones it can reach. It cannot reach thralls whose zone is unloaded right now,
/// which is why RaisedThrall also checks for itself once it is home again - between the two,
/// nothing outlives its pile.
/// </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();
// Said once, by the client that just knocked it down, because the hover text that would
// otherwise explain this is going away with the pile.
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
$"The pile is broken. {bound.Count} will not outlast it by more than a minute.");
}
SetFlesh(0f);
SetReserve(0);
SetReserveElite(0);
}
// ---------------------------------------------------------------- state and display
public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private int AliveCap() => IsUpgraded() ? DraughSpawner.AliveCapUpgraded : DraughSpawner.AliveCap;
private int EliteCap() => IsUpgraded() ? DraughSpawner.EliteCapUpgraded : DraughSpawner.EliteCap;
/// <summary>Full when there is nowhere left to put a finished thrall.</summary>
private bool IsFull() => GetReserve() >= DraughSpawner.ReserveCap;
/// <summary>
/// Everything a player needs to know 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()
{
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
int aliveNormal = 0;
int aliveElite = 0;
foreach (RaisedThrall thrall in bound)
{
if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++;
}
string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " +
$"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}";
if (IsUpgraded())
{
body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {GetReserveElite()}/{DraughSpawner.ReserveCapElite}";
}
if (m_respawnTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer));
body += $"\nnext rises in {left}s";
}
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Feed it flesh, or a draugr's head";
return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})");
}
// ---------------------------------------------------------------- ZDO accessors
private float GetFlesh() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFlesh) : 0f;
private void SetFlesh(float value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFlesh, Mathf.Max(0f, value));
}
private int GetReserve() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserve) : 0;
private void SetReserve(int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserve, Mathf.Clamp(value, 0, DraughSpawner.ReserveCap));
}
private int GetReserveElite() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserveElite) : 0;
private void SetReserveElite(int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserveElite, Mathf.Clamp(value, 0, DraughSpawner.ReserveCapElite));
}
}
}

View file

@ -17,10 +17,16 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })]
public static class FactionHostilityPatch
{
// "Fuling" was in this set and is not a prefab: the Fuling family is named Goblin* in code,
// so the basic Fuling and the Archer were never exempted for any of the three races that
// read this set (Trenta, Trol, Furling) while the Berserker and Shaman were. In a camp that
// is the same as no truce at all - the unexempted Fulings open fire, the player defends
// themselves, and every Berserker in earshot joins in through damage retaliation, which
// IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names.
private static readonly HashSet<string> NeraForestaMobs = new HashSet<string>
{
"Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman",
"Goblin", "GoblinBrute", "GoblinShaman", // "Goblin" is the real prefab id - "Fuling" is only the in-game display name
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Troll",
};

View file

@ -49,13 +49,14 @@ namespace RacesOfValheim
new CatalogEntry("Resin", 5),
new CatalogEntry("GreydwarfEye", 5),
new CatalogEntry("Dandelion", 5),
new CatalogEntry("Bukeperries", 5),
new CatalogEntry("Pukeberries", 5),
new CatalogEntry("Mushroom", 5),
new CatalogEntry("Blueberries", 5),
new CatalogEntry("Thistle", 5),
new CatalogEntry("Carrot", 5),
new CatalogEntry("CarrotSeeds", 20),
new CatalogEntry("AncientSeed", 20),
new CatalogEntry("RotSeed", 500), // gates the Trenta Composter
new CatalogEntry("TrophyGreydwarf", 20),
new CatalogEntry("TrophyGreydwarfBrute", 350),
new CatalogEntry("TrophyGreydwarfShaman", 350),
@ -72,7 +73,7 @@ namespace RacesOfValheim
new CatalogEntry("DeerHide", 2),
new CatalogEntry("DeerMeat", 2),
new CatalogEntry("LeatherScraps", 5),
new CatalogEntry("RawMeat", 5), // was "BoarMeat" - not a real prefab id, never appeared
new CatalogEntry("RawMeat", 5),
new CatalogEntry("NeckTail", 5),
new CatalogEntry("TrophyNeck", 20),
new CatalogEntry("TrophyDeer", 20),
@ -94,11 +95,18 @@ namespace RacesOfValheim
new CatalogEntry("LoxPelt", 2),
new CatalogEntry("Flax", 5),
new CatalogEntry("Barley", 5),
new CatalogEntry("Cloudberry", 5), // was "Cloudberries" - not a real prefab id, never appeared
new CatalogEntry("Cloudberry", 5),
new CatalogEntry("Tar", 5), // Growth, folded in here: Growth lives in Plains, same biome as Lox/Ocean
// UNRESOLVED, left as-is rather than guessed: vanilla fish items are named Fish1
// through Fish12 (plus Fish4_cave), so "Tuna", "CoralCod" and "Pufferfish" below
// are display names and match no prefab - these three entries never appear on the
// bench. Which number is which fish lives in the localization, which ships inside
// compressed asset bundles and cannot be read the way the rest of this file's names
// were verified. FactionMerchantSetup already logs each unresolved entry by name at
// runtime, so hovering a Fuling merchant once will name them in the log.
new CatalogEntry("Tuna", 50),
new CatalogEntry("CoralCod", 70),
new CatalogEntry("FulingTotem", 350),
new CatalogEntry("GoblinTotem", 350),
new CatalogEntry("TrophyGoblin", 350),
new CatalogEntry("TrophyGoblinShaman", 350),
new CatalogEntry("TrophyLox", 350),
@ -109,6 +117,30 @@ namespace RacesOfValheim
}
};
// The Shaman alone stocks the Furling's crop line, so it needs a bench of its own - the four
// Fuling prefabs shared one ShopDefinition instance until now. It keeps everything the Fuling
// bench sells and adds the five on top, so splitting it off takes nothing away.
//
// Declared after FulingShop because it copies that list, and static field initialisers run
// in declaration order.
private static readonly ShopDefinition GoblinShamanShop = new ShopDefinition
{
DisplayName = "Fuling Shaman",
JokeCategory = JokeGoblin,
Items = new List<CatalogEntry>(FulingShop.Items)
{
// Plantable, millable, and the only source of these three strains anywhere.
new CatalogEntry("CopperFlax", 20),
new CatalogEntry("TinFlax", 20),
new CatalogEntry("IronFlax", 50),
// Inedible. Buying one is the only way to get a bush, but a planted bush then yields
// forever - so these are a one-off cost per bush, not a running one.
new CatalogEntry("Stoneberry", 20),
new CatalogEntry("Flintberry", 20),
}
};
private static readonly ShopDefinition WolfShop = new ShopDefinition
{
DisplayName = "Wolf",
@ -166,7 +198,7 @@ namespace RacesOfValheim
Items = new List<CatalogEntry>
{
new CatalogEntry("BlackMarble", 20),
new CatalogEntry("SoftTissue", 250),
new CatalogEntry("Softtissue", 250),
new CatalogEntry("Sap", 250), // extracted from Yggdrasil roots with Dvergr extractors
new CatalogEntry("TrophyDvergr", 1500),
}
@ -186,6 +218,10 @@ namespace RacesOfValheim
new CatalogEntry("Guck", 1), // Abomination, folded in here: cannot speak at all
new CatalogEntry("Root", 1), // Abomination
new CatalogEntry("TurnipSeeds", 20),
new CatalogEntry("BloodCore", 500), // gates the Aswid Blood Refinery
new CatalogEntry("CursedBone", 500), // gates the Draugh body pile
new CatalogEntry("GreaterCursedBone", 1500), // upgrades it: officers
new CatalogEntry("TrophyDraugr", 350),
new CatalogEntry("TrophyLeech", 350), // Leech
new CatalogEntry("TrophyDraugrElite", 800),
@ -201,10 +237,13 @@ namespace RacesOfValheim
{
new CatalogEntry("BoneFragments", 1),
new CatalogEntry("Ooze", 2), // Blob/Oozer, folded in here: no talk-capable rig
new CatalogEntry("ScrapIron", 20), // Oozer
new CatalogEntry("IronScrap", 20), // Oozer
new CatalogEntry("TrophySkeleton", 350),
new CatalogEntry("TrophyBlob", 350), // Blob
new CatalogEntry("TrophySkeletonPoison", 800),
new CatalogEntry("SoulStone", 50), // binds a skeleton archer sentry
new CatalogEntry("CursedSkull", 500), // gates the Skeleton bone pile
new CatalogEntry("GreaterCursedSkull", 1500), // upgrades it: the rotten
}
};
@ -240,9 +279,10 @@ namespace RacesOfValheim
{ "Troll", TrollShop },
{ "Goblin", FulingShop }, // "Goblin" is the real prefab id - "Fuling" is only the in-game display name
{ "Goblin", FulingShop },
{ "GoblinArcher", FulingShop },
{ "GoblinBrute", FulingShop },
{ "GoblinShaman", FulingShop },
{ "GoblinShaman", GoblinShamanShop }, // the only bench carrying the crop line
{ "Wolf", WolfShop },
{ "Ulv", UlvShop },

View file

@ -0,0 +1,541 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Furling's itemization: five things only a Fuling Shaman will sell, and the two chains
/// they open.
///
/// Copper / Tin / Iron Flax -> plant, harvest, mill -> Copper / Tin / Iron Dust
/// -> smelt -> the metal itself
/// Stoneberry / Flintberry -> plant -> a bush that yields Stone / Flint
/// forever
///
/// No new station: both `windmill` and `smelter` are <see cref="Smelter"/> components (the class
/// even carries an m_windmill field to drive the blades), so all six steps are appends to a
/// conversion list - the same trick AswidBloodPotions uses on the fermenter. Every vanilla
/// recipe in both machines keeps working.
///
/// Two rules that came from the design conversation and are load-bearing:
/// - the FLAX travels through portals, the DUST does not. The dust copies the weight, stack
/// size and teleportability of the ore it becomes, so "behaves exactly like raw ore" is not
/// an approximation - it is read off that ore at registration.
/// - the flax yields what real flax yields and scales with the world modifiers the same way,
/// which is achieved by cloning Pickable_Flax and then NOT touching a single one of its
/// yield fields. See RegisterCrop.
/// </summary>
public static class FurlingCrops
{
// Prices are NOT here: they live with the rest of the shop data, in
// FactionMerchantCatalog.GoblinShamanShop. The benches are symmetric, so each figure there is
// both what the Shaman charges and what it pays.
private class MetalCrop
{
public string Metal; // "Copper" - display only
public string FlaxName;
public string FlaxDisplay;
public string DustName;
public string DustDisplay;
public string PickableName;
public string SaplingName;
public string SaplingDisplay;
/// <summary>
/// The vanilla raw ore this dust stands in for. Used for three things and never as an
/// output name: the dust's weight/stack/teleport flags, its borrowed icon, and looking up
/// what the vanilla smelter already turns that ore into.
/// </summary>
public string OrePrefab;
public Color Tint;
// Filled in during registration so the conversions can be wired from the objects we
// just built, rather than from ObjectDB - which has not been populated yet at
// CreateModAssets time. Same reason AswidBloodPotions passes GameObjects around.
public GameObject FlaxPrefab;
public GameObject DustPrefab;
}
private static readonly MetalCrop[] Crops =
{
new MetalCrop
{
Metal = "Copper", FlaxName = "CopperFlax", FlaxDisplay = "Copper Flax",
DustName = "CopperDust", DustDisplay = "Copper Dust",
PickableName = "Pickable_CopperFlax", SaplingName = "sapling_copperflax",
SaplingDisplay = "Copper Flax", OrePrefab = "CopperOre",
Tint = new Color(0.72f, 0.45f, 0.20f, 1f),
},
new MetalCrop
{
Metal = "Tin", FlaxName = "TinFlax", FlaxDisplay = "Tin Flax",
DustName = "TinDust", DustDisplay = "Tin Dust",
PickableName = "Pickable_TinFlax", SaplingName = "sapling_tinflax",
SaplingDisplay = "Tin Flax", OrePrefab = "TinOre",
Tint = new Color(0.80f, 0.82f, 0.85f, 1f),
},
new MetalCrop
{
Metal = "Iron", FlaxName = "IronFlax", FlaxDisplay = "Iron Flax",
DustName = "IronDust", DustDisplay = "Iron Dust",
PickableName = "Pickable_IronFlax", SaplingName = "sapling_ironflax",
// Iron's raw form is IronScrap, not "IronOre" - there is no IronOre prefab.
SaplingDisplay = "Iron Flax", OrePrefab = "IronScrap",
Tint = new Color(0.35f, 0.36f, 0.38f, 1f),
},
};
private class RockBerry
{
public string BerryName;
public string BerryDisplay;
public string BushName; // the cultivator entry AND the bush - one prefab
public string BushDisplay;
public string YieldPrefab; // what the bush gives instead of fruit
public Color Tint;
}
private static readonly RockBerry[] Berries =
{
new RockBerry
{
BerryName = "Stoneberry", BerryDisplay = "Stoneberry",
BushName = "StoneberryBush", BushDisplay = "Stoneberry Bush",
YieldPrefab = "Stone", Tint = new Color(0.55f, 0.55f, 0.55f, 1f),
},
new RockBerry
{
BerryName = "Flintberry", BerryDisplay = "Flintberry",
BushName = "FlintberryBush", BushDisplay = "Flintberry Bush",
YieldPrefab = "Flint", Tint = new Color(0.30f, 0.32f, 0.35f, 1f),
},
};
public static void Register()
{
foreach (MetalCrop crop in Crops) RegisterCrop(crop);
foreach (RockBerry berry in Berries) RegisterBerry(berry);
AddConversions();
}
// ---------------------------------------------------------------- metal flax
private static void RegisterCrop(MetalCrop crop)
{
crop.FlaxPrefab = BuildFlax(crop);
crop.DustPrefab = BuildDust(crop);
// Order matters: the sapling's Plant has to point at a pickable that already exists.
GameObject pickable = BuildGrownFlax(crop);
BuildSapling(crop, pickable);
}
private static GameObject BuildFlax(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.FlaxName, "Flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Flax; {crop.FlaxDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = crop.FlaxDisplay;
shared.m_description = $"Flax grown in {crop.Metal.ToLowerInvariant()}-poisoned soil, and it took. " +
"Useless as cloth. Grind it and see.";
// Teleportable is inherited from Flax and left alone on purpose: the flax travels, the
// dust does not. That asymmetry is the whole point of the chain.
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
private static GameObject BuildDust(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.DustName, "BarleyFlour");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone BarleyFlour; {crop.DustDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = crop.DustDisplay;
shared.m_description = $"A sack of {crop.Metal.ToLowerInvariant()} ground fine. " +
"A furnace cannot tell it from ore, and it will not go through a portal either.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_consumeStatusEffect = null;
// "Behaves exactly like raw ore of that type", read off the ore instead of invented:
// its weight, its stack size, and - the one that matters - its refusal to teleport.
ItemDrop.ItemData.SharedData ore = SharedOf(crop.OrePrefab);
if (ore != null)
{
shared.m_weight = ore.m_weight;
shared.m_maxStackSize = ore.m_maxStackSize;
shared.m_teleportable = ore.m_teleportable;
}
else
{
Jotunn.Logger.LogWarning($"[Furling] No '{crop.OrePrefab}' to copy ore behaviour from; " +
$"{crop.DustDisplay} falls back to blocking teleport only.");
shared.m_teleportable = false;
}
// The tint reaches the sack model but never the inventory icon - icons are atlas sprites
// and repainting one produces an empty slot, learned the hard way on the Aswid's Blood
// Essence. Three identical flour sacks in the inventory would be unusable, so the dusts
// borrow their ore's icon: it reads as "this is copper" at a glance, at the cost of not
// looking like flour.
Sprite icon = BorrowIcon(crop.OrePrefab);
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
/// <summary>
/// The harvestable stage. Cloned from Pickable_Flax and then deliberately left alone except
/// for what it drops: m_amount, m_minAmountScaled, m_dontScale and m_respawnTimeMinutes all
/// come across untouched, which is exactly how "yields what a real flax plant yields and
/// reacts to the world modifiers like a real plant" is satisfied. Writing our own numbers
/// here is the one thing that would break that.
///
/// Not a piece and not in any table - it only ever exists as the Plant's grown prefab - so it
/// is registered straight into ZNetScene with AddPrefab. That call is the thing to check in
/// the log on the first run: without it the sapling would grow into nothing.
/// </summary>
private static GameObject BuildGrownFlax(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.PickableName, "Pickable_Flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Pickable_Flax; grown {crop.FlaxDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
Pickable pickable = prefab.GetComponent<Pickable>();
if (pickable == null)
{
Jotunn.Logger.LogWarning($"[Furling] {crop.PickableName} has no Pickable; it will drop nothing.");
}
else if (crop.FlaxPrefab != null)
{
pickable.m_itemPrefab = crop.FlaxPrefab;
pickable.m_overrideName = crop.FlaxDisplay;
}
PrefabManager.Instance.AddPrefab(prefab);
return prefab;
}
private static void BuildSapling(MetalCrop crop, GameObject grown)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.SaplingName, "sapling_flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone sapling_flax; {crop.SaplingDisplay} not plantable.");
return;
}
Recolour(prefab, crop.Tint);
Plant plant = prefab.GetComponent<Plant>();
if (plant != null && grown != null)
{
plant.m_grownPrefabs = new[] { grown };
plant.m_name = crop.SaplingDisplay;
// m_growTime, m_biome, m_needCultivatedGround and the rest stay as real flax's: the
// special strains are still flax, still Plains, still want tilled ground.
}
Piece piece = prefab.GetComponent<Piece>();
if (piece != null)
{
piece.m_name = crop.SaplingDisplay;
piece.m_resources = new Piece.Requirement[0];
}
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = crop.SaplingDisplay,
Description = $"Plant it and it grows more {crop.FlaxDisplay}.",
PieceTable = PieceTables.Cultivator,
Requirements = new[] { new RequirementConfig(crop.FlaxName, 1, 0, true) },
}));
}
// ---------------------------------------------------------------- rock berries
private static void RegisterBerry(RockBerry berry)
{
BuildBerry(berry);
BuildBush(berry);
}
private static GameObject BuildBerry(RockBerry berry)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(berry.BerryName, "Cloudberry");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Cloudberry; {berry.BerryDisplay} not registered.");
return null;
}
Recolour(prefab, berry.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = berry.BerryDisplay;
shared.m_description = $"Not a berry, whatever it looks like. Bury one and a {berry.YieldPrefab.ToLowerInvariant()}-bearing bush comes up.";
// Inedible, as designed. Material with every food value at zero also keeps it clear of
// the Trenta's vegan check and of the Aswid/Skeleton food gates, all three of which only
// look at consumables that carry food values.
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_foodBurnTime = 0f;
shared.m_foodRegen = 0f;
shared.m_consumeStatusEffect = null;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
/// <summary>
/// The bush: one prefab, cloned from CloudberryBush and nothing else. It is already a Pickable
/// that regrows its fruit on a timer forever, so "once planted they regrow forever, exactly
/// like normal plants" needs nothing added - only the fruit swapped for Stone or Flint. The
/// respawn timer, the amount and the world-modifier scaling all come across untouched, the
/// same way the flax's do.
///
/// There is no growth stage and no second prefab. The first version of this did the same and
/// showed up in the cultivator as a blank square; the fix for that is the two lines marked
/// below, not a different base prefab. An attempt in between cloned sapling_flax for the
/// plantable stage, which did produce a working button - and put a grey flax sprout in the
/// middle of a chain that is supposed to be cloudberry all the way down. Reverted.
/// </summary>
private static void BuildBush(RockBerry berry)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(berry.BushName, "CloudberryBush");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone CloudberryBush; {berry.BushDisplay} not registered.");
return;
}
Recolour(prefab, berry.Tint);
Pickable pickable = prefab.GetComponent<Pickable>();
GameObject yield = PrefabManager.Cache.GetPrefab<GameObject>(berry.YieldPrefab);
if (pickable == null || yield == null)
{
Jotunn.Logger.LogWarning($"[Furling] {berry.BushName}: no Pickable or no '{berry.YieldPrefab}'; it will drop nothing.");
}
else
{
pickable.m_itemPrefab = yield;
pickable.m_overrideName = berry.BushDisplay;
}
// CloudberryBush is world scenery, so it carries no Piece and cannot be built. Adding one
// is what puts it in the cultivator, and the two things a Piece added this way is missing
// are an icon - the sprite the build menu draws, whose absence is why the entry was there
// but invisible - and a placement effect. Both are supplied below.
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_name = berry.BushDisplay;
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil
piece.m_icon = BorrowIcon(berry.YieldPrefab);
// Borrowed from a real cultivator entry so planting one looks and sounds like planting
// anything else. Only the effect list is taken - never the model, never the Plant.
Piece template = PrefabManager.Cache.GetPrefab<Piece>("sapling_flax");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = berry.BushDisplay,
Description = $"Yields {berry.YieldPrefab.ToLowerInvariant()}, and keeps yielding it.",
PieceTable = PieceTables.Cultivator,
// The one thing that was actually missing the first time round.
Icon = BorrowIcon(berry.YieldPrefab),
Requirements = new[] { new RequirementConfig(berry.BerryName, 1, 0, true) },
}));
}
// ---------------------------------------------------------------- conversions
/// <summary>
/// Six appends, three to the windmill and three to the smelter. Both are Smelter components,
/// so this is the same shape as AswidBloodPotions.AddFermenterConversion, and for the same
/// reason: the vanilla list is appended to, never replaced, so barley still becomes flour and
/// ore still becomes metal.
/// </summary>
private static void AddConversions()
{
Smelter mill = SmelterOn("windmill");
Smelter furnace = SmelterOn("smelter");
foreach (MetalCrop crop in Crops)
{
ItemDrop flax = DropOf(crop.FlaxPrefab);
ItemDrop dust = DropOf(crop.DustPrefab);
if (flax == null || dust == null) continue;
AddConversion(mill, "windmill", flax, dust);
// The output is never named: whatever the vanilla furnace already makes from this
// ore is what the dust makes too. That is also the answer to "is the bar called
// Copper or CopperIngot" - it does not matter, because it is copied, not typed.
ItemDrop metal = OutputFor(furnace, crop.OrePrefab);
if (metal == null)
{
Jotunn.Logger.LogWarning($"[Furling] The smelter has no conversion from '{crop.OrePrefab}'; " +
$"{crop.DustDisplay} cannot be smelted.");
continue;
}
AddConversion(furnace, "smelter", dust, metal);
}
}
private static Smelter SmelterOn(string piecePrefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(piecePrefabName);
Smelter smelter = prefab != null ? prefab.GetComponent<Smelter>() : null;
if (smelter == null)
{
Jotunn.Logger.LogWarning($"[Furling] No Smelter on '{piecePrefabName}'; its half of the chain is dead.");
}
return smelter;
}
/// <summary>What the machine already turns the named input into, or null.</summary>
private static ItemDrop OutputFor(Smelter smelter, string fromPrefabName)
{
if (smelter == null || smelter.m_conversion == null) return null;
foreach (Smelter.ItemConversion conversion in smelter.m_conversion)
{
if (conversion == null || conversion.m_from == null || conversion.m_to == null) continue;
if (conversion.m_from.gameObject.name == fromPrefabName) return conversion.m_to;
}
return null;
}
private static void AddConversion(Smelter smelter, string label, ItemDrop from, ItemDrop to)
{
if (smelter == null || from == null || to == null) return;
if (smelter.m_conversion == null) smelter.m_conversion = new List<Smelter.ItemConversion>();
foreach (Smelter.ItemConversion existing in smelter.m_conversion)
{
if (existing != null && existing.m_from == from) return; // already taught
}
smelter.m_conversion.Add(new Smelter.ItemConversion { m_from = from, m_to = to });
Jotunn.Logger.LogInfo($"[Furling] {label}: {from.m_itemData.m_shared.m_name} -> {to.m_itemData.m_shared.m_name}.");
}
// ---------------------------------------------------------------- known recipes
/// <summary>
/// Teaches the five new cultivator entries, the same way RaceMenuWard, the Blood Refinery and
/// the Composter all had to be taught: a piece registered after the vanilla learning pass
/// never reaches its table on its own. The purchased item is still the real gate - the entry
/// just sits greyed out until one is owned.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null) return;
HarmonyLib.Traverse traverse = HarmonyLib.Traverse.Create(player);
bool taught = false;
foreach (MetalCrop crop in Crops) taught |= Teach(traverse, crop.SaplingName);
foreach (RockBerry berry in Berries) taught |= Teach(traverse, berry.BushName);
if (taught) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static bool Teach(HarmonyLib.Traverse traverse, string piecePrefabName)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(piecePrefabName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return false;
traverse.Method("AddKnownPiece", piece).GetValue();
return true;
}
// ---------------------------------------------------------------- helpers
private static ItemDrop DropOf(GameObject prefab) => prefab != null ? prefab.GetComponent<ItemDrop>() : null;
private static ItemDrop.ItemData.SharedData SharedOf(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null;
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop.ItemData.SharedData shared = SharedOf(prefabName);
Sprite[] icons = shared != null ? shared.m_icons : null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Furling] Could not borrow the icon from '{prefabName}'.");
return null;
}
/// <summary>
/// renderer.materials instantiates a copy, so real flax, real flour, real cloudberries and
/// the real cloudberry bushes of the world all keep their own look. Particle renderers are
/// skipped - painting them just turns the effect into soot.
/// </summary>
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);
}
}
}
}
}

View file

@ -42,10 +42,34 @@ namespace RacesOfValheim
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!FurlingRace.IsFurling()) return;
__result *= 1f + FurlingConfig.RunSpeedBonus.Value;
__result *= 1.1f;
}
}
/// <summary>
/// The Furling's truce with the Plains. Every name here is the game's actual internal prefab
/// id, checked against the shipped asset manifest one at a time, because the display names do
/// not predict them at all - this is the family where "Fuling" is the word the game shows the
/// player and "Goblin" is the word the game uses in code.
///
/// The full roster under Assets/Characters, so nothing is missed by accident:
/// Goblin ............... Fuling (NOT "Fuling" - that prefab does not exist)
/// GoblinArcher ......... Fuling Archer (was missing entirely)
/// GoblinBrute .......... Fuling Berserker
/// GoblinShaman ......... Fuling Shaman
/// GoblinKing ........... Yagluth - a boss, stays hostile
/// GoblinBruteBros, GoblinBrute_Hildir, GoblinShaman_Hildir (+ _nochest variants)
/// Hildir's quest bosses - arena fights, they stay hostile too
/// The old code checked for "goblinking" inside a branch it could never reach, which is a
/// good sign the list was written from the display names rather than from the assets.
/// </summary>
private static readonly System.Collections.Generic.HashSet<string> FurlingFriends =
new System.Collections.Generic.HashSet<string>
{
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Lox", "Deathsquito", "Troll",
};
[HarmonyPatch(typeof(BaseAI), "IsEnemy", typeof(Character), typeof(Character))]
public static class Furling_BaseAI_IsEnemy_Patch
{
@ -59,23 +83,12 @@ namespace RacesOfValheim
if (a == playerChar) otherChar = b;
else if (b == playerChar) otherChar = a;
if (otherChar != null)
{
string name = otherChar.gameObject.name.Replace("(Clone)", "").ToLower();
if (name == "goblin" ||
name == "goblinbrute" ||
name == "goblinshaman" ||
name == "lox" ||
name == "deathsquito" ||
name == "troll")
{
// Exclude minibosses/bosses explicitly if needed, but normally bosses are handled separately (Yagluth is GoblinKing).
if (name != "goblinking")
{
__result = false;
}
}
}
if (otherChar == null) return;
// Trimmed as well as stripped: a stray "(Clone)" leaves a trailing space behind, and
// an exact-match set is unforgiving about it in a way the old ToLower chain also was.
string name = otherChar.gameObject.name.Replace("(Clone)", "").Trim();
if (FurlingFriends.Contains(name)) __result = false;
}
}
@ -323,14 +336,14 @@ namespace RacesOfValheim
if (isWeaponSkill)
{
factor *= FurlingConfig.WeaponSkillXPMultiplier.Value;
factor *= 2f;
}
else if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
// The King is Dead: in Plains, ALL other skills (including magic) get bonus XP
// The King is Dead: in Plains, ALL other skills (including magic) get 2x XP
if (EnvMan.instance != null && EnvMan.instance.GetCurrentBiome() == Heightmap.Biome.Plains)
{
factor *= FurlingConfig.PlainsSkillXPMultiplier.Value;
factor *= 2f;
}
}
}
@ -347,7 +360,7 @@ namespace RacesOfValheim
// Check if it's nighttime or inside a dungeon
if (BossProgressionManager.GetCurrentProgressionState() >= 2) // Master of Shadows (Eikthyr)
{
if (range <= FurlingConfig.StealthNoiseRangeThreshold.Value)
if (range <= 15f)
{
return false;
}
@ -368,12 +381,12 @@ namespace RacesOfValheim
if (state >= 8) // Through Fire and Flames (Fader): full fire immunity
{
hit.m_damage.m_fire = 0f;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= FurlingConfig.PoisonResistMultiplier.Value;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f;
}
else if (state >= 3) // The Wickerman: reduced fire and poison
else if (state >= 3) // The Wickerman: -50% fire and poison
{
if (hit.m_damage.m_fire > 0) hit.m_damage.m_fire *= FurlingConfig.WickermanFireResistMultiplier.Value;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= FurlingConfig.PoisonResistMultiplier.Value;
if (hit.m_damage.m_fire > 0) hit.m_damage.m_fire *= 0.5f;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f;
}
}
}
@ -393,11 +406,10 @@ namespace RacesOfValheim
(ammo != null && ammo.m_shared.m_skillType == Skills.SkillType.Bows))
{
// If the arrow doesn't already have significant fire damage, add it
float minFireDamage = FurlingConfig.FireArrowMinDamage.Value;
if (hitData != null && hitData.m_damage.m_fire < minFireDamage)
if (hitData != null && hitData.m_damage.m_fire < 22f)
{
// Adds fire damage equivalent to a standard fire arrow
hitData.m_damage.m_fire = Mathf.Max(hitData.m_damage.m_fire, minFireDamage);
hitData.m_damage.m_fire = Mathf.Max(hitData.m_damage.m_fire, 22f);
}
}
}
@ -495,7 +507,7 @@ namespace RacesOfValheim
if (character != null && (character.IsBoss() || character.gameObject.name.ToLower().Contains("boss"))) return;
float distance = Vector3.Distance(Player.m_localPlayer.transform.position, __instance.transform.position);
if (distance > FurlingConfig.TrophyDoublingRadius.Value) return;
if (distance > 25f) return;
var newList = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<GameObject, int>>();
foreach (var drop in __result)
@ -507,7 +519,7 @@ namespace RacesOfValheim
var itemDrop = go.GetComponent<ItemDrop>();
if (itemDrop != null && itemDrop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Trophy)
{
amount = Mathf.RoundToInt(amount * FurlingConfig.TrophyDropMultiplier.Value);
amount *= 2;
}
}
newList.Add(new System.Collections.Generic.KeyValuePair<GameObject, int>(go, amount));
@ -520,7 +532,7 @@ namespace RacesOfValheim
GameObject coinsPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Coins");
if (coinsPrefab != null)
{
int extraCoins = stars * UnityEngine.Random.Range(FurlingConfig.CoinsPerStarMin.Value, FurlingConfig.CoinsPerStarMax.Value + 1);
int extraCoins = stars * UnityEngine.Random.Range(1, 26);
newList.Add(new System.Collections.Generic.KeyValuePair<GameObject, int>(coinsPrefab, extraCoins));
}
}
@ -636,8 +648,8 @@ namespace RacesOfValheim
// Blue food = eitr > 0
if (food.m_item.m_shared.m_foodEitr > 0f)
{
// Give back the slowed-down fraction of dt that vanilla subtracted
food.m_time += dt * (1f - FurlingConfig.EitrFoodDigestionSlowdown.Value);
// Give back half of dt that vanilla subtracted
food.m_time += dt * 0.5f;
// Clamp to max burn time so we don't exceed the original duration
float maxTime = food.m_item.m_shared.m_foodBurnTime;
if (food.m_time > maxTime) food.m_time = maxTime;

View file

@ -22,15 +22,32 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Reads the race the same way every other race in the mod reads it.
///
/// This used to be `GetPlayerModel() == 5`, with a comment admitting the 5 was assumed.
/// GetPlayerModel returns the character's BODY MODEL index - 0 or 1, male or female, the
/// thing PlayerCustomizaton.SetPlayerModel writes - and has nothing to do with the race,
/// which SelectFurling stores in m_customData["Race"]. So it never returned true, and
/// everything gated behind it was dead code: the -19% visual scale, the +10% run speed, the
/// truce with the Fuling camps, and Through Fire and Flames.
/// </summary>
public static bool IsFurling()
{
return Player.m_localPlayer != null && Player.m_localPlayer.GetPlayerModel() == 5; // Assumed ID for Furling
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Furling";
}
public void CreateModAssets()
{
Jotunn.Logger.LogInfo("Initializing Furling Race...");
FurlingStatusEffects.RegisterStatusEffects();
// The metal flax and the rock berries. Registered here because the faction merchant
// catalogue resolves its entries by prefab name, so the five items have to exist before
// a Shaman is ever set up as a bench.
FurlingCrops.Register();
}
private void Update()

View file

@ -0,0 +1,189 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Borrowing a vanilla prefab's LOOK without borrowing anything it does.
///
/// This exists because of a bug that shipped: the Trol's war totem mounted trophy models by calling
/// Instantiate and then stripping the components off the copy. Instantiate runs Awake FIRST, so for
/// one frame the copy was a real, live object - and a trophy is an ItemDrop, which means a giant
/// Yagluth head fell out of the sky every time the totem's ghost was drawn.
///
/// For a world prop (the Trenta grove borrows a Yggdrasil shoot this way) the stray frame does
/// nothing visible, which is why the technique looked fine the first two times it was used. For
/// anything carrying ItemDrop, ZNetView or a Rigidbody it is a live object with physics.
///
/// The fix is one line and it is the reason this is a shared helper rather than a third copy of the
/// same loop: instantiate into a holder that is ALREADY INACTIVE. Unity does not run Awake on a
/// component that comes up disabled, so the strip happens before anything can wake.
///
/// SECOND ROUND: the borrowed model is now sized in METRES instead of by a multiplier, because a
/// multiplier against an unknown mesh is a guess and guesses shipped a Yagluth head three times
/// taller than the post it stood on. The mesh is measured and scaled to fit, and it is grounded so
/// the holder's origin is the model's BOTTOM CENTRE rather than whatever the item's author happened
/// to use as a pivot - which is what makes "put the head on top of the totem" a subtraction instead
/// of another guess. This is rule 3.2 of the house guide applied to geometry: a number that was
/// measured is already balanced.
/// </summary>
public static class ModelBorrow
{
/// <summary>
/// Hangs the renderers of a vanilla prefab under <paramref name="parent"/> and returns the holder,
/// which the caller can switch on and off. Null-safe: a missing source logs and returns an empty
/// holder rather than throwing, so a wrong name costs a warning and not a startup.
///
/// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes.
/// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres,
/// measured AFTER <paramref name="localRotation"/> has been applied.
/// </summary>
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
{
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false);
holder.transform.localPosition = localPosition;
// BEFORE the Instantiate below. This single line is the whole point of the class.
holder.SetActive(false);
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
holder.SetActive(true);
return holder;
}
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = localRotation;
copy.transform.localScale = Vector3.one;
// Everything that is not a Renderer or a Transform. Order matters for the same reason it did
// on the Aswid's lights: behaviours first, then the things they hold references to.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label);
holder.SetActive(true);
return holder;
}
/// <summary>
/// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack
/// one borrowed model on top of another without a magic offset.
/// </summary>
public static float HeightOf(GameObject holder)
{
if (holder == null) return 0f;
return TryMeasure(holder.transform, holder.transform, out Bounds bounds) ? bounds.size.y : 0f;
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// Scales the copy so its largest dimension is <paramref name="targetSize"/> metres, then slides it
/// so its bottom centre sits on the holder's origin.
/// </summary>
private static void FitAndGround(Transform copy, Transform holder, float targetSize,
string sourcePrefab, string label)
{
if (!TryMeasure(copy, holder, out Bounds raw))
{
Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' has no readable mesh, so it could not be " +
"sized or grounded; it is attached at scale 1 and may sit wrong.");
return;
}
float biggest = Mathf.Max(raw.size.x, Mathf.Max(raw.size.y, raw.size.z));
if (biggest <= 0.0001f)
{
Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' measured as a point ({raw.size}); " +
"left at scale 1.");
return;
}
float scale = targetSize / biggest;
copy.localScale = Vector3.one * scale;
if (TryMeasure(copy, holder, out Bounds fitted))
{
copy.localPosition = new Vector3(-fitted.center.x, -fitted.min.y, -fitted.center.z);
}
Jotunn.Logger.LogInfo($"[{label}] Borrowed '{sourcePrefab}': measured {raw.size}, " +
$"scaled by {scale:0.###} to fit {targetSize} m, grounded on its own base.");
}
/// <summary>
/// Bounds of every mesh under <paramref name="root"/>, expressed in <paramref name="space"/>'s local
/// coordinates. Read from sharedMesh rather than Renderer.bounds on purpose: the holder is INACTIVE
/// while this runs (that is the whole point of the class) and a renderer that has never been enabled
/// has no world bounds yet, so Renderer.bounds would quietly return zero.
/// </summary>
private static bool TryMeasure(Transform root, Transform space, out Bounds bounds)
{
bounds = new Bounds();
bool any = false;
Matrix4x4 toSpace = space.worldToLocalMatrix;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
Mesh mesh;
if (renderer is SkinnedMeshRenderer skinned)
{
mesh = skinned.sharedMesh;
}
else
{
MeshFilter filter = renderer.GetComponent<MeshFilter>();
mesh = filter != null ? filter.sharedMesh : null;
}
if (mesh == null) continue;
Encapsulate(ref bounds, ref any, toSpace * renderer.transform.localToWorldMatrix, mesh.bounds);
}
return any;
}
/// <summary>All eight corners, because a rotated box's bounds are not its centre plus its extents.</summary>
private static void Encapsulate(ref Bounds bounds, ref bool any, Matrix4x4 matrix, Bounds local)
{
Vector3 centre = local.center;
Vector3 extents = local.extents;
for (int corner = 0; corner < 8; corner++)
{
Vector3 point = matrix.MultiplyPoint3x4(centre + new Vector3(
(corner & 1) == 0 ? -extents.x : extents.x,
(corner & 2) == 0 ? -extents.y : extents.y,
(corner & 4) == 0 ? -extents.z : extents.z));
if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; }
else bounds.Encapsulate(point);
}
}
}
}

View file

@ -0,0 +1,147 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// "How many of these may stand in one region." One place, one patch, one line per station.
///
/// Every station in the per-race item-progression system that produces something continuously has
/// to be capped, or five copies are five times the effect - a field of groves is a carpet of bees,
/// five body piles are fifty draugr. Each chain used to be expected to write its own placement
/// check; this exists so the five races still to come add a limit with one call instead of
/// re-deriving ZDO counting, and so there is exactly one Player.PlacePiece prefix rather than one
/// per race.
///
/// Counting is done over ZDOs and not over loaded GameObjects, and that distinction is the whole
/// point: Valheim keeps only a handful of zones alive around the player, a few hundred metres at
/// most, so counting objects would let anyone dodge the cap by walking away and building again.
///
/// HONEST LIMIT: a client only holds the ZDOs the server has sent it. In singleplayer and on the
/// host the count is exact; on a remote client it can undercount, so a cap can be exceeded by
/// someone building far from every other copy. It still closes the case that matters - fifty of
/// them around one base - and no client-side hook can do better without a server-authoritative
/// check.
/// </summary>
public static class PieceDensityLimit
{
private class Limit
{
public float Radius;
public int Max;
public string Message;
}
private static readonly Dictionary<string, Limit> Limits = new Dictionary<string, Limit>();
/// <summary>
/// The radius of a circle with the given area, so a limit can be written the way it is
/// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance.
/// </summary>
public static float RadiusForArea(float squareKilometres)
{
return Mathf.Sqrt(squareKilometres * 1000000f / Mathf.PI);
}
/// <summary>
/// Caps a piece. Call once from the chain's Register(); calling twice just replaces the entry,
/// so a Register() that runs more than once cannot stack limits.
/// </summary>
public static void Register(string piecePrefabName, float radius, int max, string refusalMessage)
{
if (string.IsNullOrEmpty(piecePrefabName) || max < 1 || radius <= 0f)
{
Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense limit for '{piecePrefabName}' " +
$"(radius {radius}, max {max}); it will not be capped.");
return;
}
Limits[piecePrefabName] = new Limit { Radius = radius, Max = max, Message = refusalMessage };
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m.");
}
/// <summary>
/// How many of that piece already stand within the radius of a point, or -1 if the world
/// cannot be asked right now - in which case callers must let the placement through rather
/// than refuse on no information.
/// </summary>
public static int Count(string piecePrefabName, Vector3 position, float radius)
{
if (ZDOMan.instance == null) return -1;
List<ZDO> zdos = new List<ZDO>();
int index = 0;
// The iterative sweep hands back a chunk per call and reports true when it is done. The
// guard is so a pathological world cannot spin here forever.
for (int guard = 0; guard < 1000; guard++)
{
if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break;
}
float rangeSq = radius * radius;
int count = 0;
foreach (ZDO zdo in zdos)
{
if (zdo == null) continue;
if (Vector3.SqrMagnitude(zdo.GetPosition() - position) <= rangeSq) count++;
}
return count;
}
/// <summary>
/// True if one more may be placed there. Unknown pieces are always allowed - a station with no
/// registered limit is not this class's business.
/// </summary>
public static bool Allow(Player player, string piecePrefabName, Vector3 position)
{
if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true;
int nearby = Count(piecePrefabName, position, limit.Radius);
if (nearby < 0 || nearby < limit.Max) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center, string.Format(limit.Message, nearby, limit.Max));
}
return false;
}
}
/// <summary>
/// The single enforcement point, at the moment of building - which is the only moment a refusal is
/// both cheap and understandable. Refusing later, or building and then quietly deleting what it
/// produced, would spend the player's gate item before telling them no.
/// </summary>
/// <summary>
/// The single enforcement point.
///
/// The signature is spelled out because it is NOT the one every Valheim modding example uses. The
/// familiar `bool PlacePiece(Piece)` does not exist in this build; the real one is
///
/// void PlacePiece(Piece piece, Vector3 pos, Quaternion rot, bool doAttack)
///
/// read off the HarmonyX error this patch produced on the first launch. Two things follow, and the
/// first one cost a whole startup:
/// - it returns VOID, so there is no __result to write. Asking for one throws "Cannot get result
/// from void method" at patch time, and that exception propagates out of Harmony.PatchAll() -
/// which means one bad signature here stops the rest of the mod's patches from being applied
/// at all. A prefix returning false is the whole mechanism: the original simply does not run,
/// nothing is placed, and no resources are spent.
/// - the placement position is an ARGUMENT, not the piece's transform. At prefix time the Piece
/// is the build ghost, so `pos` is the authority on where this thing is actually going.
/// Parameters are bound positionally (__0, __1) so a rename cannot break startup either.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class PieceDensityLimitPatch
{
public static bool Prefix(Player __instance, Piece __0, Vector3 __1)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
}
}

View file

@ -74,8 +74,20 @@ namespace RacesOfValheim
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == TrentaConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();
// "fuling" matched nothing: the Fuling family's prefabs are Goblin,
// GoblinArcher, GoblinBrute and GoblinShaman, so the Trenta's truce with them
// never existed despite this file and TrentaConfig both describing it.
// Unlike the other entries here, the goblin name needs its bosses carved back
// out - Yagluth is GoblinKing, and Hildir's arena pair are GoblinBruteBros /
// *_Hildir - because a substring test would otherwise pacify all three.
bool isGoblinKin = prefabName.Contains("goblin")
&& !prefabName.Contains("goblinking")
&& !prefabName.Contains("hildir")
&& !prefabName.Contains("brutebros");
if (prefabName.Contains("greyling") || prefabName.Contains("greydwarf") ||
prefabName.Contains("fuling") || prefabName.Contains("troll") ||
isGoblinKin || prefabName.Contains("troll") ||
prefabName.Contains("leech") || prefabName.Contains("deathsquito"))
{
__result = false;

View file

@ -0,0 +1,491 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// One conjured servant, of any race. Keeps itself within its leash of the station that made it,
/// unless the right kind of player has told it to follow.
///
/// This started life as DraughThrall and was generalised the moment the Skeleton needed the same
/// thing - which is the call ItemProgression_Guida.txt 8.3 says to make BEFORE writing the second
/// copy rather than after. Nothing in here is draugr-specific: a leash, a wither timer, a follow
/// command and an anchor are the same problem whoever raised the body.
///
/// The leash is not custom pathing - it is vanilla's own patrol behaviour, pointed at the station.
/// BaseAI already has m_patrol and m_patrolPoint and already wanders around that point inside
/// m_randomMoveRange, which each prefab sets to its own leash. All this component does is keep the
/// point pinned, which is also what makes "stay" send one home rather than root it wherever it
/// happened to be standing.
///
/// The anchor lives in the creature's own ZDO as a Vector3 and doubles as the mark of which
/// station owns it - so a station can count its own even when one is three biomes away following
/// its master.
/// </summary>
public class RaisedThrall : MonoBehaviour
{
// Deliberately still spelled "draugh". These keys are in players' save files already, on
// thralls raised before this class was generalised; renaming them would leave every existing
// thrall anchorless - no leash, no wither, no orders - for the sake of a tidier string.
public const string KeyAnchor = "RoV_draughAnchor";
public const string KeyOrphanAt = "RoV_draughOrphanAt";
// ─── Set on the prefab at registration ───────────────────────────────
/// <summary>Groups thralls for follower caps and for a station's per-kind roster.</summary>
public string m_kind = "";
/// <summary>Only a player of this race may give orders. Empty means anyone may.</summary>
public string m_commandingRace = "";
/// <summary>How many of this KIND may follow one player at once. -1 for no limit.</summary>
public int m_maxFollowers = -1;
public float m_witherSeconds = 60f;
public float m_homeCheckRange = 20f;
/// <summary>Shown in the refusal when a station is not this player's to command.</summary>
public string m_refusalMessage = "It does not answer to you.";
/// <summary>
/// How many thralls of OTHER kinds, from the same station, come along when this one is
/// commanded directly. 0 for a thrall that only speaks for itself.
///
/// This is what makes a Rancid Remains a squad leader: clicking it takes it and five of the
/// rank and file, rather than the whole garrison the pile would send. Only applies to a direct
/// click - a station moving its whole line calls SetFollowing itself, so the two cannot nest.
/// </summary>
public int m_escortCount = 0;
// SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the
// creature's current position, is public. Resolved once here rather than per call.
private static readonly System.Reflection.MethodInfo SetPatrolPointMethod =
AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) });
/// <summary>
/// Every station currently loaded that owns thralls. Registered by the station's own behaviour
/// so a thrall can ask "is my station still standing?" without sweeping ZDOs or raycasting on a
/// two-second timer, ten thralls at a time.
///
/// TRANSFORMS, not positions, and that is the whole bug this once had: the first version cached
/// transform.position at Awake, which is not yet the object's final placement. Every lookup then
/// missed, every thrall decided it was an orphan, and with the Skeleton's zero-second wither the
/// whole garrison died about four seconds after it rose. Reading .position at query time is what
/// the Draugh's own list did before it was generalised, and why that one worked.
/// </summary>
private static readonly List<Transform> LiveStations = new List<Transform>();
public static void RegisterStation(Transform station)
{
if (station != null && !LiveStations.Contains(station)) LiveStations.Add(station);
}
public static void UnregisterStation(Transform station) => LiveStations.Remove(station);
/// <summary>True if a loaded station stands at that point. Only meaningful when the asker is
/// close enough that the station would be loaded if it existed - see m_homeCheckRange.</summary>
public static bool StationStandsAt(Vector3 position)
{
for (int i = LiveStations.Count - 1; i >= 0; i--)
{
Transform station = LiveStations[i];
if (station == null) { LiveStations.RemoveAt(i); continue; } // destroyed without notice
if (Vector3.SqrMagnitude(station.position - position) < 0.25f) return true;
}
return false;
}
private Character m_character;
private BaseAI m_ai;
private MonsterAI m_monsterAI;
private ZNetView m_nview;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<BaseAI>();
m_monsterAI = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
InvokeRepeating("TickLeash", 2f, 2f);
}
/// <summary>Where the station that made this one stands, or null if it was not made by one.</summary>
public Vector3? Anchor
{
get
{
if (m_nview == null || !m_nview.IsValid()) return null;
Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero);
return anchor == Vector3.zero ? (Vector3?)null : anchor;
}
}
public string Kind => m_kind;
public bool IsFollowing(Player player)
{
return m_monsterAI != null && player != null && m_monsterAI.GetFollowTarget() == player.gameObject;
}
/// <summary>Called at spawn by the station. Tames it, marks it, and sends it home.</summary>
public void Bind(Vector3 anchor)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyAnchor, anchor);
if (m_monsterAI != null) m_monsterAI.MakeTame();
if (m_character != null) m_character.SetTamed(true);
GoHome();
}
// ---------------------------------------------------------------- the leash
private void TickLeash()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_character == null || m_character.IsDead()) return;
// Checked before anything else, and NOT skipped while following: a thrall out with its
// master still has to wither if the station behind it has fallen.
if (TickWither()) return;
// Following overrides the leash entirely; that is the whole point of the command.
if (m_monsterAI != null && m_monsterAI.GetFollowTarget() != null) return;
GoHome();
}
/// <summary>Starts the clock when the station is gone, and stops the thrall when it runs out.
/// Returns true once it has killed this one, so the caller stops bothering with it.</summary>
private bool TickWither()
{
Vector3? anchor = Anchor;
if (anchor == null || ZNet.instance == null) return false;
long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L);
if (stamp == 0L)
{
// The station marks its own thralls when it falls, but it can only mark the ones that
// are loaded at that moment. This is the other half: a thrall that was away comes
// home, finds nothing there, and marks itself.
//
// Deliberately only asked near home. Further out the station's zone is almost
// certainly unloaded, so "nothing here" would be a lie - and acting on it would kill
// the escort of anyone who walked away from their base.
if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
m_homeCheckRange * m_homeCheckRange) return false;
if (StationStandsAt(anchor.Value)) return false;
MarkOrphaned();
return false;
}
// Rebuilt in time, on the same spot: the clock is cleared and the thrall lives. Safe to
// ask unconditionally - StationStandsAt can only answer true where one is actually
// loaded, so being far from home simply never rescues anything. And it opens no exploit:
// a station on the same spot adopts these thralls by anchor anyway.
if (StationStandsAt(anchor.Value))
{
m_nview.GetZDO().Set(KeyOrphanAt, 0L);
return false;
}
double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds;
if (elapsed < m_witherSeconds) return false;
Kill();
return true;
}
/// <summary>
/// Starts the wither clock, once. Called by the station as it is destroyed, and by the thrall
/// itself if it comes home to nothing. Idempotent so the two cannot restart each other's clock
/// and keep an orphan alive forever.
/// </summary>
public void MarkOrphaned()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return;
if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return;
m_nview.ClaimOwnership();
m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
}
/// <summary>
/// Pins the patrol point back onto the station. Cheap enough to call on a timer, and calling it
/// repeatedly is what stops a thrall drifting after it has been pushed, knocked back or told to
/// stay somewhere far from home.
/// </summary>
private void GoHome()
{
Vector3? anchor = Anchor;
if (anchor == null || m_ai == null) return;
if (SetPatrolPointMethod != null)
{
SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value });
}
else
{
// Fall back to writing the two fields the private method writes.
Traverse traverse = Traverse.Create(m_ai);
traverse.Field("m_patrolPoint").SetValue(anchor.Value);
traverse.Field("m_patrol").SetValue(true);
}
}
// ---------------------------------------------------------------- commands
public bool MayBeCommandedBy(Player player)
{
if (player == null) return false;
if (string.IsNullOrEmpty(m_commandingRace)) return true;
return player.m_customData != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == m_commandingRace;
}
/// <summary>Sends it after the player, or home. Returns false if it refused.</summary>
public bool SetFollowing(Player player, bool follow, bool announce)
{
if (player == null || m_monsterAI == null || m_character == null) return false;
if (!MayBeCommandedBy(player))
{
if (announce) player.Message(MessageHud.MessageType.Center, m_refusalMessage);
return false;
}
if (!follow)
{
m_monsterAI.SetFollowTarget(null);
GoHome();
if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} returns.");
return true;
}
// Counted fresh on every command so deaths and dismissals free slots up on their own,
// with no tally to drift out of step.
if (m_maxFollowers >= 0 && CountFollowers(player, m_kind) >= m_maxFollowers)
{
if (announce)
{
player.Message(MessageHud.MessageType.Center, $"Only {m_maxFollowers} may walk with you.");
}
return false;
}
m_monsterAI.SetFollowTarget(player.gameObject);
if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} follows.");
return true;
}
/// <summary>
/// Follow if it is not, come home if it is - the wolf's own single-key behaviour, plus an escort
/// if this thrall leads one.
/// </summary>
public void ToggleCommand(Player player)
{
bool follow = !IsFollowing(player);
if (!SetFollowing(player, follow, announce: m_escortCount <= 0)) return;
if (m_escortCount <= 0) return;
// A squad, not the whole line. Anchor-bound, other kinds only - the rank and file, never
// another leader - and capped at m_escortCount.
Vector3? anchor = Anchor;
if (anchor == null) return;
int taken = 0;
foreach (RaisedThrall other in BoundTo(anchor.Value))
{
if (other == this || other.m_kind == m_kind) continue;
// Going out: only pick up ones that are not already out. Coming home: only send back
// the ones that are actually with this player, so another squad is left alone.
if (follow ? other.IsFollowing(player) : !other.IsFollowing(player)) continue;
if (taken >= m_escortCount) break;
if (other.SetFollowing(player, follow, announce: false)) taken++;
}
player.Message(MessageHud.MessageType.Center, follow
? $"{m_character.m_name} rises with {taken}."
: $"{m_character.m_name} stands down with {taken}.");
}
private static int CountFollowers(Player player, string kind)
{
int count = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null || thrall.m_kind != kind) continue;
if (thrall.IsFollowing(player)) count++;
}
return count;
}
/// <summary>Every living thrall bound to the station at this position.</summary>
public static List<RaisedThrall> BoundTo(Vector3 anchor)
{
List<RaisedThrall> bound = new List<RaisedThrall>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
Vector3? own = thrall.Anchor;
// A generous epsilon: a station never moves, so this only has to survive float
// round-tripping through the ZDO.
if (own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f) bound.Add(thrall);
}
return bound;
}
// ---------------------------------------------------------------- the call
/// <summary>Earshot. A shouted gesture reaches what is nearby, not the whole world.</summary>
public const float TauntRange = 30f;
/// <summary>
/// The emote that calls thralls to their master. A SET rather than one string because the emote
/// names are not in the assembly at all - Valheim builds them from what the player types in
/// chat, so unlike every other name in this project this one could not be read off the game and
/// verified. The patch below logs whatever it actually receives, so a wrong guess here is one
/// line away from being right instead of a mystery.
/// </summary>
private static readonly HashSet<string> TauntEmotes = new HashSet<string>
{
"comehere", "come_here", "followme",
};
/// <summary>
/// Everything within earshot that answers to this player falls in behind them.
///
/// Only ever a call, never a dismissal: "come here" means come here. Sending them home stays
/// with the station and with a click on the thrall itself.
///
/// The per-race follower cap needs no special handling - SetFollowing enforces m_maxFollowers
/// itself, so the Skeleton's whole garrison answers (-1, no limit) and the Draugh's gets three
/// draugr and one officer, from exactly the same call.
/// </summary>
public static void CallToArms(Player player)
{
if (player == null) return;
int came = 0;
int refused = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null || thrall.IsFollowing(player)) continue;
if (!thrall.MayBeCommandedBy(player)) continue;
if (Vector3.SqrMagnitude(character.transform.position - player.transform.position) >
TauntRange * TauntRange) continue;
if (thrall.SetFollowing(player, true, announce: false)) came++;
else refused++;
}
if (came > 0)
{
player.Message(MessageHud.MessageType.Center, $"{came} answer the call.");
}
else if (refused > 0)
{
// The only way SetFollowing refuses a thrall that may be commanded is the cap.
player.Message(MessageHud.MessageType.Center, "No more may walk with you.");
}
}
public static bool IsTauntEmote(string emote)
{
return emote != null && TauntEmotes.Contains(emote.ToLowerInvariant());
}
public void Kill()
{
if (m_character == null || m_character.IsDead()) return;
HitData hit = new HitData();
hit.m_damage.m_damage = 1E+10f;
hit.m_hitType = HitData.HitType.Undefined;
m_character.ApplyDamage(hit, true, false);
}
}
/// <summary>
/// Routes E on a thrall to <see cref="RaisedThrall.ToggleCommand"/>, before vanilla resolves the
/// target itself.
///
/// This is a prefix on Player.Interact rather than an Interactable on the thrall, and that is not
/// a style choice. AswidPatches' own Character.Awake postfix adds AswidThrall - also Interactable
/// - to essentially every mob carrying a MonsterAI, and it wins vanilla's
/// GetComponentInParent&lt;Interactable&gt;() race on whatever it touches. That is the exact bug
/// FactionMerchantInteractPatch exists to work around, where pressing E called AswidThrall.Interact
/// instead of Trader.Interact, silently and with no error. Handling our own thralls here sidesteps
/// component order entirely instead of depending on it.
///
/// The feedback is a centre-screen message and not hover text for the same reason: Character is
/// itself Hoverable and sits ahead of everything added later, so hover is a race this cannot win
/// cleanly. The station's own hover text carries the roster and the rules.
/// </summary>
/// <summary>
/// The "come here" gesture calls every thrall in earshot to its master.
///
/// A POSTFIX with positional binding and no __result, which is the safest shape available: postfixes
/// need no return value, so this cannot repeat the PlacePiece failure where asking for a __result on
/// a void method threw at patch time and stopped the rest of the mod being patched.
///
/// The emote name is logged on every emote the local player performs, because the names are the one
/// class of string in this project that could not be verified against the game - they are built from
/// the player's own chat input, not stored in the assembly. Do the gesture once and the log names it.
/// </summary>
[HarmonyPatch(typeof(Player), "StartEmote")]
public static class RaisedThrallTauntPatch
{
public static void Postfix(Player __instance, string __0)
{
if (__instance != Player.m_localPlayer) return;
Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" +
(RaisedThrall.IsTauntEmote(__0) ? " - calling thralls." : "."));
if (RaisedThrall.IsTauntEmote(__0)) RaisedThrall.CallToArms(__instance);
}
}
[HarmonyPatch(typeof(Player), "Interact")]
public static class RaisedThrallInteractPatch
{
public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt)
{
if (go == null || hold) return true;
if (__instance != Player.m_localPlayer) return true;
RaisedThrall thrall = go.GetComponentInParent<RaisedThrall>();
if (thrall == null) return true; // not ours - let vanilla's own resolution run
thrall.ToggleCommand(__instance);
return false;
}
}
}

View file

@ -0,0 +1,383 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Skeleton station: a bone pile from the crypts that raises a standing garrison.
///
/// Same family as the Draugh's body pile and it shares that feature's whole thrall layer
/// (<see cref="RaisedThrall"/>), but the economy is the opposite way round on purpose. The Draugh
/// pays per draugr out of a reserve that empties; the Skeleton pays ONCE PER SLOT and that slot
/// then refills itself forever. Skeletons are fragile - a troll or a drake clears the whole line
/// in one swing - so an army you have to re-buy after every fight is an army nobody would take
/// out of the house.
///
/// That permanent slot is also, by itself, the "skeletons leave exactly the materials that made
/// them" idea: the bones are not dropped and re-fed, they simply get up again. Nothing is
/// generated, nothing is consumed, and the same twenty fragments stand back up as many times as
/// they are knocked down. It needs no death hook and no drop table - which is why the thralls have
/// their CharacterDrop stripped like the Draugh's, rather than filled in.
///
/// Two differences from the Draugh worth stating because they are deliberate, not oversights:
/// - a destroyed pile kills its garrison INSTANTLY, where a body pile gives its draugr a minute.
/// Free perpetual regeneration is the trade for a hard off switch.
/// - melee and ranged are the same vanilla creature with different hands. There is no ranged
/// skeleton prefab: Skeleton_NoArcher is vanilla's own guaranteed-melee variant, and the
/// archer is a plain Skeleton whose loadout is forced to the bow.
/// </summary>
public static class SkeletonBonePile
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "SkeletonBonePile";
public const string PieceDisplayName = "Bound Bone Pile";
// The Soul Stone: a green ruby, sold by the Skeleton bench, and the thing that binds a skull and
// ten fragments into a sentry that cannot walk. Cheap on purpose - 50 coins - because the real
// cost of a sentry is the skull, which has to be taken off a skeleton rather than bought.
public const string SoulStoneName = "SoulStone";
public const string SoulStoneDisplayName = "Soul Stone";
public const int SoulStonePrice = 50;
private static readonly Color SoulStoneTint = new Color(0.15f, 0.85f, 0.35f, 1f);
public const string SkullName = "CursedSkull";
public const string SkullDisplayName = "Cursed Skull";
public const string GreaterSkullName = "GreaterCursedSkull";
public const string GreaterSkullDisplayName = "Greater Cursed Skull";
public const string ThrallMeleeName = "SkeletonThrall_Melee";
public const string ThrallRangedName = "SkeletonThrall_Ranged";
public const string ThrallRancidName = "SkeletonThrall_Rancid";
public const string ThrallMeleeDisplay = "Bound Skeleton";
public const string ThrallRangedDisplay = "Bound Archer";
public const string ThrallRancidDisplay = "Bound Rancid Remains";
public const string KindMelee = "SkeletonMelee";
public const string KindRanged = "SkeletonRanged";
public const string KindRancid = "SkeletonRancid";
public const string RaceId = "Skeleton";
/// <summary>The one material a slot is bought with. Fixed, not a fungible bone tank - see the
/// class comment on why "exactly the materials that made them" needs a recipe.</summary>
public const string BonePrefab = "BoneFragments";
public const int BonesPerSlot = 20;
/// <summary>Buys a Rancid slot outright, the way an Elite trophy buys the Draugh an officer.</summary>
public const string RancidTrophy = "TrophySkeletonPoison";
// ─── Balance ─────────────────────────────────────────────────────────
public const int MeleeSlots = 4;
public const int RangedSlots = 4;
public const int MeleeSlotsUpgraded = 5;
public const int RangedSlotsUpgraded = 5;
public const int RancidSlots = 0; // none at all until upgraded
public const int RancidSlotsUpgraded = 2;
// Local seconds, and only while the zone is loaded - a garrison should not quietly rebuild
// itself in an unloaded zone. Faster once upgraded: the pile gets better at it.
public const float RespawnSeconds = 20f;
public const float RespawnSecondsUpgraded = 15f;
// NOT the "instant" from the design conversation - that lives in the pile's OnDestroyed, which
// calls Kill() on the spot. This number only governs the FALLBACK: a skeleton that was in an
// unloaded zone when the pile fell and finds nothing at home when it loads again.
//
// It was 0, and zero has no tolerance for a hiccup: a pile whose zone unloads for a moment
// while a skeleton at the boundary stays loaded reads as "no pile" and wipes the garrison with
// no appeal. Five seconds costs nothing anyone can perceive - the deliberate destruction path
// is still immediate - and it means one bad frame is not a wipe.
public const float OrphanWitherSeconds = 5f;
public const float HomeCheckRange = 20f;
public const float LeashRange = 10f;
// No cap: the whole point of the new command is that the garrison moves as one.
public const int MaxFollowers = -1;
// A Rancid Remains clicked directly takes five of the rank and file with it, instead of the
// whole line the pile would send. Its own squad, and small enough that it stays a squad.
public const int RancidEscort = 5;
public const int UpgradeProgressionState = 4; // Bonemass, same gate as the Draugh's officers
public const int MaxPilesInRange = 5;
public const float DensityAreaKm2 = 1.6f;
// ─── Looks ───────────────────────────────────────────────────────────
private const float ModelScale = 1.2f;
// Cold bone-white, so it never reads as the Draugh's green pile at a glance.
private static readonly Color PileTint = new Color(0.82f, 0.84f, 0.78f, 1f);
private static readonly Color SkullTint = new Color(0.78f, 0.80f, 0.74f, 1f);
private static readonly Color GreaterSkullTint = new Color(0.62f, 0.72f, 0.80f, 1f);
public static void Register()
{
RegisterSkull(SkullName, SkullDisplayName, SkullTint,
"A skull that keeps counting. Set it down and the ground starts answering.");
RegisterSkull(GreaterSkullName, GreaterSkullDisplayName, GreaterSkullTint,
"Older, and it counts higher. A pile given one of these raises the rotten too.");
RegisterSoulStone();
RegisterThrall(ThrallMeleeName, "Skeleton_NoArcher", ThrallMeleeDisplay, KindMelee, null);
RegisterThrall(ThrallRangedName, "Skeleton", ThrallRangedDisplay, KindRanged, "skeleton_bow");
RegisterThrall(ThrallRancidName, "Skeleton_Poison", ThrallRancidDisplay, KindRancid, null, RancidEscort);
RegisterPiece();
// The standing sentry. Registered after the archer it clones, so that prefab exists first.
SkeletonSentry.Register();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"There are already {0} of these listening nearby. Take it further out.");
}
// ---------------------------------------------------------------- items
private static void RegisterSkull(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "TrophySkeleton");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Could not clone TrophySkeleton; {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;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
/// <summary>
/// A ruby, turned green. Cloned rather than tinted in place so real rubies keep being red, the
/// same discipline every other borrowed prefab in this project follows.
///
/// One caveat that always applies and is worth repeating on a gemstone: the tint reaches the
/// world and held models but NOT the inventory icon, because icons are atlas sprites and
/// repainting one produces an empty slot. In the inventory this reads as a ruby; the name and
/// the tooltip are what tell it apart. If that matters, borrow the icon of a green vanilla item
/// instead - it is one line.
/// </summary>
private static void RegisterSoulStone()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SoulStoneName, "Ruby");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Skeleton] Could not clone Ruby; Soul Stone not registered.");
return;
}
Recolour(prefab, SoulStoneTint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = SoulStoneDisplayName;
shared.m_description = "Something is still in there, and it is still angry. Bind it to a skull " +
"and it will stand watch as long as the bones hold.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 20;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- thralls
/// <summary>
/// One kind of bound skeleton, born tame and leashed to its pile.
///
/// The weapon argument is what separates melee from ranged, because the distinction does not
/// exist at the prefab level: Skeleton_NoArcher is vanilla's guaranteed-melee variant, and a
/// plain Skeleton rolls its own weapon. Forcing m_defaultItems and clearing the random lists is
/// what makes an archer an archer every time instead of four times in eight.
///
/// CharacterDrop is destroyed for the same reason as the Draugh's, plus one of its own: a
/// garrison that regenerates for free and drops its bones on death would be a bone mill.
/// </summary>
private static void RegisterThrall(string prefabName, string source, string displayName,
string kind, string forcedWeapon, int escortCount = 0)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
if (forcedWeapon != null)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
GameObject weapon = PrefabManager.Cache.GetPrefab<GameObject>(forcedWeapon);
if (humanoid != null && weapon != null)
{
humanoid.m_defaultItems = new[] { weapon };
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
Jotunn.Logger.LogInfo($"[Skeleton] {prefabName}: loadout forced to '{forcedWeapon}'.");
}
else
{
Jotunn.Logger.LogWarning($"[Skeleton] {prefabName}: could not force '{forcedWeapon}'; " +
"it will roll a random weapon like a wild one.");
}
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
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 = "These bones answer only to their own kind.";
thrall.m_escortCount = escortCount;
PrefabManager.Instance.AddPrefab(prefab);
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// BonePileSpawner is the skeleton's own crypt spawner - the right base rather than a
// repainted body pile, and it already has hit and destruction effects of its own.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "BonePileSpawner");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Skeleton] Could not clone BonePileSpawner; the bone pile is not registered.");
return;
}
// Its whole vanilla job is throwing hostile skeletons at whoever walks past. All of it goes.
foreach (SpawnArea area in prefab.GetComponentsInChildren<SpawnArea>(true))
{
if (area != null) Object.DestroyImmediate(area);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
SkeletonBonePileBehaviour behaviour = prefab.AddComponent<SkeletonBonePileBehaviour>();
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 * ModelScale;
Recolour(prefab, PileTint);
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("TrophySkeleton");
// A Piece added to world scenery is born with no icon and no place effect - the Furling's
// bushes taught this the hard way, where the entry existed as a blank unclickable square.
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 = "Twenty fragments buy a place in the line. The one who fills it will keep standing up.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophySkeleton"),
Requirements = new[]
{
new RequirementConfig(SkullName, 1, 0, true),
new RequirementConfig("BoneFragments", 30, 0, true),
new RequirementConfig("Ooze", 10, 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
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($"[Skeleton] 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 SkeletonBonePileKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
SkeletonBonePile.EnsureKnown(__instance);
SkeletonSentry.EnsureKnown(__instance);
}
}
}

View file

@ -0,0 +1,403 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bone pile's logic. Simpler than the body pile's, because there is no reserve to keep books
/// on: the ZDO holds how many SLOTS have been paid for per kind, and a slot with nobody standing
/// in it refills itself on a timer, forever.
///
/// That is the whole "skeletons are immortal" mechanic, and it is why nothing here drops or
/// consumes bones on death. Twenty fragments buy a place in the line once; whoever is standing in
/// that place gets back up as often as they are knocked down. No death hook, no drop table, no
/// resource created or destroyed.
///
/// The roster is counted from the world rather than tallied, exactly like the body pile's, so a
/// death, a despawn or a player killing his own skeleton all correct themselves.
/// </summary>
public class SkeletonBonePileBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyBones = "RoV_skelBones";
private const string KeySlotsMelee = "RoV_skelSlotsMelee";
private const string KeySlotsRanged = "RoV_skelSlotsRanged";
private const string KeySlotsRancid = "RoV_skelSlotsRancid";
private const string KeyUpgraded = "RoV_skelUpgraded";
private ZNetView m_nview;
private float m_respawnTimer;
private void Awake()
{
// The registry RaisedThrall consults to answer "is my pile still standing?".
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_SkelFeed", RPC_Feed);
m_nview.Register("RoV_SkelUpgrade", RPC_Upgrade);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("UpdatePile", 2f, 2f);
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
// ---------------------------------------------------------------- interaction
/// <summary>
/// Bones in hand feed it, a Greater Cursed Skull upgrades it, a Rancid trophy buys an officer -
/// and EMPTY HANDS move the whole garrison. That last one is the mechanic the Draugh does not
/// have: a body pile is commanded draugr by draugr, a bone pile is commanded as a line.
///
/// Empty hands were free to use for this because the pile's own hover already carries the
/// status the Draugh needs an empty-handed click to report.
/// </summary>
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;
// EMPTY HANDS MEAN THE COMMAND, always, and nothing else is consulted.
//
// This used to scan the pack for something to feed first, copied from the body pile where
// empty hands mean nothing else. Two bugs came out of it: a Rancid trophy in the pack was
// skipped in SILENCE when the pile was not upgraded yet - the refusal that explains why was
// only reachable by holding the item - and, worse, anyone carrying bone fragments (which is
// everyone) would feed the pile when they meant to move the line. The hover has always said
// "bone in hand to buy a place, empty hands to move the line"; now the code agrees with it.
if (item == null) return ToggleGarrison(player);
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName == null) return false;
if (prefabName == SkeletonBonePile.GreaterSkullName) return TryUpgrade(player, inventory, item);
// How many of this the pile can still take. Not "is there room for one" - that was the bug:
// the old check only asked whether a single trophy would fit and then handed over the WHOLE
// stack, so ten Rancid trophies went in, RPC_Feed clamped the slots to two, and eight were
// destroyed for nothing. Anything taken from the player has to be something the pile will
// actually keep.
int room;
if (prefabName == SkeletonBonePile.RancidTrophy)
{
if (!IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, "This pile cannot hold the rotten yet.");
return false;
}
room = RancidCap() - GetSlots(SkeletonBonePile.KindRancid);
}
else if (prefabName == SkeletonBonePile.BonePrefab)
{
// Bone is measured in fragments, not places: what is left to buy, minus what is already
// part-paid towards the next place.
room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot
- m_nview.GetZDO().GetInt(KeyBones);
}
else
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
inventory.RemoveItem(item, taken);
m_nview.InvokeRPC("RoV_SkelFeed", prefabName, taken);
return true;
}
/// <summary>
/// The new command: every skeleton of this pile follows, or every one of them comes home. One
/// click for the line, decided by whether any of them is already out.
/// </summary>
private bool ToggleGarrison(Player player)
{
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
if (bound.Count == 0)
{
player.Message(MessageHud.MessageType.Center, "Nothing is standing yet. It wants bone.");
return false;
}
bool anyFollowing = false;
foreach (RaisedThrall thrall in bound)
{
if (thrall.IsFollowing(player)) { anyFollowing = true; break; }
}
int moved = 0;
foreach (RaisedThrall thrall in bound)
{
// announce: false - one message for the line, not one per skeleton.
if (thrall.SetFollowing(player, !anyFollowing, announce: false)) moved++;
}
if (moved == 0)
{
// Every one of them refused, which for these means the player is not a Skeleton.
player.Message(MessageHud.MessageType.Center, "These bones answer only to their own kind.");
return false;
}
player.Message(MessageHud.MessageType.Center, anyFollowing
? $"{moved} return to the pile."
: $"{moved} rise and follow.");
return true;
}
private bool TryUpgrade(Player player, Inventory inventory, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < SkeletonBonePile.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, "The skull will not wake. Something older has to fall first.");
return false;
}
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_SkelUpgrade");
player.Message(MessageHud.MessageType.Center, "The pile deepens. The rotten will stand here too.");
return true;
}
// ---------------------------------------------------------------- accounting
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) count = 1;
if (prefabName == SkeletonBonePile.RancidTrophy)
{
if (!IsUpgraded()) return;
SetSlots(SkeletonBonePile.KindRancid,
Mathf.Min(RancidCap(), GetSlots(SkeletonBonePile.KindRancid) + count));
return;
}
if (prefabName != SkeletonBonePile.BonePrefab) return;
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
// Melee places fill first, then the archers'. A loop rather than a single test so a whole
// stack cannot overflow into bones that are never counted.
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
{
bones -= SkeletonBonePile.BonesPerSlot;
if (GetSlots(SkeletonBonePile.KindMelee) < MeleeCap())
{
SetSlots(SkeletonBonePile.KindMelee, GetSlots(SkeletonBonePile.KindMelee) + 1);
}
else
{
SetSlots(SkeletonBonePile.KindRanged, GetSlots(SkeletonBonePile.KindRanged) + 1);
}
}
m_nview.GetZDO().Set(KeyBones, bones);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
private void UpdatePile()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
string empty = FirstEmptyKind();
if (empty == null)
{
m_respawnTimer = 0f;
return;
}
m_respawnTimer += 2f; // the tick interval
if (m_respawnTimer < RespawnSeconds()) return;
m_respawnTimer = 0f;
Spawn(empty);
}
/// <summary>A kind that has a paid slot with nobody standing in it, or null. Rotten first -
/// they are the scarcest and the reason to upgrade.</summary>
private string FirstEmptyKind()
{
Dictionary<string, int> alive = CountAlive();
if (alive[SkeletonBonePile.KindRancid] < GetSlots(SkeletonBonePile.KindRancid)) return SkeletonBonePile.KindRancid;
if (alive[SkeletonBonePile.KindMelee] < GetSlots(SkeletonBonePile.KindMelee)) return SkeletonBonePile.KindMelee;
if (alive[SkeletonBonePile.KindRanged] < GetSlots(SkeletonBonePile.KindRanged)) return SkeletonBonePile.KindRanged;
return null;
}
private Dictionary<string, int> CountAlive()
{
Dictionary<string, int> alive = new Dictionary<string, int>
{
{ SkeletonBonePile.KindMelee, 0 },
{ SkeletonBonePile.KindRanged, 0 },
{ SkeletonBonePile.KindRancid, 0 },
};
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
if (thrall.Kind != null && alive.ContainsKey(thrall.Kind)) alive[thrall.Kind]++;
}
return alive;
}
private void Spawn(string kind)
{
string prefabName =
kind == SkeletonBonePile.KindRancid ? SkeletonBonePile.ThrallRancidName :
kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName :
SkeletonBonePile.ThrallMeleeName;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] No '{prefabName}' in ZNetScene; the pile cannot raise anything.");
return;
}
Vector3 offset = UnityEngine.Random.insideUnitSphere * 2f;
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));
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
}
/// <summary>
/// Instantly, unlike the body pile's minute. The garrison rebuilds itself for free forever, so
/// the pile being broken has to be an immediate off switch or there is no counterweight at all.
/// MarkOrphaned still covers any that were unloaded when it fell - with a wither of zero they
/// die on their first tick home rather than lingering.
/// </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();
thrall.Kill();
}
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
$"The pile is broken. {bound.Count} fall where they stand.");
}
}
// ---------------------------------------------------------------- state and display
public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private int MeleeCap() => IsUpgraded() ? SkeletonBonePile.MeleeSlotsUpgraded : SkeletonBonePile.MeleeSlots;
private int RangedCap() => IsUpgraded() ? SkeletonBonePile.RangedSlotsUpgraded : SkeletonBonePile.RangedSlots;
private int RancidCap() => IsUpgraded() ? SkeletonBonePile.RancidSlotsUpgraded : SkeletonBonePile.RancidSlots;
private float RespawnSeconds() =>
IsUpgraded() ? SkeletonBonePile.RespawnSecondsUpgraded : SkeletonBonePile.RespawnSeconds;
/// <summary>Paid melee and archer places. Rotten ones are bought with trophies, not bone, so
/// they are counted separately and do not compete for the same twenty fragments.</summary>
private int PaidSlots() => GetSlots(SkeletonBonePile.KindMelee) + GetSlots(SkeletonBonePile.KindRanged);
private int TotalCap() => MeleeCap() + RangedCap();
private string Hover()
{
Dictionary<string, int> alive = CountAlive();
// A line per kind, each reading "standing / places bought / places possible", because the
// first version told the player none of that: the rotten line was hidden until the pile was
// upgraded, so there was no way to know the cap was two until ten trophies had gone in.
// Every shelf is now visible whether or not it can be used yet, and says why when it cannot.
string body =
$"\nmelee {alive[SkeletonBonePile.KindMelee]}/{GetSlots(SkeletonBonePile.KindMelee)} of {MeleeCap()}" +
$"\narchers {alive[SkeletonBonePile.KindRanged]}/{GetSlots(SkeletonBonePile.KindRanged)} of {RangedCap()}" +
$"\nrotten {alive[SkeletonBonePile.KindRancid]}/{GetSlots(SkeletonBonePile.KindRancid)} of {RancidCap()}";
if (!IsUpgraded()) body += " (needs a Greater Cursed Skull)";
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
int placesLeft = TotalCap() - PaidSlots();
body += placesLeft > 0
? $"\nbone {bonesToward}/{SkeletonBonePile.BonesPerSlot} toward the next of {placesLeft} places"
: "\nevery place is bought";
if (m_respawnTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(RespawnSeconds() - m_respawnTimer));
body += $"\nnext rises in {left}s";
}
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Bone in hand to buy a place, empty hands to move the line";
return Localization.instance.Localize($"{SkeletonBonePile.PieceDisplayName} ({body})");
}
// ---------------------------------------------------------------- ZDO accessors
private int GetSlots(string kind)
{
if (m_nview == null || !m_nview.IsValid()) return 0;
return m_nview.GetZDO().GetInt(KeyFor(kind));
}
private void SetSlots(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFor(kind), Mathf.Max(0, value));
}
private static string KeyFor(string kind)
{
if (kind == SkeletonBonePile.KindRanged) return KeySlotsRanged;
if (kind == SkeletonBonePile.KindRancid) return KeySlotsRancid;
return KeySlotsMelee;
}
}
}

View file

@ -84,7 +84,9 @@ namespace RacesOfValheim
__result = false;
return false;
}
else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
// Blood Essence is the one real food an Aswid can still chew, so it has to
// survive this blanket refusal - everything else mortal still bounces.
else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && !AswidBloodRefinery.IsAswidMeal(item) && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
{
__instance.Message(MessageHud.MessageType.Center, "Mortal food disgusts you.");
__result = false;

View file

@ -17,6 +17,11 @@ namespace RacesOfValheim
public void CreateModAssets()
{
// The bone pile and its garrison. Registered here because the faction merchant catalogue
// resolves its entries by prefab name, so the two cursed skulls have to exist before a
// Skeleton is ever set up as a bench.
SkeletonBonePile.Register();
var se = ScriptableObject.CreateInstance<SE_SkeletonStats>();
se.name = "SE_SkeletonStats";
se.m_name = "Undead Fortitude";

View file

@ -0,0 +1,283 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A bound archer that cannot walk: built with the hammer, stands where it is put, shoots what comes
/// near, knits itself back together when left alone, and hands its parts back when it falls.
///
/// TWO PREFABS, and that is forced rather than chosen. The design settled on cloning the tamed
/// archer, so the sentry is a CHARACTER - and a Character cannot sit in the hammer's piece table,
/// because the hammer builds Piece. So a small seed piece goes in the table, spawns the sentry the
/// moment it is placed, and removes itself. The alternative was cloning the Ballista, which would
/// have brought WearNTear's health, repair and component refund for free; cloning the archer instead
/// means those are written here, which is the trade that was made deliberately.
///
/// The refund is a CharacterDrop at full chance - which makes the sentry the one skeleton in this mod
/// that drops anything. Every other thrall has its drop table stripped precisely so a garrison that
/// regenerates for free cannot be farmed; this one is not free and does not regenerate its slot, so
/// giving the parts back is safe and is what was asked for.
/// </summary>
public static class SkeletonSentry
{
public const string SentryName = "SkeletonSentry";
public const string SeedPieceName = "SkeletonSentrySeed";
public const string DisplayName = "Bound Sentry";
/// <summary>Seconds without being hit before it starts closing its wounds.</summary>
public const float RegenDelay = 10f;
/// <summary>Fraction of maximum health per second once it starts.</summary>
public const float RegenPerSecond = 0.02f;
// What it costs, and therefore exactly what it gives back.
public const int BoneCost = 10;
public static void Register()
{
GameObject sentry = BuildSentry();
if (sentry != null) BuildSeedPiece();
}
// ---------------------------------------------------------------- the sentry
private static GameObject BuildSentry()
{
// The archer we already register for the bone pile, so its forced bow loadout comes along.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SentryName, SkeletonBonePile.ThrallRangedName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {SkeletonBonePile.ThrallRangedName}; the sentry is not registered.");
return null;
}
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = DisplayName;
// Rooted. Every way it could move, set to nothing - and m_randomMoveRange so it does not
// even try to wander. If the AI still shuffles or stops shooting because it wants to
// close distance and cannot, the fallback is to pin it from the AI side instead, with
// the patrol trick the thralls and the grove already use.
character.m_speed = 0f;
character.m_walkSpeed = 0f;
character.m_runSpeed = 0f;
character.m_acceleration = 0f;
character.m_jumpForce = 0f;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = 0f;
// Its parts back, all of them, every time. Replaces the stripped table the archer clone
// inherits rather than adding to it.
foreach (CharacterDrop existing in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
CharacterDrop drops = prefab.AddComponent<CharacterDrop>();
drops.m_drops = new System.Collections.Generic.List<CharacterDrop.Drop>();
AddDrop(drops, SkeletonBonePile.SoulStoneName, 1);
AddDrop(drops, "TrophySkeleton", 1);
AddDrop(drops, SkeletonBonePile.BonePrefab, BoneCost);
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
return prefab;
}
private static void AddDrop(CharacterDrop drops, string prefabName, int amount)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Sentry: no '{prefabName}' to give back; that part is lost on death.");
return;
}
drops.m_drops.Add(new CharacterDrop.Drop
{
m_prefab = prefab,
m_amountMin = amount,
m_amountMax = amount,
m_chance = 1f,
m_levelMultiplier = false,
m_dontScale = true, // the refund is the cost, not a loot roll
m_onePerPlayer = false,
});
}
// ---------------------------------------------------------------- the seed
/// <summary>
/// The hammer entry. Exists only to be placed and immediately replaced by the sentry, which is
/// how a creature gets into a piece table at all.
/// </summary>
private static void BuildSeedPiece()
{
// An armour stand, because the seed's real job is its BUILD GHOST: the sentry itself only
// exists a frame later, so what the player aims at while placing is this prefab's silhouette.
// A workbench read as furniture; a standing human frame reads as "someone will be here", which
// is what is about to happen. ArmorStand is the buildable one, so it arrives with the Piece,
// ZNetView and WearNTear the strip below keeps.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, "ArmorStand");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Skeleton] Could not clone ArmorStand; the sentry cannot be built.");
return;
}
// Everything the stand actually DOES goes - its armour slots included. All that is wanted is a
// placeable shell with the right outline, alive for one frame.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
prefab.AddComponent<SkeletonSentrySeed>();
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = DisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophySkeleton");
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayName,
Description = "A skull on a soul stone. It will not walk, and it will not stop watching.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophySkeleton"),
Requirements = new[]
{
new RequirementConfig(SkeletonBonePile.SoulStoneName, 1, 0, true),
new RequirementConfig("TrophySkeleton", 1, 0, true),
new RequirementConfig(SkeletonBonePile.BonePrefab, BoneCost, 0, true),
}
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName);
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;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
return null;
}
}
/// <summary>
/// Lives for one frame: swaps itself for the sentry and goes. Owner only, so in multiplayer exactly
/// one archer stands up rather than one per client.
/// </summary>
public class SkeletonSentrySeed : MonoBehaviour
{
private void Start()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
GameObject prefab = ZNetScene.instance != null
? ZNetScene.instance.GetPrefab(SkeletonSentry.SentryName)
: null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] No '{SkeletonSentry.SentryName}' in ZNetScene; nothing was raised.");
return;
}
GameObject spawned = Instantiate(prefab, transform.position, transform.rotation);
// Tamed, so it never turns on the person who built it. The bone pile's thralls get this from
// RaisedThrall.Bind; a sentry has no pile to be bound to, so it is done here.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
ZNetScene.instance.Destroy(gameObject);
}
}
/// <summary>
/// The regeneration: untouched for ten seconds, then two percent of maximum health a second until
/// whole. The clock is local rather than world time on purpose - a sentry nobody is near is a sentry
/// in an unloaded zone, and healing through that would mean coming home to a full-health guard that
/// was left at death's door.
/// </summary>
public class SkeletonSentryBehaviour : MonoBehaviour
{
private Character m_character;
private ZNetView m_nview;
private float m_sinceDamage;
private void Awake()
{
m_character = GetComponent<Character>();
m_nview = GetComponent<ZNetView>();
InvokeRepeating("TickRegen", 1f, 1f);
}
/// <summary>Called from the Character.Damage postfix below.</summary>
public void NoteDamage() => m_sinceDamage = 0f;
private void TickRegen()
{
if (m_character == null || m_character.IsDead()) return;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
m_sinceDamage += 1f;
if (m_sinceDamage < SkeletonSentry.RegenDelay) return;
float max = m_character.GetMaxHealth();
if (m_character.GetHealth() >= max) return;
m_character.Heal(max * SkeletonSentry.RegenPerSecond, false);
}
}
/// <summary>
/// Resets a sentry's regeneration clock whenever it is hit. A postfix on the same method the Trenta's
/// Thorns already patches, so the shape is known to work.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class SkeletonSentryDamagePatch
{
public static void Postfix(Character __instance)
{
if (__instance == null) return;
SkeletonSentryBehaviour sentry = __instance.GetComponent<SkeletonSentryBehaviour>();
if (sentry != null) sentry.NoteDamage();
}
}
}

View file

@ -0,0 +1,279 @@
using System;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Composter's logic. Modelled on <see cref="Fermenter"/> - same one-second tick, same
/// owner-only accounting with all state in the ZDO - but with a numeric tank filled by many
/// different meats in place of the barrel's single stored item.
///
/// Three states, and the barrel already has a visual for each of them: filling, composting,
/// ready. Raw flesh is destroyed on the spot and becomes mass; at capacity the lid closes and
/// the clock starts; when it runs out the tap gives a batch of Fertilizer and the cycle resets.
///
/// One simplification over <see cref="BloodRefineryBehaviour"/> worth pointing out: the refinery
/// has to carry a time accumulator because it produces continuously and must catch up on every
/// second it spent unloaded. This works in batches, so the whole timer is one stored timestamp
/// compared against ZNet's world clock - which gets "keeps composting while the zone is
/// unloaded and the game is shut" for free rather than by bookkeeping.
/// </summary>
public class ComposterBehaviour : MonoBehaviour
{
// Handed over from the vanilla Fermenter before it is destroyed, which is what keeps the
// three visual states, the sounds and the tap effects identical to the real barrel's. The
// Switch is ours - see the comment in TrentaComposter.RegisterPiece for why.
public Switch m_switch;
public GameObject m_topObject;
public GameObject m_fermentingObject;
public GameObject m_readyObject;
public Transform m_outputPoint;
public EffectList m_addedEffects;
public EffectList m_tapEffects;
public EffectList m_spawnEffects;
public float m_capacity = 100f;
public float m_compostSeconds = 2400f;
public int m_yield = 20;
private const string KeyFlesh = "RoV_compostFlesh";
private const string KeySealed = "RoV_compostSealed";
private ZNetView m_nview;
public enum State
{
Filling,
Composting,
Ready,
}
private void Awake()
{
m_nview = GetComponent<ZNetView>();
if (m_nview == null) m_nview = GetComponentInParent<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_CompostAdd", RPC_Add);
m_nview.Register("RoV_CompostTap", RPC_Tap);
WearNTear wear = GetComponent<WearNTear>();
if (wear == null) wear = GetComponentInParent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("UpdateComposter", 1f, 1f);
}
// ---------------------------------------------------------------- interaction
/// <summary>
/// One interaction point, exactly like the vanilla barrel: the item in hand decides what the
/// click means. Holding flesh feeds it; empty hands tap it when it is ready and otherwise
/// just report what it is doing.
/// </summary>
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
if (user == null) return false;
State state = GetState();
if (state == State.Ready)
{
m_nview.InvokeRPC("RoV_CompostTap");
return true;
}
if (state == State.Composting)
{
user.Message(MessageHud.MessageType.Center, $"Still rotting. {MinutesLeft()} minutes.");
return false;
}
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindFlesh(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, "No raw flesh to rot.");
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (AswidBloodRefinery.FleshValue(prefabName) <= 0)
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_CompostAdd", prefabName);
return true;
}
private ItemDrop.ItemData FindFlesh(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
if (AswidBloodRefinery.FleshValue(candidate.m_dropPrefab.name) > 0) return candidate;
}
return null;
}
private void RPC_Add(long sender, string prefabName)
{
if (!m_nview.IsOwner()) return;
if (GetState() != State.Filling) return;
int value = AswidBloodRefinery.FleshValue(prefabName);
if (value <= 0) return;
float flesh = Mathf.Min(m_capacity, GetFlesh() + value);
SetFlesh(flesh);
// Reaching capacity is what starts the clock. Stamped once, here, so a barrel that fills
// up while nobody is watching still seals at the right moment.
if (flesh >= m_capacity) m_nview.GetZDO().Set(KeySealed, ZNet.instance.GetTime().Ticks);
if (m_addedEffects != null) m_addedEffects.Create(transform.position, transform.rotation);
}
private void RPC_Tap(long sender)
{
if (!m_nview.IsOwner()) return;
if (GetState() != State.Ready) return;
SetFlesh(0f);
m_nview.GetZDO().Set(KeySealed, 0L);
Produce();
}
private void Produce()
{
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName)
: null;
if (prefab == null || m_outputPoint == null) return;
if (m_tapEffects != null) m_tapEffects.Create(transform.position, transform.rotation);
if (m_spawnEffects != null) m_spawnEffects.Create(m_outputPoint.position, m_outputPoint.rotation);
// One stack rather than twenty objects on the ground: Fertilizer stacks to 50, so the
// whole batch fits, the same way Smelter.m_spawnStack gathers its output.
GameObject spawned = Instantiate(prefab, m_outputPoint.position, m_outputPoint.rotation);
ItemDrop drop = spawned.GetComponent<ItemDrop>();
if (drop != null)
{
drop.m_itemData.m_stack = m_yield;
ItemDrop.OnCreateNew(drop);
}
}
/// <summary>
/// A finished batch is given back; flesh that has already rotted is not. Same rule the Blood
/// Refinery follows for blood, and for the same reason - what the machine has absorbed is
/// gone by design, and the hover text says so before anyone swings a hammer at it.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
bool ready = GetState() == State.Ready;
SetFlesh(0f);
m_nview.GetZDO().Set(KeySealed, 0L);
if (!ready) return;
GameObject prefab = ObjectDB.instance != null
? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName)
: null;
if (prefab == null) return;
Vector3 position = transform.position + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
ItemDrop drop = spawned.GetComponent<ItemDrop>();
if (drop != null)
{
drop.m_itemData.m_stack = m_yield;
ItemDrop.OnCreateNew(drop);
}
}
// ---------------------------------------------------------------- state and display
public State GetState()
{
if (GetFlesh() < m_capacity) return State.Filling;
return SecondsSealed() >= m_compostSeconds ? State.Ready : State.Composting;
}
private void UpdateComposter()
{
if (m_nview == null || !m_nview.IsValid()) return;
State state = GetState();
if (m_topObject != null) m_topObject.SetActive(state == State.Filling);
if (m_fermentingObject != null) m_fermentingObject.SetActive(state == State.Composting);
if (m_readyObject != null) m_readyObject.SetActive(state == State.Ready);
}
private int MinutesLeft()
{
double left = m_compostSeconds - SecondsSealed();
return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f));
}
private string Hover()
{
string body;
switch (GetState())
{
case State.Ready:
body = $"ready: {m_yield} {TrentaConfig.FertilizerDisplayName}\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Empty it";
break;
case State.Composting:
body = $"rotting, {MinutesLeft()} minutes left";
break;
default:
body = $"flesh {Mathf.Floor(GetFlesh())}/{m_capacity}\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Feed it raw flesh";
break;
}
return Localization.instance.Localize($"{TrentaConfig.ComposterDisplayName} ({body})");
}
// ---------------------------------------------------------------- ZDO accessors
/// <summary>
/// Seconds since the barrel sealed itself, on ZNet's world clock rather than on frames - so
/// it keeps counting while the zone is unloaded and across a restart. 0 while still filling.
/// </summary>
private double SecondsSealed()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0;
long ticks = m_nview.GetZDO().GetLong(KeySealed, 0L);
if (ticks == 0L) return 0.0;
return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds;
}
private float GetFlesh() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFlesh) : 0f;
private void SetFlesh(float value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFlesh, Mathf.Max(0f, value));
}
}
}

View file

@ -0,0 +1,373 @@
using System;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Heartwood Grove's logic: three independent jobs on one timer.
///
/// GROWING UP one timestamp on ZNet's world clock, exactly like the Composter's seal time, so
/// a planted grove keeps ageing with the zone unloaded and the game shut. The only
/// visible effect is which of the two models is showing.
/// FERTILISING once grown, one plant per minute inside the radius, one Fertilizer each, drawn
/// from a tank the player fills through the Switch on the trunk. Deliberately one
/// plant per tick and not the whole radius: a full tank is then twenty minutes of
/// autonomy instead of one tick's worth.
/// HONEY accrues into the Container on the root at the vanilla Beehive's own rate, read
/// off that prefab rather than invented.
///
/// A tank that is empty stops the fertilising and nothing else. The bees do not care, and neither
/// does the honey - they are three jobs, not three stages.
///
/// Everything that changes state runs on the ZNetView owner only, which is also why the swarm is
/// spawned there: bees on every client would mean every client's copy landing its own sting.
/// </summary>
public class GroveBehaviour : MonoBehaviour
{
public Switch m_switch;
public Container m_container;
public GameObject m_youngModel;
public GameObject m_grownModel;
private const string KeyPlanted = "RoV_grovePlanted";
private const string KeyFertilizer = "RoV_groveFert";
private const string KeyHoneyTime = "RoV_groveHoneyTime";
// Container.Save is private, so it is reached the same way AswidBloodPotions reaches
// Fermenter.GetContent. Honey added by us has to be written to the ZDO explicitly: a player
// dropping items in goes through the inventory's own change callback, and nothing guarantees
// that callback covers a write made from outside the container's own UI.
private static readonly System.Reflection.MethodInfo ContainerSaveMethod =
HarmonyLib.AccessTools.Method(typeof(Container), "Save");
private ZNetView m_nview;
private GameObject m_bees;
// Read off the vanilla Beehive at Awake, so the grove uses the game's own honey rate. Only
// the capacity is scaled - a tree of bees has to last while the player is away.
private float m_secPerHoney = 1200f;
private int m_honeyCapacity = 20;
private GameObject m_honeyPrefab;
// The fertilise tick is local time, not world time, and that is correct rather than lazy: an
// unloaded grove cannot grow plants in a zone that is not there, so banking the time it spent
// unloaded would hand back growth that never could have happened. Honey banks; growth does not.
private float m_fertilizeTimer;
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("RoV_GroveFeed", RPC_Feed);
ReadHoneyRates();
if (m_nview.IsOwner())
{
// Stamped once, on the first client to own it, which is the moment it was planted.
if (m_nview.GetZDO().GetLong(KeyPlanted, 0L) == 0L)
{
m_nview.GetZDO().Set(KeyPlanted, ZNet.instance.GetTime().Ticks);
}
if (m_nview.GetZDO().GetLong(KeyHoneyTime, 0L) == 0L)
{
m_nview.GetZDO().Set(KeyHoneyTime, ZNet.instance.GetTime().Ticks);
}
}
InvokeRepeating("UpdateGrove", 1f, 1f);
}
private void OnDestroy()
{
if (m_bees != null) Destroy(m_bees);
}
/// <summary>
/// Borrows m_secPerUnit, m_maxHoney and the honey item off the vanilla Beehive. The rate is
/// not a design decision this mod gets to make - a hive's is already tuned - so only the
/// capacity is multiplied.
/// </summary>
private void ReadHoneyRates()
{
Beehive hive = TrentaConfig.FindVanillaBeehive();
if (hive != null)
{
if (hive.m_secPerUnit > 0f) m_secPerHoney = hive.m_secPerUnit;
if (hive.m_maxHoney > 0) m_honeyCapacity = hive.m_maxHoney * TrentaConfig.GroveHoneyCapacityFactor;
if (hive.m_honeyItem != null) m_honeyPrefab = hive.m_honeyItem.gameObject;
}
else
{
Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no vanilla beehive; falling back to default honey rates.");
}
if (m_honeyPrefab == null && ObjectDB.instance != null)
{
m_honeyPrefab = ObjectDB.instance.GetItemPrefab("Honey");
}
// Without this the honey half fails silently, which is exactly how the night-gate bug
// managed to hide: nothing appeared and nothing said why. The log line also settles a
// question the design doc left open - whether the tuned Beehive component lives on
// "Beehive" or on "piece_beehive" - by printing what was actually read.
if (m_honeyPrefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no honey prefab found; this grove will never produce honey.");
return;
}
Jotunn.Logger.LogInfo($"[Trenta] Heartwood Grove: honey every {m_secPerHoney:0}s, capacity {m_honeyCapacity} " +
$"(rates {(hive != null ? "read from the vanilla beehive" : "defaulted")}).");
}
// ---------------------------------------------------------------- the loop
private void UpdateGrove()
{
if (m_nview == null || !m_nview.IsValid()) return;
bool grown = IsGrown();
if (m_youngModel != null) m_youngModel.SetActive(!grown);
if (m_grownModel != null) m_grownModel.SetActive(grown);
if (!m_nview.IsOwner()) return;
if (!grown) return;
EnsureBees();
TickHoney();
m_fertilizeTimer += 1f;
if (m_fertilizeTimer >= TrentaConfig.GroveFertilizeInterval)
{
m_fertilizeTimer = 0f;
TickFertilize();
}
}
private void EnsureBees()
{
if (m_bees != null) return;
m_bees = TrentaHornetSwarm.SpawnAtAnchor(transform, TrentaConfig.GroveStingRadius);
}
/// <summary>
/// Grows exactly one thing per tick, through the very same method a player's Fertilizer click
/// goes through. That sharing is the point: two tiers growing plants by two slightly
/// different sets of rules is the failure this is written to prevent.
/// </summary>
private void TickFertilize()
{
if (GetFertilizer() <= 0) return;
foreach (Collider collider in Physics.OverlapSphere(transform.position, TrentaConfig.GroveRadius))
{
if (collider == null) continue;
if (TrentaComposter.TryGrow(collider.gameObject) != TrentaComposter.GrowOutcome.Grown) continue;
SetFertilizer(GetFertilizer() - 1);
return; // One per tick, by design
}
}
private void TickHoney()
{
if (m_honeyPrefab == null || m_container == null) return;
long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L);
if (stamp == 0L) return;
DateTime now = ZNet.instance.GetTime();
// No night gate. There used to be one, and it was what stopped the honey ever appearing -
// see the long note in TrentaConfig where GroveHoneyAtNight used to live.
double elapsed = (now - new DateTime(stamp)).TotalSeconds;
if (elapsed < m_secPerHoney) return;
Inventory inventory = m_container.GetInventory();
if (inventory == null) return;
int produced = 0;
bool blocked = false;
while (elapsed >= m_secPerHoney)
{
if (CountHoney(inventory) >= m_honeyCapacity || !inventory.AddItem(m_honeyPrefab, 1))
{
blocked = true;
break;
}
elapsed -= m_secPerHoney;
produced++;
}
if (blocked)
{
// Full chest: the clock is reset to now and the surplus is thrown away, so an
// untouched grove cannot bank an unbounded debt that dumps all at once the moment
// the player finally empties it. This is also what a vanilla hive does when it caps.
m_nview.GetZDO().Set(KeyHoneyTime, now.Ticks);
}
else
{
// Only the time actually spent on the honey produced is consumed. Resetting to now
// here instead would silently throw away the remainder on every single unit and
// leave the grove producing slower than the hive whose rate it borrowed.
m_nview.GetZDO().Set(KeyHoneyTime, now.AddSeconds(-elapsed).Ticks);
}
if (produced > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(m_container, null);
}
private int CountHoney(Inventory inventory)
{
if (m_honeyPrefab == null) return 0;
ItemDrop drop = m_honeyPrefab.GetComponent<ItemDrop>();
string name = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_name
: null;
if (name == null) return 0;
// Counted by hand rather than through Inventory.CountItems so no overload's quality and
// world-level arguments have to be guessed at.
int total = 0;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_shared != null && item.m_shared.m_name == name) total += item.m_stack;
}
return total;
}
// ---------------------------------------------------------------- interaction
/// <summary>
/// E on the tree. Holding Fertilizer fills the tank; empty-handed it reports what the grove is
/// doing. Loading a tank before the tree has grown is allowed on purpose - there is no reason
/// to make the player come back twice.
/// </summary>
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 = FindFertilizer(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, IsGrown()
? "Nothing to feed it. It wants Fertilizer."
: $"Still growing. {MinutesLeft()} minutes.");
return false;
}
if (!TrentaComposter.IsFertilizer(item))
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (GetFertilizer() >= TrentaConfig.GroveFertilizerCapacity)
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_GroveFeed");
return true;
}
private ItemDrop.ItemData FindFertilizer(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (TrentaComposter.IsFertilizer(candidate)) return candidate;
}
return null;
}
private void RPC_Feed(long sender)
{
if (!m_nview.IsOwner()) return;
int stored = GetFertilizer();
if (stored >= TrentaConfig.GroveFertilizerCapacity) return;
SetFertilizer(stored + 1);
}
private string Hover()
{
if (!IsGrown())
{
return Localization.instance.Localize(
$"{TrentaConfig.GroveDisplayName} (growing, {MinutesLeft()} minutes left)");
}
// The honey line is here because it was missing, and its absence is why a grove that
// was quietly producing nothing looked exactly like one that was working.
return Localization.instance.Localize(
$"{TrentaConfig.GroveDisplayName} ({TrentaConfig.FertilizerDisplayName} " +
$"{GetFertilizer()}/{TrentaConfig.GroveFertilizerCapacity}, honey {HoneyStatus()})\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Feed it Fertilizer");
}
/// <summary>How much honey is in the crate and how long until the next drop of it.</summary>
private string HoneyStatus()
{
if (m_honeyPrefab == null) return "none (no honey item found)";
Inventory inventory = m_container != null ? m_container.GetInventory() : null;
int stored = inventory != null ? CountHoney(inventory) : 0;
string status = $"{stored}/{m_honeyCapacity}";
if (stored >= m_honeyCapacity) return status + ", full";
long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L);
if (stamp == 0L || ZNet.instance == null) return status;
double left = m_secPerHoney - (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds;
return status + $", next in {Mathf.Max(1, Mathf.CeilToInt((float)left / 60f))} min";
}
// ---------------------------------------------------------------- state
public bool IsGrown() => SecondsSincePlanted() >= TrentaConfig.GroveGrowSeconds;
private double SecondsSincePlanted()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0;
long ticks = m_nview.GetZDO().GetLong(KeyPlanted, 0L);
if (ticks == 0L) return 0.0;
return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds;
}
private int MinutesLeft()
{
double left = TrentaConfig.GroveGrowSeconds - SecondsSincePlanted();
return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f));
}
private int GetFertilizer() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyFertilizer) : 0;
private void SetFertilizer(int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFertilizer, Mathf.Max(0, value));
}
}
}

View file

@ -0,0 +1,488 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trenta station: a slightly smaller fermenter wearing the Draugr's flies and green gas,
/// which rots raw flesh into Fertilizer. A Fertilizer used on any plant grows it on the spot.
///
/// Second half of the per-race "item progression" system the Aswid's Blood Refinery started,
/// and deliberately the same shape: an item bought from a faction merchant gates a buildable
/// station, and the station produces the race's own material. Design doc: Trenta_Composter.txt.
///
/// Where it differs from the refinery is worth stating, because it drove the code: the refinery
/// produces FOOD for its race and runs continuously off two tanks, while this produces a TOOL
/// that acts on the world and runs in batches, because that is what a fermenter does. And the
/// vanilla <see cref="Fermenter"/> is one item in, N items out, which is no more usable here
/// than <see cref="Smelter"/>'s ore queue was there - so the component is stripped after its
/// scene references are handed to <see cref="ComposterBehaviour"/>, which is what keeps the
/// barrel's three visual states and its sounds identical to the vanilla one's.
/// </summary>
public static class TrentaComposter
{
/// <summary>What a single use of Fertilizer managed to do, so callers can pick the message.</summary>
public enum GrowOutcome
{
NoTarget,
NotGrowable,
AlreadyRipe,
Unhealthy,
Grown,
}
/// <summary>
/// Every Pickable the Fertilizer is allowed to bring back, as a CLOSED list - the same
/// standard the Aswid's bone table is held to, and for a sharper reason here.
///
/// The "wild plant" branch works by un-picking a Pickable, and Pickable is also what a tin
/// deposit, a flint pile, a tar pit, a meteorite and every crypt remains pile are. Deducing
/// "is this a plant?" from the component would hand the player a fertilizer that regenerates
/// ore, which is an exploit made entirely of code nobody wrote. Names verified against the
/// shipped asset manifest; entries the running game does not have are simply never matched.
/// </summary>
public static readonly HashSet<string> GrowablePickables = new HashSet<string>
{
// Cultivated crops, in their grown-and-harvestable form
"Pickable_Carrot", "Pickable_Turnip", "Pickable_Onion",
"Pickable_Barley", "Pickable_Flax",
"Pickable_SeedCarrot", "Pickable_SeedOnion", "Pickable_SeedTurnip",
// Wild versions of the same
"Pickable_Barley_Wild", "Pickable_Flax_Wild",
// Wild plants and mushrooms
"Pickable_Mushroom", "Pickable_Mushroom_yellow", "Pickable_Mushroom_blue",
"Pickable_Mushroom_Magecap", "Pickable_Mushroom_JotunPuffs", "Pickable_SmokePuff",
"Pickable_Thistle", "Pickable_Dandelion", "Pickable_Fiddlehead",
// Berry bushes - not Pickable_-prefixed, the Pickable sits on the bush itself
"RaspberryBush", "BlueberryBush", "CloudberryBush",
// Grown vines (the sapling stages are Plants and go through the other branch)
"VineGreen", "VineAsh",
};
public static void Register()
{
RegisterRotSeed();
RegisterFertilizer();
RegisterPiece();
}
/// <summary>True for the Fertilizer, by prefab first and display name only as a fallback.</summary>
public static bool IsFertilizer(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == TrentaConfig.FertilizerName;
return item.m_shared.m_name == TrentaConfig.FertilizerDisplayName;
}
// ---------------------------------------------------------------- items
private static void RegisterRotSeed()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.RotSeedName, "AncientSeed");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone AncientSeed; Rot Seed not registered.");
return;
}
Recolour(prefab, TrentaConfig.RotSeedTint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = TrentaConfig.RotSeedDisplayName;
shared.m_description = "A seed that died before it could sprout, and did not stop. " +
"The forest folk sell them; only the forest knows what grows from one.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 20;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
private static void RegisterFertilizer()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.FertilizerName, "Entrails");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone Entrails; Fertilizer not registered.");
return;
}
Recolour(prefab, TrentaConfig.FertilizerTint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = TrentaConfig.FertilizerDisplayName;
shared.m_description = "Everything that was meat, a month later. Press it into the soil and " +
"whatever is rooted there stops waiting.";
// Consumable, not Material, and this is the only reason: a Material never reaches
// Humanoid.UseItem - vanilla refuses it before that - while a Consumable does, which is
// where TrentaFertilizerUsePatch takes it over. With every food value at zero it also
// stays invisible to the two prefixes that would otherwise fight over it: the vegan
// check in TrentaFoodPatches, and the "Mortal food disgusts you" block on
// Player.ConsumeItem in Skeleton/SkeletonPatches.cs.
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_foodBurnTime = 0f;
shared.m_foodRegen = 0f;
shared.m_consumeStatusEffect = null;
shared.m_weight = 0.5f;
shared.m_maxStackSize = 50;
// The tint above only reaches the world and held models. Icons are atlas sprites and
// cannot be repainted - repainting one produced an empty inventory slot when the Aswid
// tried it - so a vanilla dark icon is borrowed instead.
Sprite icon = BorrowIcon(TrentaConfig.FertilizerIconSource);
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// "fermenter", not "piece_fermenter" - the same name AswidBloodPotions already reads.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.ComposterPieceName, "fermenter");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone fermenter; Composter not registered.");
return;
}
Fermenter fermenter = prefab.GetComponentInChildren<Fermenter>(true);
if (fermenter == null)
{
Jotunn.Logger.LogWarning("[Trenta] fermenter clone has no Fermenter; Composter not registered.");
return;
}
ComposterBehaviour composter = fermenter.gameObject.AddComponent<ComposterBehaviour>();
composter.m_topObject = fermenter.m_topObject;
composter.m_fermentingObject = fermenter.m_fermentingObject;
composter.m_readyObject = fermenter.m_readyObject;
composter.m_outputPoint = fermenter.m_outputPoint;
composter.m_addedEffects = fermenter.m_addedEffects;
composter.m_tapEffects = fermenter.m_tapEffects;
composter.m_spawnEffects = fermenter.m_spawnEffects;
composter.m_capacity = TrentaConfig.ComposterCapacity;
composter.m_compostSeconds = TrentaConfig.ComposterCompostSeconds;
composter.m_yield = TrentaConfig.ComposterYield;
// The vanilla barrel is its own Hoverable and Interactable: one interaction point on the
// root, unlike the eitr refinery, whose two assigned Switches the Blood Refinery could
// simply inherit. So the interaction is rebuilt with a Switch of our own on the same
// object, which is a component this repo already drives (see BloodRefineryBehaviour) and
// costs no interface implementation. Any Switch the prefab happened to carry is dropped
// first so it cannot win the hover from a child collider - the components only, never
// their colliders, which the barrel still needs.
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
Object.DestroyImmediate(fermenter);
composter.m_switch = composter.gameObject.AddComponent<Switch>();
composter.m_switch.m_name = TrentaConfig.ComposterDisplayName;
// A barrel carries nothing that shoots, unlike the eitr refinery and its two Radiators.
// Called anyway as a belt: it logs whatever it finds, and a silent log is the proof.
AswidBloodRefinery.StripOffensive(prefab, TrentaConfig.ComposterPieceName);
prefab.transform.localScale = Vector3.one * TrentaConfig.ComposterScale;
BuildRotVfx(prefab.transform);
Piece piece = prefab.GetComponent<Piece>();
if (piece != null)
{
// Same call as RaceMenuWard and the Blood Refinery: a piece with a crafting station
// set vanishes from the hammer whenever that station is out of range, and this one
// has to stay findable.
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = TrentaConfig.ComposterDisplayName;
}
PieceConfig config = new PieceConfig
{
Name = TrentaConfig.ComposterDisplayName,
Description = "What rots is not lost. It feeds.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Requirements = new[]
{
new RequirementConfig(TrentaConfig.RotSeedName, 1, 0, true),
new RequirementConfig("Wood", 20, 0, true),
new RequirementConfig("Resin", 10, 0, true),
new RequirementConfig("Bronze", 5, 0, true),
}
};
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
}
/// <summary>
/// Hangs the Draugr's flies and green gas over the lid.
///
/// The same particles, off the same prefab, with the same loop filter DraughVisuals.BuildAura
/// uses - looping is what separates a creature's ambient rot from its one-shot hit and death
/// effects. Copied rather than shared: DraughVisuals takes a Player, is driven by both
/// DraughRace and ZdoVisualSync, and generalising it to oblige a compost barrel would put a
/// working multiplayer aura at risk to save twenty lines.
///
/// The holder is parented to the ROOT, never to the three state objects, which
/// ComposterBehaviour switches on and off - the VFX would blink out with them.
/// </summary>
private static void BuildRotVfx(Transform root)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.ComposterVfxSourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Composter: could not find VFX source prefab '{TrentaConfig.ComposterVfxSourcePrefab}'.");
return;
}
GameObject holder = new GameObject("ComposterVFX");
holder.transform.SetParent(root, false);
holder.transform.localPosition = TrentaConfig.ComposterVfxLocalPosition;
foreach (ParticleSystem particles in source.GetComponentsInChildren<ParticleSystem>(true))
{
if (particles == null || !particles.main.loop) continue;
string name = particles.gameObject.name.ToLowerInvariant();
// Dripping water reads as rain coming off the barrel. DraughVisuals rejects the
// same three for the same reason.
if (name.Contains("drip") || name.Contains("drop") || name.Contains("rain") || name.Contains("splash")) continue;
GameObject copy = Object.Instantiate(particles.gameObject, holder.transform);
copy.name = particles.gameObject.name;
copy.SetActive(true);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = particles.transform.localRotation;
}
}
/// <summary>
/// A piece only reaches the hammer once it is in the player's known recipes, and the vanilla
/// learning pass misses pieces injected after the fact - the trap RaceMenuWard and the Blood
/// Refinery both fell into. The Rot Seed requirement is the real gate; this only makes the
/// entry visible, greyed out until one is owned.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.ComposterPieceName);
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();
}
// ---------------------------------------------------------------- growing things
/// <summary>
/// Grows one thing, now. The single place that knows how, called both by a player clicking a
/// Fertilizer and by a Heartwood Grove's own tick - the two tiers must not grow plants by
/// two slightly different rules, which is exactly what would happen if this were written
/// twice.
///
/// Three families, and the order matters: a planted carrot is a Plant (sapling_carrot) and
/// only becomes a Pickable (Pickable_Carrot) once grown, so asking Pickable first would try
/// to "un-pick" a seedling, do nothing visible, and eat the item.
/// </summary>
public static GrowOutcome TryGrow(GameObject candidate)
{
if (candidate == null) return GrowOutcome.NoTarget;
// a. Cultivated crops and tree saplings. Plant.Grow is the very method Plant.SUpdate
// calls once the natural timer runs out, so calling it by hand means literally "the
// time has passed" - no state is faked and nothing is short-circuited.
Plant plant = candidate.GetComponentInParent<Plant>();
if (plant != null)
{
// Growing regardless of conditions would beat sun, space, biome and cultivated
// ground all at once and make half of vanilla farming pointless. GetStatus is
// public, so this costs one comparison.
if (plant.GetStatus() != Plant.Status.Healthy) return GrowOutcome.Unhealthy;
ZNetView nview = plant.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return GrowOutcome.NotGrowable;
// Grow() instantiates the grown prefab and destroys this one through ZNetScene:
// both are the owner's work.
nview.ClaimOwnership();
plant.Grow();
return GrowOutcome.Grown;
}
// b. Wild plants that are already grown. A berry bush does not grow, it ripens: for
// those, "grow instantly" means "be ripe again now".
Pickable pickable = candidate.GetComponentInParent<Pickable>();
if (pickable != null)
{
if (!IsGrowablePickable(pickable)) return GrowOutcome.NotGrowable;
if (!pickable.GetPicked()) return GrowOutcome.AlreadyRipe;
ZNetView nview = pickable.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return GrowOutcome.NotGrowable;
nview.ClaimOwnership();
pickable.SetPicked(false);
return GrowOutcome.Grown;
}
// c. Everything else, a full-grown tree included: TreeBase.Grow is the growth animation
// a fresh trunk plays for itself, not a stage to advance.
return GrowOutcome.NotGrowable;
}
private static bool IsGrowablePickable(Pickable pickable)
{
if (GrowablePickables.Contains(Utils.GetPrefabName(pickable.gameObject))) return true;
// Safety net for modded plants the closed list above cannot know about: allow one if
// what it produces is something the Trenta itself calls food. Deliberately NOT a plain
// "does it drop something edible" test - that would let a meat pile through.
ItemDrop drop = pickable.m_itemPrefab != null ? pickable.m_itemPrefab.GetComponent<ItemDrop>() : null;
if (drop == null) return false;
return TrentaConfig.VeganFoodPrefabNames.Contains(Utils.GetPrefabName(pickable.m_itemPrefab));
}
/// <summary>
/// A Fertilizer used from the hotbar. The plant is whatever the player is looking at:
/// Player.GetHoverObject already enforces the vanilla interact distance on its own, so
/// there is no raycast and no radius here.
///
/// One unit per plant grown, and only when something actually grew - every refusal leaves
/// the inventory alone.
/// </summary>
public static void UseFertilizer(Player player, Inventory inventory, ItemDrop.ItemData item)
{
if (player == null || item == null) return;
if (inventory == null) inventory = player.GetInventory();
GrowOutcome outcome = TryGrow(player.GetHoverObject());
switch (outcome)
{
case GrowOutcome.Grown:
if (inventory != null) inventory.RemoveItem(item, 1);
player.Message(MessageHud.MessageType.Center, "It grows.");
break;
case GrowOutcome.AlreadyRipe:
player.Message(MessageHud.MessageType.Center, "It is ripe already.");
break;
case GrowOutcome.Unhealthy:
player.Message(MessageHud.MessageType.Center, "This one is not well. Nothing will hurry it.");
break;
case GrowOutcome.NoTarget:
player.Message(MessageHud.MessageType.Center, "Nothing there to feed.");
break;
default:
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
break;
}
}
// ---------------------------------------------------------------- prefab surgery
/// <summary>
/// Darkens every material on the clone. renderer.materials instantiates a copy, so the real
/// Entrails and the real Ancient seed keep their own look - which is the whole reason this
/// is the technique the Aswid settled on too.
/// </summary>
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
if (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);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
}
}
}
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($"[Trenta] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
/// <summary>
/// Teaches every piece this mod registers after the vanilla learning pass, exactly like
/// RaceMenuWard does - none of them reach their table on their own. It lives in the Trenta's file
/// for historical reasons and now also covers the Furling's cultivator entries; one OnSpawned
/// postfix teaching all of them beats three postfixes doing the same thing.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class TrentaComposterKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
TrentaComposter.EnsureKnown(__instance);
TrentaHeartwoodGrove.EnsureKnown(__instance);
FurlingCrops.EnsureKnown(__instance);
}
}
/// <summary>
/// Turns using a Fertilizer into growing whatever the player is looking at.
///
/// A prefix on the same method - and with the same signature - as
/// TrentaFoodPatches.Trenta_Humanoid_UseItem_Patch. The two never collide: that one returns
/// early for anything without food values, and the Fertilizer has none.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class TrentaFertilizerUsePatch
{
public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!TrentaComposter.IsFertilizer(item)) return true;
TrentaComposter.UseFertilizer(player, inventory, item);
return false; // Never let vanilla try to eat it
}
}
}

View file

@ -209,7 +209,6 @@ namespace RacesOfValheim
// Source of the buzz: the ambient bee-swarm effect a placed Beehive plays, read for its
// AudioClip only - never instantiated, so nothing about how it looks ever enters this
// ability, matching "la sua unica componente visiva sarà le mosche" literally.
public const string HornetsNestBeehivePrefab = "Beehive";
// ─── Muspell (Fader) ─────────────────────────────────────────────────
// A toggled transformation, the same shape as FenrirRace's own G/H/J forms: press J to
@ -399,7 +398,163 @@ namespace RacesOfValheim
return lookup;
}
// ─── Composter (item progression, tier 1) ────────────────────────────
// The Trenta's half of the per-race station system the Aswid's Blood Refinery started.
// Full design in Trenta_Composter.txt; every number it settles on lives here.
//
// The chain: a Rot Seed bought from the Greydwarf faction bench gates the Composter, the
// Composter rots raw flesh into Fertilizer, and Fertilizer grows any plant on the spot.
public const string ComposterPieceName = "TrentaComposter";
public const string ComposterDisplayName = "Composter";
public const string FertilizerName = "Fertilizer";
public const string FertilizerDisplayName = "Fertilizer";
public const string RotSeedName = "RotSeed";
public const string RotSeedDisplayName = "Rot Seed";
// Same band as the Aswid's Blood Core, which does the same job for the same reason.
public const int RotSeedPrice = 500;
// "Slightly smaller than a fermenter" - the vanilla barrel is already human-sized, so this
// is a shave rather than the halving the (enormous) eitr refinery needed.
public const float ComposterScale = 0.85f;
// One batch: 100 units of flesh in, 20 Fertilizer out after the compost time, so 5 units
// of flesh per Fertilizer. Flesh is valued by AswidBloodRefinery.FleshValue.
public const float ComposterCapacity = 100f;
public const float ComposterCompostSeconds = 2400f; // as a normal fermenter
public const int ComposterYield = 20;
// Where the Draugr's flies and green gas hang over the lid. The scaled barrel is roughly a
// metre tall; this is an eyeball figure and is meant to be adjusted in game.
public static readonly Vector3 ComposterVfxLocalPosition = new Vector3(0f, 1f, 0f);
// Same prefab TrentaHornetsNest and DraughVisuals already read their particles off. The
// Composter keeps the same subset DraughVisuals keeps - flies plus the green smoke - which
// is why the swarm on a Heartwood Grove and the haze over a Composter match by default.
public const string ComposterVfxSourcePrefab = "Draugr";
// Entrails, darkened to loam. Only the world/held model takes the tint - the inventory
// icon is an atlas sprite and cannot be repainted (proven the hard way on the Aswid's
// Blood Essence), so the icon is borrowed from Guck instead: green-black reads as
// "compost" without reading as "intestine".
public static readonly Color FertilizerTint = new Color(0.18f, 0.13f, 0.09f, 1f);
public const string FertilizerIconSource = "Guck";
public static readonly Color RotSeedTint = new Color(0.16f, 0.12f, 0.08f, 1f);
// ─── Heartwood Grove (item progression, tier 2) ──────────────────────
// Plant a seed, wait, and the tree that comes up fertilises what surrounds it, stings what
// approaches it, and fills a chest with honey. Three independent functions on one piece.
public const string GroveSeedName = "HeartwoodSeed";
public const string GroveSeedDisplayName = "Heartwood Seed";
public const string GroveSaplingPieceName = "TrentaHeartwoodSapling";
public const string GroveSaplingDisplayName = "Heartwood Sapling";
public const string GrovePieceName = "TrentaHeartwoodGrove";
public const string GroveDisplayName = "Heartwood Grove";
// A grove costs exactly one full Composter batch. That is the whole balance argument.
public const int GroveSeedFertilizerCost = ComposterYield;
// World time, not session time: Plant.TimeSincePlanted reads ZNet's clock, so a sapling
// keeps growing with the zone unloaded and the game shut, same as the Composter's timer.
public const float GroveGrowSeconds = 7200f;
// One radius for both halves on purpose - the grove defends exactly the ground it farms,
// and the player only has to learn one number. Matches PurpleRainRadius.
public const float GroveRadius = 8f;
// One plant per tick, not the whole radius: 20 Fertilizer is then 20 minutes of autonomy.
// Growing everything at once would empty the trough in a single tick.
public const float GroveFertilizeInterval = 60f;
public const int GroveFertilizerCapacity = ComposterYield;
// The honey rate is not invented: m_secPerUnit and m_maxHoney are read off the vanilla
// Beehive at registration. Only the capacity is scaled - a whole tree of bees has to last
// while the player is away, where a hive only has to last until they walk past it.
public const int GroveHoneyCapacityFactor = 5;
// Honey accrues day and night, exactly as a vanilla hive's does.
//
// This used to be a GroveHoneyAtNight knob defaulting to false, on the reading that
// Beehive.m_effectOnlyInDaylight meant "bees only work in daylight". It does not: by its
// name and by the only method that touches it (Beehive.UpdateBees), it gates m_beeEffect -
// the buzz and the particles - not production. Vanilla hives make honey overnight.
//
// Getting that wrong did not merely slow the grove down, it starved it. The night was
// discarded by resetting the accrual stamp, which meant a whole m_secPerUnit had to fit
// inside one unbroken stretch of daylight - and m_secPerUnit is of the same order as a
// Valheim day is long (a full cycle is EnvMan.m_dayLengthSec, 1800s by default, of which
// roughly 1260s is not night). So honey was somewhere between rare and arithmetically
// impossible depending on the hive's real rate and what time it was when the tree matured.
//
// If the "bees sleep at night" flavour is ever wanted, it belongs where vanilla puts it:
// on the swarm's buzz, not on the honey.
// Only the model is taken off this prefab, never its TreeBase or its log drop - the same
// discipline the VFX borrowing follows. A Yggdrasil shoot reads as "grown from a root of
// the world" rather than as any old beech, and matches YggdrasilWood being in the recipe.
public const string GroveModelPrefab = "YggaShoot_small1";
public const float GroveModelScale = 1f;
// Cloned for the sapling stage; must be a prefab that carries a Plant component.
public const string GroveSaplingSourcePrefab = "Beech_Sapling";
// The grove's swarm is the Hornet's Nest swarm with a different anchor - deliberately not
// a second copy of that code, so a change to the sting is a change to both. It therefore
// reads HornetsNestDamagePerTick / HornetsNestTickInterval and has no damage of its own.
//
// A grove is a piece, not a Character, so BaseAI.IsEnemy cannot be asked directly the way
// the player-anchored swarm asks it. The fallback rule lives in TrentaHornetSwarm.
public const float GroveStingRadius = GroveRadius;
// Density cap, enforced by PieceDensityLimit. Without one, a field of groves is a carpet of
// bees that kills anything that comes near, and this was a known open point for two rounds.
//
// More permissive than the Draugh body pile's five, on the reading that a grove is a farm
// rather than an army and costs a Composter batch rather than a 500-coin bone. Unlike almost
// every other number in this file it has no vanilla equivalent to be read off, so it IS a
// guess - change it freely, it is one line and nothing else depends on it.
public const int GroveMaxInRange = 10;
public const float GroveDensityAreaKm2 = 1.6f; // the same frame the body pile uses
// ─── The vanilla beehive ─────────────────────────────────────────────
// Two features read this prefab: the grove borrows its honey rate and capacity, and the
// Hornet's Nest borrows the AudioClip off its bee effect.
//
// Both used to look up "Beehive" and both silently got nothing - confirmed from the BepInEx
// log, which is the whole reason those lookups now warn instead of returning quietly. There is
// a Beehive.prefab in the asset manifest, but it is not what PrefabManager resolves under that
// name; the buildable hive is "piece_beehive", and that is the one carrying the tuned Beehive
// component. Both names are tried in order so a game update that moves it cannot silence this
// again without saying so.
public static readonly string[] BeehiveSourcePrefabs = { "piece_beehive", "Beehive" };
// ─── Helpers ─────────────────────────────────────────────────────────
/// <summary>
/// The vanilla Beehive component, or null. Shared by the grove and the Hornet's Nest so the
/// two cannot disagree about where it lives.
/// </summary>
public static Beehive FindVanillaBeehive()
{
foreach (string name in BeehiveSourcePrefabs)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(name);
Beehive hive = prefab != null ? prefab.GetComponent<Beehive>() : null;
if (hive != null)
{
Jotunn.Logger.LogInfo($"[Trenta] Vanilla beehive resolved from '{name}'.");
return hive;
}
}
Jotunn.Logger.LogWarning("[Trenta] No vanilla beehive found under any of: " +
string.Join(", ", BeehiveSourcePrefabs));
return null;
}
/// <summary>Clamped table lookup, so a state outside 1..8 can never index out of range.</summary>
public static float Lookup(float[] table, int state)
{

View file

@ -0,0 +1,237 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Tier 2 of the Trenta's item chain: plant it, wait, and the tree that comes up fertilises what
/// surrounds it, stings what approaches it, and fills a chest with honey. Three functions that do
/// not depend on each other, on one piece. Design doc: Trenta_Composter.txt section 11.
///
/// ONE piece, not two. The doc called for a sapling carrying a vanilla Plant whose m_grownPrefabs
/// pointed at a separate grown prefab; this grows in place instead - same crate, same ZNetView,
/// with the young model swapped for the grown one when the clock runs out. Three risks went away
/// with that decision and nothing was lost:
/// - no second prefab to register outside a piece table, and no question about whether Jotunn
/// has put it in ZNetScene by the time a Plant tries to instantiate it;
/// - no dependency on Beech_Sapling actually carrying a Plant, which was the one link in the
/// tier-1 design nobody had opened yet;
/// - the honey chest and the Fertilizer trough survive the transition, because there is no
/// transition - nothing is destroyed and re-spawned, so nothing has to be carried over.
/// The growth timer is the same shape as the Composter's: one timestamp on ZNet's world clock, so
/// it advances with the zone unloaded and across a restart.
///
/// The layout is forced by a single fact worth stating plainly: there is one ZNetView per
/// instantiated prefab, and Container keeps its inventory in the ZDO. So there can be exactly one
/// real chest, and it is the honey one. The Fertilizer goes in through a Switch on the plant
/// itself - E on the crate opens the honey, E on the tree feeds it - which is the same division
/// of labour the vanilla fermenter uses between its root component and its child switches.
/// </summary>
public static class TrentaHeartwoodGrove
{
public static void Register()
{
RegisterSeed();
RegisterPiece();
PieceDensityLimit.Register(TrentaConfig.GrovePieceName,
PieceDensityLimit.RadiusForArea(TrentaConfig.GroveDensityAreaKm2), TrentaConfig.GroveMaxInRange,
"This country already answers to {0} of these. Plant it somewhere else.");
}
// ---------------------------------------------------------------- the seed
private static void RegisterSeed()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.GroveSeedName, "AncientSeed");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone AncientSeed; Heartwood Seed not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = TrentaConfig.GroveSeedDisplayName;
shared.m_description = "A seed fed on a whole barrel of rot. Plant it and go away for a while.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 1f;
shared.m_maxStackSize = 10;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
// One grove costs exactly one full Composter batch - 100 units of flesh and forty
// minutes. That is the whole balance argument, and it is why the cost is expressed in
// Fertilizer rather than in some second currency.
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = TrentaConfig.GroveSeedName,
Amount = 1,
CraftingStation = "piece_preptable",
Requirements = new[]
{
new RequirementConfig(TrentaConfig.FertilizerName, TrentaConfig.GroveSeedFertilizerCost),
new RequirementConfig(TrentaConfig.RotSeedName, 1),
new RequirementConfig("YggdrasilWood", 10),
}
}));
}
// ---------------------------------------------------------------- the piece
private static void RegisterPiece()
{
// A wooden chest is the base because it arrives with everything a honey store needs
// already wired: ZNetView, Piece, WearNTear, colliders, and a Container whose lid
// objects and effect lists are assigned. Building one from scratch would mean assigning
// all of that by hand and finding out in game which field Container.Awake dereferences
// without checking.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.GrovePieceName, "piece_chest_wood");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone piece_chest_wood; Heartwood Grove not registered.");
return;
}
Container container = prefab.GetComponent<Container>();
if (container == null)
{
Jotunn.Logger.LogWarning("[Trenta] piece_chest_wood clone has no Container; Heartwood Grove not registered.");
return;
}
container.m_name = TrentaConfig.GroveDisplayName;
GroveBehaviour grove = prefab.AddComponent<GroveBehaviour>();
grove.m_container = container;
grove.m_youngModel = BuildModel(prefab.transform, "GroveYoung", TrentaConfig.GroveSaplingSourcePrefab, TrentaConfig.GroveModelScale);
grove.m_grownModel = BuildModel(prefab.transform, "GroveGrown", TrentaConfig.GroveModelPrefab, TrentaConfig.GroveModelScale);
// The plant is the second interaction point. It carries its own collider so the hover
// raycast resolves to the Switch on it rather than walking up to the Container on the
// root - which is how the crate keeps meaning "open the honey" while the tree means
// "feed me". Sized generously: it has to be clickable at both growth stages.
grove.m_switch = BuildTroughSwitch(grove.m_grownModel, grove.m_youngModel);
Piece piece = prefab.GetComponent<Piece>();
if (piece != null)
{
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = TrentaConfig.GroveDisplayName;
}
PieceConfig config = new PieceConfig
{
Name = TrentaConfig.GroveDisplayName,
Description = "A crate of rot with something growing out of it. Give it time.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
Requirements = new[]
{
new RequirementConfig(TrentaConfig.GroveSeedName, 1, 0, true),
}
};
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
}
/// <summary>
/// Borrows the visible half of a world prefab and nothing else.
///
/// The same discipline the VFX borrowing follows, and here it matters more: the Yggdrasil
/// shoot is a TreeBase, so taken whole it would bring a choppable trunk, a log drop and a
/// tree collider along with the mesh - a grove that can be felled for wood instead of being
/// destroyed as a piece. Only Renderers and their transforms survive; every component that
/// is not a Renderer, and every collider, is stripped.
/// </summary>
private static GameObject BuildModel(Transform root, string name, string sourcePrefabName, float scale)
{
GameObject holder = new GameObject(name);
holder.transform.SetParent(root, false);
holder.transform.localPosition = Vector3.zero;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefabName);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Heartwood Grove: could not find model prefab '{sourcePrefabName}'.");
return holder;
}
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localScale = Vector3.one * scale;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
return holder;
}
/// <summary>
/// The Fertilizer input: a Switch with a collider of its own, hung off the grown model but
/// parented so it stays live at both stages (the models get toggled, this does not).
/// </summary>
private static Switch BuildTroughSwitch(GameObject grownModel, GameObject youngModel)
{
// Parented to the models' shared parent - the piece root - precisely so GroveBehaviour
// can switch the two models on and off without taking the interaction point with them.
Transform parent = grownModel != null ? grownModel.transform.parent : youngModel.transform.parent;
GameObject holder = new GameObject("GroveTrough");
holder.transform.SetParent(parent, false);
holder.transform.localPosition = new Vector3(0f, 1.2f, 0f);
// Two decisions here that both come down to "will the hover raycast find this at all",
// which is the one thing about this piece that cannot be settled by reading code:
// - the layer is copied from the piece root rather than left on Default, because
// Player.FindHoverObject raycasts against a mask and a brand new GameObject starts
// on whatever layer 0 happens to be;
// - it is NOT a trigger. Physics.queriesHitTriggers is a global whose value here is
// not ours, so a trigger collider might simply be invisible to that raycast. Solid
// also happens to be right: it is a tree trunk, and walking through it would be odd.
holder.layer = parent.gameObject.layer;
BoxCollider collider = holder.AddComponent<BoxCollider>();
collider.size = new Vector3(1.2f, 2.4f, 1.2f);
collider.isTrigger = false;
Switch trough = holder.AddComponent<Switch>();
trough.m_name = TrentaConfig.GroveDisplayName;
return trough;
}
/// <summary>
/// Same reason as the Composter's: a piece registered after the vanilla learning pass never
/// reaches the hammer on its own. The Heartwood Seed requirement is the real gate.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.GrovePieceName);
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();
}
}
}

View file

@ -7,13 +7,22 @@ namespace RacesOfValheim
/// <summary>
/// The swarm itself. Not a Character - it has no health, no hitbox anything else can target,
/// so "indistruttibile" falls out of what it simply isn't rather than needing invulnerability
/// code of its own. Idles in a slow orbit around the Trenta; the instant an enemy comes within
/// range it breaks off, hovers over that enemy instead, and sting-ticks it on a timer until it
/// dies or leaves range, then returns to orbiting.
/// code of its own. Idles in a slow orbit around whatever it is tied to; the instant an enemy
/// comes within range it breaks off, hovers over that enemy instead, and sting-ticks it on a
/// timer until it dies or leaves range, then returns to orbiting.
///
/// Two things it can be tied to, and the difference is only in what counts as an enemy:
/// - a Trenta player (the Hornet's Nest perk), which can be asked BaseAI.IsEnemy directly;
/// - a Heartwood Grove's trunk (the tier-2 station), which cannot, because a piece is not a
/// Character. See IsHostile.
/// Deliberately one class rather than two copies: the sting is combat logic, and a second copy
/// means the next tweak to the venom gets made in one place and forgotten in the other.
/// </summary>
public class TrentaHornetSwarm : MonoBehaviour
{
private Player owner;
private Player owner; // null for a grove swarm
private Transform anchor; // what it orbits; the owner's own transform for a player swarm
private float engageRadius;
private Character target;
private float tickTimer;
private float orbitAngle;
@ -21,11 +30,38 @@ namespace RacesOfValheim
public static GameObject Spawn(Player player)
{
GameObject go = new GameObject("TrentaHornetsNest");
go.transform.position = player.transform.position + Vector3.up;
GameObject go = Build("TrentaHornetsNest", player.transform.position + Vector3.up);
TrentaHornetSwarm swarm = go.GetComponent<TrentaHornetSwarm>();
swarm.owner = player;
swarm.anchor = player.transform;
swarm.engageRadius = TrentaConfig.HornetsNestEngageRadius;
return go;
}
/// <summary>
/// The grove's swarm: same bees, tied to a fixed point instead of to a player. The radius is
/// its own number because 6 metres is tuned for something that walks - a tree that cannot
/// chase has to reach further, and it matches the ground the grove fertilises.
/// </summary>
public static GameObject SpawnAtAnchor(Transform anchorPoint, float radius)
{
GameObject go = Build("TrentaGroveBees", anchorPoint.position + Vector3.up);
TrentaHornetSwarm swarm = go.GetComponent<TrentaHornetSwarm>();
swarm.anchor = anchorPoint;
swarm.engageRadius = radius;
return go;
}
private static GameObject Build(string name, Vector3 position)
{
GameObject go = new GameObject(name);
go.transform.position = position;
TrentaHornetSwarm swarm = go.AddComponent<TrentaHornetSwarm>();
swarm.owner = player;
BuildFliesVfx(go.transform);
swarm.buzz = BuildBuzzAudio(go.transform);
@ -33,15 +69,20 @@ namespace RacesOfValheim
return go;
}
private Vector3 AnchorPosition => anchor != null ? anchor.position : transform.position;
private void Update()
{
if (owner == null || owner.IsDead())
// A player swarm dies with its player; a grove swarm dies with its tree. Either way the
// check is "is there still something to orbit", which is also what makes the swarm clean
// itself up when the grove is destroyed without the grove having to say so.
if (anchor == null || (owner != null && owner.IsDead()))
{
Destroy(gameObject);
return;
}
if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, owner.transform.position) > TrentaConfig.HornetsNestEngageRadius * 1.5f))
if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, AnchorPosition) > engageRadius * 1.5f))
{
target = null;
}
@ -74,7 +115,7 @@ namespace RacesOfValheim
// them - reads as "trying to stay on him" without looking glued in place.
orbitAngle += Time.deltaTime * 60f;
Vector3 orbitOffset = new Vector3(Mathf.Cos(orbitAngle * Mathf.Deg2Rad), 0.3f, Mathf.Sin(orbitAngle * Mathf.Deg2Rad)) * TrentaConfig.HornetsNestOrbitRadius;
Vector3 restPoint = owner.transform.position + Vector3.up + orbitOffset;
Vector3 restPoint = AnchorPosition + Vector3.up + orbitOffset;
transform.position = Vector3.MoveTowards(transform.position, restPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime);
}
}
@ -83,16 +124,17 @@ namespace RacesOfValheim
{
Character nearest = null;
float nearestDist = float.MaxValue;
Vector3 centre = AnchorPosition;
foreach (Collider collider in Physics.OverlapSphere(owner.transform.position, TrentaConfig.HornetsNestEngageRadius))
foreach (Collider collider in Physics.OverlapSphere(centre, engageRadius))
{
if (collider == null) continue;
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == owner || character.IsDead()) continue;
if (!BaseAI.IsEnemy(owner, character)) continue;
if (character == null || character == owner) continue;
if (!IsHostile(character)) continue;
float dist = Vector3.Distance(character.transform.position, owner.transform.position);
float dist = Vector3.Distance(character.transform.position, centre);
if (dist < nearestDist)
{
nearestDist = dist;
@ -103,6 +145,59 @@ namespace RacesOfValheim
return nearest;
}
/// <summary>
/// Who gets stung.
///
/// For a player swarm this is one line - BaseAI.IsEnemy - and it is the most valuable line in
/// the file: RaceHostilityManager is a postfix on that very method, so the Trenta's own
/// alliances (greyling, greydwarf, fuling, troll, leech, deathsquito) are honoured for free.
///
/// A grove has no Character to ask on its own behalf, so the rule is rebuilt from parts:
/// never players, never tamed, and only things carrying a MonsterAI - which is the cut that
/// spares wild deer and boar, since vanilla gives passive animals AnimalAI instead. And if
/// there is a Trenta standing inside the radius, IsEnemy is consulted against them too, so
/// the alliances come back the moment someone is there to carry them.
/// </summary>
private bool IsHostile(Character character)
{
if (character == null || character.IsDead()) return false;
if (character.IsPlayer()) return false;
if (character.IsTamed()) return false;
if (owner != null) return BaseAI.IsEnemy(owner, character);
if (character.GetComponent<MonsterAI>() == null) return false;
Player trenta = NearestTrenta();
return trenta == null || BaseAI.IsEnemy(trenta, character);
}
/// <summary>
/// The nearest Trenta inside the swarm's own radius, or null. Used both to borrow their
/// alliances and to attribute the sting - a hit with no attacker at all is what the old eitr
/// refinery's mystery damage looked like, and worth avoiding whenever there is a real one.
/// </summary>
private Player NearestTrenta()
{
Player nearest = null;
float nearestDist = float.MaxValue;
Vector3 centre = AnchorPosition;
foreach (Player player in Player.GetAllPlayers())
{
if (player == null || player.IsDead() || !TrentaVisuals.IsTrentaPlayer(player)) continue;
float dist = Vector3.Distance(player.transform.position, centre);
if (dist <= engageRadius && dist < nearestDist)
{
nearestDist = dist;
nearest = player;
}
}
return nearest;
}
/// <summary>
/// Two hits, matching "come se il giocatore fosse costantemente avvelenato dalle api, più
/// lo stesso danno ma perforante da sopra" literally: one Poison hit at the wild Bee
@ -111,16 +206,20 @@ namespace RacesOfValheim
/// </summary>
private void Sting(Character victim)
{
// A grove's bees are still somebody's bees when a Trenta is standing under the tree;
// when nobody is, the sting lands with no attacker rather than picking one at random.
Character attacker = owner != null ? owner : NearestTrenta();
HitData poison = new HitData();
poison.m_damage.m_poison = TrentaConfig.HornetsNestDamagePerTick;
poison.SetAttacker(owner);
if (attacker != null) poison.SetAttacker(attacker);
poison.m_point = victim.GetCenterPoint();
poison.m_dir = Vector3.zero;
victim.Damage(poison);
HitData pierce = new HitData();
pierce.m_damage.m_pierce = TrentaConfig.HornetsNestDamagePerTick;
pierce.SetAttacker(owner);
if (attacker != null) pierce.SetAttacker(attacker);
pierce.m_point = victim.GetCenterPoint();
pierce.m_dir = Vector3.down;
victim.Damage(pierce);
@ -165,8 +264,10 @@ namespace RacesOfValheim
source.spatialBlend = 1f; // 3D - it should sound like it is coming from the swarm
source.volume = 0.6f;
GameObject beehivePrefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.HornetsNestBeehivePrefab);
Beehive beehive = beehivePrefab != null ? beehivePrefab.GetComponent<Beehive>() : null;
// Resolved through TrentaConfig, which tries "piece_beehive" before "Beehive". This used
// to look up "Beehive" alone and got nothing, every time, which is why the swarm has been
// silent since it was written - found in the BepInEx log, not by listening.
Beehive beehive = TrentaConfig.FindVanillaBeehive();
GameObject beeEffect = beehive != null ? Traverse.Create(beehive).Field<GameObject>("m_beeEffect").Value : null;
AudioSource sourceClipHolder = beeEffect != null ? beeEffect.GetComponentInChildren<AudioSource>(true) : null;

View file

@ -27,6 +27,13 @@ namespace RacesOfValheim
{
TrentaStatusEffects.RegisterStatusEffects();
CreateAwakenedSeedFoods();
// The item-progression chain: the Composter and its Fertilizer, then the Heartwood Grove
// that runs on that Fertilizer. Registered here rather than lazily because the faction
// merchant catalogue resolves the Rot Seed by prefab name, so the item has to exist
// before that catalogue is read.
TrentaComposter.Register();
TrentaHeartwoodGrove.Register();
}
/// <summary>

View file

@ -38,6 +38,10 @@ namespace RacesOfValheim
Jotunn.Logger.LogInfo("Initializing Trol Race...");
TrolStatusEffects.RegisterStatusEffects();
// The war totem and every creature it can hire. Race-locked at placement, unlike every
// other station in the mod.
TrolTotem.Register();
// No custom projectile needed anymore
string[] logNames = new string[] {

View file

@ -0,0 +1,368 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trol's totem: a troll's head on a core-wood post that hires warbands for coin.
///
/// The first station in the mod that is RACE LOCKED. Every other chain can be built by anyone and
/// only its output is restricted; this one refuses the hammer outright to anyone who is not a Trol,
/// because a warband of trolls and greydwarves for money is the Trol's whole identity rather than a
/// tool it happens to own.
///
/// The troops are the real creatures, unaltered - a Troll is a Troll - with three differences:
/// - they answer to the follow command, because they carry RaisedThrall like every other servant
/// in this mod, so the taunt and the click already work on them with no new code;
/// - they knit their wounds back up when left alone, the sentry's regeneration reused whole;
/// - they drop NOTHING and never come back. A dead warband is money spent. That is the balance
/// against troops that cost coin instead of materials, and it is why they are worth what they
/// are worth.
/// </summary>
public static class TrolTotem
{
public const string PieceName = "TrolWarTotem";
public const string PieceDisplayName = "War Totem";
public const string RaceId = "Trol";
/// <summary>Core wood. The item is RoundLog - another display name that does not predict the id.</summary>
public const string CoreWood = "RoundLog";
public const string TrollHead = "TrophyForestTroll";
/// <summary>Yagluth's secondary drop, already mapped to state 6 in BossProgressionManager.
/// Distinct from TrophyGoblinKing, which is the head that replaces the troll's on upgrade.</summary>
public const string UpgradeItem = "YagluthDrop";
public const string YagluthHead = "TrophyGoblinKing";
public const int UpgradeProgressionState = 6; // Yagluth
public const int MaxTroops = 5;
// ---------------------------------------------------------------- the look, in metres
// These used to be bare multipliers (3f for the totem, 1.5f for the head) guessed against meshes
// nobody had measured, and the head came out with a circumference three times the height of the
// post under it. ModelBorrow now measures the mesh and scales it to fit, so a number here is a
// SIZE and not a factor: 2.2 m is a totem you can stand next to, 0.55 m is a head on top of it.
private const float TotemHeight = 2.2f;
private const float HeadSize = 0.9f;
/// <summary>
/// How far the head sinks into the totem's crown, as a fraction of its own size. Mounting it exactly
/// ON the measured top left it hovering with daylight under it - a trophy sitting on a post shares
/// some of the post, so the two models are made to overlap instead of merely touching.
/// </summary>
private const float HeadSink = 0.35f;
/// <summary>
/// A trophy is authored lying down, and the first correction (Euler(90,0,0)) stood it up but left it
/// upside down and facing away - seen in game, not reasoned about. Another half turn on each of the
/// two axes that were wrong puts it the right way up and looking out.
/// If it is still off, this is the ONE line to touch: the two 180s are what was added.
/// </summary>
private static readonly Quaternion HeadTilt = Quaternion.Euler(90f + 180f, 180f, 0f);
/// <summary>Written into each hired creature's ZDO so the totem can tell its warbands apart -
/// five slots means counting groups, not bodies.</summary>
public const string KeyGroup = "RoV_trolGroup";
public const float LeashRange = 12f;
public const float WitherSeconds = 60f;
public const float HomeCheckRange = 25f;
/// <summary>No cap: a hired warband follows as a warband.</summary>
public const int MaxFollowers = -1;
public class Troop
{
public string Id;
public string Display;
public int Price;
public bool NeedsUpgrade;
/// <summary>Trophy of the strongest thing in the band - 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 2000 for the strongest, as specified, and laddered by what each band can actually
// do rather than by head count.
public static readonly Troop[] Troops =
{
new Troop
{
Id = "greydwarf_patrol", Display = "Greydwarf Patrol", Price = 400, NeedsUpgrade = false, Icon = "TrophyGreydwarfBrute",
Members = new[]
{
new KeyValuePair<string, int>("Greydwarf", 4),
new KeyValuePair<string, int>("Greydwarf_Shaman", 1),
new KeyValuePair<string, int>("Greydwarf_Elite", 1),
}
},
new Troop
{
Id = "troll", Display = "Troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll",
Members = new[] { new KeyValuePair<string, int>("Troll", 1) }
},
new Troop
{
Id = "troll_summoned", Display = "Staff Troll", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll",
Members = new[] { new KeyValuePair<string, int>("Troll_Summoned", 1) }
},
new Troop
{
Id = "goblin_patrol", Display = "Fuling Patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute",
Members = new[]
{
new KeyValuePair<string, int>("Goblin", 4),
new KeyValuePair<string, int>("GoblinShaman", 1),
new KeyValuePair<string, int>("GoblinBrute", 1),
}
},
new Troop
{
Id = "goblin_band", Display = "Fuling War Band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin",
Members = new[]
{
new KeyValuePair<string, int>("Goblin", 4),
new KeyValuePair<string, int>("GoblinArcher", 4),
}
},
};
public static Troop Find(string id)
{
foreach (Troop troop in Troops) if (troop.Id == id) return troop;
return null;
}
/// <summary>Every distinct creature the totem can hire, so their clones exist before anyone buys.</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;
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();
}
// ---------------------------------------------------------------- the hired
/// <summary>
/// One hired creature: the vanilla thing, tamed, leashed, healing, and worth nothing dead.
///
/// CharacterDrop is destroyed for the reason it always is here - a mercenary that dropped a troll
/// hide would make the totem a farm - and this time it is also what "leaves nothing when it dies"
/// literally means.
/// </summary>
private static void RegisterHired(string source)
{
string prefabName = "TrolHired_" + source;
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Trol] Could not clone {source}; that troop cannot be hired.");
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 = "They were not paid by you.";
// The sentry's regeneration, reused whole: untouched for ten seconds, then two percent a
// second. "Rigenerarsi come i nostri scheletri" is the healing, not a respawn - a dead
// mercenary stays dead and has to be hired again.
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
HiredPrefabs[source] = prefabName;
}
// ---------------------------------------------------------------- the totem
private static void RegisterPiece()
{
// A REAL PIECE as the base, and this is the whole bug fix. The first version cloned
// "GoblinTotem", which lives in Assets/GameElements/Items/misc - it is the ITEM offered at
// Yagluth's altar, not a building. An ItemDrop wearing a Piece destroyed itself the moment it
// was placed and left the item lying on the ground. Verified in this very project when the
// merchant catalogue's "FulingTotem" was corrected to "GoblinTotem" as an ITEM, and then
// contradicted here.
//
// piece_workbench is a genuine piece and is already the stripped base of the Skeleton
// sentry's seed, so the pattern is proven. goblin_totempole was the other candidate and is
// not a piece either - it is dungeon scenery under Assets/world.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_workbench");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trol] Could not clone piece_workbench; the war totem is not registered.");
return;
}
// Strip the workbench down to a placeable shell: no station, no crafting, no furniture. The
// look comes from the borrowed totem below.
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);
}
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
// The look the player asked for: the totem itself, not a log with a head on it. Grounded on
// its own base, so Vector3.zero really is "standing on the spot the hammer picked".
GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", "GoblinTotem",
Vector3.zero, Quaternion.identity, TotemHeight, "Trol");
TrolTotemBehaviour totem = prefab.AddComponent<TrolTotemBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
totem.m_switch = prefab.AddComponent<Switch>();
totem.m_switch.m_name = PieceDisplayName;
// A Trader with an empty catalogue: StoreGui needs one to open at all, and an empty list is
// exactly "sells troops, buys nothing". An empty catalogue is also what used to kill the whole
// window - see StoreGuiEmptyCatalogueGuardPatch in TrolTotemStore.cs, which is the fix.
//
// Every list is filled in even though this trader never talks: a Trader added with
// AddComponent comes up with all of them null, and Trader.Interact - which fires if the
// player's E happens to reach the Trader instead of our Switch, both being on this same
// GameObject - walks straight into Say(m_randomStartTrade, ...) right after opening the store.
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>();
// Only ONE head now, and only for the upgraded tier. At tier one the totem is just a totem,
// which is what was asked for - the troll head on a post was the thing being replaced, and
// mounting trophies is also what dropped a giant Yagluth head out of the sky. Borrowed
// safely this time, and mounted on the MEASURED top of the totem rather than at a guessed
// 2.2 m up an unmeasured post - sunk into the crown so it sits on it instead of over it.
float crown = ModelBorrow.HeightOf(totemModel);
Jotunn.Logger.LogInfo($"[Trol] Totem crown measured at {crown:0.##} m; the king's head is " +
$"{HeadSize} m across and sunk {HeadSize * HeadSink:0.##} m into it.");
totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", YagluthHead,
new Vector3(0f, crown - HeadSize * HeadSink, 0f),
HeadTilt, HeadSize, "Trol");
totem.m_yagluthHead.SetActive(false);
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(TrollHead);
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 = "A head that still remembers how to shout. Coin goes in, a warband walks out.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon(TrollHead),
Requirements = new[]
{
new RequirementConfig(CoreWood, 1, 0, true),
new RequirementConfig(TrollHead, 1, 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 TrolTotemKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
TrolTotem.EnsureKnown(__instance);
}
}
/// <summary>
/// The race lock. Every other station in this mod is buildable by anyone; this one is not, so the
/// refusal is caught at placement - before the core wood and the head are spent.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class TrolTotemRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != TrolTotem.PieceName) return true;
if (TrolRace.IsTrol()) return true;
__instance.Message(MessageHud.MessageType.Center, "The head will not shout for you.");
return false;
}
}
}

View file

@ -0,0 +1,288 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The totem's logic: five warband slots, bought with coin, disbanded on demand.
///
/// Slots count GROUPS, not bodies - a six-greydwarf patrol is one slot, and it stays one slot as its
/// members die. Each hired creature carries the group's id in its own ZDO, so the count survives a
/// reload and corrects itself when a whole band is wiped, with nothing tallied anywhere.
///
/// E opens the vanilla store with a warband column in it, built in TrolTotemStore. It replaced a
/// hold-to-cycle gesture on the Switch that fired faster than anyone could read it.
/// Factions/FactionMerchantSellPanel.cs is the blueprint that made it possible without guessing at a
/// single UI field name.
///
/// There is no disband button and no rack of slots: a warband that dies is dead, and a butcher knife
/// already dismisses one that has outlived its use. The count is the only bookkeeping there is.
/// </summary>
public class TrolTotemBehaviour : MonoBehaviour
{
public Switch m_switch;
public GameObject m_yagluthHead;
private const string KeyUpgraded = "RoV_trolTotemUpgraded";
private const string KeyNextGroup = "RoV_trolTotemNextGroup";
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_TrolHire", RPC_Hire);
m_nview.Register("RoV_TrolUpgrade", RPC_Upgrade);
InvokeRepeating("UpdateHeads", 0.5f, 2f);
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
/// <summary>Both heads are mounted; the tier decides which one is looking at you.</summary>
private void UpdateHeads()
{
// Tier one is a plain totem; the king's head only appears once it has been earned.
if (m_yagluthHead != null) m_yagluthHead.SetActive(IsUpgraded());
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (!TrolRace.IsTrol())
{
player.Message(MessageHud.MessageType.Center, "The head will not shout for you.");
return false;
}
// Yagluth's drop in hand upgrades it: a new head, and two more warbands on the list.
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == TrolTotem.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() < TrolTotem.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, "Not until the one it belonged to has fallen.");
return false;
}
player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_TrolUpgrade");
player.Message(MessageHud.MessageType.Center, "The totem wears a king now.");
return true;
}
/// <summary>
/// Opens the vanilla store window, with the warband column hung off it by
/// TrolTotemStore. A Trader has to be present for StoreGui.Show to have anything to show; the
/// totem's own sells nothing, which is how "does not buy from the player" is expressed.
/// </summary>
private bool OpenStore(Player player)
{
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, "The head has nothing to say.");
return false;
}
// Nothing is handed to the panel here on purpose: TrolTotemStore reads the totem back out of
// StoreGui's own m_trader when it repaints, so the window cannot end up drawing one totem's
// warbands 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>Hire by id, from a row the player clicked. Every check TryHire makes still applies.</summary>
public void HireFromStore(string troopId)
{
Player player = Player.m_localPlayer;
if (player == null) return;
TrolTotem.Troop troop = TrolTotem.Find(troopId);
if (troop == null) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
if (CountGroups() >= TrolTotem.MaxTroops)
{
player.Message(MessageHud.MessageType.Center, "Five warbands is all it can shout for.");
return;
}
Inventory inventory = player.GetInventory();
if (inventory == null) return;
if (CountCoins(inventory) < troop.Price)
{
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney");
return;
}
TakeCoins(inventory, troop.Price);
m_nview.InvokeRPC("RoV_TrolHire", troop.Id);
player.Message(MessageHud.MessageType.Center, $"{troop.Display} answers.");
}
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;
TrolTotem.Troop troop = TrolTotem.Find(troopId);
if (troop == null || CountGroups() >= TrolTotem.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 = TrolTotem.HiredNameFor(member.Key);
if (hired == null) continue;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Trol] No '{hired}' in ZNetScene; part of {troop.Display} did not arrive.");
continue;
}
for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group);
}
}
private void SpawnOne(GameObject prefab, string group)
{
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));
ZNetView nview = spawned.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(TrolTotem.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(TrolTotem.KeyGroup, "");
return string.IsNullOrEmpty(group) ? null : group;
}
/// <summary>
/// Live warbands, counted as distinct groups rather than as bodies. This is the whole of the
/// five-slot mechanic now that the rack is gone: nothing is stored, the count is the truth, and it
/// corrects itself the moment a band 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 = $"warbands {CountGroups()}/{TrolTotem.MaxTroops}";
if (!IsUpgraded()) body += "\n(a Yagluth drop in hand buys a king's head, and two more bands)";
// The roster lives in the window now, not in the hover - so this only has to get the player
// to open it. The hold gesture it used to advertise was unreadable: it cycled faster than
// anyone could see what was selected.
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Call the warbands";
return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})");
}
}
}

View file

@ -0,0 +1,257 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// The war totem's window: the merchant's own store, with a column of hireable warbands in it.
///
/// Built by cloning the vanilla store's list the way Factions/FactionMerchantSellPanel.cs already
/// does - same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick of
/// instantiating StoreGui.m_listElement for rows. That file is the reason this one could be written
/// without guessing at a single UI field name.
///
/// It replaces a hold-to-cycle gesture on the Switch, which was unreadable: the hold fired faster
/// than anyone could see what was selected.
///
/// NO SLOT RACK. There was one, with five squares wearing the trophies of the bands standing in them
/// and a yes/no box to disband one. It is gone at the player's call: a warband that dies is simply
/// dead, and a butcher knife already dismisses one that has outlived its use - tested in game. The
/// five-band CEILING stays, counted in TrolTotemBehaviour and reported by the totem's hover text; it
/// was only ever the rack that was UI, not the limit.
///
/// WHY THIS FILE ONCE DREW NOTHING AT ALL - see StoreGuiEmptyCatalogueGuardPatch at the bottom. It
/// was not this panel failing; it was vanilla FillList throwing on its last instruction, and a
/// Postfix never runs when the original throws.
/// </summary>
public static class TrolTotemStore
{
private static RectTransform _troopList;
private static readonly List<GameObject> _rows = new List<GameObject>();
/// <summary>
/// The totem the open window belongs to, read back out of StoreGui's own m_trader instead of being
/// pushed in by the totem before Show().
///
/// It used to be a static the totem set on its way in, which meant the panel's correctness depended
/// on the order Show/Hide/FillList happen to run in. Reading it back makes the question local: this
/// window belongs to whatever trader vanilla says it belongs to, and if that trader has a
/// TrolTotemBehaviour on it, it is a totem. Same field the factions sell panel reads.
/// </summary>
public static TrolTotemBehaviour ActiveTotem(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<TrolTotemBehaviour>() : null;
}
// ---------------------------------------------------------------- build
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null)
{
Jotunn.Logger.LogWarning("[Trol] StoreGui has no m_listRoot; the war totem's window cannot be built.");
return;
}
if (_troopList != null) return;
GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "TrolTroopList";
_troopList = clone.GetComponent<RectTransform>();
_troopList.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 _troopList) Object.Destroy(child.gameObject);
_troopList.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) Object.Destroy(row);
_rows.Clear();
if (_troopList != null) _troopList.gameObject.SetActive(false);
}
// ---------------------------------------------------------------- fill
public static void Refresh(StoreGui gui)
{
Clear();
TrolTotemBehaviour totem = ActiveTotem(gui);
if (totem == null) return; // an ordinary merchant. Not ours, and not worth a line in the log.
if (_troopList == null)
{
Jotunn.Logger.LogWarning("[Trol] The war totem's column was never built (did the patch on " +
"StoreGui.Awake fail?), so nothing can be drawn into it.");
return;
}
_troopList.gameObject.SetActive(true);
int row = 0;
int hidden = 0;
foreach (TrolTotem.Troop troop in TrolTotem.Troops)
{
if (troop.NeedsUpgrade && !totem.IsUpgraded()) { hidden++; continue; }
BuildRow(gui, totem, troop, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_troopList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
Mathf.Max(baseSize, row * gui.m_itemSpacing));
Jotunn.Logger.LogInfo($"[Trol] War totem window: {row} warbands on offer, {hidden} still behind " +
$"the king's head, {totem.CountGroups()}/{TrolTotem.MaxTroops} bands alive.");
}
private static void BuildRow(StoreGui gui, TrolTotemBehaviour totem, TrolTotem.Troop troop, int rowIndex)
{
GameObject element = Object.Instantiate(gui.m_listElement, _troopList);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_troopList.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($"[Trol] 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;
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = troop.Price.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(() =>
{
totem.HireFromStore(id);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
/// <summary>Who actually turns up, so a two thousand coin button is not bought blind.</summary>
private static string Composition(TrolTotem.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));
}
text.Append("\n\nThey answer the follow command, knit their own wounds shut, drop nothing, and do " +
"not come back. A dead warband 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 TrolTotemStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => TrolTotemStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class TrolTotemStoreFillPatch
{
public static void Postfix(StoreGui __instance) => TrolTotemStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class TrolTotemStoreHidePatch
{
public static void Postfix() => TrolTotemStore.Clear();
}
/// <summary>
/// The reason the totem's window opened empty, and it was never this mod's UI code.
///
/// Read out of the IL of THIS build's assembly_valheim, not assumed. StoreGui.FillList ends with:
/// int index = GetSelectedItemIndex(); // returns 0 when there is nothing to select
/// if (index &lt; 0) index = 0;
/// SelectItem(index, false);
/// and the last line of SelectItem is:
/// m_selectedItem = m_trader.GetAvailableItems()[index];
///
/// With an EMPTY catalogue that is element 0 of an empty list. FillList threw on its very last
/// instruction - and a Harmony Postfix does not run when the original throws, so BOTH postfixes on
/// FillList died with it: this file's warband column and the factions sell panel's. The window came
/// up (Show activates the panel before it calls FillList) with nothing drawn in it whatsoever, which
/// is exactly what the player described.
///
/// The totem's catalogue is empty ON PURPOSE - an empty list is how "sells warbands, buys nothing"
/// is expressed - so the crash is guarded rather than dodged. Vanilla merchants are untouched: the
/// prefix only stands in when there is genuinely nothing to select, which for them never happens
/// unless every one of their wares is behind a global key they have not earned. A prefix returning
/// false IS the mechanism on a void method (trap 5.16); there is no __result to fake.
/// </summary>
[HarmonyPatch(typeof(StoreGui), "SelectItem", new[] { typeof(int), typeof(bool) })]
public static class StoreGuiEmptyCatalogueGuardPatch
{
private static bool _reported;
public static bool Prefix(StoreGui __instance)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(__instance);
if (trader == null) return true;
if (trader.GetAvailableItems().Count > 0) return true;
// Nothing to select, and nothing to highlight either: m_itemList is emptied by FillList and
// only refilled from the same catalogue, so skipping the original loses no work.
Traverse.Create(__instance).Field("m_selectedItem").SetValue(null);
if (!_reported)
{
_reported = true;
Jotunn.Logger.LogInfo($"[Trol] '{trader.m_name}' has an empty catalogue; vanilla SelectItem was " +
"skipped so FillList can finish. Said once per session.");
}
return false;
}
}
}