RacesOfValheim/JotunnModStub/Trenta/TrentaFoodPatches.cs
Ferdinando d0ed92c553 feat(trenta): add the Trenta race
A vegan, tree-born race unlocking new perks per boss defeated: skin/hair
tint, blocked non-vegan food, awakened seed foods after Eikthyr, a mob
hostility list, Photosynthesis, elemental resistances, Purple Rain after
the Elder, swim/poison/wet immunity after Bonemass, Last Stand and Thorns
after Moder, a Homecoming Portal after Yagluth, Hornet's Nest after the
Queen, and Muspell (a half-size Elder transformation with Stomp/Spike
attacks) after Fader.

Also fixes RaceScale never listing Trenta as self-sizing, which let a
shared Player.Update postfix fight Muspell's own scale changes every
frame.
2026-08-04 20:58:01 +02:00

205 lines
10 KiB
C#

using HarmonyLib;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every hook the Trenta's diet needs. Mirrors DraughFoodPatches.cs - the Draugh's own
/// "restricted diet" file - closely enough that the two are worth reading side by side:
/// the Draugh only eats raw flesh and swaps a raw material for a custom edible on the spot;
/// the Trenta only eats plants and, after Eikthyr falls, does the same raw-material swap for
/// every seed, cone, acorn and self-seeding mushroom in the game.
/// </summary>
public static class TrentaFoodPatches
{
// Awakened-seed foods go through Player.EatFood the same way Draugh's EdibleUncooked_
// items do: called directly from inside a UseItem prefix rather than through the normal
// right-click flow. Native EatFood's own duplicate-slot handling does not reliably
// refresh a food added this way, so - exactly as DraughFoodPatches.hiddenFoods does -
// any existing slot with a matching name is pulled out of m_foods before the call and
// put back afterwards, forcing EatFood to always see room for a fresh entry.
private static List<object> hiddenFoods = new List<object>();
/// <summary>
/// Blocks a Trenta from eating anything that is not vegan, and - once Eikthyr is dead -
/// turns eating a raw seed, cone, acorn or self-seeding mushroom into eating the dish it
/// awakens into instead.
///
/// The seed check runs first and, if it matches, owns the whole outcome: before Eikthyr
/// it falls through to normal item behaviour (a seed has nothing to do with the vegan
/// check below, it isn't food yet), and after Eikthyr it always returns false, win or
/// lose, because a failed eat should not fall through into planting the seed instead.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Trenta_Humanoid_UseItem_Patch
{
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 (!TrentaRace.IsTrenta()) return true;
if (item == null || item.m_dropPrefab == null) return true;
string prefabName = item.m_dropPrefab.name;
if (TrentaConfig.AwakenedSeedFoodByRawPrefab.TryGetValue(prefabName, out TrentaConfig.AwakenedSeedFood seedFood))
{
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.EikthyrDefeatedState)
{
return true; // Not woken yet - let the seed behave normally (i.e. plant it)
}
GameObject customPrefab = ObjectDB.instance.GetItemPrefab(seedFood.AwakenedPrefabName);
if (customPrefab == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Missing awakened seed prefab: {seedFood.AwakenedPrefabName}");
return true;
}
ItemDrop customDrop = customPrefab.GetComponent<ItemDrop>();
if (customDrop == null) return true;
bool ate = player.EatFood(customDrop.m_itemData);
if (ate)
{
inventory.RemoveItem(item, 1);
var consumeEffects = Traverse.Create(player).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null) consumeEffects.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
}
return false; // Skip native UseItem either way
}
if (item.m_shared == null) return true;
bool isFood = item.m_shared.m_food > 0f || item.m_shared.m_foodStamina > 0f || item.m_shared.m_foodEitr > 0f;
if (!isFood) return true;
if (TrentaConfig.VeganFoodPrefabNames.Contains(prefabName)) return true;
player.Message(MessageHud.MessageType.Center, "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey.");
return false; // Block consumption
}
}
/// <summary>
/// Doubles the digestion time of whatever vegan food a Trenta just ate - the whitelisted
/// vanilla dishes and the awakened seed foods alike.
///
/// item.m_shared is a reference shared by every instance of that food across every
/// player - the same fact SkeletonRace.GetBestRealFoods works around when it scales a
/// food's HP. Multiplying m_foodBurnTime on it directly would double the duration for
/// every race eating a Carrot soup, not just the Trenta. So this clones the item, then
/// MemberwiseClones m_shared off of that clone, and only then doubles the burn time -
/// the clone is what Player.EatFood goes on to store in m_foods, the original prefab
/// data is never touched.
///
/// A Prefix rather than a Postfix because the doubled burn time has to be in place
/// *before* EatFood builds the Food entry it puts in m_foods; a Postfix would be
/// rewriting state EatFood had already finished computing from the old value.
/// </summary>
[HarmonyPatch(typeof(Player), "EatFood")]
public static class Trenta_Player_EatFood_Patch
{
public static void Prefix(Player __instance, ref ItemDrop.ItemData item)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!TrentaRace.IsTrenta()) return;
if (item == null || item.m_dropPrefab == null) return;
string prefabName = item.m_dropPrefab.name;
bool isDietFood = TrentaConfig.VeganFoodPrefabNames.Contains(prefabName)
|| prefabName.StartsWith(TrentaConfig.AwakenedSeedPrefabPrefix);
if (!isDietFood) return;
ItemDrop.ItemData doubled = item.Clone();
doubled.m_shared = (ItemDrop.ItemData.SharedData)typeof(object)
.GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(doubled.m_shared, null);
doubled.m_shared.m_foodBurnTime *= TrentaConfig.FoodDurationMultiplier;
item = doubled;
}
}
/// <summary>
/// The duplicate-slot workaround an awakened seed food needs because it is handed to
/// EatFood directly from the UseItem prefix above rather than through the native
/// right-click path - see DraughFoodPatches.EatFood_Prefix/Postfix for the original of
/// this exact trick and why it exists. Scoped to awakened-seed prefabs only: the 21
/// whitelisted vanilla foods already go through native UseItem normally and have never
/// needed this.
/// </summary>
[HarmonyPatch(typeof(Player), "EatFood")]
public static class Trenta_Player_EatFood_DuplicateGuard_Patch
{
public static bool Prefix(Player __instance, ItemDrop.ItemData item)
{
hiddenFoods.Clear();
if (__instance != Player.m_localPlayer || !TrentaRace.IsTrenta()) return true;
if (item == null || item.m_dropPrefab == null) return true;
if (!item.m_dropPrefab.name.StartsWith(TrentaConfig.AwakenedSeedPrefabPrefix)) return true;
var m_foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods == null) return true;
if (m_foods.Count >= 3)
{
foreach (object foodObj in m_foods)
{
Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{
f.m_time = 0f;
f.m_item = item.Clone();
var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
return false; // Refreshed ourselves - skip native EatFood
}
}
return false; // Full, and nothing to refresh
}
// Temporarily hide any existing slot with the same name to force native EatFood
// to add a fresh entry instead of trying (and failing) to extend this one.
for (int i = m_foods.Count - 1; i >= 0; i--)
{
var foodObj = m_foods[i];
var foodItem = Traverse.Create(foodObj).Field("m_item").GetValue<ItemDrop.ItemData>();
if (foodItem != null && foodItem.m_shared.m_name == item.m_shared.m_name)
{
hiddenFoods.Add(foodObj);
m_foods.RemoveAt(i);
}
}
return true;
}
public static void Postfix(Player __instance)
{
if (hiddenFoods.Count == 0) return;
var m_foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)
{
foreach (var h in hiddenFoods) m_foods.Add(h);
}
hiddenFoods.Clear();
}
}
}
}