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