RacesOfValheim/JotunnModStub/Skeleton/SkeletonRace.cs
kanym 9ed606a9aa feat(skeleton): per-player options to eat real food and spend stamina
Two options in "Skeleton - Mortal Habits", both off and not synced by
the server, since each only gives up an advantage.

Eats Mortal Food: the Skeleton eats like the living. The max health
override and the fake foods step aside, so meals decide health and
stamina and the tier's health bonus, which stood in for food, no longer
applies. The food HUD shows again.

Feels Fatigue: the Skeleton spends stamina. Without eating, its max
stamina is base plus the stamina of the tier's stand-in meals, because
the fake foods sit at m_time 0 and give none.

The compendium builds its diet line from four new keys (English,
Italian, Russian) when either option is on.
2026-11-02 23:31:58 +01:00

602 lines
27 KiB
C#

using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
using System.Collections.Generic;
namespace RacesOfValheim
{
public class SkeletonRace : MonoBehaviour
{
public static SkeletonRace Instance;
public static SE_SkeletonStats skeletonStatsSE;
private void Awake()
{
Instance = this;
}
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();
// The bone ship, Karve first. Same window, same reason: new pieces only register now.
BoneShip.Register();
var se = ScriptableObject.CreateInstance<SE_SkeletonStats>();
se.name = "SE_SkeletonStats";
se.m_name = "$rov_se_skeleton_stats_name";
// Icon
GameObject skelTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySkeleton")?.gameObject;
if (skelTrophy != null)
{
ItemDrop trophyDrop = skelTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
se.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
CustomStatusEffect skeletonStats = new CustomStatusEffect(se, fixReference: false);
ItemManager.Instance.AddStatusEffect(skeletonStats);
skeletonStatsSE = skeletonStats.StatusEffect as SE_SkeletonStats;
var resurrectSE = ScriptableObject.CreateInstance<SE_SkeletonResurrectCooldown>();
resurrectSE.name = "SE_SkeletonResurrectCooldown";
CustomStatusEffect customResurrectSE = new CustomStatusEffect(resurrectSE, fixReference: false);
ItemManager.Instance.AddStatusEffect(customResurrectSE);
// The "Summon on Kill is on" icon. The Dead Raiser's, since the Skeleton trophy is
// already Undead Fortitude's and this is the staff that raises skeletons in vanilla.
var raiseSE = ScriptableObject.CreateInstance<StatusEffect>();
raiseSE.name = RaiseDeadEffectName;
raiseSE.m_name = "$rov_se_skeleton_raisedead_name";
raiseSE.m_tooltip = "$rov_se_skeleton_raisedead_tooltip";
raiseSE.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("StaffSkeleton")?.m_itemData.GetIcon()
?? PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySkeleton")?.m_itemData.GetIcon();
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(raiseSE, fixReference: false));
}
// ─── Summon on Kill switch ──────────────────────────────────────────
private const string RaiseDeadEffectName = "SE_SkeletonRaiseDead";
private static readonly int RaiseDeadEffectHash = RaiseDeadEffectName.GetStableHashCode();
// Stored as "off" on the character, so a character that never pressed the key - every
// existing one - keeps the perk on.
private const string SummonOffKey = "RacesOfValheim_SkeletonSummonOff";
/// <summary>Whether this character wants a skeleton raised from each kill. Per character, saved with it.</summary>
public static bool SummonOnKillEnabled
{
get
{
Player player = Player.m_localPlayer;
return player == null || player.m_customData == null || !player.m_customData.ContainsKey(SummonOffKey);
}
set
{
Player player = Player.m_localPlayer;
if (player == null || player.m_customData == null) return;
if (value) player.m_customData.Remove(SummonOffKey);
else player.m_customData[SummonOffKey] = "1";
}
}
/// <summary>
/// The toggle key, and the icon that says the perk is on. The icon is put back whenever it
/// is missing, because status effects do not survive death or a relog.
/// </summary>
private static void TickSummonToggle(Player player, SkeletonProgression.SkeletonRules rules)
{
if (RaceInput.Allowed && SkeletonConfig.SummonToggleKey.Value.IsDownIgnoringHeldKeys())
{
if (!rules.SummonOnKill)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_summon_locked"));
}
else
{
SummonOnKillEnabled = !SummonOnKillEnabled;
player.Message(MessageHud.MessageType.Center,
ModText.Get(SummonOnKillEnabled ? "rov_msg_skeleton_summon_on" : "rov_msg_skeleton_summon_off"));
}
}
bool on = rules.SummonOnKill && SummonOnKillEnabled;
SetRaiseDeadIcon(player, on && SkeletonConfig.RaiseDeadIcon.Value);
}
private static void SetRaiseDeadIcon(Player player, bool on)
{
SEMan seman = player.GetSEMan();
bool has = seman.HaveStatusEffect(RaiseDeadEffectHash);
if (on && !has) seman.AddStatusEffect(RaiseDeadEffectHash, true);
else if (!on && has) seman.RemoveStatusEffect(RaiseDeadEffectHash, true);
}
public static bool IsSkeleton()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skeleton";
}
/// <summary>
/// Stamina from the tier's stand-in meals, for a Skeleton who feels fatigue but does not
/// eat. The fake foods cannot supply it: they are kept at m_time 0, so UpdateFood scales
/// their stamina to nothing on every tick.
/// </summary>
public static float GetStandInStamina(int state)
{
var foods = GetBestRealFoods(state);
float stamina = 0f;
if (foods != null)
{
foreach (var f in foods) stamina += f.m_shared.m_foodStamina;
}
return stamina;
}
private static readonly int StatsEffectHash = "SE_SkeletonStats".GetStableHashCode();
private float lastAuraTime = 0f;
private GameObject fireAuraVFX = null;
// The local player's burning skull. The build lives in SkeletonVisuals so that
// RacesVisualController can grow the same one on every remote skeleton - this script only
// ever sees the player at the keyboard, which is why nobody else could see the fire.
private readonly SkeletonVisuals.HeadFlame headFlame = new SkeletonVisuals.HeadFlame();
private static List<ItemDrop.ItemData>[] cachedRealFoods = new List<ItemDrop.ItemData>[9];
private static List<ItemDrop.ItemData> GetBestRealFoods(int state)
{
if (state < 1) state = 1;
if (state > 8) state = 8;
if (cachedRealFoods[state] != null) return cachedRealFoods[state];
if (ObjectDB.instance == null || ObjectDB.instance.m_items == null) return null;
float targetHealth = SkeletonProgression.GetMaxHealthBonus(state);
List<ItemDrop.ItemData> allFoods = new List<ItemDrop.ItemData>();
foreach (GameObject obj in ObjectDB.instance.m_items)
{
ItemDrop drop = obj.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && drop.m_itemData.m_shared.m_food > 0)
{
allFoods.Add(drop.m_itemData);
}
}
if (allFoods.Count < 3) return null;
float bestDiff = float.MaxValue;
float bestRegen = -1f;
List<ItemDrop.ItemData> bestCombo = null;
if (state == 8)
{
ItemDrop.ItemData f1 = null, f2 = null, f3 = null;
foreach(var drop in allFoods)
{
string n = drop.m_shared.m_name.ToLower();
string p = drop.m_dropPrefab != null ? drop.m_dropPrefab.name.ToLower() : "";
if (f1 == null && ((n.Contains("asksvin") && n.Contains("tail")) || (p.Contains("asksvin") && p.Contains("tail")))) f1 = drop;
else if (f2 == null && ((n.Contains("mashed") && n.Contains("meat")) || (p.Contains("mashed") && p.Contains("meat")))) f2 = drop;
else if (f3 == null && ((n.Contains("piquant") && n.Contains("pie")) || (p.Contains("piquant") && p.Contains("pie")))) f3 = drop;
}
if (f1 != null && f2 != null && f3 != null)
{
bestCombo = new List<ItemDrop.ItemData> { f1.Clone(), f2.Clone(), f3.Clone() };
}
}
if (bestCombo == null)
{
for (int i = 0; i < allFoods.Count; i++)
{
for (int j = i; j < allFoods.Count; j++)
{
for (int k = j; k < allFoods.Count; k++)
{
var f1 = allFoods[i];
var f2 = allFoods[j];
var f3 = allFoods[k];
float hpSum = f1.m_shared.m_food + f2.m_shared.m_food + f3.m_shared.m_food;
float regenSum = f1.m_shared.m_foodRegen + f2.m_shared.m_foodRegen + f3.m_shared.m_foodRegen;
float diff = Mathf.Abs(hpSum - targetHealth);
if (diff < bestDiff || (Mathf.Abs(diff - bestDiff) < 0.1f && regenSum > bestRegen))
{
bestDiff = diff;
bestRegen = regenSum;
bestCombo = new List<ItemDrop.ItemData> { f1.Clone(), f2.Clone(), f3.Clone() };
}
}
}
}
}
if (bestCombo != null)
{
float actualSum = 0f;
foreach(var c in bestCombo) actualSum += c.m_shared.m_food;
float scale = actualSum > 0f ? (targetHealth / actualSum) : 1f;
foreach(var c in bestCombo)
{
c.m_shared = (ItemDrop.ItemData.SharedData)typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(c.m_shared, null);
// Modificatore per scalare perfettamente gli HP
c.m_shared.m_food = c.m_shared.m_food * scale;
// Azzerare completamente l'Eitr e la Stamina
c.m_shared.m_foodEitr = 0f;
c.m_shared.m_foodStamina = 0f;
c.m_shared.m_foodBurnTime = 999999f;
}
}
cachedRealFoods[state] = bestCombo;
return bestCombo;
}
private void DumpTransformHierarchy(Transform t, string indent)
{
if (t == null) return;
Jotunn.Logger.LogInfo(indent + t.name + " (Active: " + t.gameObject.activeSelf + ")");
for(int i = 0; i < t.childCount; i++)
{
DumpTransformHierarchy(t.GetChild(i), indent + " ");
}
}
/// <summary>
/// F8 debug: fires a ray from the camera and logs whatever it hits. Cosmetic pieces
/// (hair, beard, helmet) carry no collider, so this mostly confirms terrain/creature hits
/// - LogHeadCosmeticsState below is what actually answers "what is that floating chunk."
/// Kept anyway because it is the general-purpose "what am I looking at" tool for any other
/// bone or prefab placement question that comes up later.
/// </summary>
private void LogRaycastHit()
{
Camera cam = Camera.main;
if (cam == null)
{
Jotunn.Logger.LogInfo("[F8] No camera found for raycast.");
return;
}
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, 50f))
{
Jotunn.Logger.LogInfo("--- F8 RAYCAST HIT ---");
Jotunn.Logger.LogInfo($"Collider: '{hit.collider.gameObject.name}' at {hit.point:F2}, distance={hit.distance:F2}");
Jotunn.Logger.LogInfo($"Full path: {GetFullPath(hit.collider.transform)}");
Renderer renderer = hit.collider.GetComponentInParent<Renderer>();
if (renderer != null)
{
Jotunn.Logger.LogInfo($"Nearest renderer: '{renderer.gameObject.name}' ({renderer.GetType().Name}), enabled={renderer.enabled}, scale={renderer.transform.lossyScale:F3}");
}
Jotunn.Logger.LogInfo("----------------------");
}
else
{
Jotunn.Logger.LogInfo("[F8] Raycast hit nothing within 50m (cosmetic pieces usually have no collider anyway).");
}
}
private static string GetFullPath(Transform t)
{
string path = t.name;
for (Transform parent = t.parent; parent != null; parent = parent.parent)
{
path = parent.name + "/" + path;
}
return path;
}
/// <summary>
/// F8 debug: dumps the exact state of the three item slots this race hides (hair, beard,
/// helmet) - active flag, renderer enabled flag and scale for every renderer underneath.
/// This is the direct answer to "what is still visible and why": a chunk that survives
/// hiding will show up here as active=true, or as a renderer with enabled=true even while
/// its wrapper is scaled to zero (the skinned-mesh case scale alone cannot hide).
/// </summary>
private void LogHeadCosmeticsState()
{
if (Player.m_localPlayer == null) return;
VisEquipment vis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (vis == null) return;
Jotunn.Logger.LogInfo("--- F8 SKELETON HEAD COSMETICS ---");
DumpItemInstanceField(vis, "m_hairItemInstance");
DumpItemInstanceField(vis, "m_beardItemInstance");
DumpItemInstanceField(vis, "m_helmetItemInstance");
Jotunn.Logger.LogInfo("----------------------------------");
}
private static void DumpItemInstanceField(VisEquipment vis, string fieldName)
{
GameObject go = HarmonyLib.Traverse.Create(vis).Field<GameObject>(fieldName).Value;
if (go == null)
{
Jotunn.Logger.LogInfo($"[F8] {fieldName}: null (nothing equipped/instantiated).");
return;
}
Jotunn.Logger.LogInfo($"[F8] {fieldName}: '{go.name}' active={go.activeSelf} scale={go.transform.localScale:F3}");
foreach (Renderer r in go.GetComponentsInChildren<Renderer>(true))
{
Jotunn.Logger.LogInfo($"[F8] renderer '{r.gameObject.name}' ({r.GetType().Name}) enabled={r.enabled}");
}
}
private void Update()
{
if (Player.m_localPlayer == null) return;
if (!IsSkeleton() || Player.m_localPlayer.IsDead())
{
// Everything the race puts on the player has to come off here, because this is the
// only path taken once they stop being one. A Fader-tier Skeleton who reset to
// Human kept a burning skull and a collapsed jaw, since neither the flame nor the
// jaw was ever switched back from outside the Skeleton branch below.
SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX);
headFlame.Apply(Player.m_localPlayer, false);
RestoreJawBone();
SetRaiseDeadIcon(Player.m_localPlayer, false);
if (Player.m_localPlayer.transform.localScale != Vector3.one)
{
Player.m_localPlayer.transform.localScale = Vector3.one;
}
return;
}
// Force hide hair and beard
var profile = Game.instance?.GetPlayerProfile();
if (profile != null)
{
var hair = HarmonyLib.Traverse.Create(profile).Field<string>("m_hairItem");
var beard = HarmonyLib.Traverse.Create(profile).Field<string>("m_beardItem");
if (!string.IsNullOrEmpty(hair.Value) || !string.IsNullOrEmpty(beard.Value))
{
hair.Value = "";
beard.Value = "";
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_hairItem").SetValue("");
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_beardItem").SetValue("");
VisEquipment vis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (vis != null)
{
// Since Valheim 1.0 these take an item hash, not a prefab name. 0 is the empty slot.
vis.SetHairItem(0);
vis.SetBeardItem(0);
}
}
}
// Undead Fortitude carries every one of the race's damage modifiers - the pierce and
// slash resistance, the weakness to blunt, and the poison immunity. It was applied in
// exactly one place: the moment the player clicked "Skeleton" in the race menu. Status
// effects are not saved with a character and do not survive death, so from the next
// respawn or the next login onward a Skeleton had none of them, which is why poison
// still landed at tiers that grant immunity. Put it back whenever it is missing.
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect(StatsEffectHash))
{
Player.m_localPlayer.GetSEMan().AddStatusEffect(StatsEffectHash, true);
}
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = SkeletonProgression.GetRules(state);
TickSummonToggle(Player.m_localPlayer, rules);
// Continuously adjust equipment
VisEquipment currentVis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (currentVis != null)
{
// Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull:
// a viking body wears its helmet, and the VisEquipment postfix puts it back.
// "Show Helmet" keeps it on the skull too, and is published for other clients.
SkeletonVisuals.PublishShowHelmet(Player.m_localPlayer);
if (SkeletonConfig.BodyModelEnabled.Value)
{
SkeletonVisuals.FitHelmet(Player.m_localPlayer, currentVis, SkeletonConfig.ShowHelmet.Value);
}
// Scale Body Armor (Chest, Legs, Shoulder) by 5%
string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" };
foreach (string field in armorFields)
{
var armorList = HarmonyLib.Traverse.Create(currentVis).Field<System.Collections.Generic.List<GameObject>>(field).Value;
if (armorList != null)
{
foreach (GameObject armor in armorList)
{
if (armor != null && Mathf.Abs(armor.transform.localScale.x - 1.05f) > 0.01f)
{
armor.transform.localScale = new Vector3(1.05f, 1.05f, 1.05f);
}
}
}
}
}
// Fader used to collapse this bone, because the charred twitcher it wore there carried
// a jaw of its own and the two doubled up. That model is gone from every tier now, and
// the skeleton worn in its place has a jaw that belongs on the face - so the tier lost
// its mandible for no reason at all. Kept as a restore so anyone left with a collapsed
// jaw by the old build gets it back.
RestoreJawBone();
// Apply Scale
Vector3 targetScale = rules.ScaleMultiplier;
if (Player.m_localPlayer.transform.localScale != targetScale)
{
Player.m_localPlayer.transform.localScale = targetScale;
}
// Ensure ZDO is synced for visuals
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkeletonState", state);
// The saved look goes on the ZDO so everyone else sees the same body.
Player.m_localPlayer.m_customData.TryGetValue(SkeletonVisuals.LookDataKey, out string savedLook);
savedLook = savedLook ?? "";
if (nview.GetZDO().GetString(SkeletonVisuals.LookZdoKey, "") != savedLook)
{
nview.GetZDO().Set(SkeletonVisuals.LookZdoKey, savedLook);
}
}
// Manage Fake Foods
var foods = Player.m_localPlayer.GetFoods();
bool needsFood = false;
if (SkeletonConfig.EatsMortalFood.Value)
{
// Real meals instead. The stand-in foods are the ones held at m_time 0 or below;
// dropped here at once rather than left for UpdateFood, which would announce each
// one as "food done".
foods.RemoveAll(f => f.m_time <= 0f);
}
else if (foods.Count != 3)
{
needsFood = true;
}
else
{
foreach(var food in foods)
{
food.m_time = 0f; // Always reset time so they never degrade!
}
float expectedHp = 0f;
var expectedFoods = GetBestRealFoods(state);
if (expectedFoods != null)
{
foreach(var f in expectedFoods) expectedHp += f.m_shared.m_food;
}
float currentHp = 0f;
foreach(var food in foods)
{
if (food.m_item != null && food.m_item.m_shared != null)
currentHp += food.m_item.m_shared.m_food;
}
if (Mathf.Abs(currentHp - expectedHp) > 1f)
{
needsFood = true;
}
}
if (needsFood)
{
Player.m_localPlayer.ClearFood();
var newDiet = GetBestRealFoods(state);
if (newDiet != null)
{
foreach (var dietItem in newDiet)
{
Player.Food newFood = new Player.Food();
newFood.m_name = dietItem.m_dropPrefab != null ? dietItem.m_dropPrefab.name : "";
newFood.m_item = dietItem;
newFood.m_health = dietItem.m_shared.m_food;
newFood.m_stamina = dietItem.m_shared.m_foodStamina;
newFood.m_eitr = dietItem.m_shared.m_foodEitr;
newFood.m_time = 0f;
foods.Add(newFood);
}
}
}
// Enhanced Health Regeneration. The multiplier itself now lives on the status effect,
// which sets it on the live instance - writing it here only ever reached the template
// SEMan clones from, so it changed nothing for the player. What stays here is the tick
// rate, which is the player's own field.
if (rules.EnhancedRegen)
{
float currentTimer = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<float>("m_foodRegenTimer").Value;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_foodRegenTimer").SetValue(currentTimer + Time.deltaTime * SkeletonConfig.EnhancedRegenTickSpeedBonus.Value);
}
// Flames on the skull, worn with the fire-tier model and nothing else.
headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel);
if (rules.FireAura)
{
SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, true, ref fireAuraVFX);
if (Time.time - lastAuraTime >= SkeletonConfig.FireAuraTickInterval.Value)
{
ApplyFireAura();
lastAuraTime = Time.time;
}
}
else
{
SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX);
}
}
/// <summary>
/// Puts the player's jaw back if anything collapsed it. Safe to call every frame and for
/// any race - it does nothing unless the bone is actually at zero scale.
/// </summary>
private static void RestoreJawBone()
{
VisEquipment vis = Player.m_localPlayer != null
? Player.m_localPlayer.GetComponent<VisEquipment>()
: null;
if (vis == null || vis.m_bodyModel == null || vis.m_bodyModel.bones == null) return;
foreach (Transform bone in vis.m_bodyModel.bones)
{
if (bone == null || !bone.name.ToLower().Contains("jaw")) continue;
if (bone.localScale == Vector3.zero) bone.localScale = Vector3.one;
break;
}
}
private void ApplyFireAura()
{
if (Player.m_localPlayer == null) return;
Vector3 center = Player.m_localPlayer.transform.position;
float radius = SkeletonConfig.FireAuraRadius.Value;
HitData hitData = new HitData();
hitData.m_damage.m_fire = SkeletonConfig.FireAuraDamagePerTick.Value;
hitData.SetAttacker(Player.m_localPlayer);
hitData.m_dir = Vector3.zero;
int hits = 0;
foreach (Collider collider in Physics.OverlapSphere(center, radius))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && character != Player.m_localPlayer && BaseAI.IsEnemy(Player.m_localPlayer, character))
{
character.Damage(hitData);
hits++;
}
}
}
}
}