RacesOfValheim/JotunnModStub/RaceGrudge.cs
kanym 4ee98d90cb fix(factions): the player can strike allied creatures again
Valheim 1.0's hit filters (Attack melee/area, Projectile OnHit/DoAOE/
IsValidTarget, Aoe.ShouldHit) skip a target when BaseAI.IsEnemy says
false and the attacker is a player without PvP. The truce said false
for every allied creature, so the blow passed through: no damage, no
grudge, nothing for kin to join. RaceGrudge.StrikeScope opens a scope
around those six methods in which both truce patches stand down for
the player's own hit; everything else keeps the truce.
2026-11-06 21:21:20 +01:00

206 lines
10 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Hit something that is at peace with you and it hits back.
///
/// WHY THIS HAS TO EXIST. Both truce patches answer BaseAI.IsEnemy with false, and the comment
/// they each carried - that retaliation runs through BaseAI.OnDamaged and no truce has a say
/// over it - is wrong. Read out of assembly_valheim:
///
/// MonsterAI.OnDamaged calls SetTarget(attacker), so the mob does take the hit
/// personally, exactly as those comments said, and then
/// MonsterAI.UpdateTarget on its very next tick does
/// if (!IsEnemy(m_targetCreature)) m_targetCreature = null;
///
/// so the target is thrown away a frame later. A truced mob could not fight back at all: it
/// stood there being hit, or - hurt, with no enemy it was allowed to have - fell into
/// UpdateAI's flee branches and ran away. That is what testers saw and reported.
///
/// WHAT THIS DOES. It remembers who hit whom, for a while, and both truce postfixes stand down
/// for that one pair while the memory lasts. The mob is an enemy again by vanilla's own rules,
/// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla
/// behaviour rather than anything reimplemented here.
///
/// WHERE IT RUNS. On the client that owns the mob's AI, which is the only one whose UpdateTarget
/// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached
/// through the character's damage callback on exactly that machine, so the record is made where
/// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the
/// same mob is not the one deciding who it chases.
///
/// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here:
/// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers
/// do.
/// </summary>
public static class RaceGrudge
{
private struct Grudge
{
public ZDOID Attacker;
public float Until;
}
// One grudge per mob, against the last thing that hit it. A creature can only chase one
// target anyway, and if two players of the same race are both poking it, the one it wants
// is whoever hit it last.
private static readonly Dictionary<ZDOID, Grudge> grudges = new Dictionary<ZDOID, Grudge>();
private static float lastSweep = 0f;
private static float Duration => FactionsConfig.GrudgeSeconds;
/// <summary>
/// True while <paramref name="monster"/> is owed a hit by <paramref name="player"/>. Both
/// truce postfixes ask this first and leave IsEnemy alone when it answers yes.
/// </summary>
public static bool Holds(Character monster, Character player)
{
if (monster == null || player == null) return false;
if (Duration <= 0f) return false;
if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false;
if (Time.time >= grudge.Until) return false;
return grudge.Attacker == player.GetZDOID();
}
public static void Remember(Character monster, Character attacker)
{
if (monster == null || attacker == null) return;
if (Duration <= 0f) return;
grudges[monster.GetZDOID()] = new Grudge
{
Attacker = attacker.GetZDOID(),
Until = Time.time + Duration
};
Sweep();
}
/// <summary>
/// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of
/// damage events and the list should not be walked on each one.
/// </summary>
private static void Sweep()
{
if (Time.time - lastSweep < Duration) return;
lastSweep = Time.time;
List<ZDOID> expired = null;
foreach (var entry in grudges)
{
if (Time.time < entry.Value.Until) continue;
if (expired == null) expired = new List<ZDOID>();
expired.Add(entry.Key);
}
if (expired == null) return;
foreach (ZDOID id in expired) grudges.Remove(id);
}
/// <summary>
/// The one place a grudge is born. BaseAI.OnDamaged is the base every AI's own override
/// calls first, so patching it here covers MonsterAI and AnimalAI both, and it lands before
/// MonsterAI.OnDamaged's SetTarget on the same hit - the grudge is on the books by the time
/// UpdateTarget next asks whether that target is allowed.
///
/// Only a player's hit counts. A greydwarf caught in another greydwarf's swing has vanilla's
/// own rules for that and no truce of ours in the way.
/// </summary>
[HarmonyPatch(typeof(BaseAI), "OnDamaged")]
public static class BaseAI_OnDamaged_Grudge_Patch
{
public static void Postfix(BaseAI __instance, Character attacker)
{
if (!FactionsConfig.Hostility) return;
if (attacker == null || !attacker.IsPlayer()) return;
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null || monster.IsPlayer()) return;
Remember(monster, attacker);
if (FactionsConfig.GrudgeSpreads && attacker is Player player) SpreadToKin(monster, player);
}
}
// How deep we are inside one of vanilla's hit filters (see StrikeScope). A counter rather
// than a bool because Projectile.OnHit calls DoAOE, and the inner exit must not end the
// outer scope.
private static int strikeDepth = 0;
/// <summary>
/// True while vanilla is deciding whether <paramref name="attacker"/>'s own weapon, arrow or
/// area hit lands. Both truce postfixes stand down for that question: the truce is about
/// who a creature attacks, never about whether the player is allowed to strike it.
/// </summary>
public static bool PlayerStrikes(Character attacker)
{
return strikeDepth > 0 && attacker != null && attacker.IsPlayer();
}
/// <summary>
/// THE PLAYER COULD NOT HIT THEIR OWN FACTION AT ALL. Valheim 1.0's hit filters (Attack's
/// melee and area swings, Projectile's direct hit, its AoE and its IsValidTarget, Aoe's
/// ShouldHit) ask BaseAI.IsEnemy(attacker, target) and skip the target when it answers false
/// and the attacker is a player without PvP on - vanilla's guard for tames. Our truce
/// answers false for every allied creature, so the blow passed through it, it took no
/// damage, BaseAI.OnDamaged never ran and no grudge was ever born. That is both reports at
/// once: "it will not allow me" to attack, and kin that never fight back, group grudge on or
/// off, because nobody was ever hit. With PvP on the filter let the hit through, which is
/// why it looked fine in some tests.
///
/// The scope is open only around those six methods, so everything else that asks IsEnemy
/// with the player first keeps the truce: the green health bar on allied creatures, sneaking
/// past them, the Aswid's aura leaving kin alone.
/// </summary>
[HarmonyPatch]
public static class StrikeScope
{
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "DoMeleeAttack");
yield return AccessTools.Method(typeof(Attack), "DoAreaAttack");
yield return AccessTools.Method(typeof(Projectile), "DoAOE");
yield return AccessTools.Method(typeof(Projectile), "IsValidTarget");
yield return AccessTools.Method(typeof(Projectile), "OnHit");
yield return AccessTools.Method(typeof(Aoe), "ShouldHit");
}
public static void Prefix() => strikeDepth++;
// Finalizer rather than Postfix: the count has to come down even when the method
// throws, or every IsEnemy afterwards would ignore the truce.
public static void Finalizer() => strikeDepth--;
}
/// <summary>
/// Vanilla's Dvergr camp, for every faction ("Grudge spreads to kin", off by default): hit
/// a creature that is at peace with you and its kin around it take up the same grudge.
///
/// Only the creatures this machine runs the AI for are told, because a grudge is read where
/// the AI runs (see WHERE IT RUNS above). The creatures around the one that was hit are
/// nearly always simulated by the same client; one owned by another player's machine stays
/// at peace until it is hit itself.
/// </summary>
private static void SpreadToKin(Character monster, Player player)
{
string race = FactionHostilityPatch.GetPlayerRace(player);
if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return;
Vector3 center = monster.transform.position;
float radius = FactionsConfig.GrudgeSpreadMeters;
foreach (Character other in Character.GetAllCharacters())
{
if (other == null || other == monster || other.IsPlayer() || other.IsDead() || other.IsTamed()) continue;
if (!other.IsOwner()) continue;
if (Vector3.Distance(other.transform.position, center) > radius) continue;
if (!FactionHostilityPatch.IsAlliedMob(race, other.gameObject.name)) continue;
Remember(other, player);
other.GetBaseAI()?.Alert();
}
}
}
}