RacesOfValheim/JotunnModStub/TrolsHammer/TrolsHammerPatches.cs
kanym 0d1f655598 feat: Shrink Hammer, and Alt + scroll to size pieces with both hammers
A player asked to build below vanilla size for small details. The new
Shrink Hammer, craftable by any race, builds from 0.25 to 1; Trol's Hammer
keeps 1 to 3. With either hammer, Alt + scroll in build mode changes the
size in steps of 0.05, an Alt: Size row joins the build hints, and the size
floats over the ghost when it is not the default. With the repair tool, the
aimed piece shows the size it was built at. Both hammers get icons of their
own.
2026-10-30 22:49:27 +01:00

214 lines
9.7 KiB
C#

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 = BuildScale.For(player.RightItem);
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;
// Trol's Hammer or the Shrink Hammer; any other tool builds at 1 and leaves here.
float factor = BuildScale.For(__instance.RightItem);
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);
}
}
}