Wargles' suggestion. A Dvergar pays 3 stone per black marble and 2 fine wood per Yggdrasil wood on structural hammer pieces; stations, furniture, containers and fires keep their cost. The swap is made on the piece prefabs of the Dvergar's own client, so the menu, the known piece check and the cost paid all follow it, and the pieces show once stone or fine wood is known. Vanilla refunds whatever m_resources says on the machine that destroys a piece, so a cheap piece is tagged on its ZDO with the ratios paid, and DropResources gets the matching cost on every client: a cheap wall never refunds black marble, and a vanilla wall still does. Swapped pieces carry the Dvergar race icon on their button in the 1.0 build menu (BuildUiPieceButton). The startup log lists every swapped piece with its station and both costs. Config: "Dvergar - Cheap Building" (Enabled, Stone per Black Marble, Fine Wood per Yggdrasil Wood).
275 lines
13 KiB
C#
275 lines
13 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|
|
}
|