feat(aswid): blood refinery and blood potions

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Ferdinando 2026-08-07 17:02:34 +02:00
commit fae82162be
5 changed files with 1185 additions and 7 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,9 +24,13 @@ namespace RacesOfValheim
{ "Leech", "TrophyLeech" },
{ "Hatchling", "TrophyHatchling" },
{ "Lox", "TrophyLox" },
{ "Fuling", "TrophyGoblin" },
{ "FulingShaman", "TrophyGoblinShaman" },
{ "FulingBerserker", "TrophyGoblinBrute" },
// 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" },
{ "Hare", "TrophyHare" },
{ "Seeker", "TrophySeeker" },
@ -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,7 +142,10 @@ namespace RacesOfValheim
{
float foodHp = Mathf.Min(c.m_health / 2f, 150f);
float burnTime = c.m_health * 2f;
if (mobName == "Cultist" || mobName.StartsWith("Fenring") || mobName.StartsWith("Fuling"))
// 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.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));
}
}
}