warvulture

This commit is contained in:
Ferdinando 2026-08-13 19:13:24 +02:00
commit d79f78e9f0
10 changed files with 901 additions and 90 deletions

View file

@ -0,0 +1,50 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The two numbers behind Trol's Hammer, bound as BepInEx ConfigEntry so they can be dragged in
/// Configuration Manager rather than recompiled - the same shape as WarVultureConfig.
///
/// Note what the switch does NOT do: turning the hammer off never un-scales anything already
/// standing. A piece carries its own size on its ZDO, and that is read back on load whatever
/// the config says, so a house built at 1.2 stays a house and not a pile of clipping walls.
/// The switch only decides whether NEW placements are enlarged.
/// </summary>
public static class TrolsHammerConfig
{
public static ConfigEntry<bool> Enabled;
public static ConfigEntry<float> ScaleFactor;
public static void Bind(ConfigFile config)
{
// No apostrophe, and not a typo: BepInEx rejects ' in a section name outright, and this
// Bind runs from the plugin's Awake - so "Trol's Hammer" did not merely fail to appear
// in Configuration Manager, it threw and took the whole mod's startup with it.
const string section = "Trols Hammer";
Enabled = config.Bind(section, "Enabled", true,
new ConfigDescription("Whether pieces placed with Trol's Hammer come out enlarged. " +
"Switching this off leaves every piece already built at the size " +
"it was built at; only new placements are affected."));
ScaleFactor = config.Bind(section, "Scale factor", 1.2f,
new ConfigDescription("How much bigger than the vanilla piece. 1.2 is the +20% the " +
"hammer exists for. Cost and drop never change - this is size " +
"only.", new AcceptableValueRange<float>(1f, 3f)));
}
/// <summary>
/// The multiplier a new placement should use, or 1 when the hammer is switched off. Clamped
/// against a zero or negative value typed straight into the .cfg file, which the
/// Configuration Manager slider cannot produce but a text editor can - and a piece scaled to
/// zero is a piece that cannot be seen, hit or removed.
/// </summary>
public static float ActiveFactor()
{
if (Enabled == null || ScaleFactor == null) return 1f;
if (!Enabled.Value) return 1f;
return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
}
}
}

View file

@ -0,0 +1,97 @@
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Trol's Hammer: the builder's hammer, one size up.
///
/// It is a straight clone of the vanilla Hammer and it deliberately keeps the ONE field that
/// makes it a hammer at all - m_buildPieces, the PieceTable. Sharing the vanilla table rather
/// than cloning it is the whole trick behind "exactly the same things to build": every piece
/// vanilla puts in the hammer's menu is there, at the same cost and with the same drop, and so
/// is every piece another mod adds to that table later. A cloned table would have been a
/// snapshot of the build menu taken at startup and would have quietly gone stale.
///
/// Nothing about the piece prefabs is touched, so the size does not live on the item: it lives
/// on the placement, and TrolsHammerPatches is where that happens.
///
/// The recipe (1 core wood, 2 fine wood) is on a workbench rather than free-hand like the
/// vanilla hammer, because both materials already require one to exist.
/// </summary>
public static class TrolsHammerItem
{
public const string PrefabName = "TrolsHammer";
public const string DisplayName = "Trol's Hammer";
private const string SourcePrefab = "Hammer";
private const string Label = "TrolsHammer";
/// <summary>Core wood. The item id is RoundLog - a display name that does not predict the id.</summary>
private const string CoreWood = "RoundLog";
private const string FineWood = "FineWood";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A hammer swung by something that never had to duck through a " +
"doorway. It builds everything the ordinary one builds, out of the " +
"same materials, and simply builds it bigger.";
if (shared.m_buildPieces == null)
{
// Not fatal, but worth saying out loud: without a piece table the item is a stick.
Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone carries no build piece table; " +
$"{DisplayName} will open an empty build menu.");
}
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Workbench,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig(CoreWood, 1, 0, true),
new RequirementConfig(FineWood, 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
}
/// <summary>
/// Whether an item in hand is this hammer.
///
/// m_dropPrefab is the reliable identity - it is the prefab the ItemData came from - but it
/// is null on an ItemData built before ObjectDB finished, so the display name is kept as a
/// second reading rather than as the only one.
/// </summary>
public static bool IsTrolsHammer(ItemDrop.ItemData item)
{
if (item == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
return item.m_shared != null && item.m_shared.m_name == DisplayName;
}
}
}

View file

@ -0,0 +1,217 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Where the +20% actually happens.
///
/// Three things had to be true for this to be a feature rather than a trick, and each one is a
/// separate patch below:
///
/// 1. the SIZE MUST SURVIVE. Valheim does not replicate localScale - a piece is rebuilt from
/// its ZDO every time the zone loads, at whatever size its prefab has. So the multiplier is
/// written onto the piece's own ZDO at placement and read back in ZNetView.Awake, which is
/// the earliest moment a ZDO is guaranteed to exist (confirmed from the assembly:
/// WearNTear.Awake returns early if GetZDO() is null, so it already assumes this order).
/// That one hook covers all three cases at once - the builder's client, every other
/// player's client, and the same world reopened next week;
///
/// 2. the PREVIEW MUST NOT LIE. The ghost is what the game tests for clipping, overlap and
/// snapping, so an unscaled ghost would let a player place a piece that immediately
/// overlapped its neighbour. SetupPlacementGhost ends by copying the prefab's localScale
/// onto the ghost, so a postfix - and only a postfix - can multiply it;
///
/// 3. the PIECE ITSELF MUST NOT BE TOUCHED. Nothing here writes to a piece prefab. Cost,
/// drop, health, comfort and build menu are vanilla's, untouched, which is exactly why the
/// same walls can still be built at normal size with the ordinary hammer.
///
/// Placement is caught with a flag around Player.PlacePiece rather than by patching the piece:
/// PlacePiece is void and instantiates the PREFAB (not the ghost) inside itself, so there is no
/// return value to read and no way to reach the new object afterwards. The instantiate runs
/// synchronously, which means every Awake it triggers happens inside that window.
/// </summary>
public static class TrolsHammerScaling
{
/// <summary>
/// The ZDO key the size is written to. Hashed once: this is read in ZNetView.Awake, which
/// runs for every networked object in the world, so it is not a place to be hashing strings.
/// </summary>
public static readonly int ScaleKey = "RoV_TrolHammerScale".GetStableHashCode();
/// <summary>
/// True only for the few milliseconds Player.PlacePiece spends instantiating a piece the
/// player asked for with Trol's Hammer in hand. Static because the only caller is the local
/// player and the window never nests.
/// </summary>
public static bool Placing;
public static float PlacingFactor = 1f;
public static void Apply(Transform t, float factor)
{
if (t == null || factor <= 0f || Mathf.Approximately(factor, 1f)) return;
// A multiply and not an assignment: a handful of vanilla pieces do not sit at scale 1,
// and the brief is "20% bigger than it was", not "20% bigger than one metre".
Vector3 s = t.localScale;
t.localScale = new Vector3(s.x * factor, s.y * factor, s.z * factor);
}
}
/// <summary>
/// The preview, at the size it will actually be built.
///
/// A postfix because vanilla's last act in this method is to copy the source prefab's
/// localScale onto the ghost - a prefix would be overwritten a few instructions later.
///
/// The hand is read through the public RightItem property and NOT through GetCurrentWeapon,
/// which is the obvious-looking call and the wrong one: it only returns the right hand when
/// ItemData.IsWeapon() is true, and that method does not count ItemType.Tool. A hammer would
/// have come back as the player's fists.
/// </summary>
public static class TrolsHammerGhost
{
private static GameObject m_tracked;
private static Vector3 m_baseScale = Vector3.one;
private static float m_applied = 1f;
/// <summary>
/// Remembers the size vanilla just gave the ghost, before anything of ours touches it. This
/// is the only moment that number is knowable: a few frames later the ghost's localScale is
/// whatever WE last wrote, and using it as a base would compound on every pass.
/// </summary>
public static void Adopt(GameObject ghost)
{
m_tracked = ghost;
m_baseScale = ghost != null ? ghost.transform.localScale : Vector3.one;
m_applied = 1f;
}
/// <summary>
/// Puts the ghost at the size the hand in the player's right hand would build it.
///
/// Called every frame because the ghost is NOT rebuilt when the player swaps tools:
/// SetupPlacementGhost only runs on Awake, on a piece-selection change and on a build menu
/// refresh (confirmed by walking its callers in the assembly). Swapping from one hammer to
/// the other with the same wall selected keeps the same ghost object alive, so a size
/// applied once at setup would go on lying about a piece that is now built at normal size.
///
/// Cheap enough to be unconditional: it exits on a float comparison in every frame but the
/// one where the answer actually changed.
/// </summary>
public static void Sync(Player player, GameObject ghost)
{
if (player == null || ghost == null)
{
m_tracked = null;
return;
}
if (ghost != m_tracked) Adopt(ghost);
float desired = TrolsHammerItem.IsTrolsHammer(player.RightItem)
? TrolsHammerConfig.ActiveFactor()
: 1f;
if (Mathf.Approximately(desired, m_applied)) return;
ghost.transform.localScale = m_baseScale * desired;
m_applied = desired;
}
}
[HarmonyPatch(typeof(Player), "SetupPlacementGhost")]
public static class TrolsHammerGhostSetupPatch
{
private static void Postfix(Player __instance, GameObject ___m_placementGhost)
{
TrolsHammerGhost.Adopt(___m_placementGhost);
TrolsHammerGhost.Sync(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The correction pass. This also runs once inside TryPlacePiece, immediately before the piece
/// is placed, which is what guarantees the thing tested for clipping is the size that lands.
/// </summary>
[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
public static class TrolsHammerGhostUpdatePatch
{
private static void Postfix(Player __instance, GameObject ___m_placementGhost)
{
TrolsHammerGhost.Sync(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The window. PlacePiece is void, so there is nothing to postfix onto - the flag is the whole
/// mechanism, and ZNetView.Awake is what reads it.
///
/// A Finalizer rather than a Postfix closes the window, so the flag is cleared even if vanilla
/// throws halfway through placing. A flag left stuck on would enlarge the next unrelated
/// networked object to spawn anywhere in the world.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece")]
public static class TrolsHammerPlacePatch
{
private static void Prefix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
float factor = TrolsHammerConfig.ActiveFactor();
if (Mathf.Approximately(factor, 1f)) return;
TrolsHammerScaling.Placing = true;
TrolsHammerScaling.PlacingFactor = factor;
}
private static void Finalizer()
{
TrolsHammerScaling.Placing = false;
}
}
/// <summary>
/// The one hook that both stamps the size and restores it.
///
/// It runs for EVERY networked object in the world, so the ordinary path is deliberately as
/// cheap as one dictionary lookup on a pre-hashed key: no GetComponent, no string work, no
/// allocation. The GetComponent&lt;Piece&gt; guard is paid only inside the placement window, and
/// it is there so an effect prefab that happens to carry a ZNetView cannot be mistaken for the
/// wall being built.
///
/// The restore branch ignores the config on purpose - see TrolsHammerConfig.
/// </summary>
[HarmonyPatch(typeof(ZNetView), "Awake")]
public static class TrolsHammerZNetViewPatch
{
private static void Postfix(ZNetView __instance)
{
if (__instance == null || !__instance.IsValid()) return;
ZDO zdo = __instance.GetZDO();
if (zdo == null) return;
if (TrolsHammerScaling.Placing && __instance.GetComponent<Piece>() != null)
{
float factor = TrolsHammerScaling.PlacingFactor;
// Written before it is applied, and only by the owner - which the placing client
// always is, since this ZDO was created a few instructions ago by this very Awake.
if (zdo.IsOwner()) zdo.Set(TrolsHammerScaling.ScaleKey, factor);
TrolsHammerScaling.Apply(__instance.transform, factor);
// The window is closed here as well as in the Finalizer: one placement is one
// piece, and leaving it open for the rest of PlacePiece would hand the same size to
// anything else that woke up inside it.
TrolsHammerScaling.Placing = false;
return;
}
float saved = zdo.GetFloat(TrolsHammerScaling.ScaleKey, 0f);
if (saved > 0f) TrolsHammerScaling.Apply(__instance.transform, saved);
}
}
}