RacesOfValheim/JotunnModStub/Aswid/AswidBloodRefinery.cs
2026-09-24 10:30:39 +02:00

576 lines
27 KiB
C#

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;
// Crossed on purpose: the sounds sit the other way round from the slots. The ore
// effect is the dry clatter and the fuel effect the wet slap, so flesh takes the
// fuel one and bone the ore one.
refinery.m_meatAddedEffects = smelter.m_fuelAddedEffects;
refinery.m_boneAddedEffects = smelter.m_oreAddedEffects;
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 + ".fuelAdded");
SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".oreAdded");
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;
}
}
}