Merge branch 'feat-dvergar-cheap-pieces'

This commit is contained in:
kanym 2026-11-05 12:42:22 +01:00
commit 446fcc7327
2 changed files with 288 additions and 0 deletions

View file

@ -0,0 +1,275 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// A Dvergar builds the black marble and Yggdrasil wood building pieces with stone and fine
/// wood (Wargles' suggestion). Only structural pieces: stations, furniture, containers and
/// fires keep their cost, so nothing with a progression role gets cheaper.
///
/// The swap is done on the piece prefabs of the Dvergar's own client. The build menu, the
/// "known piece" check and ConsumeResources all read the prefab's m_resources, so the menu
/// lists the pieces once stone or fine wood is known, and the player pays the swapped cost.
///
/// The refund is the catch. Piece.DropResources gives back whatever m_resources says on the
/// machine that destroys the piece; vanilla never records what was paid. Without help a human
/// deconstructing a Dvergar's stone wall would get black marble, and a Dvergar deconstructing a
/// vanilla wall would get stone. So a cheap piece is tagged on its ZDO when placed, with the
/// ratios it was paid at, and DropResources is given the matching cost on every client.
/// </summary>
public static class DvergarCheapBuilding
{
// The ratios a cheap piece was paid at. Absent (0) on every piece placed at full cost.
public const string StoneRatioZdoKey = "RacesOfValheim_DvergarCheapStone";
public const string WoodRatioZdoKey = "RacesOfValheim_DvergarCheapWood";
private const string BlackMarble = "BlackMarble";
private const string YggdrasilWood = "YggdrasilWood";
private const string Stone = "Stone";
private const string FineWood = "FineWood";
private const string LabelName = "rov_dvergar_cheap";
private const Piece.UsageTagFlags StructuralTags =
Piece.UsageTagFlags.Building | Piece.UsageTagFlags.Floor | Piece.UsageTagFlags.Wall |
Piece.UsageTagFlags.Roof | Piece.UsageTagFlags.Architecture | Piece.UsageTagFlags.Stairs |
Piece.UsageTagFlags.Doors;
// Piece prefab name -> its vanilla cost. Collected once and kept: the prefabs live for the
// whole session, and the originals must survive every swap.
private static Dictionary<string, Piece.Requirement[]> originals;
private static Dictionary<string, Piece> prefabs;
private static ItemDrop stoneItem, fineWoodItem;
// "" while the prefabs carry their vanilla cost, otherwise the ratios they were swapped at.
private static string appliedKey = "";
private static bool Collect()
{
if (originals != null) return true;
if (ObjectDB.instance == null) return false;
GameObject hammer = ObjectDB.instance.GetItemPrefab("Hammer");
PieceTable table = hammer != null ? hammer.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces : null;
stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent<ItemDrop>();
fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent<ItemDrop>();
if (table == null || stoneItem == null || fineWoodItem == null) return false;
originals = new Dictionary<string, Piece.Requirement[]>();
prefabs = new Dictionary<string, Piece>();
foreach (GameObject go in table.m_pieces)
{
Piece piece = go != null ? go.GetComponent<Piece>() : null;
if (piece == null || piece.m_resources == null || !UsesSwappedMaterial(piece) || !IsBuildingPiece(piece)) continue;
originals[go.name] = piece.m_resources;
prefabs[go.name] = piece;
// The list to read once in game: every piece that changes cost, and where it is built.
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {go.name} at {(piece.m_craftingStation != null ? piece.m_craftingStation.name : "no station")}, {Describe(piece.m_resources)} -> {Describe(BuildCheap(piece.m_resources, 3, 2))} (at 3/2)");
}
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {originals.Count} pieces.");
return true;
}
private static bool UsesSwappedMaterial(Piece piece)
{
foreach (Piece.Requirement req in piece.m_resources)
{
if (req.m_resItem == null) continue;
string name = req.m_resItem.name;
if (name == BlackMarble || name == YggdrasilWood) return true;
}
return false;
}
private static bool IsBuildingPiece(Piece piece)
{
bool structural = piece.m_category == Piece.PieceCategory.BuildingWorkbench
|| piece.m_category == Piece.PieceCategory.BuildingStonecutter
|| (piece.m_usage & StructuralTags) != 0;
if (!structural) return false;
if ((piece.m_usage & Piece.UsageTagFlags.Crafting) != 0) return false;
// Anything that does a job keeps its cost, whatever its tags say.
return piece.GetComponentInChildren<CraftingStation>() == null
&& piece.GetComponentInChildren<StationExtension>() == null
&& piece.GetComponentInChildren<Container>() == null
&& piece.GetComponentInChildren<Fireplace>() == null
&& piece.GetComponentInChildren<Smelter>() == null
&& piece.m_comfort <= 0;
}
/// <summary>
/// The cost with black marble and Yggdrasil wood swapped out. New Requirement objects
/// throughout: the originals are shared with the prefab and must stay untouched. A
/// material the piece already had (some marble pieces also ask for stone) is merged.
/// </summary>
private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
{
var result = new List<Piece.Requirement>();
foreach (Piece.Requirement req in original)
{
ItemDrop item = req.m_resItem;
int amount = req.m_amount;
if (item != null && item.name == BlackMarble) { item = stoneItem; amount *= stoneRatio; }
else if (item != null && item.name == YggdrasilWood) { item = fineWoodItem; amount *= woodRatio; }
Piece.Requirement same = item != null ? result.Find(r => r.m_resItem == item) : null;
if (same != null)
{
same.m_amount += amount;
continue;
}
result.Add(new Piece.Requirement
{
m_resItem = item,
m_amount = amount,
m_extraAmountOnlyOneIngredient = req.m_extraAmountOnlyOneIngredient,
m_amountPerLevel = req.m_amountPerLevel,
m_upgraderResource = req.m_upgraderResource,
m_recover = req.m_recover,
});
}
return result.ToArray();
}
private static string Describe(Piece.Requirement[] reqs)
{
var parts = new List<string>();
foreach (Piece.Requirement req in reqs)
{
if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
}
return string.Join(", ", parts);
}
/// <summary>
/// Puts the cost the local player should see on the prefabs. Returns whether anything
/// changed, so the caller knows to refresh the build menu.
/// </summary>
private static bool Apply(bool cheap)
{
int stone = DvergarConfigManagement.CheapStonePerBlackMarble.Value;
int wood = DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value;
string key = cheap ? stone + "/" + wood : "";
if (key == appliedKey) return false;
foreach (var pair in originals)
{
if (!prefabs.TryGetValue(pair.Key, out Piece prefab) || prefab == null) continue;
prefab.m_resources = cheap ? BuildCheap(pair.Value, stone, wood) : pair.Value;
}
appliedKey = key;
return true;
}
private static bool IsSwapped(Piece piece)
{
return appliedKey != "" && piece != null && originals != null
&& originals.ContainsKey(Utils.GetPrefabName(piece.gameObject.name));
}
/// <summary>
/// Keeps the prefabs in step with the local player: a Dvergar with the option on sees the
/// cheap cost, anyone else the vanilla one. Checked every frame because the race can change
/// mid-session (resetrace) and the ratios with the server's config; the check is a string
/// compare unless something changed.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_CheapBuildingSync_Patch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !Collect()) return;
bool cheap = DvergarConfigManagement.CheapBuildingEnabled.Value && DvergarRace.IsDvergar();
if (Apply(cheap)) Traverse.Create(__instance).Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>
/// Tags a piece placed at the cheap cost. SetCreator is called once, by PlacePiece, on the
/// placing client, right after the piece was paid for from the same prefab cost.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_CheapBuildingTag_Patch
{
public static void Postfix(Piece __instance)
{
if (!IsSwapped(__instance)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
}
}
/// <summary>
/// Gives back what the piece cost: the cheap materials at the ratios it was paid at for a
/// tagged piece, the vanilla cost for every other one, whoever destroys it and whatever
/// cost this client's prefab carries right now.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_CheapBuildingRefund_Patch
{
public static void Prefix(Piece __instance)
{
if (!Collect()) return;
if (!originals.TryGetValue(Utils.GetPrefabName(__instance.gameObject.name), out Piece.Requirement[] original)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
int stone = zdo != null ? zdo.GetInt(StoneRatioZdoKey, 0) : 0;
int wood = zdo != null ? zdo.GetInt(WoodRatioZdoKey, 0) : 0;
__instance.m_resources = stone > 0 && wood > 0 ? BuildCheap(original, stone, wood) : original;
}
}
/// <summary>
/// The Dvergar icon on every swapped piece in the hammer menu. Valheim 1.0
/// draws that menu with BuildUi, one pooled BuildUiPieceButton per piece, and Setup is
/// where a button takes its piece. The old Hud.UpdatePieceList grid still runs but is
/// hidden, so a label there is never seen.
/// </summary>
[HarmonyPatch(typeof(BuildUiPieceButton), nameof(BuildUiPieceButton.Setup))]
public static class Dvergar_CheapBuildingLabel_Patch
{
public static void Postfix(BuildUiPieceButton __instance, Piece pieceInfo)
{
bool cheap = IsSwapped(pieceInfo);
Transform label = __instance.transform.Find(LabelName);
if (label == null)
{
if (!cheap) return;
label = CreateLabel(__instance.transform);
}
if (label.gameObject.activeSelf != cheap) label.gameObject.SetActive(cheap);
}
private static Transform CreateLabel(Transform button)
{
var obj = new GameObject(LabelName, typeof(RectTransform));
obj.transform.SetParent(button, false);
// The race's own icon in the bottom-right corner, as the race menu and the build
// panel's race requirement show it: no text, so it fits in every language.
var rect = (RectTransform)obj.transform;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(1f, 0f);
rect.anchoredPosition = new Vector2(-2f, 2f);
rect.sizeDelta = new Vector2(22f, 22f);
var image = obj.AddComponent<Image>();
image.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
image.preserveAspect = true;
image.raycastTarget = false;
return obj.transform;
}
}
}
}

View file

@ -57,6 +57,11 @@ namespace RacesOfValheim
public static ConfigEntry<float> RunicOverchargeWindow;
public static ConfigEntry<float> RunicOverchargeCooldown;
// ─── Cheap Building ───────────────────────────────────────────────────────
public static ConfigEntry<bool> CheapBuildingEnabled;
public static ConfigEntry<int> CheapStonePerBlackMarble;
public static ConfigEntry<int> CheapFineWoodPerYggdrasil;
public static void Bind(ConfigFile config)
{
const string keybinds = "Dvergar - Keybinds";
@ -106,6 +111,14 @@ namespace RacesOfValheim
new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string building = "Dvergar - Cheap Building";
CheapBuildingEnabled = config.Bind(building, "Enabled", true,
new ConfigDescription("A Dvergar builds the black marble and Yggdrasil wood building pieces (walls, floors, beams, roofs, arches, stairs) with stone and fine wood instead. Stations and furniture keep their cost. A deconstructed piece gives back what was paid for it."));
CheapStonePerBlackMarble = config.Bind(building, "Stone per Black Marble", 3,
new ConfigDescription("Stone a Dvergar pays for each black marble in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
CheapFineWoodPerYggdrasil = config.Bind(building, "Fine Wood per Yggdrasil Wood", 2,
new ConfigDescription("Fine wood a Dvergar pays for each Yggdrasil wood in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
}
}
}