RacesOfValheim/JotunnModStub/Furling/FurlingCrops.cs
kanym 916ba5bd6f fix(pieces): placement ghost vanished off terrain for most stations
Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches
the ghost off outright and returns whenever the aim is not on a
Heightmap, which vanilla means for hoe and cultivator pieces. Floors,
rocks and a troll cave's mesh floor are not a Heightmap, so players
saw no ghost at all there, and with either flag Valheim never shows
the blue placement marker. Reported for the Trol War Totem.

m_groundPiece is off everywhere now. The stations (War Totem, Cursed
Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone
Servants) drop m_groundOnly too and go on floors, foundations and in
caves, like the Bone Pile since 1.5.8. The living pieces (Furling
bushes, Sverm nest and Hive Market, Trenta Elder Root) keep
m_groundOnly: terrain only, and the ghost shows red elsewhere.
2026-10-17 15:59:08 +02:00

553 lines
26 KiB
C#

using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Furling's itemization: five things only a Fuling Shaman will sell, and the two chains
/// they open.
///
/// Copper / Tin / Iron Flax -> plant, harvest, mill -> Copper / Tin / Iron Dust
/// -> smelt -> the metal itself
/// Stoneberry / Flintberry -> plant -> a bush that yields Stone / Flint
/// forever
///
/// No new station: both `windmill` and `smelter` are <see cref="Smelter"/> components (the class
/// even carries an m_windmill field to drive the blades), so all six steps are appends to a
/// conversion list - the same trick AswidBloodPotions uses on the fermenter. Every vanilla
/// recipe in both machines keeps working.
///
/// Two rules that came from the design conversation and are load-bearing:
/// - the FLAX travels through portals, the DUST does not. The dust copies the weight, stack
/// size and teleportability of the ore it becomes, so "behaves exactly like raw ore" is not
/// an approximation - it is read off that ore at registration.
/// - the flax yields what real flax yields and scales with the world modifiers the same way,
/// which is achieved by cloning Pickable_Flax and then NOT touching a single one of its
/// yield fields. See RegisterCrop.
/// </summary>
public static class FurlingCrops
{
// Prices are NOT here: they live with the rest of the shop data, in
// FactionMerchantCatalog.GoblinShamanShop. The benches are symmetric, so each figure there is
// both what the Shaman charges and what it pays.
private class MetalCrop
{
public string Metal; // "Copper" - display only
public string FlaxName;
public string FlaxDisplay;
public string DustName;
public string DustDisplay;
public string PickableName;
public string SaplingName;
public string SaplingDisplay;
/// <summary>
/// The vanilla raw ore this dust stands in for. Used for three things and never as an
/// output name: the dust's weight/stack/teleport flags, its borrowed icon, and looking up
/// what the vanilla smelter already turns that ore into.
/// </summary>
public string OrePrefab;
public Color Tint;
// Filled in during registration so the conversions can be wired from the objects we
// just built, rather than from ObjectDB - which has not been populated yet at
// CreateModAssets time. Same reason AswidBloodPotions passes GameObjects around.
public GameObject FlaxPrefab;
public GameObject DustPrefab;
}
private static readonly MetalCrop[] Crops =
{
new MetalCrop
{
Metal = "Copper", FlaxName = "CopperFlax", FlaxDisplay = "$rov_item_furling_copperflax_name",
DustName = "CopperDust", DustDisplay = "$rov_item_furling_copperdust_name",
PickableName = "Pickable_CopperFlax", SaplingName = "sapling_copperflax",
SaplingDisplay = "$rov_piece_furling_copperflaxsapling_name", OrePrefab = "CopperOre",
Tint = new Color(0.72f, 0.45f, 0.20f, 1f),
},
new MetalCrop
{
Metal = "Tin", FlaxName = "TinFlax", FlaxDisplay = "$rov_item_furling_tinflax_name",
DustName = "TinDust", DustDisplay = "$rov_item_furling_tindust_name",
PickableName = "Pickable_TinFlax", SaplingName = "sapling_tinflax",
SaplingDisplay = "$rov_piece_furling_tinflaxsapling_name", OrePrefab = "TinOre",
Tint = new Color(0.80f, 0.82f, 0.85f, 1f),
},
new MetalCrop
{
Metal = "Iron", FlaxName = "IronFlax", FlaxDisplay = "$rov_item_furling_ironflax_name",
DustName = "IronDust", DustDisplay = "$rov_item_furling_irondust_name",
PickableName = "Pickable_IronFlax", SaplingName = "sapling_ironflax",
// Iron's raw form is IronScrap, not "IronOre" - there is no IronOre prefab.
SaplingDisplay = "$rov_piece_furling_ironflaxsapling_name", OrePrefab = "IronScrap",
Tint = new Color(0.35f, 0.36f, 0.38f, 1f),
},
};
private class RockBerry
{
public string BerryName;
public string BerryDisplay;
public string BushName; // the cultivator entry AND the bush - one prefab
public string BushDisplay;
public string YieldPrefab; // what the bush gives instead of fruit
public Color Tint;
}
private static readonly RockBerry[] Berries =
{
new RockBerry
{
BerryName = "Stoneberry", BerryDisplay = "$rov_item_furling_stoneberry_name",
BushName = "StoneberryBush", BushDisplay = "$rov_piece_furling_stoneberrybush_name",
YieldPrefab = "Stone", Tint = new Color(0.55f, 0.55f, 0.55f, 1f),
},
new RockBerry
{
BerryName = "Flintberry", BerryDisplay = "$rov_item_furling_flintberry_name",
BushName = "FlintberryBush", BushDisplay = "$rov_piece_furling_flintberrybush_name",
YieldPrefab = "Flint", Tint = new Color(0.30f, 0.32f, 0.35f, 1f),
},
};
/// <summary>
/// The description token that goes with a name token: "$rov_item_furling_tinflax_name" gives
/// "$rov_item_furling_tinflax_desc". One whole sentence per crop in the translation files,
/// rather than one sentence with the metal dropped in, so a translator can decline the metal
/// or move it wherever their language wants it.
/// </summary>
private static string DescriptionFor(string nameToken)
{
return nameToken.EndsWith("_name") ? nameToken.Substring(0, nameToken.Length - 5) + "_desc" : nameToken;
}
public static void Register()
{
foreach (MetalCrop crop in Crops) RegisterCrop(crop);
foreach (RockBerry berry in Berries) RegisterBerry(berry);
AddConversions();
}
// ---------------------------------------------------------------- metal flax
private static void RegisterCrop(MetalCrop crop)
{
crop.FlaxPrefab = BuildFlax(crop);
crop.DustPrefab = BuildDust(crop);
// Order matters: the sapling's Plant has to point at a pickable that already exists.
GameObject pickable = BuildGrownFlax(crop);
BuildSapling(crop, pickable);
}
private static GameObject BuildFlax(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.FlaxName, "Flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Flax; {crop.FlaxDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = crop.FlaxDisplay;
shared.m_description = DescriptionFor(crop.FlaxDisplay);
// Teleportable is inherited from Flax and left alone on purpose: the flax travels, the
// dust does not. That asymmetry is the whole point of the chain.
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
private static GameObject BuildDust(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.DustName, "BarleyFlour");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone BarleyFlour; {crop.DustDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = crop.DustDisplay;
shared.m_description = DescriptionFor(crop.DustDisplay);
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_consumeStatusEffect = null;
// "Behaves exactly like raw ore of that type", read off the ore instead of invented:
// its weight, its stack size, and - the one that matters - its refusal to teleport.
ItemDrop.ItemData.SharedData ore = SharedOf(crop.OrePrefab);
if (ore != null)
{
shared.m_weight = ore.m_weight;
shared.m_maxStackSize = ore.m_maxStackSize;
shared.m_teleportable = ore.m_teleportable;
}
else
{
Jotunn.Logger.LogWarning($"[Furling] No '{crop.OrePrefab}' to copy ore behaviour from; " +
$"{crop.DustDisplay} falls back to blocking teleport only.");
shared.m_teleportable = false;
}
// The tint reaches the sack model but never the inventory icon - icons are atlas sprites
// and repainting one produces an empty slot, learned the hard way on the Aswid's Blood
// Essence. Three identical flour sacks in the inventory would be unusable, so the dusts
// borrow their ore's icon: it reads as "this is copper" at a glance, at the cost of not
// looking like flour.
Sprite icon = BorrowIcon(crop.OrePrefab);
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
/// <summary>
/// The harvestable stage. Cloned from Pickable_Flax and then deliberately left alone except
/// for what it drops: m_amount, m_minAmountScaled, m_dontScale and m_respawnTimeMinutes all
/// come across untouched, which is exactly how "yields what a real flax plant yields and
/// reacts to the world modifiers like a real plant" is satisfied. Writing our own numbers
/// here is the one thing that would break that.
///
/// Not a piece and not in any table - it only ever exists as the Plant's grown prefab - so it
/// is registered straight into ZNetScene with AddPrefab. That call is the thing to check in
/// the log on the first run: without it the sapling would grow into nothing.
/// </summary>
private static GameObject BuildGrownFlax(MetalCrop crop)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.PickableName, "Pickable_Flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Pickable_Flax; grown {crop.FlaxDisplay} not registered.");
return null;
}
Recolour(prefab, crop.Tint);
Pickable pickable = prefab.GetComponent<Pickable>();
if (pickable == null)
{
Jotunn.Logger.LogWarning($"[Furling] {crop.PickableName} has no Pickable; it will drop nothing.");
}
else if (crop.FlaxPrefab != null)
{
pickable.m_itemPrefab = crop.FlaxPrefab;
pickable.m_overrideName = crop.FlaxDisplay;
}
PrefabManager.Instance.AddPrefab(prefab);
return prefab;
}
private static void BuildSapling(MetalCrop crop, GameObject grown)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(crop.SaplingName, "sapling_flax");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone sapling_flax; {crop.SaplingDisplay} not plantable.");
return;
}
Recolour(prefab, crop.Tint);
Plant plant = prefab.GetComponent<Plant>();
if (plant != null && grown != null)
{
plant.m_grownPrefabs = new[] { grown };
plant.m_name = crop.SaplingDisplay;
// m_growTime, m_biome, m_needCultivatedGround and the rest stay as real flax's: the
// special strains are still flax, still Plains, still want tilled ground.
}
Piece piece = prefab.GetComponent<Piece>();
if (piece != null)
{
piece.m_name = crop.SaplingDisplay;
piece.m_resources = new Piece.Requirement[0];
}
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = crop.SaplingDisplay,
Description = DescriptionFor(crop.SaplingDisplay),
PieceTable = PieceTables.Cultivator,
Requirements = new[] { new RequirementConfig(crop.FlaxName, 1, 0, true) },
}));
}
// ---------------------------------------------------------------- rock berries
private static void RegisterBerry(RockBerry berry)
{
BuildBerry(berry);
BuildBush(berry);
}
private static GameObject BuildBerry(RockBerry berry)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(berry.BerryName, "Cloudberry");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone Cloudberry; {berry.BerryDisplay} not registered.");
return null;
}
Recolour(prefab, berry.Tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return null;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = berry.BerryDisplay;
shared.m_description = DescriptionFor(berry.BerryDisplay);
// Inedible, as designed. Material with every food value at zero also keeps it clear of
// the Trenta's vegan check and of the Aswid/Skeleton food gates, all three of which only
// look at consumables that carry food values.
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodEitr = 0f;
shared.m_foodBurnTime = 0f;
shared.m_foodRegen = 0f;
shared.m_consumeStatusEffect = null;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
return prefab;
}
/// <summary>
/// The bush: one prefab, cloned from CloudberryBush and nothing else. It is already a Pickable
/// that regrows its fruit on a timer forever, so "once planted they regrow forever, exactly
/// like normal plants" needs nothing added - only the fruit swapped for Stone or Flint. The
/// respawn timer, the amount and the world-modifier scaling all come across untouched, the
/// same way the flax's do.
///
/// There is no growth stage and no second prefab. The first version of this did the same and
/// showed up in the cultivator as a blank square; the fix for that is the two lines marked
/// below, not a different base prefab. An attempt in between cloned sapling_flax for the
/// plantable stage, which did produce a working button - and put a grey flax sprout in the
/// middle of a chain that is supposed to be cloudberry all the way down. Reverted.
/// </summary>
private static void BuildBush(RockBerry berry)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(berry.BushName, "CloudberryBush");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Furling] Could not clone CloudberryBush; {berry.BushDisplay} not registered.");
return;
}
Recolour(prefab, berry.Tint);
Pickable pickable = prefab.GetComponent<Pickable>();
GameObject yield = PrefabManager.Cache.GetPrefab<GameObject>(berry.YieldPrefab);
if (pickable == null || yield == null)
{
Jotunn.Logger.LogWarning($"[Furling] {berry.BushName}: no Pickable or no '{berry.YieldPrefab}'; it will drop nothing.");
}
else
{
pickable.m_itemPrefab = yield;
pickable.m_overrideName = berry.BushDisplay;
}
// CloudberryBush is world scenery, so it carries no Piece and cannot be built. Adding one
// is what puts it in the cultivator, and the two things a Piece added this way is missing
// are an icon - the sprite the build menu draws, whose absence is why the entry was there
// but invisible - and a placement effect. Both are supplied below.
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_name = berry.BushDisplay;
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_canBeRemoved = true;
// Terrain only, as a living thing should be - but through m_groundOnly alone, which shows
// the ghost red off the terrain. m_groundPiece switched the ghost off outright there
// (Player.UpdatePlacementGhost), and players saw nothing at all.
piece.m_groundPiece = false;
piece.m_groundOnly = true;
piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil
piece.m_icon = BorrowIcon(berry.YieldPrefab);
// Borrowed from a real cultivator entry so planting one looks and sounds like planting
// anything else. Only the effect list is taken - never the model, never the Plant.
Piece template = PrefabManager.Cache.GetPrefab<Piece>("sapling_flax");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = berry.BushDisplay,
Description = DescriptionFor(berry.BushDisplay),
PieceTable = PieceTables.Cultivator,
// The one thing that was actually missing the first time round.
Icon = BorrowIcon(berry.YieldPrefab),
Requirements = new[] { new RequirementConfig(berry.BerryName, 1, 0, true) },
}));
}
// ---------------------------------------------------------------- conversions
/// <summary>
/// Six appends, three to the windmill and three to the smelter. Both are Smelter components,
/// so this is the same shape as AswidBloodPotions.AddFermenterConversion, and for the same
/// reason: the vanilla list is appended to, never replaced, so barley still becomes flour and
/// ore still becomes metal.
/// </summary>
private static void AddConversions()
{
Smelter mill = SmelterOn("windmill");
Smelter furnace = SmelterOn("smelter");
foreach (MetalCrop crop in Crops)
{
ItemDrop flax = DropOf(crop.FlaxPrefab);
ItemDrop dust = DropOf(crop.DustPrefab);
if (flax == null || dust == null) continue;
AddConversion(mill, "windmill", flax, dust);
// The output is never named: whatever the vanilla furnace already makes from this
// ore is what the dust makes too. That is also the answer to "is the bar called
// Copper or CopperIngot" - it does not matter, because it is copied, not typed.
ItemDrop metal = OutputFor(furnace, crop.OrePrefab);
if (metal == null)
{
Jotunn.Logger.LogWarning($"[Furling] The smelter has no conversion from '{crop.OrePrefab}'; " +
$"{crop.DustDisplay} cannot be smelted.");
continue;
}
AddConversion(furnace, "smelter", dust, metal);
}
}
private static Smelter SmelterOn(string piecePrefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(piecePrefabName);
Smelter smelter = prefab != null ? prefab.GetComponent<Smelter>() : null;
if (smelter == null)
{
Jotunn.Logger.LogWarning($"[Furling] No Smelter on '{piecePrefabName}'; its half of the chain is dead.");
}
return smelter;
}
/// <summary>What the machine already turns the named input into, or null.</summary>
private static ItemDrop OutputFor(Smelter smelter, string fromPrefabName)
{
if (smelter == null || smelter.m_conversion == null) return null;
foreach (Smelter.ItemConversion conversion in smelter.m_conversion)
{
if (conversion == null || conversion.m_from == null || conversion.m_to == null) continue;
if (conversion.m_from.gameObject.name == fromPrefabName) return conversion.m_to;
}
return null;
}
private static void AddConversion(Smelter smelter, string label, ItemDrop from, ItemDrop to)
{
if (smelter == null || from == null || to == null) return;
if (smelter.m_conversion == null) smelter.m_conversion = new List<Smelter.ItemConversion>();
foreach (Smelter.ItemConversion existing in smelter.m_conversion)
{
if (existing != null && existing.m_from == from) return; // already taught
}
smelter.m_conversion.Add(new Smelter.ItemConversion { m_from = from, m_to = to });
Jotunn.Logger.LogInfo($"[Furling] {label}: {from.m_itemData.m_shared.m_name} -> {to.m_itemData.m_shared.m_name}.");
}
// ---------------------------------------------------------------- known recipes
/// <summary>
/// Teaches the five new cultivator entries, the same way RaceMenuWard, the Blood Refinery and
/// the Composter all had to be taught: a piece registered after the vanilla learning pass
/// never reaches its table on its own. The purchased item is still the real gate - the entry
/// just sits greyed out until one is owned.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null) return;
HarmonyLib.Traverse traverse = HarmonyLib.Traverse.Create(player);
bool taught = false;
foreach (MetalCrop crop in Crops) taught |= Teach(traverse, crop.SaplingName);
foreach (RockBerry berry in Berries) taught |= Teach(traverse, berry.BushName);
if (taught) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static bool Teach(HarmonyLib.Traverse traverse, string piecePrefabName)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(piecePrefabName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return false;
traverse.Method("AddKnownPiece", piece).GetValue();
return true;
}
// ---------------------------------------------------------------- helpers
private static ItemDrop DropOf(GameObject prefab) => prefab != null ? prefab.GetComponent<ItemDrop>() : null;
private static ItemDrop.ItemData.SharedData SharedOf(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null;
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop.ItemData.SharedData shared = SharedOf(prefabName);
Sprite[] icons = shared != null ? shared.m_icons : null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Furling] Could not borrow the icon from '{prefabName}'.");
return null;
}
/// <summary>
/// renderer.materials instantiates a copy, so real flax, real flour, real cloudberries and
/// the real cloudberry bushes of the world all keep their own look. Particle renderers are
/// skipped - painting them just turns the effect into soot.
/// </summary>
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || 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);
}
}
}
}
}