Merge branch 'war-vulture' into main

Brings in v1.4.3-v1.4.5 work: Trol's Hammer, Bone Servants, War Vulture
craftability, and the Aswid/Fenrir timed-claws rework, on top of the
bugfixes merged into main since v1.4.2.

Resolved conflicts in 7 files where main's post-v1.4.2 fixes overlapped
war-vulture's claws rework:
- README.md, manifest.json: took war-vulture's v1.4.5 content (main
  hadn't touched either since the v1.4.2 release).
- RacesOfValheim.cs: plugin version -> 1.4.5.
- RaceClaws.cs: kept war-vulture's lazy EnsureRoster() fix for the
  Fenrir claw-registration bug over main's belt-and-suspenders
  Register(this), and dropped the now-stale comment referencing the
  removed static constructor. Main's SetupDragItem race-ownership fix
  carried through untouched.
- AswidConfig.cs/AswidRace.cs/AswidPatches.cs: adopted war-vulture's
  single-key design (I toggles both Vampiric Aura and Devour together)
  to match the documented v1.4.5 trader-safety fix, removing a duplicate
  AuraEnabled field the two branches had each declared independently.
  Kept main's IsDownIgnoringHeldKeys() input fix on top.
- RaceCompendium.cs: kept main's fact-checked Aswid/Fenrir entries
  (war-vulture's copies were pre-fix stubs, one referencing a
  nonexistent variable) and layered in war-vulture's timed-claws
  wording.

Build verified clean (0 errors) after resolution.
This commit is contained in:
kanym 2026-08-18 17:36:42 +02:00
commit c2212df322
38 changed files with 3831 additions and 192 deletions

View file

@ -5,9 +5,10 @@ namespace RacesOfValheim
/// <summary>
/// The Claws of the Beast: the Bjorn claw, burned down to almost black.
///
/// Everything about how they behave - issued once, never dropped, back in hand the moment the
/// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Aswid's
/// half of the answer: which model, what colour, and when the race is wearing another body.
/// Everything about how they behave - a timed skill (RaceClawsConfig.ActivateKey), issued and
/// retracted on its own, back in hand the moment the hands are free while it runs, tier damage
/// as slash - lives in RaceClawSet. This file is only the Aswid's half of the answer: which
/// model, what colour, and when the race is wearing another body.
///
/// The tint is config rather than a constant because "almost black" is a look, not a number,
/// and it needs one pass in front of a mirror. It is applied to the item's own copies of the

View file

@ -23,7 +23,6 @@ namespace RacesOfValheim
public static ConfigEntry<KeyboardShortcut> MistFormKey;
public static ConfigEntry<KeyboardShortcut> EclipseKey;
public static ConfigEntry<KeyboardShortcut> TameKey;
public static ConfigEntry<KeyboardShortcut> ToggleAuraKey;
public static ConfigEntry<KeyboardShortcut> ToggleDevourKey;
// ─── Passive combat (scales with progression state, doubles at night) ────
@ -106,13 +105,8 @@ namespace RacesOfValheim
new ConfigDescription("Casts Eclipse, tier 6+. Fails silently at night."));
TameKey = config.Bind(keybinds, "Tame", new KeyboardShortcut(KeyCode.U),
new ConfigDescription("Tames the creature under your cursor, if your tier allows it."));
ToggleAuraKey = config.Bind(keybinds, "Toggle Vampiric Aura", new KeyboardShortcut(KeyCode.I),
new ConfigDescription("Turns the passive Vampiric Aura's damage/lifesteal on or off."));
// Unbound by default: Devour always stays on now that I is the Aura's toggle. Left as
// a real keybind, not removed, so anyone who still wants a switch for it can bind one
// themselves in Configuration Manager.
ToggleDevourKey = config.Bind(keybinds, "Toggle Devour Ability", new KeyboardShortcut(KeyCode.None),
new ConfigDescription("Turns the automatic Devour-on-kill behavior on or off. Unbound by default - Devour stays on unless you assign a key here."));
ToggleDevourKey = config.Bind(keybinds, "Toggle Devour Ability", new KeyboardShortcut(KeyCode.I),
new ConfigDescription("Turns the Vampiric Aura and the automatic Devour-on-kill behavior on or off together. Turn this off before talking to Haldor/Hildir - the aura does not recognize traders and will attack them."));
const string combat = "Aswid - Passive Combat";
DamageBonusPerState = config.Bind(combat, "Damage Bonus Per State", 2f,

View file

@ -529,17 +529,11 @@ namespace RacesOfValheim
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
if (__instance == Player.m_localPlayer && RaceInput.Allowed && AswidConfig.ToggleAuraKey.Value.IsDownIgnoringHeldKeys())
{
AswidRace.AuraEnabled = !AswidRace.AuraEnabled;
string msg = AswidRace.AuraEnabled ? "Vampiric Aura: ENABLED" : "Vampiric Aura: DISABLED";
__instance.Message(MessageHud.MessageType.Center, msg);
}
if (__instance == Player.m_localPlayer && RaceInput.Allowed && AswidConfig.ToggleDevourKey.Value.IsDownIgnoringHeldKeys())
{
AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
string msg = AswidRace.DevourEnabled ? "Devour Ability: ENABLED" : "Devour Ability: DISABLED";
AswidRace.AuraEnabled = AswidRace.DevourEnabled;
string msg = AswidRace.DevourEnabled ? "Vampiric Aura: ENABLED" : "Vampiric Aura: DISABLED";
__instance.Message(MessageHud.MessageType.Center, msg);
}

View file

@ -831,17 +831,18 @@ namespace RacesOfValheim
private float damageTickTimer = 0f;
/// <summary>Toggled by AswidConfig.ToggleAuraKey (Aswid_PlayerUpdate_Patch); on by default.</summary>
public static bool AuraEnabled = true;
/// <summary>
/// The Vampiric Aura is passive: it drains on its own, in every form, with no key to hold and
/// no icon or message of its own beyond the on/off toggle. The form only decides how hard it
/// bites.
/// The Vampiric Aura drains on its own, in every form, with no key to hold - but it does not
/// distinguish traders from monsters, so it can execute Haldor/Hildir on approach. AuraEnabled
/// (toggled with Devour on the same key) is the escape hatch for that.
/// </summary>
private void HandleVampiricAura()
{
if (!AuraEnabled) return;
if (!AuraEnabled)
{
damageTickTimer = 0f;
return;
}
damageTickTimer += Time.deltaTime;
if (damageTickTimer < AswidConfig.AuraTickInterval.Value) return;
@ -920,6 +921,7 @@ namespace RacesOfValheim
}
public static bool DevourEnabled = true;
public static bool AuraEnabled = true;
private static float lastConsumeTime = 0f;
public static void TryConsumeMob(Character c, float maxHp, bool bypassCooldown = false)

View file

@ -0,0 +1,292 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The two Bone Servants and their tables. Servants that work the stations around them and never
/// lift a hand against anything.
///
/// TWO TRADES, and that was the first thing the working version asked for. One servant serving a
/// whole yard spends its life walking: with the kitchen at one edge of the circle and the furnaces
/// at the other, travel eats the margin that keeps food off the fire. So there is a SMITH for the
/// Smelter family and a COOK for cooking stations and mead, each with its own table, each with its
/// own twenty-metre circle - and the two circles may sit on top of each other, because the servants
/// never look at the same station. PieceDensityLimit counts by prefab name, so "no second table
/// within forty metres" keeps smith away from smith and cook away from cook, and needed no change
/// at all to let a smith and a cook stand side by side.
///
/// The smith keeps the ORIGINAL prefab names, BoneServant and ServantTable. That is not tidiness -
/// it means a table already standing in a test world keeps working and keeps its servant instead of
/// becoming a missing prefab at the next load.
///
/// TWO PREFABS EACH, forced the same way the sentry's are: a Character cannot sit in the hammer's
/// piece table, so the buildable thing is the table and the servant is instantiated by it. Unlike
/// the sentry there is no seed piece to throw away, because here the table is not scaffolding - it
/// is the anchor, the summoning point and the only interface the feature has.
///
/// WHAT WAS DELIBERATELY NOT REUSED. The design said the servant would be a RaisedThrall, and it is
/// not. RaisedThrall brings the anchor, the leash and the withering, all of which are wanted - but
/// it also brings RaisedThrallInteractPatch, which turns E on the creature into a follow command.
/// A servant that can be told to follow you out of its own circle is a servant that stops serving,
/// and "E does nothing on the servant" was decided explicitly. So the useful half is reused as a
/// static - RaisedThrall.RegisterStation / StationStandsAt, which is what makes the table findable -
/// and the anchor and wither clock are thirty lines inside BoneServantAI. The alternative was
/// editing RaisedThrall.cs, which is shared with five other chains.
/// </summary>
public static class BoneServant
{
// The smith inherits the names the single servant had, so nothing already built is orphaned.
public const string SmithName = "BoneServant";
public const string SmithTableName = "ServantTable";
public const string SmithDisplay = "Bone Smith";
public const string SmithTableDisplay = "Smith's Table";
public const string CookName = "BoneCook";
public const string CookTableName = "CookTable";
public const string CookDisplay = "Bone Cook";
public const string CookTableDisplay = "Cook's Table";
/// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the
/// point here is to have none at all.</summary>
private const string ServantSource = "Skeleton_NoArcher";
public const float Health = 100f;
/// <summary>Two circles of twenty metres cannot overlap if the tables are forty apart, which is
/// how the question of two servants of the SAME trade fighting over one chest was answered - by
/// making the situation impossible to build rather than by sharing state between them.</summary>
public const float TableSpacing = 40f;
private const float TableScale = 0.8f;
/// <summary>
/// One skull, one wishbone, eight stone - the same price for both tables.
///
/// The skull is TrophySkeleton and NOT this mod's own CursedSkull, and that is forced rather
/// than chosen: the cursed skull is bought from the Skeleton faction's merchant, so building it
/// into the cook's price would make the cook unbuildable by the only race allowed to build it.
/// A skeleton trophy is a skull anyone can go and get.
///
/// The wishbone is a real cost and worth knowing about: it is Bonemass's drop and the only
/// treasure-finder in the game, so a standing table keeps yours locked up. Recovered in full
/// when the table is removed, like every other recipe in this mod.
/// </summary>
private static RequirementConfig[] Recipe()
{
return new[]
{
new RequirementConfig("TrophySkeleton", 1, 0, true),
new RequirementConfig("Wishbone", 1, 0, true),
new RequirementConfig("Stone", 8, 0, true),
};
}
public static void Register()
{
if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge))
{
RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge,
"A slab of bone and slate, dusted with ore. Something patient waits by the fires.",
"Coal");
PieceDensityLimit.Register(SmithTableName, TableSpacing, 1,
"Another smith's table stands within forty paces. One smith to a yard.");
// Two races, and it is the wider of the two locks: the Skeleton raises the dead to work
// for it, and Skadi's hold is a forge under ice.
PieceDensityLimit.RegisterGate(SmithTableName, (player, position) =>
{
if (SkeletonRace.IsSkeleton() || SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
"The bones do not answer to your blood.");
}
return false;
});
}
if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen))
{
RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen,
"A slab of bone and slate, worn smooth. Something patient waits by the hearth.",
"CookedMeat");
PieceDensityLimit.Register(CookTableName, TableSpacing, 1,
"Another cook's table stands within forty paces. One cook to a yard.");
// Skadi alone. A hearth kept by something dead is hers, not the Skeleton's.
PieceDensityLimit.RegisterGate(CookTableName, (player, position) =>
{
if (SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
"Only Skadi's hearth is kept by the dead.");
}
return false;
});
}
}
// ---------------------------------------------------------------- the servants
private static bool RegisterServant(string prefabName, string displayName, ButlerFamily family)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, ServantSource);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone {ServantSource}; " +
$"{displayName} is not registered.");
return false;
}
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = displayName;
character.m_health = Health;
character.m_faction = Character.Faction.Players;
}
// Nothing in its hands, and nothing to roll for. Belt and braces with the AI prefix: the
// code that would swing a weapon never runs, but a servant carrying a rusty sword around
// the kitchen would still look like a mistake.
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
humanoid.m_defaultItems = new GameObject[0];
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
ai.m_randomMoveRange = 0f; // it never wanders: every step it takes is a decision
ai.m_avoidFire = false; // it works next to kilns for a living
ai.m_afraidOfFire = false;
}
// A servant that dropped bones would be a bone mill, exactly as with the garrison.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Ten seconds unhurt, then two percent a second. The sentry's regeneration, whole.
prefab.AddComponent<SkeletonSentryBehaviour>();
BoneServantAI servant = prefab.AddComponent<BoneServantAI>();
servant.m_family = family;
PrefabManager.Instance.AddPrefab(prefab);
return true;
}
// ---------------------------------------------------------------- the tables
private static void RegisterTable(string pieceName, string displayName, string servantPrefab,
ButlerFamily family, string description, string iconSource)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone piece_cartographytable; " +
$"the {displayName} is not registered.");
return;
}
// The MapTable trap, and it is the reason this is a blanket sweep by capability rather than
// a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key
// before our own Switch ever sees it and opens the shared map instead. Same bug as the
// barrel's Container on the Fenrir trough and the Trader on the vanilla wolf; the Dvergar
// contract bank pays for this lesson already.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
prefab.transform.localScale = Vector3.one * TableScale;
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>();
table.m_switch.m_name = displayName;
table.m_title = displayName;
table.m_servantPrefab = servantPrefab;
table.m_family = family;
Sprite icon = BorrowIcon(iconSource) ?? BorrowIcon("TrophySkeleton");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = displayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = displayName,
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = Recipe(),
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
LearnPiece(traverse, SmithTableName);
LearnPiece(traverse, CookTableName);
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static void LearnPiece(Traverse player, string pieceName)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(pieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
player.Method("AddKnownPiece", piece).GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneServantKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneServant.EnsureKnown(__instance);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,50 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The four knobs the Bone Servant exposes, and deliberately only four.
///
/// Butler_BoneServant.txt sec. 14 turned down "expose everything": tick cadence, safety margins,
/// penalty-box time and the spacing between tables are constants in the code, because they are
/// numbers that get tuned once during the test and then never again - and every config entry is
/// maintained forever.
///
/// The sigil is here for a different reason from the other three. It is a PLACEHOLDER: bone
/// fragments stand in for a craftable sigil that only gets made if the feature leaves the test,
/// and being able to move the mark onto another item without a rebuild is the whole point of the
/// entry.
/// </summary>
public static class ButlerConfig
{
public static ConfigEntry<string> SigilItem;
public static ConfigEntry<float> WorkRadius;
public static ConfigEntry<float> FuelThreshold;
public static ConfigEntry<float> ResummonSeconds;
public static void Bind(ConfigFile config)
{
const string section = "Butler - Bone Servant";
SigilItem = config.Bind(section, "Sigil Item", "BoneFragments",
new ConfigDescription("Prefab name of the item that marks a chest as the servant's. " +
"A chest holding at least one of these is worked from and " +
"delivered to; every other chest is left alone. The sigil itself " +
"is never taken and never processed."));
WorkRadius = config.Bind(section, "Work Radius", 20f,
new ConfigDescription("Metres from the Servant's Table within which chests and stations " +
"are served.", new AcceptableValueRange<float>(5f, 40f)));
FuelThreshold = config.Bind(section, "Fuel Threshold", 0.25f,
new ConfigDescription("Refuel a station when its fuel drops below this fraction of its " +
"maximum, and only while it has something to work on.",
new AcceptableValueRange<float>(0f, 1f)));
ResummonSeconds = config.Bind(section, "Resummon Cooldown", 0f,
new ConfigDescription("Seconds that must pass before a fallen servant can be raised " +
"again. Zero is free and immediate, which is what the test runs on.",
new AcceptableValueRange<float>(0f, 600f)));
}
}
}

View file

@ -0,0 +1,496 @@
using System;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Which servant a station belongs to.
///
/// The split is not cosmetic, it is the answer to the one complaint the first working version drew:
/// with a kitchen at one edge of the circle and three furnaces at the other, a single servant spends
/// its life walking and the margin that keeps food off the fire gets eaten by travel. Two servants
/// with two tables in the same yard walk half as far each.
///
/// It also cuts the AI in half along a seam that was already there. FORGE cannot spoil - a smelter
/// holds its ore forever and drops its own output - so the forge servant has no clock, never runs,
/// and never pre-empts itself. All of that machinery lives on in the KITCHEN, which is the only
/// place it was ever needed.
/// </summary>
public enum ButlerFamily
{
/// <summary>Smelter: furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
/// refinery. Nothing here has a deadline.</summary>
Forge,
/// <summary>CookingStation and Fermenter: hearths, ovens and mead. The only family with a
/// clock.</summary>
Kitchen,
}
/// <summary>
/// One working station, seen through the handful of questions the servant ever asks it.
///
/// THREE FAMILIES, and they are not variations on a theme - they behave OPPOSITELY on output, which
/// is the single fact the whole feature is built around (Butler_BoneServant.txt sec. 5, all of it
/// read off assembly_valheim.dll with Cecil rather than guessed):
///
/// Smelter furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
/// refinery. Its output FALLS ON THE GROUND BY ITSELF - UpdateSmelter runs
/// RemoveOneOre -> QueueProcessed -> SpawnProcessed with nobody asking. Nothing
/// to pull; the servant just picks the bars up.
/// CookingStation hearth, iron cooking station, stone oven. Output STAYS IN THE SLOT and keeps
/// cooking: Done at m_cookTime, Burnt at exactly twice it (verified: the IL
/// literally loads m_cookTime, pushes 2 and multiplies). This is the family that
/// can lose you food, and the only one with a clock.
/// Fermenter mead. Output stays in until the tap is opened, and never spoils.
///
/// NOTHING HERE KNOWS WHAT A MATERIAL IS. Every family exposes IsItemAllowed(string) and
/// GetItemConversion(string), matching on the PREFAB name (m_from.gameObject.name - verified), so
/// the servant asks the station "do you take this?" instead of carrying a list of ores and crops.
/// That is what makes it serve this mod's own stations, other races' stations, and other mods'
/// stations without a line of code per station.
///
/// WHY SO MUCH REFLECTION. Every one of those question methods is PRIVATE in this build -
/// GetQueueSize, IsItemAllowed, GetSlot, GetFuel, HaveDoneItem, IsFireLit, GetStatus, the lot - and
/// both Status enums are private nested types, so they cannot even be named in source. The
/// alternative was reimplementing each station's rules by reading its public m_conversion list,
/// which would be a second copy of vanilla's logic drifting out of step at the next patch. Calling
/// the real method through a cached MethodInfo is the smaller lie. The enum values are hard-coded
/// as ints, and they are not guesses: Cecil reports NotDone=0, Done=1, Burnt=2 and Empty=0,
/// Fermenting=1, Exposed=2, Ready=3.
///
/// Every write goes through InvokeRPC with the name the station REGISTERED, which carries the
/// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op,
/// which is exactly the class of bug that takes an evening to find, so the four names below were
/// read out of each Awake() rather than remembered.
/// </summary>
public abstract class ButlerStation
{
public Component Behaviour;
public ZNetView Nview;
public Transform Transform;
public Vector3 Position { get { return Transform.position; } }
public ZDOID Id
{
get { return Nview != null && Nview.IsValid() ? Nview.GetZDO().m_uid : ZDOID.None; }
}
public bool Alive { get { return Behaviour != null && Nview != null && Nview.IsValid(); } }
/// <summary>Wraps whichever of the three this object is, or null if it is not a station.</summary>
public static ButlerStation From(GameObject go)
{
if (go == null) return null;
ZNetView nview = go.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return null;
Smelter smelter = go.GetComponent<Smelter>();
if (smelter != null) return Fill(new SmelterStation { m_smelter = smelter }, smelter, nview);
CookingStation cooking = go.GetComponent<CookingStation>();
if (cooking != null) return Fill(new CookingStationStation { m_cooking = cooking }, cooking, nview);
Fermenter fermenter = go.GetComponent<Fermenter>();
if (fermenter != null) return Fill(new FermenterStation { m_fermenter = fermenter }, fermenter, nview);
return null;
}
private static ButlerStation Fill(ButlerStation station, Component behaviour, ZNetView nview)
{
station.Behaviour = behaviour;
station.Nview = nview;
station.Transform = behaviour.transform;
return station;
}
/// <summary>
/// Taking ownership before writing is the multiplayer rule of this feature (sec. 10), and it
/// buys a second thing that matters here: once we own the ZDO the RPC runs locally and
/// immediately, so GetQueueSize and GetFuel answer truthfully on the very next line instead of
/// a network round trip later.
/// </summary>
protected void Claim()
{
if (Nview != null && Nview.IsValid() && !Nview.IsOwner()) Nview.ClaimOwnership();
}
// ---------------------------------------------------------------- what the servant asks
/// <summary>Which of the two servants this one belongs to.</summary>
public abstract ButlerFamily Family { get; }
/// <summary>Can it work at all right now - fire lit, roof up? An inoperable station is skipped
/// in silence, which is a decision and not an oversight (sec. 7.7).</summary>
public abstract bool Operable { get; }
/// <summary>How many more items it can take. Zero means full.</summary>
public abstract int FreeSlots { get; }
public abstract bool Accepts(string prefabName);
/// <summary>Puts one unit in. Called FreeSlots times at most, never more.</summary>
public abstract void Add(string prefabName);
/// <summary>True while it has something to work on - so an empty furnace is never stoked.</summary>
public abstract bool HasWork { get; }
public abstract string FuelPrefab { get; }
/// <summary>Units of fuel it wants right now, already filtered by the configured threshold.</summary>
public abstract int FuelWanted { get; }
public abstract void AddFuel();
/// <summary>Something finished and needs a hand to get out. Always false for the Smelter, which
/// throws its own output on the floor.</summary>
public abstract bool HasOutput { get; }
/// <summary>Gets the finished goods onto the ground at <paramref name="at"/>, where the one
/// pickup routine will find them.</summary>
public abstract void PullOutput(Vector3 at);
/// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that
/// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary>
public virtual float SecondsToSpoil { get { return float.MaxValue; } }
// ================================================================ the private doors
/// <summary>
/// Every private member of the three station classes this feature touches, resolved once.
///
/// Anything that fails to resolve stays null and its caller falls back to the safe answer -
/// "cannot tell, do not act" - so a future patch that renames one method costs that one
/// capability and a line in the log, not a servant that stands still or, worse, one that keeps
/// pouring ore into a station it can no longer read.
/// </summary>
private static class Vanilla
{
public static readonly MethodInfo SmelterQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize");
public static readonly MethodInfo SmelterAllowed =
AccessTools.Method(typeof(Smelter), "IsItemAllowed", new[] { typeof(string) });
public static readonly MethodInfo SmelterFuel = AccessTools.Method(typeof(Smelter), "GetFuel");
public static readonly FieldInfo SmelterHaveRoof = AccessTools.Field(typeof(Smelter), "m_haveRoof");
public static readonly MethodInfo CookGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot");
public static readonly MethodInfo CookEmpty = AccessTools.Method(typeof(CookingStation), "IsEmpty");
public static readonly MethodInfo CookHaveDone = AccessTools.Method(typeof(CookingStation), "HaveDoneItem");
public static readonly MethodInfo CookAllowed =
AccessTools.Method(typeof(CookingStation), "IsItemAllowed", new[] { typeof(string) });
public static readonly MethodInfo CookConversion =
AccessTools.Method(typeof(CookingStation), "GetItemConversion", new[] { typeof(string) });
public static readonly MethodInfo CookFuel = AccessTools.Method(typeof(CookingStation), "GetFuel");
public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit");
public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus");
public static readonly MethodInfo FermenterAllowed =
AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(string) });
// CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named
// in source, so they travel as ints. Values read from the assembly, not assumed.
public const int CookNotDone = 0;
public const int CookDone = 1;
public const int CookBurnt = 2;
public const int FermentEmpty = 0;
public const int FermentExposed = 2;
public const int FermentReady = 3;
public static bool Call(MethodInfo method, object target, bool fallback)
{
if (method == null) return fallback;
return (bool)method.Invoke(target, null);
}
public static int CallInt(MethodInfo method, object target, int fallback)
{
if (method == null) return fallback;
return Convert.ToInt32(method.Invoke(target, null));
}
public static float CallFloat(MethodInfo method, object target, float fallback)
{
if (method == null) return fallback;
return Convert.ToSingle(method.Invoke(target, null));
}
public static bool Allowed(MethodInfo method, object target, string prefabName)
{
if (method == null || string.IsNullOrEmpty(prefabName)) return false;
return (bool)method.Invoke(target, new object[] { prefabName });
}
}
// ================================================================ Smelter
private class SmelterStation : ButlerStation
{
public Smelter m_smelter;
public override ButlerFamily Family { get { return ButlerFamily.Forge; } }
public override bool Operable
{
get
{
if (!m_smelter.m_requiresRoof) return true;
if (Vanilla.SmelterHaveRoof == null) return true; // cannot tell: let it try
return (bool)Vanilla.SmelterHaveRoof.GetValue(m_smelter);
}
}
private int Queued { get { return Vanilla.CallInt(Vanilla.SmelterQueueSize, m_smelter, int.MaxValue); } }
public override int FreeSlots
{
get { return Mathf.Max(0, m_smelter.m_maxOre - Queued); }
}
public override bool Accepts(string prefabName)
{
return Vanilla.Allowed(Vanilla.SmelterAllowed, m_smelter, prefabName);
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddOre", prefabName);
}
public override bool HasWork { get { return Queued > 0; } }
public override string FuelPrefab
{
get { return m_smelter.m_fuelItem != null ? m_smelter.m_fuelItem.gameObject.name : null; }
}
public override int FuelWanted
{
get
{
if (m_smelter.m_fuelItem == null || m_smelter.m_maxFuel <= 0) return 0;
if (!HasWork) return 0;
float fuel = Vanilla.CallFloat(Vanilla.SmelterFuel, m_smelter, float.MaxValue);
if (fuel >= m_smelter.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
return Mathf.Max(0, Mathf.FloorToInt(m_smelter.m_maxFuel - fuel));
}
}
public override void AddFuel()
{
Claim();
Nview.InvokeRPC("RPC_AddFuel");
}
// The whole point of this family: nothing to collect, it drops its own.
public override bool HasOutput { get { return false; } }
public override void PullOutput(Vector3 at) { }
}
// ================================================================ CookingStation
private class CookingStationStation : ButlerStation
{
public CookingStation m_cooking;
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
private int SlotCount
{
get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; }
}
/// <summary>GetSlot hands back three values through out parameters, one of which is a
/// private enum. Through reflection that means an args array and an int.</summary>
private bool ReadSlot(int index, out string name, out float cooked, out int status)
{
name = null;
cooked = 0f;
status = Vanilla.CookNotDone;
if (Vanilla.CookGetSlot == null) return false;
object[] args = new object[] { index, null, null, null };
Vanilla.CookGetSlot.Invoke(m_cooking, args);
name = args[1] as string;
cooked = Convert.ToSingle(args[2]);
status = Convert.ToInt32(args[3]);
return true;
}
public override bool Operable
{
get { return !m_cooking.m_requireFire || Vanilla.Call(Vanilla.CookFireLit, m_cooking, false); }
}
public override int FreeSlots
{
get
{
int free = 0;
for (int i = 0; i < SlotCount; i++)
{
string name;
float cooked;
int status;
if (!ReadSlot(i, out name, out cooked, out status)) return 0;
if (string.IsNullOrEmpty(name)) free++;
}
return free;
}
}
public override bool Accepts(string prefabName)
{
return Vanilla.Allowed(Vanilla.CookAllowed, m_cooking, prefabName);
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName);
}
public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } }
public override string FuelPrefab
{
get
{
return m_cooking.m_useFuel && m_cooking.m_fuelItem != null
? m_cooking.m_fuelItem.gameObject.name
: null;
}
}
public override int FuelWanted
{
get
{
if (!m_cooking.m_useFuel || m_cooking.m_fuelItem == null || m_cooking.m_maxFuel <= 0) return 0;
if (!HasWork) return 0;
float fuel = Vanilla.CallFloat(Vanilla.CookFuel, m_cooking, float.MaxValue);
if (fuel >= m_cooking.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
return Mathf.Max(0, Mathf.FloorToInt(m_cooking.m_maxFuel - fuel));
}
}
public override void AddFuel()
{
Claim();
Nview.InvokeRPC("RPC_AddFuel");
}
public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } }
/// <summary>
/// ONE per done slot, and the 1 is not a stylistic choice. RPC_RemoveDoneItem spawns the
/// item <c>amount</c> times PER SLOT (verified in the IL: the inner loop runs to the
/// argument), so passing anything above 1 would not collect faster - it would print money.
/// </summary>
public override void PullOutput(Vector3 at)
{
Claim();
Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1);
}
/// <summary>
/// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is
/// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its
/// remaining half is all that stands between dinner and charcoal.
///
/// GetItemConversion is asked with whatever name the slot currently holds, which is the raw
/// item before Done and the COOKED one after: CookingStation.GetItemConversion matches on
/// both m_from and m_to (verified), so the cook time is readable in either phase.
/// </summary>
public override float SecondsToSpoil
{
get
{
if (Vanilla.CookConversion == null) return float.MaxValue;
float soonest = float.MaxValue;
for (int i = 0; i < SlotCount; i++)
{
string name;
float cooked;
int status;
if (!ReadSlot(i, out name, out cooked, out status)) break;
if (string.IsNullOrEmpty(name)) continue;
if (status == Vanilla.CookBurnt) continue; // already lost, no hurry
CookingStation.ItemConversion conversion =
Vanilla.CookConversion.Invoke(m_cooking, new object[] { name })
as CookingStation.ItemConversion;
if (conversion == null) continue;
float left = conversion.m_cookTime * 2f - cooked;
if (left < soonest) soonest = left;
}
return soonest;
}
}
}
// ================================================================ Fermenter
private class FermenterStation : ButlerStation
{
public Fermenter m_fermenter;
/// <summary>Mead goes with the food. It has no deadline of its own, so it costs the cook
/// nothing beyond one more thing to fill and one more tap to open.</summary>
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
private int Status
{
get { return Vanilla.CallInt(Vanilla.FermenterStatus, m_fermenter, Vanilla.FermentExposed); }
}
public override bool Operable { get { return Status != Vanilla.FermentExposed; } }
public override int FreeSlots { get { return Status == Vanilla.FermentEmpty ? 1 : 0; } }
public override bool Accepts(string prefabName)
{
return Vanilla.Allowed(Vanilla.FermenterAllowed, m_fermenter, prefabName);
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName);
}
public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } }
public override string FuelPrefab { get { return null; } }
public override int FuelWanted { get { return 0; } }
public override void AddFuel() { }
public override bool HasOutput { get { return Status == Vanilla.FermentReady; } }
/// <summary>Opens the tap. The bottles are not out yet when this returns - DelayedTap waits
/// m_tapDelay for the animation - so the servant collects them on a later pass, which the
/// pickup sweep handles without knowing anything about fermenting.</summary>
public override void PullOutput(Vector3 at)
{
Claim();
Nview.InvokeRPC("RPC_Tap");
}
}
}
}

View file

@ -0,0 +1,170 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A servant's table: an anchor, a summoning point and the feature's only window. One class serves
/// both trades - what changes between the smith's and the cook's is three fields set at
/// registration, not behaviour.
///
/// It does no work of its own. Everything it knows it asks the servant, and everything the servant
/// says it says here - the hover text is the ONE feedback channel this feature has, by decision, so
/// a servant that has stopped must be able to explain itself from a line of text or it is
/// indistinguishable from a broken mod.
///
/// E RAISES, and that is all E does. There is no pause switch and no automatic re-forming: a fallen
/// servant leaves the table empty until somebody notices. That was chosen over a sixty-second
/// respawn on the grounds that a death nobody notices is a death that might as well not happen.
///
/// It registers itself with RaisedThrall's station list, which is what BoneServantAI's wither clock
/// asks when it wants to know whether its table is still standing. That list is the only part of
/// the thrall machinery this feature uses.
/// </summary>
public class ServantTableBehaviour : MonoBehaviour
{
public Switch m_switch;
/// <summary>Set on the prefab at registration, so both travel to every instance.</summary>
public string m_title = "Servant's Table";
public string m_servantPrefab = BoneServant.SmithName;
public ButlerFamily m_family = ButlerFamily.Forge;
private const string KeyLastRaise = "RoV_butlerRaisedAt";
/// <summary>Where the servant stands up: in front of the table, clear of the mesh.</summary>
private const float RaiseOffset = 1.2f;
private ZNetView m_nview;
private void Awake()
{
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (Servant() != null)
{
player.Message(MessageHud.MessageType.Center, "It is already at work.");
return false;
}
float wait = Cooldown();
if (wait > 0f)
{
player.Message(MessageHud.MessageType.Center,
$"The bones are not ready. {Mathf.CeilToInt(wait)}s.");
return false;
}
return Raise(player);
}
private bool Raise(Player player)
{
if (m_nview == null || !m_nview.IsValid()) return false;
if (ZNetScene.instance == null) return false;
GameObject prefab = ZNetScene.instance.GetPrefab(m_servantPrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised.");
player.Message(MessageHud.MessageType.Center, "Nothing answers.");
return false;
}
// Owner-only, so in multiplayer exactly one servant stands up rather than one per client.
m_nview.ClaimOwnership();
Vector3 at = transform.position + transform.forward * RaiseOffset;
GameObject spawned = Object.Instantiate(prefab, at, Quaternion.identity);
BoneServantAI servant = spawned.GetComponent<BoneServantAI>();
if (servant != null) servant.Bind(transform.position);
if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks);
player.Message(MessageHud.MessageType.Center, "The servant rises.");
return true;
}
/// <summary>Seconds still to wait, or zero. Kept in world time so logging out does not pay it off
/// for free - and configured to zero for the test, where it is simply never in the way.</summary>
private float Cooldown()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0f;
float required = ButlerConfig.ResummonSeconds.Value;
if (required <= 0f) return 0f;
long stamp = m_nview.GetZDO().GetLong(KeyLastRaise, 0L);
if (stamp == 0L) return 0f;
double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds;
return Mathf.Max(0f, required - (float)elapsed);
}
// ---------------------------------------------------------------- the hover
private string Hover()
{
BoneServantAI servant = Servant();
if (servant == null)
{
return m_title + "\nNo servant stands here.\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Raise one";
}
string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = "Waiting.";
return m_title + "\n" + status;
}
/// <summary>
/// This table's servant, if it is alive and loaded.
///
/// Matched by anchor rather than by a stored id, so a table rebuilt on the same spot adopts the
/// servant already standing there - and by TRADE as well, because a smith's table and a cook's
/// table are allowed to stand a metre apart and must not adopt each other's servant.
/// </summary>
private BoneServantAI Servant()
{
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
BoneServantAI servant = character.GetComponent<BoneServantAI>();
if (servant == null || servant.m_family != m_family) continue;
if (servant.IsBoundTo(transform.position)) return servant;
}
return null;
}
}
}

View file

@ -295,6 +295,17 @@ namespace RacesOfValheim
// Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here.
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplayName;
// DISABLED ON PURPOSE, and it is the line that keeps the log clean. Trader was written for
// Haldor, who is a creature with an animator and a LookAt rig: Trader.Update() calls
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() with no null check on every
// frame no player is nearby, and Trader.Start() calls InvokeRepeating("RandomTalk", 0, 0)
// on a component nobody authored in the editor. On a table both of those are null, so the
// bank threw a NullReferenceException every frame from the moment it was built. A disabled
// component runs neither, and StoreGui needs neither: Show() only reads fields off the
// Trader and asks it for its item list, and GetComponent finds it disabled just the same.
// This is the same fix SvermHiveStore.Mount already carries for the Hive Market.
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();

View file

@ -38,14 +38,41 @@ namespace RacesOfValheim
public const string JokeNonMortoZombie = "NonMortoZombie";
public const string JokeFantasma = "Fantasma";
// Every merchant in the mod buys/sells these regardless of what its own list
// carries - players kept running into benches that could not fence basic building
// mats. Folded into each ShopDefinition.Items below (WithDefaults) rather than
// handled in FactionMerchantSetup/FactionMerchantSellPanel, so both the buy and
// sell columns pick it up for free.
private static readonly List<CatalogEntry> DefaultItems = new List<CatalogEntry>
{
new CatalogEntry("Wood", 1),
new CatalogEntry("Stone", 1),
new CatalogEntry("FineWood", 5),
new CatalogEntry("Flint", 5),
new CatalogEntry("RoundLog", 10), // Core wood's internal prefab name
};
// Appends whichever DefaultItems aren't already named in items, explicit entries
// win so a shop can still special-price one of these if it ever needs to.
private static List<CatalogEntry> WithDefaults(List<CatalogEntry> items)
{
var combined = new List<CatalogEntry>(items);
foreach (CatalogEntry defaultEntry in DefaultItems)
{
if (!combined.Exists(e => e.PrefabName == defaultEntry.PrefabName))
{
combined.Add(defaultEntry);
}
}
return combined;
}
private static readonly ShopDefinition GreydwarfShop = new ShopDefinition
{
DisplayName = "Greydwarf",
JokeCategory = JokeLegnoFalegname,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("Wood", 1),
new CatalogEntry("Stone", 2),
new CatalogEntry("Resin", 5),
new CatalogEntry("GreydwarfEye", 5),
new CatalogEntry("Dandelion", 5),
@ -60,14 +87,14 @@ namespace RacesOfValheim
new CatalogEntry("TrophyGreydwarf", 20),
new CatalogEntry("TrophyGreydwarfBrute", 350),
new CatalogEntry("TrophyGreydwarfShaman", 350),
}
})
};
private static readonly ShopDefinition TrollShop = new ShopDefinition
{
DisplayName = "Troll",
JokeCategory = JokeTroll,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("TrollHide", 1),
new CatalogEntry("DeerHide", 2),
@ -79,14 +106,14 @@ namespace RacesOfValheim
new CatalogEntry("TrophyDeer", 20),
new CatalogEntry("TrophyBoar", 50),
new CatalogEntry("TrophyForestTroll", 1500),
}
})
};
private static readonly ShopDefinition FulingShop = new ShopDefinition
{
DisplayName = "Fuling",
JokeCategory = JokeGoblin,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("BlackMetalScrap", 1),
new CatalogEntry("LoxMeat", 1),
@ -114,7 +141,7 @@ namespace RacesOfValheim
new CatalogEntry("TrophyGrowth", 800), // Growth
new CatalogEntry("TrophyGoblinBrute", 1500),
new CatalogEntry("TrophySerpent", 1500),
}
})
};
// The Shaman alone stocks the Furling's crop line, so it needs a bench of its own - the four
@ -160,7 +187,7 @@ namespace RacesOfValheim
{
DisplayName = "Ulv",
JokeCategory = JokeLupoLicantropo,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("WolfFang", 5),
new CatalogEntry("WolfMeat", 5),
@ -171,52 +198,52 @@ namespace RacesOfValheim
new CatalogEntry("TrophyWolf", 350),
new CatalogEntry("TrophyUlv", 350),
new CatalogEntry("TrophyHatchling", 350), // Drake (internal id "Hatchling")
}
})
};
private static readonly ShopDefinition FenringShop = new ShopDefinition
{
DisplayName = "Fenring",
JokeCategory = JokeLupoLicantropo,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("WolfFang", 5),
new CatalogEntry("Ulvsblod", 500), // gates the Fenrir pack trough
new CatalogEntry("GreaterUlvsblod", 1500), // upgrades it: the fenrir themselves
new CatalogEntry("TrophyFenring", 350),
}
})
};
private static readonly ShopDefinition CultistShop = new ShopDefinition
{
DisplayName = "Cultist",
JokeCategory = JokeStrega,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("JuteRed", 2),
new CatalogEntry("GreaterFrostHeart", 1500), // the Skadi's bought reagent
new CatalogEntry("TrophyCultist", 1500),
}
})
};
private static readonly ShopDefinition DvergShop = new ShopDefinition
{
DisplayName = "Dverg",
JokeCategory = JokeNano,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("BlackMarble", 20),
new CatalogEntry("Softtissue", 250),
new CatalogEntry("Sap", 250), // extracted from Yggdrasil roots with Dvergr extractors
new CatalogEntry("TrophyDvergr", 1500),
}
})
};
private static readonly ShopDefinition DraugrShop = new ShopDefinition
{
DisplayName = "Draugr",
JokeCategory = JokeNonMortoZombie,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("Entrails", 2),
new CatalogEntry("Mushroom", 5),
@ -234,14 +261,14 @@ namespace RacesOfValheim
new CatalogEntry("TrophyLeech", 350), // Leech
new CatalogEntry("TrophyDraugrElite", 800),
new CatalogEntry("TrophyAbomination", 1500), // Abomination
}
})
};
private static readonly ShopDefinition SkeletonShop = new ShopDefinition
{
DisplayName = "Skeleton",
JokeCategory = JokeScheletro,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("BoneFragments", 1),
new CatalogEntry("Ooze", 2), // Blob/Oozer, folded in here: no talk-capable rig
@ -252,29 +279,29 @@ namespace RacesOfValheim
new CatalogEntry("SoulStone", 50), // binds a skeleton archer sentry
new CatalogEntry("CursedSkull", 500), // gates the Skeleton bone pile
new CatalogEntry("GreaterCursedSkull", 1500), // upgrades it: the rotten
}
})
};
private static readonly ShopDefinition GhostShop = new ShopDefinition
{
DisplayName = "Ghost",
JokeCategory = JokeFantasma,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("Ectoplasm", 2),
new CatalogEntry("TrophyGhost", 350),
}
})
};
private static readonly ShopDefinition WraithShop = new ShopDefinition
{
DisplayName = "Wraith",
JokeCategory = JokeFantasma,
Items = new List<CatalogEntry>
Items = WithDefaults(new List<CatalogEntry>
{
new CatalogEntry("Chain", 5),
new CatalogEntry("TrophyWraith", 1500),
}
})
};
// Key = vanilla creature prefab name (internal id, not the wiki display name).

View file

@ -11,19 +11,63 @@ namespace RacesOfValheim
// 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

View file

@ -5,9 +5,10 @@ namespace RacesOfValheim
/// <summary>
/// The Cursed Claws: the flesh rippers, worn exactly as the game authored them.
///
/// Everything about how they behave - issued once, never dropped, back in hand the moment the
/// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Fenrir's
/// half: which model, and when the race is currently a wolf.
/// Everything about how they behave - a timed skill (RaceClawsConfig.ActivateKey), issued and
/// retracted on its own, back in hand the moment the hands are free while it runs, tier damage
/// as slash - lives in RaceClawSet. This file is only the Fenrir's half: which model, and when
/// the race is currently a wolf.
///
/// No tint. The fenrir claw already looks like something a Fenrir would grow, which is the
/// whole reason it is the one being borrowed.

View file

@ -1,33 +1,42 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Claws that are part of the body, for the races that grow a pair.
/// Claws that are part of the body, for the races that grow a pair - as an ACTIVE SKILL. A
/// keypress (RaceClawsConfig.ActivateKey) grows them for RaceClawsConfig.DurationSeconds, and
/// they retract - unequipped and removed from the inventory outright - the moment that timer
/// runs out. Recasting mid-window simply restarts the timer.
///
/// This is SvermClawSlot generalised, not reinvented: the Sverm's Vilebone Maulclaws worked out
/// This is SvermClawSlot generalised, not reinvented: the Sverm's Chitin Claws worked out
/// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object
/// with a different face. So the machinery moved here and each race supplies only what is
/// genuinely its own - the item name, the model to wear, and whether it is currently a wolf.
/// The Sverm still runs its own copy, untouched, because it also carries a carapace, a stinger
/// form and a fire term at Fader that none of this knows about.
/// The Sverm still runs its own copy, untouched (permanent, not timed), because it also carries
/// a carapace, a stinger form and a fire term at Fader that none of this knows about.
///
/// WHY A REAL ITEM AND NOT A COSMETIC. Bolting a model to the hand bones works right up until
/// the game rebuilds equipment visuals - which it does on every equip - and wipes it. A real
/// item in a real slot has nothing to put back. The trade is that a real weapon occupies the
/// right hand, so three rules keep that reading as intended rather than as a bug: sheathe
/// anything else and the claws come back, the holster key cannot put them away, and they
/// cannot be dragged, moved or dropped.
/// anything else and the claws come back (while the skill is still running), the holster key
/// cannot put them away, and they cannot be dragged, moved or dropped. None of that costs an
/// inventory slot outside the two-minute window any more, which was the whole reason to move
/// off the earlier "issued once, forever" version: a slot permanently occupied by an
/// unremovable item was a standing annoyance, not a feature.
///
/// BALANCE IS SHARED ON PURPOSE. The damage is not read from the model each race wears - the
/// Fenrir's flesh rippers and the Bjorn claw are not worth the same, and a race should not be
/// stronger because its claws are prettier. Every set reads the Sverm's own reference weapon at
/// quality 4 and the Sverm's own per-tier percentages, so all three races hit for identical
/// numbers at identical tiers. What differs here is the shape of the damage: these two land it
/// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader.
/// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader. The
/// damage bonus itself only applies while the claws are the thing actually equipped - see
/// ApplyToUnarmedHit - so a bare-fisted punch after they retract is a bare-fisted punch.
/// </summary>
public abstract class RaceClawSet
{
@ -69,39 +78,52 @@ namespace RacesOfValheim
// ─── Registry ────────────────────────────────────────────────────────
private static readonly List<RaceClawSet> sets = new List<RaceClawSet>();
private static bool rosterBuilt;
/// <summary>
/// The roster. Kept here rather than in RacesOfValheim.Awake so the whole feature is this
/// file plus one short file per race, and adding a third clawed race is one line - not one
/// line here and another one three hundred lines away in the plugin's startup.
///
/// A BACKSTOP ONLY - EnsureRegistered is what actually fills this list, and it has to be.
/// This constructor cannot be trusted to register a race that is still being constructed,
/// and one of them always is:
/// BUILT LAZILY, AND NOT FROM A STATIC CONSTRUCTOR. That is the fix for a bug that cost the
/// Fenrir this entire feature while the Aswid worked perfectly, which is exactly what made
/// it hard to see: the item registered, the model resolved, the patch ran, and the race
/// resolved to "Fenrir" - the set simply was not in this list.
///
/// FenrirRace.CreateModAssets touches FenrirClaws.Instance
/// -> the CLR begins FenrirClaws' static init: Instance = new FenrirClaws()
/// -> constructing a derived type runs the BASE type's static ctor first, i.e. this one
/// -> this one reads FenrirClaws.Instance... which is still null, because the static
/// init that will assign it is the thing waiting on us
/// -> Register(null) returns silently, and the Fenrir is left out of the roster for the
/// rest of the session: For() never matches it, so Maintain never runs, so the
/// Cursed Claws are never issued and never do their damage.
/// The trap is .NET type initialisation re-entrancy. FenrirRace.CreateModAssets touches
/// FenrirClaws.Instance first (before AswidRace does its own), which starts FenrirClaws's
/// type initialiser; constructing that instance triggers this base type's static
/// constructor, which reaches back for FenrirClaws.Instance - still null, because its field
/// initialiser is halfway through running further down the same stack. The CLR does not
/// wait and does not re-run it: it hands back null. Register(null) then returned quietly and
/// the Fenrir was absent from the roster forever, while the Aswid - reached from inside the
/// static constructor rather than from outside it - was added normally.
///
/// It bit the Fenrir and not the Aswid purely because FenrirRace.CreateModAssets runs
/// first in RacesOfValheim.CreateAllModAssets - whichever race gets there first is the one
/// that is half-built when this runs. Register(this) in EnsureRegistered closes it for
/// good: `this` is a live object by definition, so there is nothing to be null.
/// Called from For/SetOwning, which only ever run from Player.Update and the inventory GUI,
/// long after every type initialiser has finished. Register also complains about a null now
/// rather than swallowing it, so this class of failure is loud the next time.
/// </summary>
static RaceClawSet()
private static void EnsureRoster()
{
if (rosterBuilt) return;
rosterBuilt = true; // set first: a re-entrant call must not build the list twice
Register(AswidClaws.Instance);
Register(FenrirClaws.Instance);
List<string> names = new List<string>();
foreach (RaceClawSet set in sets) names.Add(set.RaceId);
Jotunn.Logger.LogInfo($"[RaceClaws] Roster: {(names.Count > 0 ? string.Join(", ", names.ToArray()) : "EMPTY")}.");
}
public static void Register(RaceClawSet set)
{
if (set == null || sets.Contains(set)) return;
if (set == null)
{
Jotunn.Logger.LogWarning("[RaceClaws] Refused to register a null claw set - that race will have no claws.");
return;
}
if (sets.Contains(set)) return;
sets.Add(set);
}
@ -109,6 +131,7 @@ namespace RacesOfValheim
public static RaceClawSet For(Player player)
{
if (player == null) return null;
EnsureRoster();
string race = GetRace(player);
foreach (RaceClawSet set in sets)
@ -122,6 +145,7 @@ namespace RacesOfValheim
public static RaceClawSet SetOwning(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return null;
EnsureRoster();
foreach (RaceClawSet set in sets)
{
@ -133,6 +157,13 @@ namespace RacesOfValheim
/// <summary>
/// Reads the race off the ZDO, falling back to m_customData - the same order every visual
/// in this mod reads it in, so a remote player and the menu preview both answer correctly.
///
/// "Human" in the ZDO is treated as no answer rather than as an answer, and that is not
/// cosmetic: ResetRace writes exactly that string into the ZDO before reopening the
/// selection menu, so a client whose ZDO write lost the race afterwards would otherwise be
/// stuck reading "Human" forever with a perfectly correct "Fenrir" sitting in m_customData
/// right next to it. Falling through to m_customData costs one dictionary lookup and closes
/// that hole.
/// </summary>
private static string GetRace(Player player)
{
@ -140,7 +171,7 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
if (!string.IsNullOrEmpty(race) && race != "Human") return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
@ -151,6 +182,26 @@ namespace RacesOfValheim
return "Human";
}
/// <summary>
/// Both raw values the race is read from, for the diagnostic line. Kept next to GetRace so
/// the two cannot drift apart.
/// </summary>
internal static string DescribeRaceSources(Player player)
{
if (player == null) return "player is null";
ZNetView nview = player.GetComponent<ZNetView>();
string zdo = nview == null ? "no ZNetView"
: !nview.IsValid() ? "ZDO not valid"
: $"'{nview.GetZDO().GetString("RacesOfValheim_Race", "")}'";
string custom = player.m_customData == null ? "no customData"
: player.m_customData.TryGetValue("Race", out string c) ? $"'{c}'"
: "absent";
return $"ZDO={zdo}, customData={custom}, resolved='{GetRace(player)}'";
}
// ─── Registration of the item ────────────────────────────────────────
private bool registered;
@ -164,11 +215,6 @@ namespace RacesOfValheim
/// </summary>
public void EnsureRegistered()
{
// BEFORE the early return, and before anything else: this is the one place the roster
// is filled reliably. See the static constructor for why it cannot do this itself.
// Idempotent, so calling it on every tick as well as at startup costs nothing.
Register(this);
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
@ -201,6 +247,15 @@ namespace RacesOfValheim
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// INDESTRUCTIBLE, and it has to be the flag rather than a big number. The claws are
// never crafted, so no workbench will ever repair them: left on normal durability
// they wear down to zero and Humanoid.EquipItem then refuses to put them back in
// hand, which strands the race bare-fisted for good. m_useDurability = false is the
// single switch every path reads - the attack drain, the broken-item check, the
// inventory bar and the tooltip line all skip the item entirely.
shared.m_useDurability = false;
shared.m_canBeReparied = false;
// No recipe and no station: this item is never crafted, only issued.
}
@ -210,9 +265,50 @@ namespace RacesOfValheim
registered = true;
Jotunn.Logger.LogInfo($"[{RaceId}] Registered '{ItemName}' from '{source.name}'.");
RegisterActiveStatusEffect(drop);
RefreshTint();
}
/// <summary>
/// The buff the player sees while the claws are out: the claw item's OWN icon, with the
/// countdown the game draws under any effect carrying a m_ttl. No custom HUD, no second
/// timer to keep in sync with this one - vanilla already draws exactly this.
///
/// Registered from here, which is to say from CreateModAssets, and that timing is the whole
/// point rather than a detail: an earlier version created this effect lazily on the first
/// activation and it never appeared, because Jotunn only takes new entries into ObjectDB at
/// OnVanillaPrefabsAvailable. SEMan.AddStatusEffect then looked the name up, found nothing,
/// and did nothing - silently, exactly the way the claws themselves failed the first time
/// round (see the WarnOnce in MaintainInner).
///
/// The icon is read off the cloned item rather than named here, so each race shows its own
/// claws and nobody has to remember to update a second list when a model changes.
/// </summary>
private void RegisterActiveStatusEffect(ItemDrop drop)
{
Sprite icon = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null &&
drop.m_itemData.m_shared.m_icons != null && drop.m_itemData.m_shared.m_icons.Length > 0
? drop.m_itemData.m_shared.m_icons[0]
: null;
if (icon == null)
{
// Worth saying out loud: the effect still works and still counts down, but a buff
// with no icon is nearly invisible in the HUD, which would read as "the timer is
// broken" rather than "the sprite was missing".
Jotunn.Logger.LogWarning($"[{RaceId}] '{ItemName}' carries no icon, so the claws' buff will show without one.");
}
StatusEffect se = ScriptableObject.CreateInstance<StatusEffect>();
se.name = ActiveSeName;
se.m_name = DisplayName;
se.m_tooltip = "Your claws are out. They retract when this runs out.";
se.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(se, fixReference: false));
Jotunn.Logger.LogInfo($"[{RaceId}] Registered the claws' buff '{ActiveSeName}'.");
}
private GameObject ResolveModel()
{
foreach (string name in ModelPrefabs)
@ -322,6 +418,124 @@ namespace RacesOfValheim
}
}
// ─── Active skill: grow, then retract ─────────────────────────────────
/// <summary>
/// Time.time at which the skill's current window ends. Starts in the past, so a set that
/// has never been activated - including a save carried over from before this was a timed
/// skill - reads as inactive and MaintainInner strips whatever leftover item it finds.
/// </summary>
private float activeUntil = -1f;
/// <summary>True while the two-minute window is still running.</summary>
public bool IsActive => Time.time < activeUntil;
/// <summary>Seconds left on the window, floored at zero. What the HUD timer counts down.</summary>
public float SecondsRemaining => Mathf.Max(0f, activeUntil - Time.time);
/// <summary>
/// Published on the local player's own ZDO every Maintain tick, one flag shared by both
/// races (whichever set is running is the only one that could ever be true for a given
/// player, since a player is only ever one race). Read back for a REMOTE attacker in
/// ApplyToUnarmedHit - IsActive itself is this client's own timer and answers nothing about
/// somebody else's, the same problem GetState solves for progression tier.
/// </summary>
private const string ClawsActiveZdoKey = "RacesOfValheim_ClawsActive";
/// <summary>
/// Grows the claws for RaceClawsConfig.DurationSeconds. Safe to call again mid-window - it
/// just restarts the timer rather than stacking or refusing.
/// </summary>
public void Activate(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
// Logged rather than silent: this is the one path a keypress can go nowhere from, and
// "nothing happened" with no line in the log is exactly the failure mode that cost the
// registration timing bug an evening (see the comment in MaintainInner).
if (For(player) != this)
{
Jotunn.Logger.LogInfo(
$"[{RaceId}] Grow-claws key ignored: this player's race is not {RaceId} " +
$"({DescribeRaceSources(player)}).");
return;
}
if (player.IsDead())
{
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key ignored: player is dead.");
return;
}
if (IsTransformed(player))
{
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key ignored: player is currently transformed.");
return;
}
activeUntil = Time.time + RaceClawsConfig.DurationSeconds.Value;
ApplyActiveIcon(RaceClawsConfig.DurationSeconds.Value);
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key pressed: growing the {DisplayName} for {RaceClawsConfig.DurationSeconds.Value}s.");
// Issues and equips immediately rather than waiting for the next throttled Maintain
// tick, so the keypress reads as instant rather than landing up to half a second late.
Maintain(player);
PlayGrowAnimation(player);
}
/// <summary>
/// The draw gesture, so the claws arrive with a movement rather than simply being in hand
/// on the next frame.
///
/// "equip_hip" is not a guess and not a borrowed approximation: it is the trigger vanilla's
/// own Humanoid.ShowHandItems fires when it takes a sheathed weapon back out, read out of
/// assembly_valheim rather than assumed. That makes it exactly the right motion here - the
/// claws are being drawn - and it carries no baked Animation Event, unlike the "gpower"
/// gesture the transformations borrow, which needed a suppressor to stop it casting the
/// player's real Guardian Power (see RaceInput.SuppressGuardianPowerBriefly).
/// </summary>
private static void PlayGrowAnimation(Player player)
{
ZSyncAnimation zanim = player.GetComponent<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("equip_hip");
}
// ─── The buff the player sees ────────────────────────────────────────
/// <summary>
/// One effect per race rather than one shared between them, so each shows its own claws in
/// the buff bar. Derived from the item name, so a new clawed race needs nothing here.
/// </summary>
private string ActiveSeName => "SE_" + ItemName + "Active";
/// <summary>
/// Puts the buff up (or restarts it, if the skill was recast mid-window) and gives it the
/// remaining time. The countdown under the icon is the game's own - see
/// RegisterActiveStatusEffect.
/// </summary>
private void ApplyActiveIcon(float seconds)
{
if (Player.m_localPlayer == null || seconds <= 0f) return;
int hash = ActiveSeName.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
/// <summary>
/// Takes the buff down. The effect's own m_ttl already expires on its own when the window
/// runs out normally; this is for the retractions that happen off the clock - a race change,
/// or a form taken while the claws were still out.
/// </summary>
private void ClearActiveIcon(Player player)
{
if (player == null) return;
player.GetSEMan().RemoveStatusEffect(ActiveSeName.GetStableHashCode(), true);
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
@ -334,8 +548,9 @@ namespace RacesOfValheim
private static bool maintaining;
/// <summary>
/// Makes sure the player owns exactly one pair and is holding them whenever both hands are
/// free. Safe to call on a timer: every step checks first.
/// While the skill is active: makes sure the player owns exactly one pair and is holding
/// them whenever both hands are free. Once the window closes: takes that pair back off the
/// player entirely. Safe to call on a timer either way - every step checks first.
/// </summary>
public void Maintain(Player player)
{
@ -354,11 +569,29 @@ namespace RacesOfValheim
EnsureRegistered();
RefreshTint();
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ClawsActiveZdoKey, IsActive);
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
// The window has closed (or never opened this session). Retract: unequip if still in
// hand, then remove the item outright - no slot sits occupied between activations,
// which is the entire point of moving this off the old "issued once, forever" design.
if (!IsActive)
{
if (claws != null)
{
if (player.IsItemEquiped(claws)) player.UnequipItem(claws, false);
inventory.RemoveItem(claws);
ClearActiveIcon(player);
Jotunn.Logger.LogInfo($"[{RaceId}] The {DisplayName} retracted.");
}
return;
}
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
@ -398,6 +631,11 @@ namespace RacesOfValheim
Jotunn.Logger.LogInfo($"[{RaceId}] Issued the {DisplayName}.");
}
// A pair issued before the claws stopped wearing out is still carrying whatever it had
// ground down to. Nothing reads that number any more, but it is saved with the item, so
// it is put back to full once rather than left as a stale figure in the save file.
if (claws.m_durability < claws.GetMaxDurability()) claws.m_durability = claws.GetMaxDurability();
// Empty-handed means clawed. Anything else in the right hand wins until it is put away,
// which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
@ -478,7 +716,9 @@ namespace RacesOfValheim
}
/// <summary>
/// Rewrites a bare-handed blow into a claw blow, as slash and nothing else.
/// Rewrites a bare-handed blow into a claw blow, as slash and nothing else - but only while
/// the claws are actually the thing in hand, which since this became a timed skill is no
/// longer every unarmed hit by default.
///
/// The figure is the Sverm's - its reference weapon at quality 4, times its percentage for
/// this tier - but where the Sverm keeps the weapon's own three-way split, this collapses
@ -491,6 +731,22 @@ namespace RacesOfValheim
if (hit == null || attacker == null) return;
if (IsTransformed(attacker)) return; // the form is doing its own damage
// Outside the skill's window this is just a bare fist - vanilla's own unarmed damage,
// not the claw tier. IsActive answers for the local player; a remote Aswid/Fenrir's
// punch reads the same flag published on their own ZDO, the same fallback GetState
// uses for progression tier - inventories are not something a remote client can read.
bool active;
if (attacker == Player.m_localPlayer)
{
active = IsActive;
}
else
{
ZNetView nview = attacker.GetComponent<ZNetView>();
active = nview != null && nview.IsValid() && nview.GetZDO().GetBool(ClawsActiveZdoKey, false);
}
if (!active) return;
HitData.DamageTypes reference = SvermClaws.GetReferenceDamage();
float percent = SvermClaws.GetDamagePercent(GetState(attacker));
if (percent <= 0f) return;
@ -510,8 +766,9 @@ namespace RacesOfValheim
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Issues the claws and puts them back in hand. On a throttle rather than every frame: it is a
/// handful of checks that all short-circuit once the claws exist.
/// Reads the activation key every frame (a keypress lasts one frame, so this cannot be
/// throttled), then issues/retracts the claws and puts them back in hand on a throttle - that
/// half is a handful of checks that all short-circuit once state matches the target.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RaceClaws_PlayerUpdate_Patch
@ -522,11 +779,27 @@ namespace RacesOfValheim
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
RaceClawSet set = RaceClawSet.For(__instance);
if (set == null) return;
if (RaceClawsConfig.ActivateKey.Value.IsDown())
{
if (RaceInput.Allowed)
{
set.Activate(__instance);
}
else
{
Jotunn.Logger.LogInfo($"[{set.RaceId}] Grow-claws key pressed but ignored: RaceInput.Allowed is false (a menu/GUI has focus).");
}
}
if (Time.time < next) return;
next = Time.time + Interval;
RaceClawSet set = RaceClawSet.For(__instance);
if (set != null) set.Maintain(__instance);
set.Maintain(__instance);
}
}
@ -607,9 +880,9 @@ namespace RacesOfValheim
}
/// <summary>
/// The tier's damage, on any bare-handed blow. Fist weapons report Unarmed, so this covers both
/// the equipped claws and an actually empty hand - which is what keeps the two halves of the
/// feature agreeing with each other.
/// The tier's damage, on any bare-handed blow - RaceClawSet.ApplyToUnarmedHit itself checks
/// whether the claws are actually equipped, so a genuinely empty hand (skill not running, or
/// still mid-retract) falls through to vanilla's own unarmed damage instead.
/// </summary>
[HarmonyPatch(typeof(Character), nameof(Character.Damage))]
public static class RaceClaws_Damage_Patch

View file

@ -0,0 +1,33 @@
using UnityEngine;
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The one keybind and the one duration behind the Claws skill (RaceClaws.cs), shared by every
/// race that grows a pair rather than bound separately per race - there is only one skill here,
/// not one per race wearing it. Bound once, from RacesOfValheim.Awake(), alongside the other
/// non-race shared config (WarVultureConfig, ButlerConfig, ...).
///
/// The default is K rather than O: O was the first pick, but Fenrir already owns it for Howl
/// (FenrirConfig.HowlKey), and colliding the two on one client would leave one of them dead
/// without any error to say why. Either can still be moved onto the other from Configuration
/// Manager if that turns out to be wanted after all.
/// </summary>
public static class RaceClawsConfig
{
public static ConfigEntry<KeyboardShortcut> ActivateKey;
public static ConfigEntry<float> DurationSeconds;
public static void Bind(ConfigFile config)
{
const string keybinds = "Race Claws - Keybinds";
ActivateKey = config.Bind(keybinds, "Grow Claws", new KeyboardShortcut(KeyCode.K),
new ConfigDescription("Grows the claws (Aswid: Claws of the Beast, Fenrir: Cursed Claws) for the duration below. Pressed again mid-window, restarts the timer instead of stacking."));
const string skill = "Race Claws - Skill";
DurationSeconds = config.Bind(skill, "Duration", 120f,
new ConfigDescription("Seconds the claws stay grown before retracting on their own. The remaining time shows under the claws' own icon in the buff bar.", new AcceptableValueRange<float>(10f, 600f)));
}
}
}

View file

@ -140,7 +140,7 @@ namespace RacesOfValheim
sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n");
sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n");
sb.AppendLine($"[Base Passive] Chitin Claws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n");
if (rules.MetabolicSurge)
sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n");
@ -389,12 +389,12 @@ namespace RacesOfValheim
sb.AppendLine("[Base Passive] Benedictus et Afflictus:");
sb.AppendLine($"You take no fall damage, and physical kills automatically devour edible enemies (Vae Victis) for Blood Magic XP. Your physical stats scale with every boss you defeat: +{arm} Armor, +{dmg} Damage, +{spd}% Speed and Jump, and +{lifesteal}% Lifesteal on physical hits. All of these bonuses double during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill rises {AswidConfig.BloodMagicSkillGainMultiplier.Value:0.#}x as fast.\n");
sb.AppendLine("Vampiric Aura (Passive, toggle with 'I'):");
sb.AppendLine($"Always active, in every form, with no key to hold - only the on/off toggle. Drains a {auraRadiusDay}m radius by day, {auraRadiusNight}m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below {auraExecute}% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist.\n");
sb.AppendLine("Vampiric Aura (Passive, [I] to toggle):");
sb.AppendLine($"Always active, in every form, with no key to hold - only the on/off toggle. Drains a {auraRadiusDay}m radius by day, {auraRadiusNight}m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below {auraExecute}% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist. It cannot tell traders from monsters, so switch it off with [I] before talking to Haldor or Hildir.\n");
// The live figure, so the entry cannot drift from the code: it is the same yardstick
// the Sverm's own claws are measured against, which is what keeps the three races even.
sb.AppendLine($"[Base Passive] Claws of the Beast: Blackened claws you did not forge and cannot put down. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in bat or mist form you have no hands to hold them with.\n");
sb.AppendLine($"[Base Passive] Claws of the Beast ([K], {RaceClawsConfig.DurationSeconds.Value:0}s): Grows blackened claws for a limited time instead of a weapon. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in bat or mist form you have no hands to hold them with.\n");
if (state >= 2)
sb.AppendLine("[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n");
@ -461,7 +461,7 @@ namespace RacesOfValheim
// The live figure, so the entry cannot drift from the code: the same yardstick the
// Sverm's own claws are measured against, which is what keeps the three races even.
sb.AppendLine($"[Base Passive] Cursed Claws: The wolf's hands, kept on in the man's shape. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in beast form the jaws do the work instead.\n");
sb.AppendLine($"[Base Passive] Cursed Claws ([K], {RaceClawsConfig.DurationSeconds.Value:0}s): The wolf's hands, kept on in the man's shape for a limited time instead of a weapon. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in beast form the jaws do the work instead.\n");
if (state >= 3)
sb.AppendLine("[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n");

View file

@ -15,7 +15,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.4.2";
public const string PluginVersion = "1.4.5";
private readonly Harmony harmony = new Harmony(PluginGUID);
@ -40,6 +40,15 @@ namespace RacesOfValheim
// Not a race: a summoned mount two races share, so it binds after the races rather
// than inside the alphabetical run above.
WarVultureConfig.Bind(Config);
// Not a race either: a tool any race can craft, so it sits beside the vulture rather
// than inside the alphabetical run above.
TrolsHammerConfig.Bind(Config);
// Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they
// bind here rather than inside either race's run.
ButlerConfig.Bind(Config);
// Not a race either: the Claws skill Aswid and Fenrir share, so it binds here rather
// than inside either race's run.
RaceClawsConfig.Bind(Config);
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
@ -81,6 +90,8 @@ namespace RacesOfValheim
Player player = Player.m_localPlayer;
if (player == null) return;
RemovePermanentRaceEquipment(player);
player.m_customData.Remove("Race");
player.m_customData.Remove("FenrirCurse_Active");
@ -144,6 +155,30 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Strips whatever body-part weapon the outgoing race grew. The Aswid/Fenrir claws
/// (RaceClawSet) and the Sverm's Chitin Claws (SvermClawSlot) are quest items a player can
/// neither drop nor sell, so a race change has to take them off the same way it takes the
/// stats away - otherwise they sit in the inventory forever as leftovers from a race that
/// no longer applies. Checked by item identity rather than by the race being left, so it
/// also mops up anything a previous, already-abandoned race left behind.
/// </summary>
private static void RemovePermanentRaceEquipment(Player player)
{
Inventory inventory = player.GetInventory();
if (inventory == null) return;
// Copied out first: removing items while GetAllItems()'s own list is still being
// walked corrupts the enumeration.
foreach (ItemDrop.ItemData item in inventory.GetAllItems().ToArray())
{
if (RaceClawSet.SetOwning(item) == null && !SvermClawSlot.IsClaws(item)) continue;
if (player.IsItemEquiped(item)) player.UnequipItem(item, false);
inventory.RemoveItem(item);
}
}
private void CreateAllModAssets() {
PrefabManager.OnVanillaPrefabsAvailable -= CreateAllModAssets;
RaceMenuWard.Register();
@ -158,6 +193,8 @@ namespace RacesOfValheim
TrentaRace.Instance.CreateModAssets();
SvermRace.Instance.CreateModAssets();
WarVultureItem.Register();
TrolsHammerItem.Register();
BoneServant.Register();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()

View file

@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
@ -158,9 +159,16 @@ namespace RacesOfValheim
// SkadiSEManPatch above from tier 1 onward, so the tier 2 "Freezing to Cold" conversion never
// gets a chance to run. These two patches scope out just that one environmental check: while
// Player.UpdateEnvStatusEffects is running for the local Skadi player, GetDamageModifiers is
// reported as Normal for Frost, so vanilla always attempts to apply the real status and
// SkadiSEManPatch's per-tier logic (block/convert/allow) is what actually decides the outcome.
// Frost damage resistance from hits (SkadiDamagePatch) is untouched by this.
// reported without SE_SkadiStats' own Frost contribution, so vanilla attempts to apply the
// real status and SkadiSEManPatch's per-tier logic (block/convert/allow) is what actually
// decides the outcome. Frost damage resistance from hits (SkadiDamagePatch) is untouched.
//
// Only the race's own contribution is discounted. This used to report a flat Normal, which
// also erased Frost resistance coming from a wolf/lox cape, a frost resistance mead or food:
// a Skadi who had beaten Moder still caught the converted Cold on the Mountain while wearing
// gear that makes a human immune, and below tier 4 caught real Freezing through the same gear.
// The tiered ladder is meant to make the race better than a bare human, never worse than an
// equipped one, so anything the player is actually wearing or drinking still counts.
[HarmonyPatch(typeof(Player), "UpdateEnvStatusEffects")]
public static class SkadiEnvCheckScope
{
@ -180,11 +188,38 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(Character), "GetDamageModifiers")]
public static class SkadiEnvFrostModifierPatch
{
private static readonly int SkadiStatsHash = "SE_SkadiStats".GetStableHashCode();
// Handed to the aura in place of its own list while the recompute runs. SE_Stats applies
// m_mods as-is, so an empty list is simply "this effect grants nothing".
private static readonly List<HitData.DamageModPair> NoMods = new List<HitData.DamageModPair>();
private static bool recomputing = false;
public static void Postfix(Character __instance, ref HitData.DamageModifiers __result)
{
if (SkadiEnvCheckScope.Active && __instance == Player.m_localPlayer)
if (recomputing) return;
if (!SkadiEnvCheckScope.Active || __instance != Player.m_localPlayer) return;
// Character.GetDamageModifiers composes base modifiers + equipment + status effects,
// and DamageModifiers.Apply keeps the strongest of the lot - there is no way to
// subtract one contributor from a finished result. So the aura is muted and the whole
// thing recomputed: what comes back is exactly what this player would have without
// the race. The recursive call re-enters this postfix, which the flag turns into a
// no-op. The status effect on the player is a clone of the registered prototype
// (SEMan.AddStatusEffect clones on add), hence the lookup by hash rather than
// SkadiRace.skadiCurseSE.
SE_Stats aura = __instance.GetSEMan().GetStatusEffect(SkadiStatsHash) as SE_Stats;
List<HitData.DamageModPair> auraMods = aura != null ? aura.m_mods : null;
recomputing = true;
if (aura != null) aura.m_mods = NoMods;
try
{
__result.m_frost = HitData.DamageModifier.Normal;
__result.m_frost = __instance.GetDamageModifiers(null).m_frost;
}
finally
{
if (aura != null) aura.m_mods = auraMods;
recomputing = false;
}
}
}

View file

@ -167,11 +167,24 @@ namespace RacesOfValheim
// Update the stats SE
if (skadiCurseSE != null)
{
int auraHash = skadiCurseSE.name.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
skadiCurseSE.UpdateStats(rules);
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect(skadiCurseSE.name.GetStableHashCode()))
if (!seman.HaveStatusEffect(auraHash))
{
Player.m_localPlayer.GetSEMan().AddStatusEffect(skadiCurseSE.name.GetStableHashCode(), true);
seman.AddStatusEffect(auraHash, true);
}
// SEMan.AddStatusEffect stores a Clone() of the prototype, so updating
// skadiCurseSE alone only changed the copy that gets stamped out at the next add:
// the aura already running on the player kept whatever tier it was born with.
// Beating a boss mid-session left the old frost modifier and eitr regen in place
// until the effect was re-added (race reselection or a relog) - most visibly at
// the Queen, where Immune never replaced Resistant. Refresh the live one as well;
// UpdateStats is a no-op unless the tier actually moved a value.
SE_SkadiStats liveAura = seman.GetStatusEffect(auraHash) as SE_SkadiStats;
if (liveAura != null) liveAura.UpdateStats(rules);
}
if (rules.FrostAura)

View file

@ -27,8 +27,29 @@ namespace RacesOfValheim
m_tooltip = "Empowered by the frost.";
}
// What the last UpdateStats call actually wrote. SEMan.AddStatusEffect stores a Clone() of
// the registered prototype, so the effect running on the player is a separate object that
// has to be refreshed too (SkadiRace.Update does that) - and both of them are asked to
// update every frame. Rebuilding the mod list each time would churn a List per frame per
// instance, so nothing is rewritten until a tier change actually moves a value. These
// fields are not serialized, so a fresh clone starts at "never applied" and rebuilds once.
private bool statsApplied = false;
private float appliedFrostResistance = 0f;
private float appliedEitrRegenMultiplier = 0f;
public void UpdateStats(SkadiProgression.FormRules rules)
{
if (statsApplied &&
rules.FrostResistance == appliedFrostResistance &&
rules.EitrRegenMultiplier == appliedEitrRegenMultiplier)
{
return;
}
statsApplied = true;
appliedFrostResistance = rules.FrostResistance;
appliedEitrRegenMultiplier = rules.EitrRegenMultiplier;
m_mods = new List<HitData.DamageModPair>();
if (rules.FrostResistance >= 1f)
{

View file

@ -163,35 +163,23 @@ namespace RacesOfValheim
private static void Clone(GameObject source, Transform parentBone, string namePrefix)
{
GameObject copy = Object.Instantiate(source, parentBone);
copy.name = namePrefix + source.name;
// Through BorrowEffect, which builds the copy inside an inactive holder and strips it
// there. This used to instantiate straight onto the bone and clean up afterwards, and
// "afterwards" is a frame too late: a borrowed node gets its Awake the moment it lands
// on a live player. That is what left burnt-in torches in people's worlds when the head
// flame did the same thing - see the note on FlameSourcePrefabs. Nothing on a creature
// is known to be as expensive as an ItemDrop, but the eye glow reads whatever the
// creature happens to carry, which is exactly the kind of place that surprise comes
// from.
GameObject copy = SkeletonVisuals.BorrowEffect(source, parentBone, namePrefix + source.name,
true, "Skeleton");
if (copy == null) return;
// The pose it was authored at on the creature. Instantiate keeps the world transform,
// which for a prefab means nothing useful.
copy.transform.localPosition = source.transform.localPosition;
copy.transform.localRotation = source.transform.localRotation;
copy.transform.localScale = source.transform.localScale;
// Allowlist, not a blocklist - the same rule the head flame is built under. Whatever
// else rode along (an AnimEvent, a collider, a script that expects a Character above
// it) goes, whatever type it turns out to be; what is left is a light and the things
// that draw it.
foreach (Component comp in copy.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is Light || comp is ParticleSystem ||
comp is ParticleSystemRenderer || comp is MeshRenderer || comp is MeshFilter)
{
continue;
}
Object.Destroy(comp);
}
// A creature can leave its own effects switched off for a script to turn on later, and
// that script is exactly what was just destroyed.
copy.SetActive(true);
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
}
/// <summary>

View file

@ -1,3 +1,4 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
@ -96,13 +97,78 @@ namespace RacesOfValheim
return BossProgressionManager.GetCurrentProgressionState();
}
// Fire sources in preference order. The torch is an item every world has; the ground
// torch and the fire pit are the building pieces to fall back on.
/// <summary>
/// Fire sources in preference order. BUILDING PIECES ONLY, and that is the bug fix.
///
/// This list used to start with "Torch", which is the ITEM prefab, and an item in Valheim
/// is a live world object: ItemDrop, a Rigidbody and a ZNetView, all of them on the same
/// node the fire particles are on. That the borrow was reaching that node and not a bare
/// flame was already known here - the strip below used to name "the stick mesh, ItemDrop,
/// durability", and the Rigidbody it had to destroy was the one that made an early version
/// of the clone visibly fall away from the skull.
///
/// What was missed is that the copy was made into a holder that was ALREADY SWITCHED ON,
/// so all of it woke up for a frame before the strip could take any of it off - and a woken
/// ZNetView is not a cosmetic mistake. ZNetView.Awake with no init ZDO calls
/// ZDOMan.CreateNewZDO at the object's position, marks it persistent, stamps it with the
/// prefab hash and registers it with the scene; ZNetView.OnDestroy does none of that in
/// reverse - it only releases asset references. So every rebuild of the flame left the
/// world holding a persistent "there is a Torch here" record that nothing was drawing,
/// saved with everything else, and the next time that zone was built from the save every
/// client spawned the torch. That is the whole of the report: a torch dropped on logging
/// in and out, and a portal handing it to everyone.
///
/// A ground torch is a building piece. It has the same fire (both carry fx_Torch_Basic) and
/// no item behaviour at all, so there is nothing on it to bring across by accident. The
/// inactive holder in Build and the two filters below are the lines of defence behind that,
/// for whatever a future source turns out to carry.
/// </summary>
private static readonly string[] FlameSourcePrefabs =
{
"Torch", "piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
"piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
};
/// <summary>
/// Particle systems that are not fire. Matched on the object name, which is how these are
/// named in the prefabs that carry them - an item's pickup glitter above all, which is a
/// ParticleSystem like any other and was worn on the skull along with the flame.
/// </summary>
private static readonly string[] NotFire =
{
"sparkle", "sparcle", "glitter", "pickup", "shine", "twinkle"
};
private static bool IsFire(GameObject candidate)
{
string name = candidate.name.ToLower();
foreach (string word in NotFire)
{
if (name.Contains(word)) return false;
}
return true;
}
// Said once per particle name per session, with everything the borrowed node carries that
// is not a particle. The point is that the next time something rides along, the log names
// it - this bug cost a bug report because nothing ever said "that flame is an item".
private static readonly HashSet<string> loggedParticles = new HashSet<string>();
private static void LogClonedOnce(GameObject source)
{
if (!loggedParticles.Add(source.name)) return;
List<string> passengers = new List<string>();
foreach (Component comp in source.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, true)) continue;
passengers.Add(comp.GetType().Name);
}
Jotunn.Logger.LogInfo(
$"[Skeleton] Head flame: cloned '{source.name}'" +
(passengers.Count == 0 ? "." : ", stripped " + string.Join(", ", passengers.ToArray()) + "."));
}
private static GameObject cachedFlameSource;
private static bool flameSourceResolved;
@ -119,7 +185,13 @@ namespace RacesOfValheim
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
if (prefab.GetComponentsInChildren<ParticleSystem>(true).Length == 0) continue;
bool hasFire = false;
foreach (ParticleSystem ps in prefab.GetComponentsInChildren<ParticleSystem>(true))
{
if (IsFire(ps.gameObject)) { hasFire = true; break; }
}
if (!hasFire) continue;
Jotunn.Logger.LogInfo($"[Skeleton] Head flame source resolved to '{name}'.");
cachedFlameSource = prefab;
@ -132,6 +204,108 @@ namespace RacesOfValheim
return null;
}
/// <summary>
/// Strips a borrowed subtree down to what a pure VFX needs, and nothing else.
///
/// Allowlist, not a blocklist: keep the particle systems, their renderers and the lights
/// (and the loose meshes, for the eye glow), destroy every other component whatever it
/// turns out to be. A blocklist of "known bad" types (MonoBehaviour, Collider) missed
/// Rigidbody - not a MonoBehaviour in Unity - and a fire node carrying one meant physics
/// kept acting on the clone independently of the holder being repositioned every frame.
///
/// DestroyImmediate rather than Destroy, because the caller is about to switch the holder
/// on and Destroy does not take effect until the end of the frame - by which time every
/// script it was supposed to remove would have had its Awake.
///
/// Repeated passes, because Unity refuses to destroy a component another one still
/// requires ("Can't remove Humanoid because CharacterDrop depends on it"): the dependent
/// goes on one pass and the component it held down goes on the next. Behaviours first
/// within each pass, for the same reason.
/// </summary>
public static void StripToVfx(GameObject root, bool keepMeshes, string label)
{
if (root == null) return;
for (int pass = 0; pass < 4; pass++)
{
bool anyLeft = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
Object.DestroyImmediate(behaviour);
}
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
Object.DestroyImmediate(comp);
anyLeft = true;
}
if (!anyLeft) return;
}
// Four passes and something is still holding on. Say what it is: a survivor here is the
// exact shape of bug this whole class exists to prevent, and it is about to be woken.
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
Jotunn.Logger.LogWarning(
$"[{label}] '{comp.GetType().Name}' on '{comp.gameObject.name}' could not be stripped " +
"off the borrowed effect; it will run on the player.");
}
}
private static bool IsPureVfx(Component comp, bool keepMeshes)
{
if (comp is Transform || comp is ParticleSystem || comp is ParticleSystemRenderer || comp is Light)
{
return true;
}
return keepMeshes && (comp is MeshRenderer || comp is MeshFilter);
}
/// <summary>
/// Clones one node of a vanilla prefab as pure VFX and hangs it under <paramref name="parent"/>.
///
/// The temporary holder is created INACTIVE and the copy is made inside it. That single
/// line is the point of this method: Unity does not run Awake on an object that is not
/// active in its hierarchy, so ItemDrop, ZNetView, Rigidbody and every script on the
/// borrowed node are destroyed before any of them ever exists as far as the game is
/// concerned. Stripping AFTER the copy is already live - which is what the head flame and
/// the eye glow both used to do - is a frame too late, and one frame is all a ZNetView
/// needs to write a persistent object into the save. Same lesson, same fix, as ModelBorrow.
///
/// The copy is handed back parented to <paramref name="parent"/> and switched on, with its
/// pose left to the caller.
/// </summary>
public static GameObject BorrowEffect(GameObject source, Transform parent, string cloneName,
bool keepMeshes, string label)
{
if (source == null || parent == null) return null;
GameObject holder = new GameObject("BorrowedEffectHolder");
holder.SetActive(false); // BEFORE the Instantiate below.
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = cloneName;
StripToVfx(copy, keepMeshes, label);
copy.transform.SetParent(parent, false);
Object.DestroyImmediate(holder);
// A prefab can leave its own effects switched off for a script to turn on later, and
// that script is exactly what was just destroyed.
copy.SetActive(true);
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
return copy;
}
/// <summary>
/// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing.
///
@ -191,13 +365,22 @@ namespace RacesOfValheim
// Real fire is cloned rather than built by hand. The first attempt at this made a
// particle system from scratch on the smoke material, and a hand-rolled gradient
// over a smoke sprite reads as a wisp, not a burning skull.
//
// Every clone goes through BorrowEffect, which builds it inactive and strips it
// before it can wake. Nothing from the source prefab - a script, a Rigidbody, a
// ZNetView - ever gets a frame of life on the player.
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
{
GameObject copy = Object.Instantiate(ps.gameObject, m_instance.transform);
copy.name = ps.gameObject.name;
if (!IsFire(ps.gameObject)) continue;
GameObject copy = BorrowEffect(ps.gameObject, m_instance.transform,
ps.gameObject.name, false, "Skeleton");
if (copy == null) continue;
LogClonedOnce(ps.gameObject);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.SetActive(true);
// So the holder's scale actually enlarges the fire rather than just spreading
// out where the particles spawn.
@ -213,22 +396,6 @@ namespace RacesOfValheim
light.intensity *= 0.6f;
}
// Allowlist, not a blocklist: keep only what a pure VFX actually needs (the
// particle systems, their renderers, and the light tweaked above) and destroy
// every other component, whatever it turns out to be. A blocklist of "known bad"
// types (MonoBehaviour, Collider) missed Rigidbody - not a MonoBehaviour in Unity,
// so the old loop never touched it - and a torch's fire-particle node carrying one
// meant physics kept acting on the clone independently of m_instance being
// repositioned onto the head every frame: it visibly fell away while the empty
// parent stayed correctly tracked above it. Anything that made the source a torch
// rather than a bare flame - the stick mesh, ItemDrop, durability, all of it -
// goes the same way.
foreach (Component comp in m_instance.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is ParticleSystem || comp is ParticleSystemRenderer || comp is Light) continue;
Object.Destroy(comp);
}
return true;
}
}

View file

@ -6,7 +6,7 @@ using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and
/// The Chitin Claws as a REAL equipped weapon, sitting in the inventory in plain sight and
/// refusing to be moved.
///
/// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the
@ -36,8 +36,13 @@ namespace RacesOfValheim
/// </summary>
public static class SvermClawSlot
{
/// <summary>
/// The prefab id, and it keeps the old spelling on purpose: it is what every save on disk
/// names the item by, and renaming it would leave a Sverm holding an item ObjectDB can no
/// longer resolve. The display name below is the only half a player ever reads.
/// </summary>
public const string ItemName = "SvermMaulclaws";
public const string ItemDisplayName = "Vilebone Maulclaws";
public const string ItemDisplayName = "Chitin Claws";
/// <summary>Row in the reserved column the claws sit on. The other three await the carapace.</summary>
private const int ClawRow = 0;
@ -84,6 +89,15 @@ namespace RacesOfValheim
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// INDESTRUCTIBLE, and it has to be the flag rather than a big number. The claws are
// never crafted, so no workbench will ever repair them: left on normal durability
// they wear down to zero and Humanoid.EquipItem then refuses to put them back in
// hand, which strands the Sverm bare-fisted for good. m_useDurability = false is the
// single switch every path reads - the attack drain, the broken-item check, the
// inventory bar and the tooltip line all skip the item entirely.
shared.m_useDurability = false;
shared.m_canBeReparied = false;
// No recipe and no station: this item is never crafted, only issued.
}
@ -153,9 +167,14 @@ namespace RacesOfValheim
claws.m_gridPos = corner;
}
Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws.");
Jotunn.Logger.LogInfo("[Sverm] Issued the Chitin Claws.");
}
// A pair issued before the claws stopped wearing out is still carrying whatever it had
// ground down to. Nothing reads that number any more, but it is saved with the item, so
// it is put back to full once rather than left as a stale figure in the save file.
if (claws.m_durability < claws.GetMaxDurability()) claws.m_durability = claws.GetMaxDurability();
// Empty-handed means clawed. Anything else in the right hand wins until it is put
// away, which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;

View file

@ -3,7 +3,7 @@ using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Vilebone Maulclaws: attached to the hands for good, and never equipped.
/// The Chitin Claws: attached to the hands for good, and never equipped.
///
/// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks
/// the Sverm out of every sword, bow and staff in the game for the whole run, which is not
@ -52,7 +52,7 @@ namespace RacesOfValheim
if (candidate != null)
{
resolved = candidate;
Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'.");
Jotunn.Logger.LogInfo($"[Sverm] Chitin Claws resolved to '{name}'.");
return resolved;
}
}
@ -70,7 +70,7 @@ namespace RacesOfValheim
/// <summary>
/// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier
/// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws.
/// percentages are a fraction of, and state 7 is 100% of it - the real Chitin Claws.
///
/// Public because it is the shared yardstick: the Aswid's and the Fenrir's claws
/// (RaceClawSet) are balanced against this same figure rather than against the models they
@ -108,7 +108,7 @@ namespace RacesOfValheim
};
referenceRead = true;
Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " +
Jotunn.Logger.LogInfo($"[Sverm] Chitin Claws at quality {SvermConfig.ArmorReferenceQuality}: " +
$"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " +
$"blunt {referenceDamage.m_blunt:0.#}.");
return referenceDamage;

View file

@ -88,7 +88,7 @@ namespace RacesOfValheim
public const string CarapaceLegsVisual = "ArmorCarapaceLegs";
public const string CarapaceHelmetVisual = "HelmetCarapace";
// ─── Vilebone Maulclaws ──────────────────────────────────────────────
// ─── Chitin Claws ────────────────────────────────────────────────────
// FOUR near-identical names exist in the manifest and only some carry a recipe, so the
// prefab is resolved by trying them in order and logging which one answered. A wrong guess
// here fails soft and silently - two empty hands - which is exactly the failure this
@ -106,7 +106,7 @@ namespace RacesOfValheim
/// <summary>
/// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state.
/// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than
/// State 7 is the ceiling - the real Chitin Claws - and state 8 adds fire on top rather than
/// going past it. Index 0 unused, as above.
/// </summary>
public static readonly float[] ClawDamagePercentByState =

View file

@ -28,7 +28,7 @@ namespace RacesOfValheim
/// </summary>
public float FireWeakness;
/// <summary>Fraction of the Maulclaws' quality-4 damage a bare-handed blow lands for.</summary>
/// <summary>Fraction of the Chitin Claws' quality-4 damage a bare-handed blow lands for.</summary>
public float ClawDamagePercent;
public bool MetabolicSurge; // cheaper running and jumping, higher jump

View file

@ -84,7 +84,7 @@ namespace RacesOfValheim
//
// The first version emptied the hands completely and the form could not attack: with
// nothing equipped there is no weapon to swing, and Valheim's bare fist is not the
// thing this form is supposed to be throwing. Leaving the Maulclaws equipped makes the
// thing this form is supposed to be throwing. Leaving the Chitin Claws equipped makes the
// sting an ordinary weapon attack - which works - and costs nothing visually, because
// the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed,
// so the damage patch still recognises the blow and swaps the deathsquito's figure in.
@ -254,7 +254,7 @@ namespace RacesOfValheim
}
Jotunn.Logger.LogWarning($"[Sverm] Could not read a weapon off '{SvermConfig.StingerCreature}'; " +
"the sting falls back to the Maulclaws.");
"the sting falls back to the Chitin Claws.");
stingerDamageRead = true;
return stingerDamage; // all zeroes: the damage patch then leaves the claw values alone
}
@ -316,7 +316,16 @@ namespace RacesOfValheim
Character character = GetComponent<Character>();
if (character == null || character.IsDead())
{
Destroy(gameObject);
// ZNetScene.Destroy, NEVER Object.Destroy, and this line was the teleport crash.
//
// An escort is a real networked creature, and ZNetView.OnDestroy - read out of the
// assembly, not assumed - only releases asset references: it does not take the
// object out of ZNetScene.m_instances. A plain Object.Destroy therefore left the
// scene holding a dead ZNetView, and the next time the world unloaded around the
// player, which is exactly what a teleport is, ZNetScene.RemoveObjects walked that
// entry and threw. See ZNetSceneOrphanPatch.cs for the whole chain.
if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
else Destroy(gameObject);
return;
}

View file

@ -16,7 +16,7 @@ namespace RacesOfValheim
/// matures on screen as it advances.
///
/// What gets mounted, all of it borrowed from vanilla:
/// the claws - the Vilebone Maulclaws, on both hands, always;
/// the claws - the Chitin Claws, on both hands, always;
/// the spines - UndeadBjornRibcage worn spine-up, a static crest, from tier 5;
/// the eyes - two emissive spheres, the Aswid's geometry unchanged;
/// the motes - a firefly swarm under the body, only while falling;

View file

@ -261,6 +261,17 @@ namespace RacesOfValheim
// GameObject - walks straight into Say(m_randomStartTrade, ...) right after opening the store.
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplayName;
// DISABLED ON PURPOSE, and it is the line that keeps the log clean. Trader was written for
// Haldor, who is a creature with an animator and a LookAt rig: Trader.Update() calls
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() with no null check on every
// frame no player is nearby, and Trader.Start() calls InvokeRepeating("RandomTalk", 0, 0)
// on a component nobody authored in the editor. On a totem both of those are null, so the
// piece threw a NullReferenceException every frame from the moment it was raised. A
// disabled component runs neither, and StoreGui needs neither: Show() only reads fields off
// the Trader and asks it for its item list, and GetComponent finds it disabled just the
// same. This is the same fix SvermHiveStore.Mount already carries for the Hive Market.
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();

View file

@ -0,0 +1,50 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The two numbers behind Trol's Hammer, bound as BepInEx ConfigEntry so they can be dragged in
/// Configuration Manager rather than recompiled - the same shape as WarVultureConfig.
///
/// Note what the switch does NOT do: turning the hammer off never un-scales anything already
/// standing. A piece carries its own size on its ZDO, and that is read back on load whatever
/// the config says, so a house built at 1.2 stays a house and not a pile of clipping walls.
/// The switch only decides whether NEW placements are enlarged.
/// </summary>
public static class TrolsHammerConfig
{
public static ConfigEntry<bool> Enabled;
public static ConfigEntry<float> ScaleFactor;
public static void Bind(ConfigFile config)
{
// No apostrophe, and not a typo: BepInEx rejects ' in a section name outright, and this
// Bind runs from the plugin's Awake - so "Trol's Hammer" did not merely fail to appear
// in Configuration Manager, it threw and took the whole mod's startup with it.
const string section = "Trols Hammer";
Enabled = config.Bind(section, "Enabled", true,
new ConfigDescription("Whether pieces placed with Trol's Hammer come out enlarged. " +
"Switching this off leaves every piece already built at the size " +
"it was built at; only new placements are affected."));
ScaleFactor = config.Bind(section, "Scale factor", 1.2f,
new ConfigDescription("How much bigger than the vanilla piece. 1.2 is the +20% the " +
"hammer exists for. Cost and drop never change - this is size " +
"only.", new AcceptableValueRange<float>(1f, 3f)));
}
/// <summary>
/// The multiplier a new placement should use, or 1 when the hammer is switched off. Clamped
/// against a zero or negative value typed straight into the .cfg file, which the
/// Configuration Manager slider cannot produce but a text editor can - and a piece scaled to
/// zero is a piece that cannot be seen, hit or removed.
/// </summary>
public static float ActiveFactor()
{
if (Enabled == null || ScaleFactor == null) return 1f;
if (!Enabled.Value) return 1f;
return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
}
}
}

View file

@ -0,0 +1,97 @@
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Trol's Hammer: the builder's hammer, one size up.
///
/// It is a straight clone of the vanilla Hammer and it deliberately keeps the ONE field that
/// makes it a hammer at all - m_buildPieces, the PieceTable. Sharing the vanilla table rather
/// than cloning it is the whole trick behind "exactly the same things to build": every piece
/// vanilla puts in the hammer's menu is there, at the same cost and with the same drop, and so
/// is every piece another mod adds to that table later. A cloned table would have been a
/// snapshot of the build menu taken at startup and would have quietly gone stale.
///
/// Nothing about the piece prefabs is touched, so the size does not live on the item: it lives
/// on the placement, and TrolsHammerPatches is where that happens.
///
/// The recipe (1 core wood, 2 fine wood) is on a workbench rather than free-hand like the
/// vanilla hammer, because both materials already require one to exist.
/// </summary>
public static class TrolsHammerItem
{
public const string PrefabName = "TrolsHammer";
public const string DisplayName = "Trol's Hammer";
private const string SourcePrefab = "Hammer";
private const string Label = "TrolsHammer";
/// <summary>Core wood. The item id is RoundLog - a display name that does not predict the id.</summary>
private const string CoreWood = "RoundLog";
private const string FineWood = "FineWood";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A hammer swung by something that never had to duck through a " +
"doorway. It builds everything the ordinary one builds, out of the " +
"same materials, and simply builds it bigger.";
if (shared.m_buildPieces == null)
{
// Not fatal, but worth saying out loud: without a piece table the item is a stick.
Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone carries no build piece table; " +
$"{DisplayName} will open an empty build menu.");
}
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Workbench,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig(CoreWood, 1, 0, true),
new RequirementConfig(FineWood, 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
}
/// <summary>
/// Whether an item in hand is this hammer.
///
/// m_dropPrefab is the reliable identity - it is the prefab the ItemData came from - but it
/// is null on an ItemData built before ObjectDB finished, so the display name is kept as a
/// second reading rather than as the only one.
/// </summary>
public static bool IsTrolsHammer(ItemDrop.ItemData item)
{
if (item == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
return item.m_shared != null && item.m_shared.m_name == DisplayName;
}
}
}

View file

@ -0,0 +1,217 @@
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 = TrolsHammerItem.IsTrolsHammer(player.RightItem)
? TrolsHammerConfig.ActiveFactor()
: 1f;
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;
if (!TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
float factor = TrolsHammerConfig.ActiveFactor();
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);
}
}
}

View file

@ -89,6 +89,36 @@ namespace RacesOfValheim
"cloned from vanilla's mount stamina bar."));
}
/// <summary>
/// The race of a player, read m_customData first and the ZDO second.
///
/// That order is the one the summon has always used, and it is kept rather than swapped for
/// the ZDO-first order the visuals use, for a reason: this only ever asks about the LOCAL
/// player, whose m_customData is authoritative and is written before the ZDO on a race
/// change. The ZDO is the fallback for the one frame after a load where m_customData has not
/// been filled in yet - without it the crafting list would flicker the recipe away.
/// </summary>
public static string RaceOf(Player player)
{
if (player == null) return null;
if (player.m_customData != null &&
player.m_customData.TryGetValue("Race", out string custom) &&
!string.IsNullOrEmpty(custom))
{
return custom;
}
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
return null;
}
/// <summary>
/// Whether a race id may call the bird. An empty list means everyone, which is the honest
/// reading of "no restriction" and is also what makes this testable on any character.

View file

@ -1,4 +1,6 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
@ -36,6 +38,12 @@ namespace RacesOfValheim
private const string TrophyPrefab = "TrophyVolture";
private const string Label = "WarVulture";
/// <summary>The three materials. Ids, not display names: the ingot is BlackMetal (the SCRAP
/// is the ore), and the raw lox meat is LoxMeat, with CookedLoxMeat being the other one.</summary>
private const string GreydwarfEye = "GreydwarfEye";
private const string BlackMetalIngot = "BlackMetal";
private const string RawLoxMeat = "LoxMeat";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
@ -73,9 +81,24 @@ namespace RacesOfValheim
// is not. Getting that wrong once put a live Ashlands predator in the player's world.
WarVultureVisual.BuildTemplate();
// No recipe, on purpose and for now: the item is spawned from the console
// ("spawn WarVulture") while the flight is being proven. A recipe costs nothing to add
// later and would only be materials invented before anyone knows what this is worth.
// The forge, and not the workbench, for the same reason Trol's Hammer sits on a
// workbench: the station is picked by the material that is hardest to have. Eyes and
// meat are picked up off the ground; a black metal ingot means a blast furnace already
// exists, and the forge is where that metal is worked.
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig(GreydwarfEye, 10, 0, true),
new RequirementConfig(BlackMetalIngot, 2, 0, true),
new RequirementConfig(RawLoxMeat, 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered: no eitr, no health, no stamina, no skeleton.");
}
@ -251,6 +274,35 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Who gets to see the recipe: the same list the bird itself answers to
/// (WarVultureConfig.AllowedRaces, "Furling,Dvergar" out of the box), read through the same
/// helper, so the crafting menu and the summon can never disagree. A race that could craft the
/// item but not call the bird would just be selling someone ten greydwarf eyes' worth of stick.
///
/// Player.GetAvailableRecipes is the single funnel the crafting list is built from, and it is
/// public and takes the list by ref - so a Postfix that removes one entry is the whole gate.
/// The recipe is still REGISTERED for everybody, which is deliberate: it stays in ObjectDB, so
/// a character who changes race sees it appear or vanish with no world edit and no re-register.
///
/// Filtering here rather than at the craft click also means the refusal never has to be
/// explained - an item that was never in the list cannot be clicked.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.GetAvailableRecipes))]
public static class WarVultureRecipeRacePatch
{
private static void Postfix(Player __instance, ref List<Recipe> available)
{
if (__instance == null || available == null) return;
if (WarVultureConfig.RaceAllowed(WarVultureConfig.RaceOf(__instance))) return;
available.RemoveAll(recipe =>
recipe != null &&
recipe.m_item != null &&
Utils.GetPrefabName(recipe.m_item.gameObject) == WarVultureItem.PrefabName);
}
}
/// <summary>
/// The click. Attack.OnAttackTrigger is used rather than Attack.Start because it takes NO
/// parameters - its signature cannot drift - and it fires when the animation reaches its

View file

@ -107,8 +107,9 @@ namespace RacesOfValheim
private static void Summon(Player rider)
{
string race = null;
if (rider.m_customData != null) rider.m_customData.TryGetValue("Race", out race);
// Through WarVultureConfig.RaceOf rather than reading m_customData here, so this gate
// and the one hiding the recipe (WarVultureRecipeRacePatch) are literally the same read.
string race = WarVultureConfig.RaceOf(rider);
if (!WarVultureConfig.RaceAllowed(race))
{

View file

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The "teleport bug", and why it is a crash about teleporting at all.
///
/// WHAT THE REPORT LOOKS LIKE. Two NullReferenceExceptions out of ZNetScene.Update, the first
/// of them through UnityEngine.Component.get_gameObject:
///
/// ZNetScene.RemoveObjects -> ZNetScene.CreateDestroyObjects -> ZNetScene.Update
///
/// WHAT IT ACTUALLY IS. ZNetScene keeps a table of every networked object it has built,
/// m_instances, mapping ZDO to ZNetView, and RemoveObjects is the pass that unloads whatever is
/// no longer near the player. Read out of the assembly rather than assumed, it does exactly
/// this:
///
/// foreach (ZNetView value in m_instances.Values)
/// if (value.GetZDO().TempRemoveEarmark != b) m_tempRemoved.Add(value); // (1)
/// ...
/// UnityEngine.Object.Destroy(zNetView.gameObject); // (2)
///
/// Neither line can survive an entry whose object is already gone: (1) throws a plain NRE if the
/// ZDO has been reset out from under it, and (2) throws through get_gameObject - Unity's "this
/// object was destroyed and you are still using it" - if the ZNetView itself is dead. That is
/// the exact pair of stack traces in the report.
///
/// AND THE ENTRY IS NEVER CLEANED UP BY UNITY, which is the part worth writing down, because it
/// is the trap every despawn in this mod has to avoid. ZNetView.OnDestroy, in full:
///
/// private void OnDestroy() { _ = (bool)ZNetScene.instance; if (m_heldReferences != null) ... }
///
/// It releases asset references and NOTHING else - it does not take itself out of m_instances.
/// So any object that is destroyed the Unity way instead of the ZNetScene way (Object.Destroy on
/// a networked creature or piece, a ZNetView stripped off a clone that had already woken, an
/// ancestor destroyed with a networked child underneath it) leaves a dead entry in the table,
/// and it sits there harmlessly until something walks the whole table.
///
/// WHICH IS WHY IT IS ALWAYS A TELEPORT. Standing still, the dead entry is earmarked as "near"
/// every frame and line (2) is never reached for it. A teleport moves the reference position a
/// world away, so on that frame everything that was around the player becomes removable, the
/// dead entry is finally reached, and RemoveObjects throws. The throw aborts
/// CreateDestroyObjects, which aborts ZNetScene.Update - and because the offending entry is
/// removed on the line AFTER the one that threw, it is still there next frame. From that moment
/// the scene manager is dead for the rest of the session: nothing new loads, nothing unloads,
/// the player stands in an empty world.
///
/// WHAT THIS PATCH DOES. It is a finalizer, so it costs nothing on the millions of calls that
/// work. When RemoveObjects does throw, it sweeps m_instances for entries whose ZNetView is dead
/// or whose ZDO has been reset, takes them out, and swallows the exception so the next frame
/// runs clean. Vanilla's own rule is used for the ZDO behind each one - a temporary ZDO this
/// client owns is destroyed with its object, a persistent one is world data and is left exactly
/// where it is, because "the view is broken" is not evidence that the player's building should
/// be deleted.
///
/// If the sweep finds nothing, the exception is handed back untouched: this patch is for one
/// specific failure and must not hide anybody else's.
///
/// AND IT NAMES THE CULPRIT. Every purge logs the PREFAB NAME behind each dead entry, which is
/// the one thing the stack trace cannot tell us. Whatever is producing these - this mod, another
/// mod, or a plain vanilla race condition - the next log from a crashed teleport says so by
/// name, and the fix can then go where it belongs: at the despawn that used Object.Destroy
/// instead of ZNetScene.Destroy.
/// </summary>
[HarmonyPatch(typeof(ZNetScene), "RemoveObjects")]
public static class ZNetScene_RemoveObjects_OrphanPatch
{
private static readonly FieldInfo InstancesField = AccessTools.Field(typeof(ZNetScene), "m_instances");
// Reused rather than allocated per sweep: a sweep runs from inside a failing frame, and the
// one thing that must not happen there is extra pressure on the frame that is already sick.
private static readonly List<ZDO> Broken = new List<ZDO>();
private static readonly Dictionary<string, int> CountByPrefab = new Dictionary<string, int>();
private static int totalPurged;
public static Exception Finalizer(Exception __exception, ZNetScene __instance)
{
if (__exception == null) return null;
int purged = Purge(__instance);
// Nothing broken in the table means this throw was not ours to catch.
return purged > 0 ? null : __exception;
}
private static int Purge(ZNetScene scene)
{
if (scene == null || InstancesField == null) return 0;
Dictionary<ZDO, ZNetView> instances = InstancesField.GetValue(scene) as Dictionary<ZDO, ZNetView>;
if (instances == null) return 0;
Broken.Clear();
CountByPrefab.Clear();
foreach (KeyValuePair<ZDO, ZNetView> instance in instances)
{
// Unity's own == is what makes the first half of this work: a component whose
// GameObject has been destroyed is still a live managed object, and only this
// comparison knows it is dead. The second half is the reset-ZDO case from line (1).
if (instance.Value != null && instance.Value.GetZDO() != null) continue;
Broken.Add(instance.Key);
}
if (Broken.Count == 0) return 0;
int purged = Broken.Count;
int persistentLeftAlone = 0;
foreach (ZDO zdo in Broken)
{
string prefab = PrefabNameOf(zdo);
int seen;
CountByPrefab.TryGetValue(prefab, out seen);
CountByPrefab[prefab] = seen + 1;
instances.Remove(zdo);
if (!zdo.Persistent && zdo.IsOwner() && ZDOMan.instance != null)
{
ZDOMan.instance.DestroyZDO(zdo);
}
else if (zdo.Persistent)
{
persistentLeftAlone++;
}
}
totalPurged += purged;
List<string> named = new List<string>(CountByPrefab.Count);
foreach (KeyValuePair<string, int> entry in CountByPrefab)
{
named.Add(entry.Value == 1 ? entry.Key : entry.Key + " x" + entry.Value);
}
Jotunn.Logger.LogWarning(
$"[RacesOfValheim] ZNetScene.RemoveObjects threw on {purged} dead scene " +
(purged == 1 ? "entry" : "entries") +
$" - the teleport crash. Purged: {string.Join(", ", named)}. " +
(persistentLeftAlone > 0
? $"{persistentLeftAlone} of them had a persistent ZDO, which is world data and was left alone. "
: "") +
$"The world keeps loading. ({totalPurged} purged this session.) " +
"Whoever destroyed those objects used Object.Destroy where ZNetScene.Destroy was needed.");
Broken.Clear();
CountByPrefab.Clear();
return purged;
}
/// <summary>
/// The name behind a dead entry, which is the whole diagnostic value of this patch. A hash
/// with no prefab behind it is still worth printing - it means the object came from a mod
/// that is no longer loaded, which is an answer too.
/// </summary>
private static string PrefabNameOf(ZDO zdo)
{
if (zdo == null) return "no ZDO";
int hash = zdo.GetPrefab();
GameObject prefab = hash != 0 && ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hash) : null;
return prefab != null ? prefab.name : $"unknown prefab (hash {hash})";
}
}
}