RacesOfValheim/JotunnModStub/Factions/FactionMerchantRuntime.cs
2026-08-06 10:13:57 +02:00

56 lines
2.3 KiB
C#

using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
// Tracks the "just traded with this mob" window used by two independent patches:
// the MonsterAI freeze (keeps the merchant from wandering off mid-chat) and the
// player attack block (keeps an accidental click from starting a fight the instant
// the trade window closes). Both share one timer so the mob is protected for
// exactly as long as its closing joke line stays on screen.
public static class FactionMerchantRuntime
{
private static Character _lastTraded;
private static float _protectUntil;
// StoreGui.m_trader is private in the assembly this project actually compiles
// against (see RacesOfValheim.csproj - it references the plain, non-publicized
// game DLL), so every read goes through Traverse like the rest of the codebase.
public static Trader GetActiveTrader(StoreGui gui)
{
return gui == null ? null : Traverse.Create(gui).Field("m_trader").GetValue<Trader>();
}
public static void BeginProtection(Character trader, float seconds)
{
_lastTraded = trader;
_protectUntil = Time.time + seconds;
}
public static bool IsProtected(Character character)
{
if (character == null) return false;
// Actively trading right now: StoreGui itself is the source of truth.
Trader activeTraderComponent = GetActiveTrader(StoreGui.instance);
if (StoreGui.IsVisible() && activeTraderComponent != null)
{
Character activeTrader = ((Component)activeTraderComponent).GetComponent<Character>();
if (activeTrader == character) return true;
}
// Just closed: covered by the post-close timer.
return character == _lastTraded && Time.time < _protectUntil;
}
public static string PickJokeLine(FactionMerchantCatalog.ShopDefinition shop)
{
if (shop == null) return null;
if (!FactionMerchantJokes.Lines.TryGetValue(shop.JokeCategory, out string[] lines) || lines.Length == 0)
{
return null;
}
return lines[Random.Range(0, lines.Length)];
}
}
}