RacesOfValheim/JotunnModStub/Factions/FactionMerchantPatches.cs
2026-08-16 07:44:44 +02:00

205 lines
10 KiB
C#

using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
// Trader.Update() was written for Haldor/Hildir, who have no AI of their own and are
// permanently idle: it unconditionally plays a "Stand" animator bool and a greet/goodbye
// speech bubble the instant any player enters m_standRange (15m by default), with no
// check for whether a trade is actually happening. Grafted onto a mob that has its own
// MonsterAI, that reads as the creature freezing and mumbling "..." the moment it merely
// notices the player - not what a "press E to talk" merchant should do. Skipping Update()
// entirely leaves Interactable.Interact() (E opens StoreGui) and Hoverable.GetHoverText()
// (the "E - Talk" prompt) untouched, since neither of those depends on Update() running.
//
// The same prefix also refuses to run Update() on a Trader that has no rig to drive, which is
// the general form of a bug that reached a tester: Trader.Start() resolves m_animator and
// m_lookAt with GetComponentInChildren, and Update() then dereferences BOTH with no null check -
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() on the branch taken whenever no
// player is nearby, which is most frames. A building is not a creature and has neither, so a
// Trader bolted onto one threw a NullReferenceException every frame and filled the BepInEx
// console. The prefabs that do that (the Dvergar bank, the Trol totem, the Hive Market) now
// disable their Trader outright, which is the real fix; this check is the net under it, and it
// costs one cached field read per trader per frame.
[HarmonyPatch(typeof(Trader), "Update")]
public static class FactionMerchantSuppressAmbientPatch
{
// Both fields are private in the assembly this project compiles against. Resolved once
// rather than through Traverse, because this runs on every trader on every frame.
private static readonly AccessTools.FieldRef<Trader, Animator> AnimatorField =
AccessTools.FieldRefAccess<Trader, Animator>("m_animator");
private static readonly AccessTools.FieldRef<Trader, LookAt> LookAtField =
AccessTools.FieldRefAccess<Trader, LookAt>("m_lookAt");
public static bool Prefix(Trader __instance)
{
if (((Component)__instance).GetComponent<FactionMerchant>() != null)
{
return false;
}
if (AnimatorField(__instance) == null || LookAtField(__instance) == null)
{
return false;
}
return true;
}
}
// Trader.Start() ends with InvokeRepeating("RandomTalk", m_randomTalkInterval,
// m_randomTalkInterval), and a Trader added with AddComponent comes up with that interval at
// zero, because nobody authored it in the editor. On a faction merchant the repeat is pure
// waste for as long as the creature exists: RandomTalk's first act is to read the animator's
// "Stand" bool, and nothing ever sets it, because Update() - the only thing that would - is
// suppressed for these by the patch above. So it wakes up, asks one question, answers no, and
// is scheduled again.
//
// Cancelled in a postfix rather than by skipping Start with a prefix: Start also resolves
// m_animator and m_lookAt and snaps a SnapToGround rig to the terrain, and none of that is in
// the way. Only the timer is.
[HarmonyPatch(typeof(Trader), "Start")]
public static class FactionMerchantStopRandomTalkPatch
{
public static void Postfix(Trader __instance)
{
if (((Component)__instance).GetComponent<FactionMerchant>() == null) return;
__instance.CancelInvoke("RandomTalk");
}
}
// Player.FindHoverObject() always figures out m_hoveringCreature correctly (it only
// needs a Character component on the hit collider, no Hoverable/Interactable
// involved) but separately sets m_hovering - the field the "E - Talk" prompt and the
// E-key handler actually use - by checking Hoverable/attachedRigidbody on the exact
// collider the raycast hit. On a full creature rig that hit is very often a limb or
// hitbox collider with no Rigidbody of its own, so m_hovering ends up pointing at
// nothing useful and the Trader added in FactionMerchantSetup is never found, even
// though the game already correctly knows which creature is being looked at. Fixing
// that one field is enough to get the vanilla prompt and E-to-open-store working.
[HarmonyPatch(typeof(Player), "UpdateHover")]
public static class FactionMerchantHoverPatch
{
// Matches vanilla Player.m_maxInteractDistance's default (5m) - FindHoverObject's
// own hoverCreature detection has no range cap of its own (only m_hovering does,
// which is exactly the field this patch is replacing), so this keeps the prompt
// from showing across the whole 50m raycast.
private const float MaxTalkDistance = 5f;
public static void Postfix(Player __instance)
{
// Both fields are private in the assembly this project compiles against.
var traverse = Traverse.Create(__instance);
Character hovering = traverse.Field("m_hoveringCreature").GetValue<Character>();
if (hovering == null) return;
GameObject go = ((Component)hovering).gameObject;
if (go.GetComponent<FactionMerchant>() == null) return;
if (!FactionHostilityPatch.IsSameFaction(__instance, hovering)) return;
if (Vector3.Distance(((Component)__instance).transform.position, go.transform.position) > MaxTalkDistance) return;
traverse.Field("m_hovering").SetValue(go);
}
}
// Player.Interact(GameObject, bool, bool) normally resolves the target itself via
// go.GetComponentInParent<Interactable>(), picking whichever Interactable-implementing
// component happens to sit first in the GameObject's component list. AswidPatches.cs's
// own Character.Awake postfix (Aswid_Awake_Patch) adds AswidThrall - also Interactable -
// to essentially every non-boss mob with a MonsterAI, unrelated to Factions entirely,
// and it wins that race on every creature FactionMerchantSetup also touches. The result:
// pressing E called AswidThrall.Interact() instead of Trader.Interact(), silently, with
// no error - confirmed by logging componentInParent's actual runtime type against a live
// game. Handling FactionMerchant targets here, before vanilla's own lookup ever runs,
// sidesteps the ambiguity completely instead of depending on component add order.
[HarmonyPatch(typeof(Player), "Interact")]
public static class FactionMerchantInteractPatch
{
public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt)
{
if (go == null) return true;
FactionMerchant merchant = go.GetComponentInParent<FactionMerchant>();
if (merchant == null) return true; // not ours - let vanilla's own resolution run
if (hold) return false; // Trader-style interactions have no "hold" behaviour
Trader trader = ((Component)merchant).GetComponent<Trader>();
if (trader == null || StoreGui.instance == null) return false;
StoreGui.instance.Show(trader);
// Say(List<string>, string) is private in this build's assembly reference.
Traverse.Create(trader).Method("Say", trader.m_randomStartTrade, "Talk").GetValue();
return false;
}
}
// Keeps a faction-merchant mob standing still while (and briefly after) trading -
// MonsterAI drives the vanilla wander/attack behaviour on these creatures, and
// Trader alone (built for the always-static Haldor/Hildir) does nothing to stop it.
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
public static class FactionMerchantFreezeAIPatch
{
public static bool Prefix(MonsterAI __instance, ref bool __result)
{
// BaseAI.m_character is private in the assembly this project compiles against.
Character character = Traverse.Create(__instance).Field("m_character").GetValue<Character>();
if (FactionMerchantRuntime.IsProtected(character))
{
__result = false;
return false;
}
return true;
}
}
// Blocks player damage against a merchant mob while trading and for a few seconds
// after closing, so an accidental click right as the window shuts does not open a
// fight with someone the player was just buying wood from.
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class FactionMerchantBlockAttackPatch
{
public static bool Prefix(Character __instance, HitData hit)
{
if (hit != null && hit.GetAttacker() == Player.m_localPlayer && FactionMerchantRuntime.IsProtected(__instance))
{
return false;
}
return true;
}
}
// On close: say a random joke for the mob's race (visible m_hideDialogDelay seconds,
// set to 6 in FactionMerchantSetup) and start the post-close protection window that
// the two patches above key off of.
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class FactionMerchantCloseDialoguePatch
{
private static Trader _closingTrader;
public static void Prefix(StoreGui __instance)
{
_closingTrader = FactionMerchantRuntime.GetActiveTrader(__instance);
}
public static void Postfix(StoreGui __instance)
{
Trader trader = _closingTrader;
_closingTrader = null;
if (trader == null) return;
GameObject go = ((Component)trader).gameObject;
FactionMerchant merchant = go.GetComponent<FactionMerchant>();
if (merchant == null) return;
string line = FactionMerchantRuntime.PickJokeLine(merchant.Shop);
if (!string.IsNullOrEmpty(line))
{
// Trader.Say(string, string) is private in this build's assembly reference.
Traverse.Create(trader).Method("Say", line, "Talk").GetValue();
}
Character character = go.GetComponent<Character>();
FactionMerchantRuntime.BeginProtection(character, trader.m_hideDialogDelay);
}
}
}