feat(factions): no raids made only of allies, and allies spare the whole base

A raid whose every spawn is at peace with the player's race is struck from
the list the client sends as possibleEvents, and from the server's valid
event points when raids are world-based.

The structure veto covered only 20 m from the creature, but
FindClosestStaticPriorityTarget searches the whole view range. It now holds
while any allied player is within 100 m, and reads the per-race lists too.
This commit is contained in:
kanym 2026-09-28 21:41:29 +02:00
commit df9c768f92
5 changed files with 291 additions and 107 deletions

View file

@ -86,12 +86,25 @@ namespace RacesOfValheim
public static bool IsSameFaction(Player player, Character monster)
{
if (player == null || monster == null) return false;
string race = GetPlayerRace(player);
if (race == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return IsFactionMob(GetPlayerRace(player), monster.gameObject.name);
}
string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim();
return mobs.Contains(prefabName);
// The same answer by name alone, for callers that only have a prefab and no live creature -
// the raid filter reads RandomEvent.m_spawn, which holds prefabs that were never spawned.
public static bool IsFactionMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return mobs.Contains(prefabName.Replace("(Clone)", "").Trim());
}
// Faction set or per-race list, whichever says yes: the two questions IsEnemy is asked
// through these two files, answered without a Character. Grudges are not in here - a grudge
// is held by one creature, not by a prefab.
public static bool IsAlliedMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
return IsFactionMob(race, prefabName) || RaceHostilityManager.IsRaceKin(race, prefabName);
}
// m_customData is the local save file's dictionary: it is only ever populated for
@ -151,9 +164,13 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch
{
// Comfortably past FindRandomStaticTarget's own 10 m search radius, so a truce holds for
// any piece the mob could have picked in the first place.
private const float FactionCheckRange = 20f;
// This used to be 20 m, sized against FindRandomStaticTarget's 10 m search. The other pick,
// FindClosestStaticPriorityTarget, searches the mob's whole m_viewRange, so a skeleton 25 m
// from an Aswid could still lock onto a piece and the veto never ran - and it never ran at
// all once the player stepped away from the base mid-raid. The rule is now "an ally is
// around, the whole base is safe": 100 m is roughly a raid's own area (RandomEvent's
// m_eventRange), so anyone still inside the raid covers every piece in it, whoever built it.
private const float FactionCheckRange = 100f;
public static void Postfix(MonsterAI __instance)
{
@ -167,7 +184,9 @@ namespace RacesOfValheim
foreach (Player player in Player.GetAllPlayers())
{
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
if (!FactionHostilityPatch.IsSameFaction(player, monster)) continue;
// A player this creature holds a grudge against is no ally of it right now.
if (RaceGrudge.Holds(monster, player)) continue;
if (!FactionHostilityPatch.IsAlliedMob(FactionHostilityPatch.GetPlayerRace(player), monster.gameObject.name)) continue;
targetStatic.SetValue(null);
return;

View file

@ -0,0 +1,152 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// No raid made only of your own allies. A swamp raid on an Aswid base used to arrive anyway:
/// the skeletons and draugr ignored the player, as the truce says, and had nothing left to do but
/// wander the base for the rest of the event.
///
/// Vanilla picks raids in two ways, set by the world's raid modifier, and each needs its own door:
///
/// - Player-based raids (global key PlayerEvents). Every client works out which raids it can
/// receive in Player.UpdateEvents and sends the list to the server as
/// m_serverSyncedPlayerData["possibleEvents"]; RandEventSystem.GetValidEventPoints only places
/// a raid on a player whose list names it. Striking allied raids from that list happens on the
/// client, so it works on a dedicated server that does not run the mod.
///
/// - World-based raids (PlayerEvents off). The server ignores that list and decides from world
/// keys alone. Each client also sends the allied raids under AlliedRaidsKey, and the server
/// drops that player's position from GetValidEventPoints for those raids. This half only runs
/// where the server does: single player and a game hosted from the client always, a dedicated
/// server only with the mod installed on it.
///
/// Only a raid whose every spawn is allied is struck. A mixed raid - Eikthyr's boars and necks for
/// an Aswid who has only won the boars over - still comes, and FactionStaticTargetPatch keeps the
/// allied half of it off the buildings.
/// </summary>
public static class FactionRaids
{
public const string AlliedRaidsKey = "RacesOfValheim_AlliedRaids";
public static bool IsAlliedRaid(string race, RandomEvent ev)
{
if (race == null || ev == null || ev.m_spawn == null) return false;
bool anySpawn = false;
foreach (SpawnSystem.SpawnData spawn in ev.m_spawn)
{
if (spawn == null || spawn.m_prefab == null) continue;
if (!FactionHostilityPatch.IsAlliedMob(race, spawn.m_prefab.name)) return false;
anySpawn = true;
}
// An event that spawns nothing is not a raid on anyone; leave it to vanilla.
return anySpawn;
}
private static HashSet<string> AlliedRaidNames(Player player)
{
HashSet<string> allied = new HashSet<string>();
if (!FactionsConfig.Hostility || RandEventSystem.instance == null) return allied;
string race = FactionHostilityPatch.GetPlayerRace(player);
if (race == null) return allied;
foreach (RandomEvent ev in RandEventSystem.instance.m_events)
{
if (IsAlliedRaid(race, ev)) allied.Add(ev.m_name);
}
return allied;
}
[HarmonyPatch(typeof(Player), nameof(Player.UpdateEvents))]
public static class UpdateEventsPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || ZNet.instance == null) return;
HashSet<string> allied = AlliedRaidNames(__instance);
Dictionary<string, string> synced = ZNet.instance.m_serverSyncedPlayerData;
synced[AlliedRaidsKey] = string.Join(",", allied);
Jotunn.Logger.LogInfo($"[Factions] Raids struck as allied: [{synced[AlliedRaidsKey]}]");
if (allied.Count > 0 && synced.TryGetValue("possibleEvents", out string possible) && !string.IsNullOrEmpty(possible))
{
List<string> kept = new List<string>();
foreach (string name in possible.Split(','))
{
if (!allied.Contains(name)) kept.Add(name);
}
synced["possibleEvents"] = string.Join(",", kept);
}
}
}
/// <summary>
/// Player.UpdateEvents only runs on load, on a new player key and on a new item. The race is
/// picked after load, and the Aswid's allies grow with boss kills, which are world keys; neither
/// calls it. So the local player asks again whenever either one changes.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RefreshPatch
{
private const float CheckInterval = 5f;
private static float nextCheck;
private static string lastRace;
private static int lastState = -1;
private static bool lastHostility = true;
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || Time.time < nextCheck) return;
nextCheck = Time.time + CheckInterval;
string race = FactionHostilityPatch.GetPlayerRace(__instance);
int state = BossProgressionManager.GetCurrentProgressionState();
bool hostility = FactionsConfig.Hostility;
if (race == lastRace && state == lastState && hostility == lastHostility) return;
lastRace = race;
lastState = state;
lastHostility = hostility;
__instance.UpdateEvents();
}
}
// Server side, for world-based raids. RandEventSystem keeps only each player's position and
// raid list, not who sent them, so the allied list is kept here next to the same position
// RetrievePlayerEventData hands vanilla, and GetValidEventPoints is filtered by it.
private static readonly List<KeyValuePair<Vector3, HashSet<string>>> alliedByPosition =
new List<KeyValuePair<Vector3, HashSet<string>>>();
[HarmonyPatch(typeof(RandEventSystem), "RefreshPlayerEventData")]
public static class RefreshPlayerEventDataPatch
{
public static void Prefix() => alliedByPosition.Clear();
}
[HarmonyPatch(typeof(RandEventSystem), "RetrievePlayerEventData")]
public static class RetrievePlayerEventDataPatch
{
public static void Postfix(Dictionary<string, string> playerData, Vector3 position, bool __result)
{
if (!__result || playerData == null) return;
if (!playerData.TryGetValue(AlliedRaidsKey, out string value) || string.IsNullOrEmpty(value)) return;
alliedByPosition.Add(new KeyValuePair<Vector3, HashSet<string>>(position, new HashSet<string>(value.Split(','))));
}
}
[HarmonyPatch(typeof(RandEventSystem), "GetValidEventPoints")]
public static class GetValidEventPointsPatch
{
public static void Postfix(RandomEvent ev, List<Vector3> __result)
{
if (!FactionsConfig.Hostility || ev == null || __result == null || alliedByPosition.Count == 0) return;
__result.RemoveAll(point => alliedByPosition.Exists(entry => entry.Key == point && entry.Value.Contains(ev.m_name)));
}
}
}
}

View file

@ -39,7 +39,8 @@ namespace RacesOfValheim
// get the truce back.
HostilityEnabled = config.Bind(factions, "Faction truce", true,
new ConfigDescription("Mobs your race is at peace with leave you alone - they will not open a fight, " +
"hunt you during events, or smash structures near you. Turn this off and every " +
"hunt you during events, or smash structures while you are nearby, and raids made only " +
"of them are not sent at you. Turn this off and every " +
"creature treats you exactly as vanilla would. Covers BOTH halves, because both " +
"answer the same BaseAI.IsEnemy and a switch over only one of them changes " +
"nothing for most races: the faction rules in FactionHostilityPatch, and the " +

View file

@ -40,111 +40,119 @@ namespace RacesOfValheim
// but the local client (e.g. a dedicated server owning the mob's AI).
string playerRace = FactionHostilityPatch.GetPlayerRace(p);
// Fenrir Race Logic
if (playerRace == "Fenrir")
if (IsRaceKin(playerRace, monster.gameObject.name))
{
string prefabName = monster.gameObject.name.ToLower();
if (prefabName.Contains("wolf") || prefabName.Contains("fenring") ||
prefabName.Contains("ulv") || prefabName.Contains("cultist"))
{
__result = false;
}
}
// Aswid Race Logic
if (playerRace == "Aswid")
{
string prefabName = monster.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 2 && prefabName.Contains("boar")) __result = false;
if (state >= 3 && prefabName.Contains("bear")) __result = false;
if (state >= 4 && (prefabName.Contains("leech") || prefabName.Contains("ghost") || prefabName.Contains("wraith"))) __result = false;
if (state >= 5 && prefabName.Contains("wolf")) __result = false;
if (state >= 6 && (prefabName.Contains("lox") || prefabName.Contains("deathsquito"))) __result = false;
if (state >= 7 && (prefabName.Contains("hare") || prefabName.Contains("gjall"))) __result = false;
if (state >= 8 && (prefabName.Contains("asksvin") || prefabName.Contains("volture") || prefabName.Contains("vulture") || prefabName.Contains("valkyrie"))) __result = false;
}
// Draugh Race Logic
if (playerRace == "Draugh")
{
string prefabName = monster.gameObject.name.ToLower();
if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") ||
prefabName.Contains("ghost") || prefabName.Contains("wraith"))
{
__result = false;
}
}
// Trenta Race Logic - base passive, live from the start (no progression
// gate, unlike Aswid's escalating list above).
//
// IsEnemy=false is the only lever this patch has, and it produces one
// behaviour: the mob never initiates. It reads as two different relationships
// only in flavour text - Greyling/Greydwarf/Leech/Deathsquito "don't see" a
// Trenta as prey (root-kin, or simply nothing with blood to sense), while
// Fuling/Troll "choose" not to fight one - but there is no third state to code
// for. Striking first is handled, though not by the AI on its own as this
// comment used to claim: MonsterAI.UpdateTarget discards any target IsEnemy
// calls a non-enemy, so retaliation needed RaceGrudge, checked at the top of
// this method.
if (playerRace == TrentaConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();
// "fuling" matched nothing: the Fuling family's prefabs are Goblin,
// GoblinArcher, GoblinBrute and GoblinShaman, so the Trenta's truce with them
// never existed despite this file and TrentaConfig both describing it.
// Unlike the other entries here, the goblin name needs its bosses carved back
// out - Yagluth is GoblinKing, and Hildir's arena pair are GoblinBruteBros /
// *_Hildir - because a substring test would otherwise pacify all three.
bool isGoblinKin = prefabName.Contains("goblin")
&& !prefabName.Contains("goblinking")
&& !prefabName.Contains("hildir")
&& !prefabName.Contains("brutebros");
if (prefabName.Contains("greyling") || prefabName.Contains("greydwarf") ||
isGoblinKin || prefabName.Contains("troll") ||
prefabName.Contains("leech") || prefabName.Contains("deathsquito"))
{
__result = false;
}
}
// Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike
// Aswid's escalating list: an invertebrate is kin from the first minute.
//
// That absence of a gate is doing real work rather than saving a few lines.
// Every invertebrate in the game lives from the Swamp onward, so a gated
// version would have handed the race nothing until Bonemass; ungated, a
// newborn Sverm walks through leeches and deathsquitoes, which is the whole
// of its early game.
//
// Bonemass is deliberately NOT here. It is a mass of ooze and it would
// qualify, but a boss that ignores the player is not a boss.
if (playerRace == SvermConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();
// "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob
// whatever it turns out to be called - which is why the one prefab name
// still unconfirmed in the design doc costs nothing here.
// "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen.
bool isKin = prefabName.Contains("blob")
|| prefabName.Contains("leech")
|| prefabName.Contains("tick")
|| prefabName.Contains("deathsquito")
|| prefabName.Contains("gjall")
|| prefabName.Contains("seeker");
if (isKin && !prefabName.Contains("bonemass"))
{
__result = false;
}
__result = false;
}
}
}
}
// The per-race lists by name alone, so the raid filter can ask about a prefab that was
// never spawned (FactionRaids reads RandomEvent.m_spawn). Substring matching, as before.
public static bool IsRaceKin(string playerRace, string monsterName)
{
if (playerRace == null || monsterName == null) return false;
string prefabName = monsterName.ToLower();
// Fenrir Race Logic
if (playerRace == "Fenrir")
{
if (prefabName.Contains("wolf") || prefabName.Contains("fenring") ||
prefabName.Contains("ulv") || prefabName.Contains("cultist"))
{
return true;
}
}
// Aswid Race Logic
if (playerRace == "Aswid")
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 2 && prefabName.Contains("boar")) return true;
if (state >= 3 && prefabName.Contains("bear")) return true;
if (state >= 4 && (prefabName.Contains("leech") || prefabName.Contains("ghost") || prefabName.Contains("wraith"))) return true;
if (state >= 5 && prefabName.Contains("wolf")) return true;
if (state >= 6 && (prefabName.Contains("lox") || prefabName.Contains("deathsquito"))) return true;
if (state >= 7 && (prefabName.Contains("hare") || prefabName.Contains("gjall"))) return true;
if (state >= 8 && (prefabName.Contains("asksvin") || prefabName.Contains("volture") || prefabName.Contains("vulture") || prefabName.Contains("valkyrie"))) return true;
}
// Draugh Race Logic
if (playerRace == "Draugh")
{
if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") ||
prefabName.Contains("ghost") || prefabName.Contains("wraith"))
{
return true;
}
}
// Trenta Race Logic - base passive, live from the start (no progression
// gate, unlike Aswid's escalating list above).
//
// IsEnemy=false is the only lever this patch has, and it produces one
// behaviour: the mob never initiates. It reads as two different relationships
// only in flavour text - Greyling/Greydwarf/Leech/Deathsquito "don't see" a
// Trenta as prey (root-kin, or simply nothing with blood to sense), while
// Fuling/Troll "choose" not to fight one - but there is no third state to code
// for. Striking first is handled, though not by the AI on its own as this
// comment used to claim: MonsterAI.UpdateTarget discards any target IsEnemy
// calls a non-enemy, so retaliation needed RaceGrudge, checked at the top of
// the postfix.
if (playerRace == TrentaConfig.RaceId)
{
// "fuling" matched nothing: the Fuling family's prefabs are Goblin,
// GoblinArcher, GoblinBrute and GoblinShaman, so the Trenta's truce with them
// never existed despite this file and TrentaConfig both describing it.
// Unlike the other entries here, the goblin name needs its bosses carved back
// out - Yagluth is GoblinKing, and Hildir's arena pair are GoblinBruteBros /
// *_Hildir - because a substring test would otherwise pacify all three.
bool isGoblinKin = prefabName.Contains("goblin")
&& !prefabName.Contains("goblinking")
&& !prefabName.Contains("hildir")
&& !prefabName.Contains("brutebros");
if (prefabName.Contains("greyling") || prefabName.Contains("greydwarf") ||
isGoblinKin || prefabName.Contains("troll") ||
prefabName.Contains("leech") || prefabName.Contains("deathsquito"))
{
return true;
}
}
// Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike
// Aswid's escalating list: an invertebrate is kin from the first minute.
//
// That absence of a gate is doing real work rather than saving a few lines.
// Every invertebrate in the game lives from the Swamp onward, so a gated
// version would have handed the race nothing until Bonemass; ungated, a
// newborn Sverm walks through leeches and deathsquitoes, which is the whole
// of its early game.
//
// Bonemass is deliberately NOT here. It is a mass of ooze and it would
// qualify, but a boss that ignores the player is not a boss.
if (playerRace == SvermConfig.RaceId)
{
// "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob
// whatever it turns out to be called - which is why the one prefab name
// still unconfirmed in the design doc costs nothing here.
// "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen.
bool isKin = prefabName.Contains("blob")
|| prefabName.Contains("leech")
|| prefabName.Contains("tick")
|| prefabName.Contains("deathsquito")
|| prefabName.Contains("gjall")
|| prefabName.Contains("seeker");
if (isKin && !prefabName.Contains("bonemass"))
{
return true;
}
}
return false;
}
}
}

View file

@ -427,6 +427,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact
## Changelog
### Unreleased
- **New - Raids made only of your allies no longer come for you:** an Aswid got raided by the swamp - skeletons and draugr that ignored the player, as the truce says, and then spent the whole event running around the base smashing it, with no way to stop them short of console commands. A raid whose every creature is at peace with your race is now left out of the raids you can receive, so an Aswid no longer gets the skeleton, blob or Bonemass raids. This counts your faction and your race's own list, the Aswid's boss-by-boss one included. Mixed raids still come. With player-based raids (the world modifier) it works on any server; with world-based raids a dedicated server needs the mod installed as well. Thanks to the player who reported it.
- **Fix - Allied creatures smashed buildings when you were not standing right next to them:** the truce only kept them off your structures while you were within 20 m of the creature, and some creatures pick a building from further away than that. Now, while any player they are at peace with is within 100 m, they leave every structure in the area alone, whoever built it. Hit one and its grudge lifts that protection for you, as it does for the truce.
### v1.5.0
- **New - The mod can be translated, and speaks Italian:** every text it shows now comes from JSON files in a `Translations` folder instead of the code - the race menu, status effects, items and pieces, messages, hover prompts, the faction merchants and their jokes, and the compendium. English and Italian ship with it; see [Translations](#translations) to add a language. Race names are separate from the internal race id, so a translated name never breaks a saved character, and merchant and boss names use the game's own translations. Thanks to the player who asked for it, and to Nando for the Italian merchant jokes.
- **Fix - Valheim 1.0 put the Crystal Golem and the Bound Sentry under Decorations:** the new build menu sorts pieces by tags the mod never set, so those two inherited the tags of the stone they are cloned from. Every station of the mod now sits under Crafting.